summaryrefslogtreecommitdiffstats
path: root/ipc
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
commit26a029d407be480d791972afb5975cf62c9360a6 (patch)
treef435a8308119effd964b339f76abb83a57c29483 /ipc
parentInitial commit. (diff)
downloadfirefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz
firefox-26a029d407be480d791972afb5975cf62c9360a6.zip
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'ipc')
-rw-r--r--ipc/app/Makefile.in44
-rw-r--r--ipc/app/MozillaRuntimeMain.cpp98
-rw-r--r--ipc/app/MozillaRuntimeMainAndroid.cpp32
-rw-r--r--ipc/app/macbuild/Contents/Info.plist.in32
-rw-r--r--ipc/app/macbuild/Contents/PkgInfo1
-rw-r--r--ipc/app/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in7
-rw-r--r--ipc/app/module.ver6
-rw-r--r--ipc/app/moz.build90
-rw-r--r--ipc/app/plugin-container.exe.manifest53
-rw-r--r--ipc/chromium/chromium-config.mozbuild28
-rw-r--r--ipc/chromium/gtest/moz.build16
-rw-r--r--ipc/chromium/gtest/name_unittest.cc78
-rw-r--r--ipc/chromium/gtest/ports_unittest.cc1829
-rw-r--r--ipc/chromium/moz.build136
-rw-r--r--ipc/chromium/src/LICENSE27
-rw-r--r--ipc/chromium/src/base/at_exit.cc73
-rw-r--r--ipc/chromium/src/base/at_exit.h76
-rw-r--r--ipc/chromium/src/base/basictypes.h262
-rw-r--r--ipc/chromium/src/base/chrome_application_mac.h60
-rw-r--r--ipc/chromium/src/base/chrome_application_mac.mm68
-rw-r--r--ipc/chromium/src/base/command_line.cc389
-rw-r--r--ipc/chromium/src/base/command_line.h188
-rw-r--r--ipc/chromium/src/base/compiler_specific.h79
-rw-r--r--ipc/chromium/src/base/condition_variable.h116
-rw-r--r--ipc/chromium/src/base/condition_variable_posix.cc110
-rw-r--r--ipc/chromium/src/base/condition_variable_win.cc40
-rw-r--r--ipc/chromium/src/base/dir_reader_bsd.h94
-rw-r--r--ipc/chromium/src/base/dir_reader_fallback.h33
-rw-r--r--ipc/chromium/src/base/dir_reader_linux.h95
-rw-r--r--ipc/chromium/src/base/dir_reader_posix.h45
-rw-r--r--ipc/chromium/src/base/eintr_wrapper.h61
-rw-r--r--ipc/chromium/src/base/file_path.cc313
-rw-r--r--ipc/chromium/src/base/file_path.h248
-rw-r--r--ipc/chromium/src/base/histogram.cc638
-rw-r--r--ipc/chromium/src/base/histogram.h432
-rw-r--r--ipc/chromium/src/base/linked_ptr.h185
-rw-r--r--ipc/chromium/src/base/linux_memfd_defs.h69
-rw-r--r--ipc/chromium/src/base/lock.h97
-rw-r--r--ipc/chromium/src/base/lock_impl.h65
-rw-r--r--ipc/chromium/src/base/lock_impl_posix.cc98
-rw-r--r--ipc/chromium/src/base/lock_impl_win.cc23
-rw-r--r--ipc/chromium/src/base/logging.cc87
-rw-r--r--ipc/chromium/src/base/logging.h132
-rw-r--r--ipc/chromium/src/base/mac_util.h17
-rw-r--r--ipc/chromium/src/base/mac_util.mm33
-rw-r--r--ipc/chromium/src/base/message_loop.cc725
-rw-r--r--ipc/chromium/src/base/message_loop.h559
-rw-r--r--ipc/chromium/src/base/message_pump.h140
-rw-r--r--ipc/chromium/src/base/message_pump_android.cc104
-rw-r--r--ipc/chromium/src/base/message_pump_android.h61
-rw-r--r--ipc/chromium/src/base/message_pump_default.cc96
-rw-r--r--ipc/chromium/src/base/message_pump_default.h43
-rw-r--r--ipc/chromium/src/base/message_pump_glib.cc291
-rw-r--r--ipc/chromium/src/base/message_pump_glib.h92
-rw-r--r--ipc/chromium/src/base/message_pump_libevent.cc410
-rw-r--r--ipc/chromium/src/base/message_pump_libevent.h181
-rw-r--r--ipc/chromium/src/base/message_pump_mac.h280
-rw-r--r--ipc/chromium/src/base/message_pump_mac.mm735
-rw-r--r--ipc/chromium/src/base/message_pump_qt.cc177
-rw-r--r--ipc/chromium/src/base/message_pump_qt.h84
-rw-r--r--ipc/chromium/src/base/message_pump_win.cc553
-rw-r--r--ipc/chromium/src/base/message_pump_win.h347
-rw-r--r--ipc/chromium/src/base/object_watcher.cc135
-rw-r--r--ipc/chromium/src/base/object_watcher.h115
-rw-r--r--ipc/chromium/src/base/observer_list.h180
-rw-r--r--ipc/chromium/src/base/pickle.cc525
-rw-r--r--ipc/chromium/src/base/pickle.h284
-rw-r--r--ipc/chromium/src/base/platform_file.h46
-rw-r--r--ipc/chromium/src/base/platform_thread.h88
-rw-r--r--ipc/chromium/src/base/platform_thread_mac.mm75
-rw-r--r--ipc/chromium/src/base/platform_thread_posix.cc151
-rw-r--r--ipc/chromium/src/base/platform_thread_win.cc80
-rw-r--r--ipc/chromium/src/base/port.h64
-rw-r--r--ipc/chromium/src/base/process.h50
-rw-r--r--ipc/chromium/src/base/process_util.h342
-rw-r--r--ipc/chromium/src/base/process_util_linux.cc368
-rw-r--r--ipc/chromium/src/base/process_util_mac.mm167
-rw-r--r--ipc/chromium/src/base/process_util_posix.cc388
-rw-r--r--ipc/chromium/src/base/process_util_win.cc392
-rw-r--r--ipc/chromium/src/base/rand_util.cc30
-rw-r--r--ipc/chromium/src/base/rand_util.h19
-rw-r--r--ipc/chromium/src/base/revocable_store.cc40
-rw-r--r--ipc/chromium/src/base/revocable_store.h75
-rw-r--r--ipc/chromium/src/base/scoped_bstr_win.h138
-rw-r--r--ipc/chromium/src/base/scoped_cftyperef.h68
-rw-r--r--ipc/chromium/src/base/scoped_handle.h52
-rw-r--r--ipc/chromium/src/base/scoped_handle_win.h193
-rw-r--r--ipc/chromium/src/base/scoped_nsautorelease_pool.h55
-rw-r--r--ipc/chromium/src/base/scoped_nsautorelease_pool.mm30
-rw-r--r--ipc/chromium/src/base/scoped_nsobject.h66
-rw-r--r--ipc/chromium/src/base/set_process_title_linux.cc206
-rw-r--r--ipc/chromium/src/base/set_process_title_linux.h12
-rw-r--r--ipc/chromium/src/base/shared_memory.h197
-rw-r--r--ipc/chromium/src/base/shared_memory_posix.cc563
-rw-r--r--ipc/chromium/src/base/shared_memory_win.cc266
-rw-r--r--ipc/chromium/src/base/stack_container.h244
-rw-r--r--ipc/chromium/src/base/stl_util-inl.h435
-rw-r--r--ipc/chromium/src/base/string16.cc74
-rw-r--r--ipc/chromium/src/base/string16.h161
-rw-r--r--ipc/chromium/src/base/string_piece.cc190
-rw-r--r--ipc/chromium/src/base/string_piece.h189
-rw-r--r--ipc/chromium/src/base/string_util.cc719
-rw-r--r--ipc/chromium/src/base/string_util.h229
-rw-r--r--ipc/chromium/src/base/string_util_posix.h44
-rw-r--r--ipc/chromium/src/base/string_util_win.h41
-rw-r--r--ipc/chromium/src/base/sys_string_conversions.h35
-rw-r--r--ipc/chromium/src/base/sys_string_conversions_mac.mm126
-rw-r--r--ipc/chromium/src/base/sys_string_conversions_win.cc68
-rw-r--r--ipc/chromium/src/base/task.h227
-rw-r--r--ipc/chromium/src/base/thread.cc201
-rw-r--r--ipc/chromium/src/base/thread.h176
-rw-r--r--ipc/chromium/src/base/thread_local.h121
-rw-r--r--ipc/chromium/src/base/thread_local_posix.cc38
-rw-r--r--ipc/chromium/src/base/thread_local_storage.h95
-rw-r--r--ipc/chromium/src/base/thread_local_win.cc41
-rw-r--r--ipc/chromium/src/base/time.cc97
-rw-r--r--ipc/chromium/src/base/time.h392
-rw-r--r--ipc/chromium/src/base/time_mac.cc122
-rw-r--r--ipc/chromium/src/base/time_posix.cc200
-rw-r--r--ipc/chromium/src/base/time_win.cc263
-rw-r--r--ipc/chromium/src/base/timer.cc31
-rw-r--r--ipc/chromium/src/base/timer.h261
-rw-r--r--ipc/chromium/src/base/tuple.h838
-rw-r--r--ipc/chromium/src/base/waitable_event.h173
-rw-r--r--ipc/chromium/src/base/waitable_event_posix.cc362
-rw-r--r--ipc/chromium/src/base/waitable_event_win.cc81
-rw-r--r--ipc/chromium/src/base/win_util.cc37
-rw-r--r--ipc/chromium/src/base/win_util.h22
-rw-r--r--ipc/chromium/src/chrome/common/child_process.cc29
-rw-r--r--ipc/chromium/src/chrome/common/child_process.h45
-rw-r--r--ipc/chromium/src/chrome/common/child_thread.cc48
-rw-r--r--ipc/chromium/src/chrome/common/child_thread.h56
-rw-r--r--ipc/chromium/src/chrome/common/chrome_switches.cc18
-rw-r--r--ipc/chromium/src/chrome/common/chrome_switches.h22
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel.h189
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_capability.h61
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_posix.cc1256
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_posix.h203
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_utils.cc58
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_utils.h21
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_win.cc814
-rw-r--r--ipc/chromium/src/chrome/common/ipc_channel_win.h167
-rw-r--r--ipc/chromium/src/chrome/common/ipc_message.cc217
-rw-r--r--ipc/chromium/src/chrome/common/ipc_message.h424
-rw-r--r--ipc/chromium/src/chrome/common/ipc_message_utils.cc105
-rw-r--r--ipc/chromium/src/chrome/common/ipc_message_utils.h1092
-rw-r--r--ipc/chromium/src/chrome/common/mach_ipc_mac.cc93
-rw-r--r--ipc/chromium/src/chrome/common/mach_ipc_mac.h40
-rw-r--r--ipc/chromium/src/chrome/common/mach_message_source_mac.cc61
-rw-r--r--ipc/chromium/src/chrome/common/mach_message_source_mac.h60
-rw-r--r--ipc/chromium/src/chrome/common/process_watcher.h38
-rw-r--r--ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc257
-rw-r--r--ipc/chromium/src/chrome/common/process_watcher_win.cc252
-rw-r--r--ipc/chromium/src/mojo/core/ports/event.cc565
-rw-r--r--ipc/chromium/src/mojo/core/ports/event.h393
-rw-r--r--ipc/chromium/src/mojo/core/ports/message_filter.h29
-rw-r--r--ipc/chromium/src/mojo/core/ports/message_queue.cc97
-rw-r--r--ipc/chromium/src/mojo/core/ports/message_queue.h88
-rw-r--r--ipc/chromium/src/mojo/core/ports/name.cc54
-rw-r--r--ipc/chromium/src/mojo/core/ports/name.h122
-rw-r--r--ipc/chromium/src/mojo/core/ports/node.cc2130
-rw-r--r--ipc/chromium/src/mojo/core/ports/node.h355
-rw-r--r--ipc/chromium/src/mojo/core/ports/node_delegate.h38
-rw-r--r--ipc/chromium/src/mojo/core/ports/port.cc95
-rw-r--r--ipc/chromium/src/mojo/core/ports/port.h277
-rw-r--r--ipc/chromium/src/mojo/core/ports/port_locker.cc75
-rw-r--r--ipc/chromium/src/mojo/core/ports/port_locker.h90
-rw-r--r--ipc/chromium/src/mojo/core/ports/port_ref.cc30
-rw-r--r--ipc/chromium/src/mojo/core/ports/port_ref.h47
-rw-r--r--ipc/chromium/src/mojo/core/ports/user_data.h25
-rw-r--r--ipc/chromium/src/mojo/core/ports/user_message.cc21
-rw-r--r--ipc/chromium/src/mojo/core/ports/user_message.h62
-rw-r--r--ipc/chromium/src/third_party/libevent/CMakeLists.txt1575
-rw-r--r--ipc/chromium/src/third_party/libevent/CONTRIBUTING.md35
-rw-r--r--ipc/chromium/src/third_party/libevent/ChangeLog2162
-rw-r--r--ipc/chromium/src/third_party/libevent/ChangeLog-1.4231
-rw-r--r--ipc/chromium/src/third_party/libevent/ChangeLog-2.01280
-rw-r--r--ipc/chromium/src/third_party/libevent/Doxyfile257
-rw-r--r--ipc/chromium/src/third_party/libevent/LICENSE99
-rw-r--r--ipc/chromium/src/third_party/libevent/Makefile.am344
-rw-r--r--ipc/chromium/src/third_party/libevent/Makefile.nmake82
-rw-r--r--ipc/chromium/src/third_party/libevent/README.md487
-rw-r--r--ipc/chromium/src/third_party/libevent/README.mozilla31
-rw-r--r--ipc/chromium/src/third_party/libevent/Vagrantfile397
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.c149
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.h33
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/getopt_long.c234
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/evconfig-private.h6
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/event2/event-config.h350
-rw-r--r--ipc/chromium/src/third_party/libevent/WIN32-Code/tree.h677
-rw-r--r--ipc/chromium/src/third_party/libevent/android/event2/event-config.h606
-rw-r--r--ipc/chromium/src/third_party/libevent/arc4random.c546
-rwxr-xr-xipc/chromium/src/third_party/libevent/autogen.sh22
-rw-r--r--ipc/chromium/src/third_party/libevent/bsd/event2/event-config.h614
-rw-r--r--ipc/chromium/src/third_party/libevent/buffer.c3467
-rw-r--r--ipc/chromium/src/third_party/libevent/buffer_iocp.c327
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent-internal.h518
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent.c1036
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_async.c706
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_filter.c625
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_openssl.c1524
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_pair.c365
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_ratelim.c1089
-rw-r--r--ipc/chromium/src/third_party/libevent/bufferevent_sock.c707
-rw-r--r--ipc/chromium/src/third_party/libevent/changelist-internal.h102
-rwxr-xr-xipc/chromium/src/third_party/libevent/checkpatch.sh299
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/AddCompilerFlags.cmake13
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/AddEventLibrary.cmake193
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/COPYING-CMAKE-SCRIPTS22
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckConstExists.cmake25
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.c14
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.cmake43
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckFunctionKeywords.cmake14
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.c.in29
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.cmake82
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CheckWorkingKqueue.cmake52
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/CodeCoverage.cmake165
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/Copyright.txt57
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/LibeventConfig.cmake.in183
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/LibeventConfigVersion.cmake.in11
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/Macros.cmake36
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/Uninstall.cmake.in23
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/UseDoxygen.cmake111
-rw-r--r--ipc/chromium/src/third_party/libevent/cmake/VersionViaGit.cmake66
-rw-r--r--ipc/chromium/src/third_party/libevent/compat/sys/queue.h488
-rw-r--r--ipc/chromium/src/third_party/libevent/configure.ac1007
-rw-r--r--ipc/chromium/src/third_party/libevent/defer-internal.h73
-rw-r--r--ipc/chromium/src/third_party/libevent/devpoll.c311
-rw-r--r--ipc/chromium/src/third_party/libevent/doxygen.am55
-rw-r--r--ipc/chromium/src/third_party/libevent/epoll.c545
-rw-r--r--ipc/chromium/src/third_party/libevent/epoll_sub.c66
-rw-r--r--ipc/chromium/src/third_party/libevent/epolltable-internal.h1166
-rw-r--r--ipc/chromium/src/third_party/libevent/evbuffer-internal.h351
-rw-r--r--ipc/chromium/src/third_party/libevent/evconfig-private.h56
-rw-r--r--ipc/chromium/src/third_party/libevent/evconfig-private.h.cmake40
-rw-r--r--ipc/chromium/src/third_party/libevent/evconfig-private.h.in55
-rw-r--r--ipc/chromium/src/third_party/libevent/evdns.3322
-rw-r--r--ipc/chromium/src/third_party/libevent/evdns.c4847
-rw-r--r--ipc/chromium/src/third_party/libevent/event-config.h.cmake513
-rw-r--r--ipc/chromium/src/third_party/libevent/event-internal.h488
-rw-r--r--ipc/chromium/src/third_party/libevent/event.3624
-rw-r--r--ipc/chromium/src/third_party/libevent/event.c4020
-rw-r--r--ipc/chromium/src/third_party/libevent/event_iocp.c294
-rwxr-xr-xipc/chromium/src/third_party/libevent/event_rpcgen.py1925
-rw-r--r--ipc/chromium/src/third_party/libevent/event_tagging.c609
-rw-r--r--ipc/chromium/src/third_party/libevent/evmap-internal.h117
-rw-r--r--ipc/chromium/src/third_party/libevent/evmap.c1062
-rw-r--r--ipc/chromium/src/third_party/libevent/evport.c451
-rw-r--r--ipc/chromium/src/third_party/libevent/evrpc-internal.h205
-rw-r--r--ipc/chromium/src/third_party/libevent/evrpc.c1171
-rw-r--r--ipc/chromium/src/third_party/libevent/evsignal-internal.h65
-rw-r--r--ipc/chromium/src/third_party/libevent/evthread-internal.h406
-rw-r--r--ipc/chromium/src/third_party/libevent/evthread.c509
-rw-r--r--ipc/chromium/src/third_party/libevent/evthread_pthread.c191
-rw-r--r--ipc/chromium/src/third_party/libevent/evthread_win32.c341
-rw-r--r--ipc/chromium/src/third_party/libevent/evutil.c2765
-rw-r--r--ipc/chromium/src/third_party/libevent/evutil_rand.c206
-rw-r--r--ipc/chromium/src/third_party/libevent/evutil_time.c621
-rw-r--r--ipc/chromium/src/third_party/libevent/extra/abi-check/README.md35
-rwxr-xr-xipc/chromium/src/third_party/libevent/extra/abi-check/abi_check.sh53
-rw-r--r--ipc/chromium/src/third_party/libevent/extra/abi-check/libevent.json12
-rw-r--r--ipc/chromium/src/third_party/libevent/extra/lsan.supp3
-rw-r--r--ipc/chromium/src/third_party/libevent/extra/tsan.supp2
-rw-r--r--ipc/chromium/src/third_party/libevent/ht-internal.h487
-rw-r--r--ipc/chromium/src/third_party/libevent/http-internal.h206
-rw-r--r--ipc/chromium/src/third_party/libevent/http.c5128
-rw-r--r--ipc/chromium/src/third_party/libevent/include/evdns.h45
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event.h83
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/buffer.h1077
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/buffer_compat.h116
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/bufferevent.h1024
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/bufferevent_compat.h104
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/bufferevent_ssl.h134
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/bufferevent_struct.h116
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/dns.h751
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/dns_compat.h358
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/dns_struct.h80
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/event.h1672
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/event_compat.h230
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/event_struct.h180
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/http.h1192
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/http_compat.h94
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/http_struct.h152
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/keyvalq_struct.h80
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/listener.h192
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/rpc.h626
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/rpc_compat.h61
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/rpc_struct.h114
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/tag.h146
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/tag_compat.h49
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/thread.h253
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/util.h888
-rw-r--r--ipc/chromium/src/third_party/libevent/include/event2/visibility.h67
-rw-r--r--ipc/chromium/src/third_party/libevent/include/evhttp.h45
-rw-r--r--ipc/chromium/src/third_party/libevent/include/evrpc.h45
-rw-r--r--ipc/chromium/src/third_party/libevent/include/evutil.h39
-rw-r--r--ipc/chromium/src/third_party/libevent/include/include.am49
-rw-r--r--ipc/chromium/src/third_party/libevent/iocp-internal.h215
-rw-r--r--ipc/chromium/src/third_party/libevent/ipv6-internal.h83
-rw-r--r--ipc/chromium/src/third_party/libevent/kqueue-internal.h39
-rw-r--r--ipc/chromium/src/third_party/libevent/kqueue.c580
-rw-r--r--ipc/chromium/src/third_party/libevent/libevent.pc.in16
-rw-r--r--ipc/chromium/src/third_party/libevent/libevent_core.pc.in16
-rw-r--r--ipc/chromium/src/third_party/libevent/libevent_extra.pc.in16
-rw-r--r--ipc/chromium/src/third_party/libevent/libevent_openssl.pc.in16
-rw-r--r--ipc/chromium/src/third_party/libevent/libevent_pthreads.pc.in16
-rw-r--r--ipc/chromium/src/third_party/libevent/linux/event2/event-config.h610
-rw-r--r--ipc/chromium/src/third_party/libevent/listener.c899
-rw-r--r--ipc/chromium/src/third_party/libevent/log-internal.h94
-rw-r--r--ipc/chromium/src/third_party/libevent/log.c244
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/ac_backport_259_ssizet.m43
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/acx_pthread.m4279
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/ax_check_funcs_ex.m422
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/ax_prog_doxygen.m4600
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/libevent_openssl.m461
-rw-r--r--ipc/chromium/src/third_party/libevent/m4/ntp_pkg_config.m427
-rw-r--r--ipc/chromium/src/third_party/libevent/mac/event2/event-config.h573
-rw-r--r--ipc/chromium/src/third_party/libevent/make-event-config.sed27
-rwxr-xr-xipc/chromium/src/third_party/libevent/make_epoll_table.py63
-rw-r--r--ipc/chromium/src/third_party/libevent/minheap-internal.h192
-rw-r--r--ipc/chromium/src/third_party/libevent/mm-internal.h92
-rw-r--r--ipc/chromium/src/third_party/libevent/openssl-compat.h47
-rw-r--r--ipc/chromium/src/third_party/libevent/poll.c358
-rw-r--r--ipc/chromium/src/third_party/libevent/ratelim-internal.h105
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/dns-example.c264
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/event-read-fifo.c162
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/hello-world.c140
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/hostcheck.c217
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/hostcheck.h30
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/http-connect.c131
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/http-server.c582
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/https-client.c544
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/include.am56
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/le-proxy.c305
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.c178
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.h56
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/signal-test.c83
-rw-r--r--ipc/chromium/src/third_party/libevent/sample/time-test.c110
-rw-r--r--ipc/chromium/src/third_party/libevent/select.c346
-rw-r--r--ipc/chromium/src/third_party/libevent/signal.c481
-rw-r--r--ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h602
-rw-r--r--ipc/chromium/src/third_party/libevent/strlcpy-internal.h24
-rw-r--r--ipc/chromium/src/third_party/libevent/strlcpy.c75
-rw-r--r--ipc/chromium/src/third_party/libevent/test-export/CMakeLists.txt15
-rw-r--r--ipc/chromium/src/third_party/libevent/test-export/test-export.c122
-rw-r--r--ipc/chromium/src/third_party/libevent/test-export/test-export.py199
-rw-r--r--ipc/chromium/src/third_party/libevent/test/Makefile.nmake79
-rw-r--r--ipc/chromium/src/third_party/libevent/test/bench.c235
-rw-r--r--ipc/chromium/src/third_party/libevent/test/bench_cascade.c188
-rw-r--r--ipc/chromium/src/third_party/libevent/test/bench_http.c200
-rw-r--r--ipc/chromium/src/third_party/libevent/test/bench_httpclient.c240
-rwxr-xr-xipc/chromium/src/third_party/libevent/test/check-dumpevents.py54
-rw-r--r--ipc/chromium/src/third_party/libevent/test/include.am176
-rw-r--r--ipc/chromium/src/third_party/libevent/test/print-winsock-errors.c86
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress.c3615
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress.h149
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress.rpc25
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_buffer.c2870
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_bufferevent.c1467
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_dns.c2518
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_et.c270
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_finalize.c395
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_http.c4807
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_iocp.c352
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_listener.c348
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_main.c528
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_minheap.c99
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_rpc.c952
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_ssl.c1078
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_testutils.c233
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_testutils.h67
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_thread.c590
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_thread.h56
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_util.c1681
-rw-r--r--ipc/chromium/src/third_party/libevent/test/regress_zlib.c348
-rwxr-xr-xipc/chromium/src/third_party/libevent/test/rpcgen_wrapper.sh43
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-changelist.c224
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-closed.c111
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-dumpevents.c179
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-eof.c117
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-fdleak.c252
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-init.c65
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-ratelim.c688
-rwxr-xr-xipc/chromium/src/third_party/libevent/test/test-ratelim.sh88
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-time.c123
-rw-r--r--ipc/chromium/src/third_party/libevent/test/test-weof.c114
-rwxr-xr-xipc/chromium/src/third_party/libevent/test/test.sh188
-rw-r--r--ipc/chromium/src/third_party/libevent/test/tinytest.c610
-rw-r--r--ipc/chromium/src/third_party/libevent/test/tinytest.h103
-rw-r--r--ipc/chromium/src/third_party/libevent/test/tinytest_demo.c292
-rw-r--r--ipc/chromium/src/third_party/libevent/test/tinytest_local.h12
-rw-r--r--ipc/chromium/src/third_party/libevent/test/tinytest_macros.h213
-rw-r--r--ipc/chromium/src/third_party/libevent/time-internal.h101
-rw-r--r--ipc/chromium/src/third_party/libevent/util-internal.h551
-rw-r--r--ipc/chromium/src/third_party/libevent/whatsnew-2.0.txt609
-rw-r--r--ipc/chromium/src/third_party/libevent/whatsnew-2.1.txt768
-rw-r--r--ipc/chromium/src/third_party/libevent/win32select.c389
-rw-r--r--ipc/chromium/src/third_party/libeventcommon.mozbuild42
-rw-r--r--ipc/chromium/src/third_party/moz.build70
-rw-r--r--ipc/contentproc/plugin-container.cpp59
-rw-r--r--ipc/docs/index.rst20
-rw-r--r--ipc/docs/ipdl.rst1836
-rw-r--r--ipc/docs/processes.rst1252
-rw-r--r--ipc/docs/utility_process.rst69
-rw-r--r--ipc/glue/AsyncBlockers.h82
-rw-r--r--ipc/glue/BackgroundChild.h76
-rw-r--r--ipc/glue/BackgroundChildImpl.cpp459
-rw-r--r--ipc/glue/BackgroundChildImpl.h193
-rw-r--r--ipc/glue/BackgroundImpl.cpp1268
-rw-r--r--ipc/glue/BackgroundParent.h112
-rw-r--r--ipc/glue/BackgroundParentImpl.cpp1397
-rw-r--r--ipc/glue/BackgroundParentImpl.h363
-rw-r--r--ipc/glue/BackgroundStarterChild.h35
-rw-r--r--ipc/glue/BackgroundStarterParent.h48
-rw-r--r--ipc/glue/BackgroundUtils.cpp1158
-rw-r--r--ipc/glue/BackgroundUtils.h194
-rw-r--r--ipc/glue/BigBuffer.cpp105
-rw-r--r--ipc/glue/BigBuffer.h131
-rw-r--r--ipc/glue/BrowserProcessSubThread.cpp83
-rw-r--r--ipc/glue/BrowserProcessSubThread.h66
-rw-r--r--ipc/glue/ByteBuf.h71
-rw-r--r--ipc/glue/ByteBufUtils.h56
-rw-r--r--ipc/glue/CrashReporterClient.cpp47
-rw-r--r--ipc/glue/CrashReporterClient.h51
-rw-r--r--ipc/glue/CrashReporterHelper.h94
-rw-r--r--ipc/glue/CrashReporterHost.cpp181
-rw-r--r--ipc/glue/CrashReporterHost.h130
-rw-r--r--ipc/glue/CrossProcessMutex.h118
-rw-r--r--ipc/glue/CrossProcessMutex_posix.cpp140
-rw-r--r--ipc/glue/CrossProcessMutex_unimplemented.cpp46
-rw-r--r--ipc/glue/CrossProcessMutex_windows.cpp65
-rw-r--r--ipc/glue/CrossProcessSemaphore.h119
-rw-r--r--ipc/glue/CrossProcessSemaphore_mach.cpp92
-rw-r--r--ipc/glue/CrossProcessSemaphore_posix.cpp164
-rw-r--r--ipc/glue/CrossProcessSemaphore_unimplemented.cpp64
-rw-r--r--ipc/glue/CrossProcessSemaphore_windows.cpp83
-rw-r--r--ipc/glue/DataPipe.cpp767
-rw-r--r--ipc/glue/DataPipe.h192
-rw-r--r--ipc/glue/Endpoint.cpp167
-rw-r--r--ipc/glue/Endpoint.h288
-rw-r--r--ipc/glue/EnumSerializer.h187
-rw-r--r--ipc/glue/EnvironmentMap.h62
-rw-r--r--ipc/glue/FileDescriptor.cpp117
-rw-r--r--ipc/glue/FileDescriptor.h79
-rw-r--r--ipc/glue/FileDescriptorShuffle.cpp113
-rw-r--r--ipc/glue/FileDescriptorShuffle.h68
-rw-r--r--ipc/glue/FileDescriptorUtils.cpp109
-rw-r--r--ipc/glue/FileDescriptorUtils.h53
-rw-r--r--ipc/glue/ForkServer.cpp316
-rw-r--r--ipc/glue/ForkServer.h46
-rw-r--r--ipc/glue/ForkServiceChild.cpp193
-rw-r--r--ipc/glue/ForkServiceChild.h113
-rw-r--r--ipc/glue/GeckoChildProcessHost.cpp1801
-rw-r--r--ipc/glue/GeckoChildProcessHost.h316
-rw-r--r--ipc/glue/IOThreadChild.h46
-rw-r--r--ipc/glue/IPCCore.h22
-rw-r--r--ipc/glue/IPCForwards.h38
-rw-r--r--ipc/glue/IPCMessageUtils.h237
-rw-r--r--ipc/glue/IPCMessageUtilsSpecializations.cpp67
-rw-r--r--ipc/glue/IPCMessageUtilsSpecializations.h841
-rw-r--r--ipc/glue/IPCStream.ipdlh22
-rw-r--r--ipc/glue/IPCStreamUtils.cpp191
-rw-r--r--ipc/glue/IPCStreamUtils.h51
-rw-r--r--ipc/glue/IPCTypes.h20
-rw-r--r--ipc/glue/IPDLParamTraits.h65
-rw-r--r--ipc/glue/IPDLStructMember.h37
-rw-r--r--ipc/glue/IdleSchedulerChild.cpp151
-rw-r--r--ipc/glue/IdleSchedulerChild.h75
-rw-r--r--ipc/glue/IdleSchedulerParent.cpp452
-rw-r--r--ipc/glue/IdleSchedulerParent.h131
-rw-r--r--ipc/glue/InputStreamParams.ipdlh101
-rw-r--r--ipc/glue/InputStreamUtils.cpp211
-rw-r--r--ipc/glue/InputStreamUtils.h50
-rw-r--r--ipc/glue/LaunchError.cpp31
-rw-r--r--ipc/glue/LaunchError.h40
-rw-r--r--ipc/glue/MessageChannel.cpp2491
-rw-r--r--ipc/glue/MessageChannel.h888
-rw-r--r--ipc/glue/MessageLink.cpp206
-rw-r--r--ipc/glue/MessageLink.h114
-rw-r--r--ipc/glue/MessagePump.cpp336
-rw-r--r--ipc/glue/MessagePump.h203
-rw-r--r--ipc/glue/MessagePump_android.cpp26
-rw-r--r--ipc/glue/MessagePump_mac.mm100
-rw-r--r--ipc/glue/MessagePump_windows.cpp96
-rw-r--r--ipc/glue/MiniTransceiver.cpp255
-rw-r--r--ipc/glue/MiniTransceiver.h118
-rw-r--r--ipc/glue/Neutering.h70
-rw-r--r--ipc/glue/NodeChannel.cpp305
-rw-r--r--ipc/glue/NodeChannel.h178
-rw-r--r--ipc/glue/NodeController.cpp869
-rw-r--r--ipc/glue/NodeController.h176
-rw-r--r--ipc/glue/PBackground.ipdl296
-rw-r--r--ipc/glue/PBackgroundSharedTypes.ipdlh78
-rw-r--r--ipc/glue/PBackgroundStarter.ipdl18
-rw-r--r--ipc/glue/PBackgroundTest.ipdl21
-rw-r--r--ipc/glue/PIdleScheduler.ipdl70
-rw-r--r--ipc/glue/PUtilityAudioDecoder.ipdl57
-rw-r--r--ipc/glue/PUtilityProcess.ipdl126
-rw-r--r--ipc/glue/ProcessChild.cpp137
-rw-r--r--ipc/glue/ProcessChild.h75
-rw-r--r--ipc/glue/ProcessUtils.h93
-rw-r--r--ipc/glue/ProcessUtils_bsd.cpp27
-rw-r--r--ipc/glue/ProcessUtils_common.cpp275
-rw-r--r--ipc/glue/ProcessUtils_linux.cpp22
-rw-r--r--ipc/glue/ProcessUtils_mac.mm116
-rw-r--r--ipc/glue/ProcessUtils_none.cpp15
-rw-r--r--ipc/glue/ProtocolMessageUtils.h121
-rw-r--r--ipc/glue/ProtocolTypes.ipdlh21
-rw-r--r--ipc/glue/ProtocolUtils.cpp849
-rw-r--r--ipc/glue/ProtocolUtils.h781
-rw-r--r--ipc/glue/RandomAccessStreamParams.ipdlh32
-rw-r--r--ipc/glue/RandomAccessStreamUtils.cpp88
-rw-r--r--ipc/glue/RandomAccessStreamUtils.h50
-rw-r--r--ipc/glue/RawShmem.cpp108
-rw-r--r--ipc/glue/RawShmem.h113
-rw-r--r--ipc/glue/ScopedPort.cpp77
-rw-r--r--ipc/glue/ScopedPort.h79
-rw-r--r--ipc/glue/SerializedStructuredCloneBuffer.cpp79
-rw-r--r--ipc/glue/SerializedStructuredCloneBuffer.h87
-rw-r--r--ipc/glue/SetProcessTitle.cpp51
-rw-r--r--ipc/glue/SetProcessTitle.h19
-rw-r--r--ipc/glue/SharedMemory.cpp84
-rw-r--r--ipc/glue/SharedMemory.h142
-rw-r--r--ipc/glue/SharedMemoryBasic.h16
-rw-r--r--ipc/glue/SharedMemoryBasic_chromium.h89
-rw-r--r--ipc/glue/SharedMemoryBasic_mach.h75
-rw-r--r--ipc/glue/SharedMemoryBasic_mach.mm175
-rw-r--r--ipc/glue/SharedMemory_posix.cpp55
-rw-r--r--ipc/glue/SharedMemory_windows.cpp41
-rw-r--r--ipc/glue/Shmem.cpp248
-rw-r--r--ipc/glue/Shmem.h190
-rw-r--r--ipc/glue/ShmemMessageUtils.h30
-rw-r--r--ipc/glue/SideVariant.h187
-rw-r--r--ipc/glue/StringUtil.cpp86
-rw-r--r--ipc/glue/TaintingIPCUtils.h41
-rw-r--r--ipc/glue/TaskFactory.h97
-rw-r--r--ipc/glue/ToplevelActorHolder.h45
-rw-r--r--ipc/glue/TransportSecurityInfoUtils.cpp78
-rw-r--r--ipc/glue/TransportSecurityInfoUtils.h43
-rw-r--r--ipc/glue/URIParams.ipdlh117
-rw-r--r--ipc/glue/URIUtils.cpp140
-rw-r--r--ipc/glue/URIUtils.h49
-rw-r--r--ipc/glue/UtilityAudioDecoder.cpp41
-rw-r--r--ipc/glue/UtilityAudioDecoder.h21
-rw-r--r--ipc/glue/UtilityAudioDecoderChild.cpp232
-rw-r--r--ipc/glue/UtilityAudioDecoderChild.h131
-rw-r--r--ipc/glue/UtilityAudioDecoderParent.cpp205
-rw-r--r--ipc/glue/UtilityAudioDecoderParent.h64
-rw-r--r--ipc/glue/UtilityProcessChild.cpp401
-rw-r--r--ipc/glue/UtilityProcessChild.h110
-rw-r--r--ipc/glue/UtilityProcessHost.cpp431
-rw-r--r--ipc/glue/UtilityProcessHost.h165
-rw-r--r--ipc/glue/UtilityProcessImpl.cpp147
-rw-r--r--ipc/glue/UtilityProcessImpl.h43
-rw-r--r--ipc/glue/UtilityProcessManager.cpp660
-rw-r--r--ipc/glue/UtilityProcessManager.h246
-rw-r--r--ipc/glue/UtilityProcessParent.cpp203
-rw-r--r--ipc/glue/UtilityProcessParent.h77
-rw-r--r--ipc/glue/UtilityProcessSandboxing.cpp70
-rw-r--r--ipc/glue/UtilityProcessSandboxing.h46
-rw-r--r--ipc/glue/WindowsMessageLoop.cpp1192
-rw-r--r--ipc/glue/WindowsMessageLoop.h134
-rw-r--r--ipc/glue/components.conf22
-rw-r--r--ipc/glue/moz.build313
-rw-r--r--ipc/glue/nsIIPCSerializableInputStream.h104
-rw-r--r--ipc/glue/test/browser/browser.toml94
-rw-r--r--ipc/glue/test/browser/browser_audio_fallback.toml17
-rw-r--r--ipc/glue/test/browser/browser_audio_fallback_content.toml17
-rw-r--r--ipc/glue/test/browser/browser_audio_locked.toml3
-rw-r--r--ipc/glue/test/browser/browser_audio_shutdown.toml5
-rw-r--r--ipc/glue/test/browser/browser_audio_telemetry_content.js39
-rw-r--r--ipc/glue/test/browser/browser_audio_telemetry_rdd.js36
-rw-r--r--ipc/glue/test/browser/browser_audio_telemetry_utility.js32
-rw-r--r--ipc/glue/test/browser/browser_audio_telemetry_utility_EME.js31
-rw-r--r--ipc/glue/test/browser/browser_child_hang.js37
-rw-r--r--ipc/glue/test/browser/browser_child_hang.toml7
-rw-r--r--ipc/glue/test/browser/browser_utility_audioDecodeCrash.js95
-rw-r--r--ipc/glue/test/browser/browser_utility_audio_locked.js28
-rw-r--r--ipc/glue/test/browser/browser_utility_audio_shutdown.js76
-rw-r--r--ipc/glue/test/browser/browser_utility_crashReporter.js34
-rw-r--r--ipc/glue/test/browser/browser_utility_filepicker_crashed.js170
-rw-r--r--ipc/glue/test/browser/browser_utility_geolocation_crashed.js70
-rw-r--r--ipc/glue/test/browser/browser_utility_hard_kill.js13
-rw-r--r--ipc/glue/test/browser/browser_utility_hard_kill_delayed.js57
-rw-r--r--ipc/glue/test/browser/browser_utility_memoryReport.js76
-rw-r--r--ipc/glue/test/browser/browser_utility_multipleAudio.js45
-rw-r--r--ipc/glue/test/browser/browser_utility_multipleAudio_fallback.js22
-rw-r--r--ipc/glue/test/browser/browser_utility_multipleAudio_fallback_content.js22
-rw-r--r--ipc/glue/test/browser/browser_utility_profiler.js76
-rw-r--r--ipc/glue/test/browser/browser_utility_start_clean_shutdown.js9
-rw-r--r--ipc/glue/test/browser/head-multiple.js78
-rw-r--r--ipc/glue/test/browser/head-telemetry.js269
-rw-r--r--ipc/glue/test/browser/head.js562
-rw-r--r--ipc/glue/test/browser/mochitest_audio_off.toml12
-rw-r--r--ipc/glue/test/browser/mochitest_audio_on.toml12
-rw-r--r--ipc/glue/test/browser/moz.build15
-rw-r--r--ipc/glue/test/browser/test_utility_audio_off.html44
-rw-r--r--ipc/glue/test/browser/test_utility_audio_on.html45
-rw-r--r--ipc/glue/test/gtest/TestAsyncBlockers.cpp166
-rw-r--r--ipc/glue/test/gtest/TestUtilityProcess.cpp155
-rw-r--r--ipc/glue/test/gtest/TestUtilityProcessSandboxing.cpp66
-rw-r--r--ipc/glue/test/gtest/moz.build22
-rw-r--r--ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp280
-rw-r--r--ipc/glue/test/utility_process_xpcom/UtilityProcessTest.h29
-rw-r--r--ipc/glue/test/utility_process_xpcom/components.conf15
-rw-r--r--ipc/glue/test/utility_process_xpcom/moz.build21
-rw-r--r--ipc/glue/test/utility_process_xpcom/nsIUtilityProcessTest.idl56
-rw-r--r--ipc/gtest/TestBigBuffer.cpp86
-rw-r--r--ipc/gtest/TestDataPipe.cpp374
-rw-r--r--ipc/gtest/TestLogging.cpp65
-rw-r--r--ipc/gtest/TestRandomAccessStreamUtils.cpp216
-rw-r--r--ipc/gtest/TestSharedMemory.cpp338
-rw-r--r--ipc/gtest/TestUnsafeSharedMemoryHandle.cpp58
-rw-r--r--ipc/gtest/moz.build20
-rw-r--r--ipc/ipdl/Makefile.in33
-rw-r--r--ipc/ipdl/ipdl.py336
-rw-r--r--ipc/ipdl/ipdl/__init__.py98
-rw-r--r--ipc/ipdl/ipdl/ast.py477
-rw-r--r--ipc/ipdl/ipdl/builtin.py76
-rw-r--r--ipc/ipdl/ipdl/cgen.py108
-rw-r--r--ipc/ipdl/ipdl/checker.py79
-rw-r--r--ipc/ipdl/ipdl/cxx/__init__.py3
-rw-r--r--ipc/ipdl/ipdl/cxx/ast.py1033
-rw-r--r--ipc/ipdl/ipdl/cxx/cgen.py559
-rw-r--r--ipc/ipdl/ipdl/cxx/code.py187
-rw-r--r--ipc/ipdl/ipdl/lower.py5738
-rw-r--r--ipc/ipdl/ipdl/parser.py680
-rw-r--r--ipc/ipdl/ipdl/type.py1764
-rw-r--r--ipc/ipdl/ipdl/util.py12
-rw-r--r--ipc/ipdl/message-metadata.ini36
-rw-r--r--ipc/ipdl/moz.build22
-rw-r--r--ipc/ipdl/msgtype-components12
-rw-r--r--ipc/ipdl/sync-messages.ini300
-rw-r--r--ipc/ipdl/test/README.txt13
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.cpp27
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.h28
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.cpp19
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.h34
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestTypes.h43
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTestUtils.h28
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTests.h85
-rw-r--r--ipc/ipdl/test/cxx/IPDLUnitTests.template.cpp345
-rw-r--r--ipc/ipdl/test/cxx/Makefile.in45
-rw-r--r--ipc/ipdl/test/cxx/PTestActorPunning.ipdl28
-rw-r--r--ipc/ipdl/test/cxx/PTestActorPunningPunned.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestActorPunningSub.ipdl19
-rw-r--r--ipc/ipdl/test/cxx/PTestAsyncReturns.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestBadActor.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestBadActorSub.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestCancel.ipdl39
-rw-r--r--ipc/ipdl/test/cxx/PTestCrashCleanup.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestDataStructures.ipdl109
-rw-r--r--ipc/ipdl/test/cxx/PTestDataStructuresCommon.ipdlh107
-rw-r--r--ipc/ipdl/test/cxx/PTestDataStructuresSub.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestDemon.ipdl24
-rw-r--r--ipc/ipdl/test/cxx/PTestDesc.ipdl24
-rw-r--r--ipc/ipdl/test/cxx/PTestDescSub.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestDescSubsub.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestEndpointBridgeMain.ipdl25
-rw-r--r--ipc/ipdl/test/cxx/PTestEndpointBridgeMainSub.ipdl28
-rw-r--r--ipc/ipdl/test/cxx/PTestEndpointBridgeSub.ipdl25
-rw-r--r--ipc/ipdl/test/cxx/PTestEndpointOpens.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestEndpointOpensOpened.ipdl25
-rw-r--r--ipc/ipdl/test/cxx/PTestFailedCtor.ipdl17
-rw-r--r--ipc/ipdl/test/cxx/PTestFailedCtorSub.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestFailedCtorSubsub.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestHandle.ipdl17
-rw-r--r--ipc/ipdl/test/cxx/PTestHangs.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestHighestPrio.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestIndirectProtocolParam.ipdlh15
-rw-r--r--ipc/ipdl/test/cxx/PTestIndirectProtocolParamFirst.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestIndirectProtocolParamManage.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestIndirectProtocolParamSecond.ipdl14
-rw-r--r--ipc/ipdl/test/cxx/PTestInterruptErrorCleanup.ipdl14
-rw-r--r--ipc/ipdl/test/cxx/PTestInterruptRaces.ipdl27
-rw-r--r--ipc/ipdl/test/cxx/PTestInterruptShutdownRace.ipdl19
-rw-r--r--ipc/ipdl/test/cxx/PTestJSON.ipdl49
-rw-r--r--ipc/ipdl/test/cxx/PTestLatency.ipdl28
-rw-r--r--ipc/ipdl/test/cxx/PTestManyChildAllocs.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestManyChildAllocsSub.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestMultiMgrs.ipdl25
-rw-r--r--ipc/ipdl/test/cxx/PTestMultiMgrsBottom.ipdl18
-rw-r--r--ipc/ipdl/test/cxx/PTestMultiMgrsLeft.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestMultiMgrsRight.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestNestedLoops.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestPaintThread.ipdl15
-rw-r--r--ipc/ipdl/test/cxx/PTestPriority.ipdl24
-rw-r--r--ipc/ipdl/test/cxx/PTestRPC.ipdl24
-rw-r--r--ipc/ipdl/test/cxx/PTestRaceDeadlock.ipdl23
-rw-r--r--ipc/ipdl/test/cxx/PTestRaceDeferral.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestRacyInterruptReplies.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestRacyReentry.ipdl23
-rw-r--r--ipc/ipdl/test/cxx/PTestRacyUndefer.ipdl30
-rw-r--r--ipc/ipdl/test/cxx/PTestSanity.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestSelfManage.ipdl21
-rw-r--r--ipc/ipdl/test/cxx/PTestSelfManageRoot.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestShmem.ipdl17
-rw-r--r--ipc/ipdl/test/cxx/PTestShutdown.ipdl29
-rw-r--r--ipc/ipdl/test/cxx/PTestShutdownSub.ipdl23
-rw-r--r--ipc/ipdl/test/cxx/PTestShutdownSubsub.ipdl17
-rw-r--r--ipc/ipdl/test/cxx/PTestStackHooks.ipdl28
-rw-r--r--ipc/ipdl/test/cxx/PTestSyncError.ipdl20
-rw-r--r--ipc/ipdl/test/cxx/PTestSyncHang.ipdl16
-rw-r--r--ipc/ipdl/test/cxx/PTestSyncWakeup.ipdl23
-rw-r--r--ipc/ipdl/test/cxx/PTestUniquePtrIPC.ipdl26
-rw-r--r--ipc/ipdl/test/cxx/PTestUrgency.ipdl22
-rw-r--r--ipc/ipdl/test/cxx/PTestUrgentHangs.ipdl31
-rw-r--r--ipc/ipdl/test/cxx/README.txt61
-rw-r--r--ipc/ipdl/test/cxx/TestActorPunning.cpp125
-rw-r--r--ipc/ipdl/test/cxx/TestActorPunning.h100
-rw-r--r--ipc/ipdl/test/cxx/TestAsyncReturns.cpp101
-rw-r--r--ipc/ipdl/test/cxx/TestAsyncReturns.h54
-rw-r--r--ipc/ipdl/test/cxx/TestBadActor.cpp59
-rw-r--r--ipc/ipdl/test/cxx/TestBadActor.h84
-rw-r--r--ipc/ipdl/test/cxx/TestCancel.cpp115
-rw-r--r--ipc/ipdl/test/cxx/TestCancel.h54
-rw-r--r--ipc/ipdl/test/cxx/TestCrashCleanup.cpp100
-rw-r--r--ipc/ipdl/test/cxx/TestCrashCleanup.h49
-rw-r--r--ipc/ipdl/test/cxx/TestDataStructures.cpp888
-rw-r--r--ipc/ipdl/test/cxx/TestDataStructures.h180
-rw-r--r--ipc/ipdl/test/cxx/TestDemon.cpp362
-rw-r--r--ipc/ipdl/test/cxx/TestDemon.h91
-rw-r--r--ipc/ipdl/test/cxx/TestDesc.cpp78
-rw-r--r--ipc/ipdl/test/cxx/TestDesc.h115
-rw-r--r--ipc/ipdl/test/cxx/TestEndpointBridgeMain.cpp226
-rw-r--r--ipc/ipdl/test/cxx/TestEndpointBridgeMain.h132
-rw-r--r--ipc/ipdl/test/cxx/TestEndpointOpens.cpp242
-rw-r--r--ipc/ipdl/test/cxx/TestEndpointOpens.h102
-rw-r--r--ipc/ipdl/test/cxx/TestFailedCtor.cpp112
-rw-r--r--ipc/ipdl/test/cxx/TestFailedCtor.h127
-rw-r--r--ipc/ipdl/test/cxx/TestHangs.cpp127
-rw-r--r--ipc/ipdl/test/cxx/TestHangs.h75
-rw-r--r--ipc/ipdl/test/cxx/TestHighestPrio.cpp91
-rw-r--r--ipc/ipdl/test/cxx/TestHighestPrio.h55
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptErrorCleanup.cpp138
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptErrorCleanup.h52
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptRaces.cpp169
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptRaces.h104
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptShutdownRace.cpp111
-rw-r--r--ipc/ipdl/test/cxx/TestInterruptShutdownRace.h56
-rw-r--r--ipc/ipdl/test/cxx/TestJSON.cpp113
-rw-r--r--ipc/ipdl/test/cxx/TestJSON.h93
-rw-r--r--ipc/ipdl/test/cxx/TestLatency.cpp210
-rw-r--r--ipc/ipdl/test/cxx/TestLatency.h107
-rw-r--r--ipc/ipdl/test/cxx/TestManyChildAllocs.cpp83
-rw-r--r--ipc/ipdl/test/cxx/TestManyChildAllocs.h82
-rw-r--r--ipc/ipdl/test/cxx/TestMultiMgrs.cpp83
-rw-r--r--ipc/ipdl/test/cxx/TestMultiMgrs.h222
-rw-r--r--ipc/ipdl/test/cxx/TestNestedLoops.cpp78
-rw-r--r--ipc/ipdl/test/cxx/TestNestedLoops.h59
-rw-r--r--ipc/ipdl/test/cxx/TestRPC.cpp107
-rw-r--r--ipc/ipdl/test/cxx/TestRPC.h60
-rw-r--r--ipc/ipdl/test/cxx/TestRaceDeadlock.cpp102
-rw-r--r--ipc/ipdl/test/cxx/TestRaceDeadlock.h68
-rw-r--r--ipc/ipdl/test/cxx/TestRaceDeferral.cpp84
-rw-r--r--ipc/ipdl/test/cxx/TestRaceDeferral.h67
-rw-r--r--ipc/ipdl/test/cxx/TestRacyInterruptReplies.cpp94
-rw-r--r--ipc/ipdl/test/cxx/TestRacyInterruptReplies.h65
-rw-r--r--ipc/ipdl/test/cxx/TestRacyReentry.cpp63
-rw-r--r--ipc/ipdl/test/cxx/TestRacyReentry.h59
-rw-r--r--ipc/ipdl/test/cxx/TestRacyUndefer.cpp83
-rw-r--r--ipc/ipdl/test/cxx/TestRacyUndefer.h62
-rw-r--r--ipc/ipdl/test/cxx/TestSanity.cpp52
-rw-r--r--ipc/ipdl/test/cxx/TestSanity.h55
-rw-r--r--ipc/ipdl/test/cxx/TestSelfManageRoot.cpp54
-rw-r--r--ipc/ipdl/test/cxx/TestSelfManageRoot.h117
-rw-r--r--ipc/ipdl/test/cxx/TestShmem.cpp106
-rw-r--r--ipc/ipdl/test/cxx/TestShmem.h55
-rw-r--r--ipc/ipdl/test/cxx/TestShutdown.cpp185
-rw-r--r--ipc/ipdl/test/cxx/TestShutdown.h168
-rw-r--r--ipc/ipdl/test/cxx/TestStackHooks.cpp122
-rw-r--r--ipc/ipdl/test/cxx/TestStackHooks.h107
-rw-r--r--ipc/ipdl/test/cxx/TestSyncError.cpp45
-rw-r--r--ipc/ipdl/test/cxx/TestSyncError.h61
-rw-r--r--ipc/ipdl/test/cxx/TestSyncHang.cpp62
-rw-r--r--ipc/ipdl/test/cxx/TestSyncHang.h50
-rw-r--r--ipc/ipdl/test/cxx/TestSyncWakeup.cpp106
-rw-r--r--ipc/ipdl/test/cxx/TestSyncWakeup.h66
-rw-r--r--ipc/ipdl/test/cxx/TestUniquePtrIPC.cpp81
-rw-r--r--ipc/ipdl/test/cxx/TestUniquePtrIPC.h61
-rw-r--r--ipc/ipdl/test/cxx/TestUrgency.cpp117
-rw-r--r--ipc/ipdl/test/cxx/TestUrgency.h57
-rw-r--r--ipc/ipdl/test/cxx/TestUrgentHangs.cpp174
-rw-r--r--ipc/ipdl/test/cxx/TestUrgentHangs.h64
-rw-r--r--ipc/ipdl/test/cxx/app/TestIPDL.cpp24
-rw-r--r--ipc/ipdl/test/cxx/app/moz.build20
-rw-r--r--ipc/ipdl/test/cxx/genIPDLUnitTests.py193
-rw-r--r--ipc/ipdl/test/cxx/moz.build172
-rw-r--r--ipc/ipdl/test/gtest/IPDLUnitTest.cpp308
-rw-r--r--ipc/ipdl/test/gtest/IPDLUnitTest.h79
-rw-r--r--ipc/ipdl/test/gtest/IPDLUnitTestChild.h32
-rw-r--r--ipc/ipdl/test/gtest/IPDLUnitTestParent.h50
-rw-r--r--ipc/ipdl/test/gtest/PIPDLUnitTest.ipdl34
-rw-r--r--ipc/ipdl/test/gtest/PTestBasic.ipdl15
-rw-r--r--ipc/ipdl/test/gtest/PTestCrossProcessSemaphore.ipdl17
-rw-r--r--ipc/ipdl/test/gtest/PTestInduceConnectionError.ipdl19
-rw-r--r--ipc/ipdl/test/gtest/PTestManyHandles.ipdl15
-rw-r--r--ipc/ipdl/test/gtest/TestBasic.cpp29
-rw-r--r--ipc/ipdl/test/gtest/TestBasicChild.h26
-rw-r--r--ipc/ipdl/test/gtest/TestBasicParent.h23
-rw-r--r--ipc/ipdl/test/gtest/TestCrossProcessSemaphore.cpp63
-rw-r--r--ipc/ipdl/test/gtest/TestInduceConnectionError.cpp95
-rw-r--r--ipc/ipdl/test/gtest/TestManyHandles.cpp78
-rw-r--r--ipc/ipdl/test/gtest/moz.build35
-rw-r--r--ipc/ipdl/test/ipdl/IPDLCompile.py78
-rw-r--r--ipc/ipdl/test/ipdl/Makefile.in17
-rw-r--r--ipc/ipdl/test/ipdl/error/AsyncCtorReturns.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/AsyncCtorReturnsManagee.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/AsyncInsideSync.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrBadValue.ipdlh5
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrEmpty.ipdlh5
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidNestedValue.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidPriorityValue.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrRepeated.ipdlh5
-rw-r--r--ipc/ipdl/test/ipdl/error/ExtendedAttrUnknown.ipdlh5
-rw-r--r--ipc/ipdl/test/ipdl/error/ForgottenManagee.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/ForgottenManager.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/InsideCpowToChild.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/IntrAsyncManagee.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/IntrAsyncManager.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/IntrSyncManagee.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/IntrSyncManager.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/ManageeForgot.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/ManagerForgot.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/Nullable.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/Nullable2.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/PBadArrayBase.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/PBadNestedManagee.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/PBadNestedManager.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/PBadSideImpl.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/PBadUniquePtrBase.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/PCompressInvalid.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/PDouble.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/PExtendedAttrInvalidValue.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PExtendedAttrRepeated.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PExtendedAttrUnexpectedValue.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PExtendedAttrUnknownAttribute.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PInconsistentMoveOnly.ipdl14
-rw-r--r--ipc/ipdl/test/ipdl/error/PIntrNested.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PIntrNestedProtocol.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PIntrPriority.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PLazySendInvalid.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PLazySendSync.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PManagerManualDealloc.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/error/PMissingProc.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/error/PNoTaintWithoutTainted.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PToplevelManualDealloc.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PUniquePtrRecursive.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecStruct.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecUnion.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/PUnknownProc.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/PasyncMessageListed.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/ReplyPrioWithoutReturns.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/SyncAsyncManagee.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/SyncAsyncManager.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/SyncPrio.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/array_Recursive.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/error/badProtocolInclude.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/compressCtor.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/compressCtorManagee.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/conflictProtocolMsg.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/cyclecheck_Child.ipdl15
-rw-r--r--ipc/ipdl/test/ipdl/error/cyclecheck_Grandchild.ipdl15
-rw-r--r--ipc/ipdl/test/ipdl/error/cyclecheck_Parent.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/error/dtorReserved.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/empty.ipdl1
-rw-r--r--ipc/ipdl/test/ipdl/error/extra/PDouble.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocManaged.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocTop.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/inconsistentRC.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/intrMessageCompress.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/lex1.ipdl2
-rw-r--r--ipc/ipdl/test/ipdl/error/manageSelfToplevel.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/managedNoDtor.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/managerNoDtor.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/maybe_Recursive.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/error/maybe_SelfRecStruct.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/maybe_SelfRecUnion.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/messageNoDirection.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/error/multimanDupMgrs.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/multimanDupMgrsMgr.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/multimanNonexistentMgrs.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/mutualRecStruct.ipdl25
-rw-r--r--ipc/ipdl/test/ipdl/error/mutualRecStructUnion.ipdl25
-rw-r--r--ipc/ipdl/test/ipdl/error/noProtocolInHeader.ipdlh7
-rw-r--r--ipc/ipdl/test/ipdl/error/oldIncludeSyntax.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/parser.ipdl3
-rw-r--r--ipc/ipdl/test/ipdl/error/redeclMessage.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/error/redeclParamReturn.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/redeclScope.ipdlh12
-rw-r--r--ipc/ipdl/test/ipdl/error/shmem.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/structRedecl.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/error/structUnknownField.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/syncMessageCompress.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/syncParentToChild.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/tooWeakIntrAsync.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/tooWeakIntrSync.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/tooWeakSyncAsync.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/error/twoprotocols.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/error/undeclParamType.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/undeclProtocol.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/error/undeclReturnType.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/undefMutualRecStruct.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/undefMutualRecStructUnion.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/undefMutualRecUnion.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/error/undefSelfRecStruct.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/undefSelfRecUnion.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/error/unknownIntrMessage.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/error/unknownSyncMessage.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/message-metadata.ini2
-rw-r--r--ipc/ipdl/test/ipdl/moz.build8
-rw-r--r--ipc/ipdl/test/ipdl/ok/MutRecHeader1.ipdlh34
-rw-r--r--ipc/ipdl/test/ipdl/ok/MutRecHeader2.ipdlh8
-rw-r--r--ipc/ipdl/test/ipdl/ok/MutRecHeader3.ipdlh8
-rw-r--r--ipc/ipdl/test/ipdl/ok/MyTypes.ipdlh6
-rw-r--r--ipc/ipdl/test/ipdl/ok/PAsyncReturn.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/ok/PDelete.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/ok/PDeleteSub.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/ok/PEndpointDecl.ipdl19
-rw-r--r--ipc/ipdl/test/ipdl/ok/PEndpointUse.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/ok/PExtendedAttrMultipleAttributes.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/PLazySend.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/PManagedEndpointDecl.ipdl23
-rw-r--r--ipc/ipdl/test/ipdl/ok/PManagedEndpointManager.ipdl15
-rw-r--r--ipc/ipdl/test/ipdl/ok/PManualDealloc.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/ok/PManualDealloc_manager.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/ok/PMessageTainted.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/PMessageTaintedWithPassback.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/PMyManaged.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/ok/PMyManager.ipdl31
-rw-r--r--ipc/ipdl/test/ipdl/ok/PNested.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/ok/PNullable.ipdl22
-rw-r--r--ipc/ipdl/test/ipdl/ok/PSideImpl.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/PStruct.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PStructComparable.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PSyncSyncManagee.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/PSyncSyncManager.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/PUniquePtrBasic.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/PUniquePtrOfActors.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PUniquePtrOfActorsSub.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/PUniquePtrRecUnion.ipdl22
-rw-r--r--ipc/ipdl/test/ipdl/ok/PUniquePtrUnion.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PVirtualSendImpl.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pactorparam.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pactorreturn.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/Parray_Basic.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/Parray_OfActors.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/Parray_OfActorsSub.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/Parray_Union.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PbasicUsing.ipdl51
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pbuiltins.ipdl22
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pbytebuf.ipdl14
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pempty.ipdl4
-rw-r--r--ipc/ipdl/test/ipdl/ok/PemptyStruct.ipdl4
-rw-r--r--ipc/ipdl/test/ipdl/ok/PheaderProto.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/PintrProtocol.ipdl14
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pjetpack.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmanageSelf.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmanageSelf_Toplevel.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmanagedProtocol.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmanagerProtocol.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pmaybe_Basic.ipdl5
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pmaybe_OfActors.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pmaybe_OfActorsSub.ipdl7
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pmaybe_Union.ipdl11
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pmedia.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmessageCompress.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmultiManaged.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmultiManager1.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmultiManager2.ipdl9
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmultipleUsingCxxTypes.ipdl8
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmutualRecStructUnion.ipdl22
-rw-r--r--ipc/ipdl/test/ipdl/ok/PmutualRecUnion.ipdl22
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pnamespace_Basic.ipdl13
-rw-r--r--ipc/ipdl/test/ipdl/ok/PnoRedeclCrossMessage.ipdl10
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pplugin.ipdl6
-rw-r--r--ipc/ipdl/test/ipdl/ok/Prio.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/PselfRecUnion.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/Pshmem.ipdl14
-rw-r--r--ipc/ipdl/test/ipdl/ok/PsyncProtocol.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/PthreeDirections.ipdl14
-rw-r--r--ipc/ipdl/test/ipdl/ok/Punion_Basic.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/Punion_Comparable.ipdl12
-rw-r--r--ipc/ipdl/test/ipdl/ok/Punion_Namespaced.ipdl19
-rw-r--r--ipc/ipdl/test/ipdl/ok/header.ipdlh15
-rw-r--r--ipc/ipdl/test/ipdl/runtests.py119
-rw-r--r--ipc/ipdl/test/ipdl/sync-messages.ini50
-rw-r--r--ipc/ipdl/test/moz.build9
-rw-r--r--ipc/moz.build28
-rw-r--r--ipc/mscom/Aggregation.h83
-rw-r--r--ipc/mscom/AgileReference.cpp64
-rw-r--r--ipc/mscom/AgileReference.h143
-rw-r--r--ipc/mscom/ApartmentRegion.h106
-rw-r--r--ipc/mscom/COMWrappers.cpp101
-rw-r--r--ipc/mscom/COMWrappers.h38
-rw-r--r--ipc/mscom/EnsureMTA.cpp189
-rw-r--r--ipc/mscom/EnsureMTA.h129
-rw-r--r--ipc/mscom/ProcessRuntime.cpp486
-rw-r--r--ipc/mscom/ProcessRuntime.h87
-rw-r--r--ipc/mscom/ProfilerMarkers.cpp236
-rw-r--r--ipc/mscom/ProfilerMarkers.h18
-rw-r--r--ipc/mscom/Utils.cpp324
-rw-r--r--ipc/mscom/Utils.h123
-rw-r--r--ipc/mscom/moz.build42
-rw-r--r--ipc/mscom/mozglue/ProcessRuntimeShared.cpp31
-rw-r--r--ipc/mscom/mozglue/ProcessRuntimeShared.h55
-rw-r--r--ipc/mscom/mozglue/moz.build15
-rw-r--r--ipc/pull-chromium.py55
-rw-r--r--ipc/testshell/PTestShell.ipdl27
-rw-r--r--ipc/testshell/PTestShellCommand.ipdl23
-rw-r--r--ipc/testshell/TestShellChild.cpp54
-rw-r--r--ipc/testshell/TestShellChild.h44
-rw-r--r--ipc/testshell/TestShellParent.cpp90
-rw-r--r--ipc/testshell/TestShellParent.h74
-rw-r--r--ipc/testshell/XPCShellEnvironment.cpp468
-rw-r--r--ipc/testshell/XPCShellEnvironment.h57
-rw-r--r--ipc/testshell/moz.build37
-rw-r--r--ipc/testshell/tests/test_ipcshell.js34
-rw-r--r--ipc/testshell/tests/test_ipcshell_child.js6
-rw-r--r--ipc/testshell/tests/xpcshell.toml9
1020 files changed, 206403 insertions, 0 deletions
diff --git a/ipc/app/Makefile.in b/ipc/app/Makefile.in
new file mode 100644
index 0000000000..b7f40e9fb5
--- /dev/null
+++ b/ipc/app/Makefile.in
@@ -0,0 +1,44 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+ifndef MOZ_WINCONSOLE
+ifdef MOZ_DEBUG
+MOZ_WINCONSOLE = 1
+else
+MOZ_WINCONSOLE = 0
+endif
+endif
+
+include $(topsrcdir)/config/config.mk
+
+include $(topsrcdir)/config/rules.mk
+
+ifneq ($(MOZ_WIDGET_TOOLKIT),android)
+#LIBS += ../contentproc/$(LIB_PREFIX)plugin-container.$(LIB_SUFFIX)
+endif
+
+ifeq ($(OS_ARCH),WINNT) #{
+# Note the manifest file exists in the tree, so we use the explicit filename
+# here.
+EXTRA_DEPS += plugin-container.exe.manifest
+endif #}
+
+ifeq (cocoa,$(MOZ_WIDGET_TOOLKIT)) #{
+
+libs::
+ # plugin-container
+ $(NSINSTALL) -D $(DIST)/bin/$(PROGRAM).app
+ rsync -a -C --exclude '*.in' $(srcdir)/macbuild/Contents $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME).app
+ $(call py_action,preprocessor $(MOZ_CHILD_PROCESS_NAME).app/Contents/Info.plist,-Fsubstitution -DEXECUTABLE='$(MOZ_CHILD_PROCESS_NAME)' -DBUNDLEID='$(MOZ_CHILD_PROCESS_BUNDLEID)' -DMOZ_DEVELOPER_REPO_PATH='$(topsrcdir)' -DMOZ_DEVELOPER_OBJ_PATH='$(topobjdir)' $(srcdir)/macbuild/Contents/Info.plist.in -o $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME).app/Contents/Info.plist)
+ $(call py_action,preprocessor $(MOZ_CHILD_PROCESS_NAME).app/Contents/Resources/English.lproj/InfoPlist.strings,-Fsubstitution --output-encoding utf-16 -DAPP_NAME='$(MOZ_CHILD_PROCESS_APPNAME)' $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in -o $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME).app/Contents/Resources/English.lproj/InfoPlist.strings)
+ $(NSINSTALL) -D $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME).app/Contents/MacOS
+ $(NSINSTALL) $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME) $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME).app/Contents/MacOS
+ # media-plugin-helper
+ $(NSINSTALL) -D $(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app
+ rsync -a -C --exclude '*.in' $(srcdir)/macbuild/Contents $(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app
+ $(call py_action,preprocessor $(MOZ_EME_PROCESS_NAME).app/Contents/Info.plist,-Fsubstitution -DEXECUTABLE='$(MOZ_EME_PROCESS_NAME_BRANDED)' -DBUNDLEID='$(MOZ_EME_PROCESS_BUNDLEID)' -DMOZ_EME_PROCESS_NAME_BRANDED='$(MOZ_EME_PROCESS_NAME_BRANDED)' -DMOZ_DEVELOPER_REPO_PATH='$(topsrcdir)' -DMOZ_DEVELOPER_OBJ_PATH='$(topobjdir)' $(srcdir)/macbuild/Contents/Info.plist.in -o $(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app/Contents/Info.plist)
+ $(call py_action,preprocessor $(MOZ_EME_PROCESS_NAME).app/Contents/Resources/English.lproj/InfoPlist.strings,-Fsubstitution --output-encoding utf-16 -DAPP_NAME='$(MOZ_EME_PROCESS_BUNDLENAME)' $(srcdir)/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in -o $(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app/Contents/Resources/English.lproj/InfoPlist.strings)
+ $(NSINSTALL) -D $(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app/Contents/MacOS
+ cp $(DIST)/bin/$(MOZ_CHILD_PROCESS_NAME) "$(DIST)/bin/$(MOZ_EME_PROCESS_NAME).app/Contents/MacOS/$(MOZ_EME_PROCESS_NAME_BRANDED)"
+endif #}
diff --git a/ipc/app/MozillaRuntimeMain.cpp b/ipc/app/MozillaRuntimeMain.cpp
new file mode 100644
index 0000000000..6741617b60
--- /dev/null
+++ b/ipc/app/MozillaRuntimeMain.cpp
@@ -0,0 +1,98 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "../contentproc/plugin-container.cpp"
+
+#include "mozilla/Bootstrap.h"
+#include "mozilla/RuntimeExceptionModule.h"
+#include "mozilla/ScopeExit.h"
+#if defined(XP_WIN)
+# include "mozilla/WindowsDllBlocklist.h"
+# include "mozilla/GeckoArgs.h"
+#endif // defined(XP_WIN)
+
+using namespace mozilla;
+
+static bool UseForkServer(int argc, char* argv[]) {
+#if defined(MOZ_ENABLE_FORKSERVER)
+ return strcmp(argv[argc - 1], "forkserver") == 0;
+#else
+ return false;
+#endif
+}
+
+static int RunForkServer(Bootstrap::UniquePtr&& bootstrap, int argc,
+ char* argv[]) {
+#if defined(MOZ_ENABLE_FORKSERVER)
+ int ret = 0;
+
+ bootstrap->NS_LogInit();
+
+ // Run a fork server in this process, single thread. When it
+ // returns, it means the fork server have been stopped or a new
+ // content process is created.
+ //
+ // For the later case, XRE_ForkServer() will return false, running
+ // in a content process just forked from the fork server process.
+ // argc & argv will be updated with the values passing from the
+ // chrome process. With the new values, this function
+ // continues the reset of the code acting as a content process.
+ if (bootstrap->XRE_ForkServer(&argc, &argv)) {
+ // Return from the fork server in the fork server process.
+ // Stop the fork server.
+ } else {
+ // In a content process forked from the fork server.
+ // Start acting as a content process.
+ ret = content_process_main(bootstrap.get(), argc, argv);
+ }
+
+ bootstrap->NS_LogTerm();
+ return ret;
+#else
+ return 0;
+#endif
+}
+
+int main(int argc, char* argv[]) {
+ auto bootstrapResult = GetBootstrap();
+ if (bootstrapResult.isErr()) {
+ return 2;
+ }
+
+ Bootstrap::UniquePtr bootstrap = bootstrapResult.unwrap();
+
+ int ret;
+ if (UseForkServer(argc, argv)) {
+ ret = RunForkServer(std::move(bootstrap), argc, argv);
+ } else {
+ // Set the process type. We don't remove the arg here as that will be done
+ // later in common code.
+ SetGeckoProcessType(argv[argc - 1]);
+
+ // Register an external module to report on otherwise uncatchable
+ // exceptions. Note that in child processes this must be called after Gecko
+ // process type has been set.
+ CrashReporter::RegisterRuntimeExceptionModule();
+
+ // Make sure we unregister the runtime exception module before returning.
+ auto unregisterRuntimeExceptionModule = MakeScopeExit(
+ [] { CrashReporter::UnregisterRuntimeExceptionModule(); });
+
+#ifdef HAS_DLL_BLOCKLIST
+ uint32_t initFlags = eDllBlocklistInitFlagIsChildProcess;
+ SetDllBlocklistProcessTypeFlags(initFlags, GetGeckoProcessType());
+ DllBlocklist_Initialize(initFlags);
+#endif
+
+ ret = content_process_main(bootstrap.get(), argc, argv);
+
+#if defined(DEBUG) && defined(HAS_DLL_BLOCKLIST)
+ DllBlocklist_Shutdown();
+#endif
+ }
+
+ return ret;
+}
diff --git a/ipc/app/MozillaRuntimeMainAndroid.cpp b/ipc/app/MozillaRuntimeMainAndroid.cpp
new file mode 100644
index 0000000000..b70015018d
--- /dev/null
+++ b/ipc/app/MozillaRuntimeMainAndroid.cpp
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <dlfcn.h>
+#include <android/log.h>
+
+int main(int argc, char* argv[]) {
+ // Check for the absolute minimum number of args we need to move
+ // forward here. We expect the last arg to be the child process type.
+ if (argc < 2) return 1;
+
+ void* mozloader_handle = dlopen("libmozglue.so", RTLD_LAZY);
+ if (!mozloader_handle) {
+ __android_log_print(ANDROID_LOG_ERROR, "GeckoChildLoad",
+ "Couldn't load mozloader because %s", dlerror());
+ return 1;
+ }
+
+ typedef int (*ChildProcessInit_t)(int, char**);
+ ChildProcessInit_t fChildProcessInit =
+ (ChildProcessInit_t)dlsym(mozloader_handle, "ChildProcessInit");
+ if (!fChildProcessInit) {
+ __android_log_print(ANDROID_LOG_ERROR, "GeckoChildLoad",
+ "Couldn't load cpi_t because %s", dlerror());
+ return 1;
+ }
+
+ return fChildProcessInit(argc, argv);
+}
diff --git a/ipc/app/macbuild/Contents/Info.plist.in b/ipc/app/macbuild/Contents/Info.plist.in
new file mode 100644
index 0000000000..0908849949
--- /dev/null
+++ b/ipc/app/macbuild/Contents/Info.plist.in
@@ -0,0 +1,32 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>English</string>
+ <key>CFBundleExecutable</key>
+ <string>@EXECUTABLE@</string>
+ <key>CFBundleIdentifier</key>
+ <string>@BUNDLEID@</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleSignature</key>
+ <string>????</string>
+ <key>CFBundleVersion</key>
+ <string>1.0</string>
+ <key>LSBackgroundOnly</key>
+ <string>1</string>
+ <key>NSRequiresAquaSystemAppearance</key>
+ <true/>
+ <key>NSSupportsAutomaticGraphicsSwitching</key>
+ <true/>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+ <key>MozillaDeveloperRepoPath</key>
+ <string>@MOZ_DEVELOPER_REPO_PATH@</string>
+ <key>MozillaDeveloperObjPath</key>
+ <string>@MOZ_DEVELOPER_OBJ_PATH@</string>
+</dict>
+</plist>
diff --git a/ipc/app/macbuild/Contents/PkgInfo b/ipc/app/macbuild/Contents/PkgInfo
new file mode 100644
index 0000000000..bd04210fb4
--- /dev/null
+++ b/ipc/app/macbuild/Contents/PkgInfo
@@ -0,0 +1 @@
+APPL???? \ No newline at end of file
diff --git a/ipc/app/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in b/ipc/app/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in
new file mode 100644
index 0000000000..55d15cad8a
--- /dev/null
+++ b/ipc/app/macbuild/Contents/Resources/English.lproj/InfoPlist.strings.in
@@ -0,0 +1,7 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* Localized versions of Info.plist keys */
+
+CFBundleName = "@APP_NAME@";
diff --git a/ipc/app/module.ver b/ipc/app/module.ver
new file mode 100644
index 0000000000..8abbd23f0e
--- /dev/null
+++ b/ipc/app/module.ver
@@ -0,0 +1,6 @@
+WIN32_MODULE_COMPANYNAME=Mozilla Corporation
+WIN32_MODULE_PRODUCTVERSION=@MOZ_APP_WINVERSION@
+WIN32_MODULE_PRODUCTVERSION_STRING=@MOZ_APP_VERSION@
+WIN32_MODULE_DESCRIPTION=Plugin Container for @MOZ_APP_DISPLAYNAME@
+WIN32_MODULE_PRODUCTNAME=@MOZ_APP_DISPLAYNAME@
+WIN32_MODULE_NAME=@MOZ_APP_DISPLAYNAME@
diff --git a/ipc/app/moz.build b/ipc/app/moz.build
new file mode 100644
index 0000000000..afe1df122b
--- /dev/null
+++ b/ipc/app/moz.build
@@ -0,0 +1,90 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+if CONFIG["MOZ_WIDGET_TOOLKIT"] == "android":
+ Program(CONFIG["MOZ_CHILD_PROCESS_NAME"])
+ SOURCES += [
+ "MozillaRuntimeMainAndroid.cpp",
+ ]
+else:
+ GeckoProgram(CONFIG["MOZ_CHILD_PROCESS_NAME"], linkage="dependent")
+
+ SOURCES += [
+ "MozillaRuntimeMain.cpp",
+ ]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+LOCAL_INCLUDES += [
+ "/toolkit/xre",
+ "/xpcom/base",
+]
+
+# DELAYLOAD_DLLS in this block ensures that the DLL blocklist is functional
+if CONFIG["OS_ARCH"] == "WINNT":
+ DELAYLOAD_DLLS += [
+ "nss3.dll",
+ ]
+
+ if CONFIG["MOZ_SANDBOX"]:
+ # For sandbox includes and the include dependencies those have
+ LOCAL_INCLUDES += [
+ "/security/sandbox/chromium",
+ "/security/sandbox/chromium-shim",
+ ]
+
+ OS_LIBS += [
+ "advapi32",
+ "user32",
+ "version",
+ "winmm",
+ ]
+
+ USE_LIBS += [
+ "sandbox_s",
+ ]
+
+ DELAYLOAD_DLLS += [
+ "winmm.dll",
+ "user32.dll",
+ ]
+
+ OS_LIBS += [
+ "ntdll",
+ ]
+
+ DELAYLOAD_DLLS += [
+ "xul.dll",
+ ]
+
+ # Don't build plugin-container.exe with CETCOMPAT for the moment, so that
+ # we can enable it using a pref during testing.
+ LINK_FLAGS["CETCOMPAT"] = []
+
+if CONFIG["OS_ARCH"] == "Darwin":
+ LDFLAGS += ["-Wl,-rpath,@executable_path/../../../"]
+
+if CONFIG["CC_TYPE"] == "clang-cl":
+ # Always enter a Windows program through wmain, whether or not we're
+ # a console application.
+ WIN32_EXE_LDFLAGS += ["-ENTRY:wmainCRTStartup"]
+
+# Control the default heap size.
+# This is the heap returned by GetProcessHeap().
+# As we use the CRT heap, the default size is too large and wastes VM.
+#
+# The default heap size is 1MB on Win32.
+# The heap will grow if need be.
+#
+# Set it to 256k. See bug 127069.
+if CONFIG["OS_ARCH"] == "WINNT" and CONFIG["CC_TYPE"] not in ("clang", "gcc"):
+ LDFLAGS += ["/HEAP:0x40000"]
+
+if CONFIG["CC_TYPE"] in ("clang", "gcc"):
+ CXXFLAGS += ["-Wshadow"]
+
+with Files("**"):
+ BUG_COMPONENT = ("Core", "DOM: Content Processes")
diff --git a/ipc/app/plugin-container.exe.manifest b/ipc/app/plugin-container.exe.manifest
new file mode 100644
index 0000000000..3ccedc20c2
--- /dev/null
+++ b/ipc/app/plugin-container.exe.manifest
@@ -0,0 +1,53 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
+<assemblyIdentity
+ version="1.0.0.0"
+ processorArchitecture="*"
+ name="plugin-container"
+ type="win32"
+/>
+<description>Firefox Runtime</description>
+<dependency>
+ <dependentAssembly>
+ <assemblyIdentity
+ type="win32"
+ name="Microsoft.Windows.Common-Controls"
+ version="6.0.0.0"
+ processorArchitecture="*"
+ publicKeyToken="6595b64144ccf1df"
+ language="*"
+ />
+ </dependentAssembly>
+</dependency>
+<dependency>
+ <dependentAssembly>
+ <assemblyIdentity
+ type="win32"
+ name="mozglue"
+ version="1.0.0.0"
+ language="*"
+ />
+ </dependentAssembly>
+</dependency>
+ <ms_asmv3:trustInfo xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
+ <ms_asmv3:security>
+ <ms_asmv3:requestedPrivileges>
+ <ms_asmv3:requestedExecutionLevel level="asInvoker" uiAccess="false" />
+ </ms_asmv3:requestedPrivileges>
+ </ms_asmv3:security>
+ </ms_asmv3:trustInfo>
+ <ms_asmv3:application xmlns:ms_asmv3="urn:schemas-microsoft-com:asm.v3">
+ <ms_asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
+ <dpiAware>True/PM</dpiAware>
+ <dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2,PerMonitor</dpiAwareness>
+ </ms_asmv3:windowsSettings>
+ </ms_asmv3:application>
+ <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
+ <application>
+ <supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
+ <supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
+ <supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
+ <supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
+ </application>
+ </compatibility>
+</assembly>
diff --git a/ipc/chromium/chromium-config.mozbuild b/ipc/chromium/chromium-config.mozbuild
new file mode 100644
index 0000000000..bafb02feaa
--- /dev/null
+++ b/ipc/chromium/chromium-config.mozbuild
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+LOCAL_INCLUDES += [
+ "!/ipc/ipdl/_ipdlheaders",
+ "/ipc/chromium/src",
+]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ OS_LIBS += [
+ "shell32",
+ "dbghelp",
+ ]
+
+ DEFINES["UNICODE"] = True
+ DEFINES["_UNICODE"] = True
+ DEFINES["_CRT_RAND_S"] = True
+ DEFINES["CERT_CHAIN_PARA_HAS_EXTRA_FIELDS"] = True
+ DEFINES["_SECURE_ATL"] = True
+ DEFINES["CHROMIUM_BUILD"] = True
+ DEFINES["U_STATIC_IMPLEMENTATION"] = True
+ DEFINES["WIN32"] = True
+ DEFINES["_WIN32"] = True
+ DEFINES["_WINDOWS"] = True
+ DEFINES["WIN32_LEAN_AND_MEAN"] = True
diff --git a/ipc/chromium/gtest/moz.build b/ipc/chromium/gtest/moz.build
new file mode 100644
index 0000000000..afa175c638
--- /dev/null
+++ b/ipc/chromium/gtest/moz.build
@@ -0,0 +1,16 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Library("ipcchromiumtest")
+
+SOURCES += [
+ "name_unittest.cc",
+ "ports_unittest.cc",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul-gtest"
diff --git a/ipc/chromium/gtest/name_unittest.cc b/ipc/chromium/gtest/name_unittest.cc
new file mode 100644
index 0000000000..ecb34100d8
--- /dev/null
+++ b/ipc/chromium/gtest/name_unittest.cc
@@ -0,0 +1,78 @@
+// Copyright 2017 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.
+
+#include "mojo/core/ports/name.h"
+
+#include "testing/gtest/include/gtest/gtest.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+namespace test {
+
+TEST(NameTest, Defaults)
+{
+ PortName default_port_name;
+ EXPECT_EQ(kInvalidPortName, default_port_name);
+
+ NodeName default_node_name;
+ EXPECT_EQ(kInvalidNodeName, default_node_name);
+}
+
+TEST(NameTest, PortNameChecks)
+{
+ PortName port_name_a(50, 100);
+ PortName port_name_b(50, 100);
+ PortName port_name_c(100, 50);
+
+ EXPECT_EQ(port_name_a, port_name_b);
+ EXPECT_NE(port_name_a, port_name_c);
+ EXPECT_NE(port_name_b, port_name_c);
+
+ EXPECT_LT(port_name_a, port_name_c);
+ EXPECT_LT(port_name_b, port_name_c);
+ EXPECT_FALSE(port_name_a < port_name_b);
+ EXPECT_FALSE(port_name_b < port_name_a);
+
+ std::hash<PortName> port_hash_fn;
+
+ size_t hash_a = port_hash_fn(port_name_a);
+ size_t hash_b = port_hash_fn(port_name_b);
+ size_t hash_c = port_hash_fn(port_name_c);
+
+ EXPECT_EQ(hash_a, hash_b);
+ EXPECT_NE(hash_a, hash_c);
+ EXPECT_NE(hash_b, hash_c);
+}
+
+TEST(NameTest, NodeNameChecks)
+{
+ NodeName node_name_a(50, 100);
+ NodeName node_name_b(50, 100);
+ NodeName node_name_c(100, 50);
+
+ EXPECT_EQ(node_name_a, node_name_b);
+ EXPECT_NE(node_name_a, node_name_c);
+ EXPECT_NE(node_name_b, node_name_c);
+
+ EXPECT_LT(node_name_a, node_name_c);
+ EXPECT_LT(node_name_b, node_name_c);
+ EXPECT_FALSE(node_name_a < node_name_b);
+ EXPECT_FALSE(node_name_b < node_name_a);
+
+ std::hash<NodeName> node_hash_fn;
+
+ size_t hash_a = node_hash_fn(node_name_a);
+ size_t hash_b = node_hash_fn(node_name_b);
+ size_t hash_c = node_hash_fn(node_name_c);
+
+ EXPECT_EQ(hash_a, hash_b);
+ EXPECT_NE(hash_a, hash_c);
+ EXPECT_NE(hash_b, hash_c);
+}
+
+} // namespace test
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/gtest/ports_unittest.cc b/ipc/chromium/gtest/ports_unittest.cc
new file mode 100644
index 0000000000..bfa8214799
--- /dev/null
+++ b/ipc/chromium/gtest/ports_unittest.cc
@@ -0,0 +1,1829 @@
+// Copyright 2016 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.
+
+#include <inttypes.h>
+#include <stdio.h>
+
+#include <map>
+#include <utility>
+
+#include "base/logging.h"
+#include "base/waitable_event.h"
+#include "base/thread.h"
+#include "base/string_util.h"
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/node.h"
+#include "mojo/core/ports/node_delegate.h"
+#include "mojo/core/ports/port_locker.h"
+#include "mojo/core/ports/user_message.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
+#include "mozilla/Mutex.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+namespace test {
+
+namespace {
+
+// TODO(rockot): Remove this unnecessary alias.
+using ScopedMessage = mozilla::UniquePtr<UserMessageEvent>;
+
+class TestMessage : public UserMessage {
+ public:
+ static const TypeInfo kUserMessageTypeInfo;
+
+ explicit TestMessage(const std::string& payload)
+ : UserMessage(&kUserMessageTypeInfo), payload_(payload) {}
+ ~TestMessage() override = default;
+
+ const std::string& payload() const { return payload_; }
+
+ private:
+ std::string payload_;
+};
+
+const UserMessage::TypeInfo TestMessage::kUserMessageTypeInfo = {};
+
+ScopedMessage NewUserMessageEvent(const std::string& payload,
+ size_t num_ports) {
+ auto event = mozilla::MakeUnique<UserMessageEvent>(num_ports);
+ event->AttachMessage(mozilla::MakeUnique<TestMessage>(payload));
+ return event;
+}
+
+bool MessageEquals(const ScopedMessage& message, const std::string& s) {
+ return message->GetMessage<TestMessage>()->payload() == s;
+}
+
+class TestNode;
+
+class MessageRouter {
+ public:
+ virtual ~MessageRouter() = default;
+
+ virtual void ForwardEvent(TestNode* from_node, const NodeName& node_name,
+ ScopedEvent event) = 0;
+ virtual void BroadcastEvent(TestNode* from_node, ScopedEvent event) = 0;
+};
+
+class TestNode : public NodeDelegate {
+ public:
+ explicit TestNode(uint64_t id)
+ : node_name_(id, 1),
+ node_(node_name_, this),
+ node_thread_(StringPrintf("Node %" PRIu64 " thread", id).c_str()),
+ events_available_event_(/* manual_reset */ false,
+ /* initially_signaled */ false),
+ idle_event_(/* manual_reset */ true, /* initially_signaled */ true) {}
+
+ ~TestNode() override {
+ StopWhenIdle();
+ node_thread_.Stop();
+ }
+
+ const NodeName& name() const { return node_name_; }
+
+ // NOTE: Node is thread-safe.
+ Node& node() { return node_; }
+
+ base::WaitableEvent& idle_event() { return idle_event_; }
+
+ bool IsIdle() {
+ mozilla::MutexAutoLock lock(lock_);
+ return started_ && !dispatching_ &&
+ (incoming_events_.empty() || (block_on_event_ && blocked_));
+ }
+
+ void BlockOnEvent(Event::Type type) {
+ mozilla::MutexAutoLock lock(lock_);
+ blocked_event_type_ = type;
+ block_on_event_ = true;
+ }
+
+ void Unblock() {
+ mozilla::MutexAutoLock lock(lock_);
+ block_on_event_ = false;
+ events_available_event_.Signal();
+ }
+
+ void Start(MessageRouter* router) {
+ router_ = router;
+ node_thread_.Start();
+ node_thread_.message_loop()->PostTask(mozilla::NewNonOwningRunnableMethod(
+ "TestNode::ProcessEvents", this, &TestNode::ProcessEvents));
+ }
+
+ void StopWhenIdle() {
+ mozilla::MutexAutoLock lock(lock_);
+ should_quit_ = true;
+ events_available_event_.Signal();
+ }
+
+ void WakeUp() { events_available_event_.Signal(); }
+
+ int SendStringMessage(const PortRef& port, const std::string& s) {
+ return node_.SendUserMessage(port, NewUserMessageEvent(s, 0));
+ }
+
+ int SendMultipleMessages(const PortRef& port, size_t num_messages) {
+ for (size_t i = 0; i < num_messages; ++i) {
+ int result = SendStringMessage(port, "");
+ if (result != OK) {
+ return result;
+ }
+ }
+ return OK;
+ }
+
+ int SendStringMessageWithPort(const PortRef& port, const std::string& s,
+ const PortName& sent_port_name) {
+ auto event = NewUserMessageEvent(s, 1);
+ event->ports()[0] = sent_port_name;
+ return node_.SendUserMessage(port, std::move(event));
+ }
+
+ int SendStringMessageWithPort(const PortRef& port, const std::string& s,
+ const PortRef& sent_port) {
+ return SendStringMessageWithPort(port, s, sent_port.name());
+ }
+
+ void set_drop_messages(bool value) {
+ mozilla::MutexAutoLock lock(lock_);
+ drop_messages_ = value;
+ }
+
+ void set_save_messages(bool value) {
+ mozilla::MutexAutoLock lock(lock_);
+ save_messages_ = value;
+ }
+
+ bool ReadMessage(const PortRef& port, ScopedMessage* message) {
+ return node_.GetMessage(port, message, nullptr) == OK && *message;
+ }
+
+ bool ReadMultipleMessages(const PortRef& port, size_t num_messages) {
+ for (size_t i = 0; i < num_messages; ++i) {
+ ScopedMessage message;
+ if (!ReadMessage(port, &message)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ bool GetSavedMessage(ScopedMessage* message) {
+ mozilla::MutexAutoLock lock(lock_);
+ if (saved_messages_.empty()) {
+ message->reset();
+ return false;
+ }
+ std::swap(*message, saved_messages_.front());
+ saved_messages_.pop();
+ return true;
+ }
+
+ void EnqueueEvent(const NodeName& from_node, ScopedEvent event) {
+ idle_event_.Reset();
+
+ // NOTE: This may be called from ForwardMessage and thus must not reenter
+ // |node_|.
+ mozilla::MutexAutoLock lock(lock_);
+ incoming_events_.push({from_node, std::move(event)});
+ events_available_event_.Signal();
+ }
+
+ void ForwardEvent(const NodeName& node_name, ScopedEvent event) override {
+ {
+ mozilla::MutexAutoLock lock(lock_);
+ if (drop_messages_) {
+ DVLOG(1) << "Dropping ForwardMessage from node " << node_name_ << " to "
+ << node_name;
+
+ mozilla::MutexAutoUnlock unlock(lock_);
+ ClosePortsInEvent(event.get());
+ return;
+ }
+ }
+
+ DCHECK(router_);
+ DVLOG(1) << "ForwardEvent from node " << node_name_ << " to " << node_name;
+ router_->ForwardEvent(this, node_name, std::move(event));
+ }
+
+ void BroadcastEvent(ScopedEvent event) override {
+ router_->BroadcastEvent(this, std::move(event));
+ }
+
+ void PortStatusChanged(const PortRef& port) override {
+ // The port may be closed, in which case we ignore the notification.
+ mozilla::MutexAutoLock lock(lock_);
+ if (!save_messages_) {
+ return;
+ }
+
+ for (;;) {
+ ScopedMessage message;
+ {
+ mozilla::MutexAutoUnlock unlock(lock_);
+ if (!ReadMessage(port, &message)) {
+ break;
+ }
+ }
+
+ saved_messages_.emplace(std::move(message));
+ }
+ }
+
+ void ClosePortsInEvent(Event* event) {
+ if (event->type() != Event::Type::kUserMessage) {
+ return;
+ }
+
+ UserMessageEvent* message_event = static_cast<UserMessageEvent*>(event);
+ for (size_t i = 0; i < message_event->num_ports(); ++i) {
+ PortRef port;
+ ASSERT_EQ(OK, node_.GetPort(message_event->ports()[i], &port));
+ EXPECT_EQ(OK, node_.ClosePort(port));
+ }
+ }
+
+ uint64_t GetUnacknowledgedMessageCount(const PortRef& port_ref) {
+ PortStatus status{};
+ if (node_.GetStatus(port_ref, &status) != OK) {
+ return 0;
+ }
+
+ return status.unacknowledged_message_count;
+ }
+
+ void AllowPortMerge(const PortRef& port_ref) {
+ SinglePortLocker locker(&port_ref);
+ locker.port()->pending_merge_peer = true;
+ }
+
+ private:
+ void ProcessEvents() {
+ for (;;) {
+ events_available_event_.Wait();
+ mozilla::MutexAutoLock lock(lock_);
+
+ if (should_quit_) {
+ return;
+ }
+
+ dispatching_ = true;
+ while (!incoming_events_.empty()) {
+ if (block_on_event_ &&
+ incoming_events_.front().second->type() == blocked_event_type_) {
+ blocked_ = true;
+ // Go idle if we hit a blocked event type.
+ break;
+ }
+ blocked_ = false;
+
+ auto node_event_pair = std::move(incoming_events_.front());
+ incoming_events_.pop();
+
+ // NOTE: AcceptMessage() can re-enter this object to call any of the
+ // NodeDelegate interface methods.
+ mozilla::MutexAutoUnlock unlock(lock_);
+ node_.AcceptEvent(node_event_pair.first,
+ std::move(node_event_pair.second));
+ }
+
+ dispatching_ = false;
+ started_ = true;
+ idle_event_.Signal();
+ };
+ }
+
+ const NodeName node_name_;
+ Node node_;
+ MessageRouter* router_ = nullptr;
+
+ base::Thread node_thread_;
+ base::WaitableEvent events_available_event_;
+ base::WaitableEvent idle_event_;
+
+ // Guards fields below.
+ mozilla::Mutex lock_ MOZ_UNANNOTATED{"TestNode"};
+ bool started_ = false;
+ bool dispatching_ = false;
+ bool should_quit_ = false;
+ bool drop_messages_ = false;
+ bool save_messages_ = false;
+ bool blocked_ = false;
+ bool block_on_event_ = false;
+ Event::Type blocked_event_type_{};
+ std::queue<std::pair<NodeName, ScopedEvent>> incoming_events_;
+ std::queue<ScopedMessage> saved_messages_;
+};
+
+class PortsTest : public testing::Test, public MessageRouter {
+ public:
+ void AddNode(TestNode* node) {
+ {
+ mozilla::MutexAutoLock lock(lock_);
+ nodes_[node->name()] = node;
+ }
+ node->Start(this);
+ }
+
+ void RemoveNode(TestNode* node) {
+ {
+ mozilla::MutexAutoLock lock(lock_);
+ nodes_.erase(node->name());
+ }
+
+ for (const auto& entry : nodes_) {
+ entry.second->node().LostConnectionToNode(node->name());
+ }
+ }
+
+ // Waits until all known Nodes are idle. Message forwarding and processing
+ // is handled in such a way that idleness is a stable state: once all nodes in
+ // the system are idle, they will remain idle until the test explicitly
+ // initiates some further event (e.g. sending a message, closing a port, or
+ // removing a Node).
+ void WaitForIdle() {
+ for (;;) {
+ mozilla::MutexAutoLock global_lock(global_lock_);
+ bool all_nodes_idle = true;
+ for (const auto& entry : nodes_) {
+ if (!entry.second->IsIdle()) {
+ all_nodes_idle = false;
+ }
+ entry.second->WakeUp();
+ }
+ if (all_nodes_idle) {
+ return;
+ }
+
+ // Wait for any Node to signal that it's idle.
+ mozilla::MutexAutoUnlock global_unlock(global_lock_);
+ std::vector<base::WaitableEvent*> events;
+ for (const auto& entry : nodes_) {
+ events.push_back(&entry.second->idle_event());
+ }
+ base::WaitableEvent::WaitMany(events.data(), events.size());
+ }
+ }
+
+ void CreatePortPair(TestNode* node0, PortRef* port0, TestNode* node1,
+ PortRef* port1) {
+ if (node0 == node1) {
+ EXPECT_EQ(OK, node0->node().CreatePortPair(port0, port1));
+ } else {
+ EXPECT_EQ(OK, node0->node().CreateUninitializedPort(port0));
+ EXPECT_EQ(OK, node1->node().CreateUninitializedPort(port1));
+ EXPECT_EQ(
+ OK, node0->node().InitializePort(*port0, node1->name(), port1->name(),
+ node1->name(), port1->name()));
+ EXPECT_EQ(
+ OK, node1->node().InitializePort(*port1, node0->name(), port0->name(),
+ node0->name(), port0->name()));
+ }
+ }
+
+ private:
+ // MessageRouter:
+ void ForwardEvent(TestNode* from_node, const NodeName& node_name,
+ ScopedEvent event) override {
+ mozilla::MutexAutoLock global_lock(global_lock_);
+ mozilla::MutexAutoLock lock(lock_);
+ // Drop messages from nodes that have been removed.
+ if (nodes_.find(from_node->name()) == nodes_.end()) {
+ from_node->ClosePortsInEvent(event.get());
+ return;
+ }
+
+ auto it = nodes_.find(node_name);
+ if (it == nodes_.end()) {
+ DVLOG(1) << "Node not found: " << node_name;
+ return;
+ }
+
+ // Serialize and de-serialize all forwarded events.
+ size_t buf_size = event->GetSerializedSize();
+ mozilla::UniquePtr<char[]> buf(new char[buf_size]);
+ event->Serialize(buf.get());
+ ScopedEvent copy = Event::Deserialize(buf.get(), buf_size);
+ // This should always succeed unless serialization or deserialization
+ // is broken. In that case, the loss of events should cause a test failure.
+ ASSERT_TRUE(copy);
+
+ // Also copy the payload for user messages.
+ if (event->type() == Event::Type::kUserMessage) {
+ UserMessageEvent* message_event =
+ static_cast<UserMessageEvent*>(event.get());
+ UserMessageEvent* message_copy =
+ static_cast<UserMessageEvent*>(copy.get());
+
+ message_copy->AttachMessage(mozilla::MakeUnique<TestMessage>(
+ message_event->GetMessage<TestMessage>()->payload()));
+ }
+
+ it->second->EnqueueEvent(from_node->name(), std::move(event));
+ }
+
+ void BroadcastEvent(TestNode* from_node, ScopedEvent event) override {
+ mozilla::MutexAutoLock global_lock(global_lock_);
+ mozilla::MutexAutoLock lock(lock_);
+
+ // Drop messages from nodes that have been removed.
+ if (nodes_.find(from_node->name()) == nodes_.end()) {
+ return;
+ }
+
+ for (const auto& entry : nodes_) {
+ TestNode* node = entry.second;
+ // Broadcast doesn't deliver to the local node.
+ if (node == from_node) {
+ continue;
+ }
+ node->EnqueueEvent(from_node->name(), event->CloneForBroadcast());
+ }
+ }
+
+ // Acquired before any operation which makes a Node busy, and before testing
+ // if all nodes are idle.
+ mozilla::Mutex global_lock_ MOZ_UNANNOTATED{"PortsTest Global Lock"};
+
+ mozilla::Mutex lock_ MOZ_UNANNOTATED{"PortsTest Lock"};
+ std::map<NodeName, TestNode*> nodes_;
+};
+
+} // namespace
+
+TEST_F(PortsTest, Basic1) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "hello", a1));
+ EXPECT_EQ(OK, node0.node().ClosePort(a0));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, Basic2) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ PortRef b0, b1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&b0, &b1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "hello", b1));
+ EXPECT_EQ(OK, node0.SendStringMessage(b0, "hello again"));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(b0));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, Basic3) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "hello", a1));
+ EXPECT_EQ(OK, node0.SendStringMessage(a0, "hello again"));
+
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "foo", a0));
+
+ PortRef b0, b1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&b0, &b1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "bar", b1));
+ EXPECT_EQ(OK, node0.SendStringMessage(b0, "baz"));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(b0));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, LostConnectionToNode1) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+ node1.set_drop_messages(true);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ // Transfer a port to node1 and simulate a lost connection to node1.
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "foo", a1));
+
+ WaitForIdle();
+
+ RemoveNode(&node1);
+
+ WaitForIdle();
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a0));
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, LostConnectionToNode2) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "take a1", a1));
+
+ WaitForIdle();
+
+ node1.set_drop_messages(true);
+
+ RemoveNode(&node1);
+
+ WaitForIdle();
+
+ // a0 should have eventually detected peer closure after node loss.
+ ScopedMessage message;
+ EXPECT_EQ(ERROR_PORT_PEER_CLOSED,
+ node0.node().GetMessage(a0, &message, nullptr));
+ EXPECT_FALSE(message);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a0));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+
+ EXPECT_EQ(OK, node1.node().GetMessage(x1, &message, nullptr));
+ EXPECT_TRUE(message);
+ node1.ClosePortsInEvent(message.get());
+
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, LostConnectionToNodeWithSecondaryProxy) {
+ // Tests that a proxy gets cleaned up when its indirect peer lives on a lost
+ // node.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ TestNode node2(2);
+ AddNode(&node2);
+
+ // Create A-B spanning nodes 0 and 1 and C-D spanning 1 and 2.
+ PortRef A, B, C, D;
+ CreatePortPair(&node0, &A, &node1, &B);
+ CreatePortPair(&node1, &C, &node2, &D);
+
+ // Create E-F and send F over A to node 1.
+ PortRef E, F;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&E, &F));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(A, ".", F));
+
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(B, &message));
+ ASSERT_EQ(1u, message->num_ports());
+
+ EXPECT_EQ(OK, node1.node().GetPort(message->ports()[0], &F));
+
+ // Send F over C to node 2 and then simulate node 2 loss from node 1. Node 1
+ // will trivially become aware of the loss, and this test verifies that the
+ // port A on node 0 will eventually also become aware of it.
+
+ // Make sure node2 stops processing events when it encounters an ObserveProxy.
+ node2.BlockOnEvent(Event::Type::kObserveProxy);
+
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(C, ".", F));
+ WaitForIdle();
+
+ // Simulate node 1 and 2 disconnecting.
+ EXPECT_EQ(OK, node1.node().LostConnectionToNode(node2.name()));
+
+ // Let node2 continue processing events and wait for everyone to go idle.
+ node2.Unblock();
+ WaitForIdle();
+
+ // Port F should be gone.
+ EXPECT_EQ(ERROR_PORT_UNKNOWN, node1.node().GetPort(F.name(), &F));
+
+ // Port E should have detected peer closure despite the fact that there is
+ // no longer a continuous route from F to E over which the event could travel.
+ PortStatus status{};
+ EXPECT_EQ(OK, node0.node().GetStatus(E, &status));
+ EXPECT_TRUE(status.peer_closed);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(B));
+ EXPECT_EQ(OK, node1.node().ClosePort(C));
+ EXPECT_EQ(OK, node0.node().ClosePort(E));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, LostConnectionToNodeAfterSendingObserveProxy) {
+ // Tests that a proxy gets cleaned up after a node disconnect if the
+ // previous port already received the ObserveProxy event.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ TestNode node2(2);
+ AddNode(&node2);
+
+ // Create A-B spanning nodes 0 and 1 and C-D spanning 1 and 2.
+ PortRef A, B, C, D;
+ CreatePortPair(&node0, &A, &node1, &B);
+ CreatePortPair(&node1, &C, &node2, &D);
+
+ // Create E-F and send F over A to node 1.
+ PortRef E, F;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&E, &F));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(A, ".", F));
+
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(B, &message));
+ ASSERT_EQ(1u, message->num_ports());
+
+ EXPECT_EQ(OK, node1.node().GetPort(message->ports()[0], &F));
+
+ // Send F over C to node 2 and then simulate node 2 loss from node 1 after
+ // node 0 received the ObserveProxy event. Node 1 needs to clean up the
+ // closed proxy while the node 0 to node 2 connection is still intact.
+ node0.BlockOnEvent(Event::Type::kObserveProxy);
+
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(C, ".", F));
+ WaitForIdle();
+
+ // Simulate node 1 and 2 disconnecting.
+ EXPECT_EQ(OK, node1.node().LostConnectionToNode(node2.name()));
+
+ // Let node2 continue processing events and wait for everyone to go idle.
+ node0.Unblock();
+ WaitForIdle();
+
+ // Port F should be gone.
+ EXPECT_EQ(ERROR_PORT_UNKNOWN, node1.node().GetPort(F.name(), &F));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(B));
+ EXPECT_EQ(OK, node1.node().ClosePort(C));
+ EXPECT_EQ(OK, node0.node().ClosePort(E));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, LostConnectionToNodeWithLocalProxy) {
+ // Tests that a proxy gets cleaned up when its direct peer lives on a lost
+ // node and it's predecessor lives on the same node.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef A, B;
+ CreatePortPair(&node0, &A, &node1, &B);
+
+ PortRef C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&C, &D));
+
+ // Send D but block node0 on an ObserveProxy event.
+ node0.BlockOnEvent(Event::Type::kObserveProxy);
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(A, ".", D));
+
+ // node0 won't collapse the proxy but node1 will receive the message before
+ // going idle.
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(B, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef E;
+ EXPECT_EQ(OK, node1.node().GetPort(message->ports()[0], &E));
+
+ RemoveNode(&node1);
+
+ node0.Unblock();
+ WaitForIdle();
+
+ // Port C should have detected peer closure.
+ PortStatus status{};
+ EXPECT_EQ(OK, node0.node().GetStatus(C, &status));
+ EXPECT_TRUE(status.peer_closed);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(B));
+ EXPECT_EQ(OK, node0.node().ClosePort(C));
+ EXPECT_EQ(OK, node1.node().ClosePort(E));
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, GetMessage1) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&a0, &a1));
+
+ ScopedMessage message;
+ EXPECT_EQ(OK, node.node().GetMessage(a0, &message, nullptr));
+ EXPECT_FALSE(message);
+
+ EXPECT_EQ(OK, node.node().ClosePort(a1));
+
+ WaitForIdle();
+
+ EXPECT_EQ(ERROR_PORT_PEER_CLOSED,
+ node.node().GetMessage(a0, &message, nullptr));
+ EXPECT_FALSE(message);
+
+ EXPECT_EQ(OK, node.node().ClosePort(a0));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, GetMessage2) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&a0, &a1));
+
+ EXPECT_EQ(OK, node.SendStringMessage(a1, "1"));
+
+ ScopedMessage message;
+ EXPECT_EQ(OK, node.node().GetMessage(a0, &message, nullptr));
+
+ ASSERT_TRUE(message);
+ EXPECT_TRUE(MessageEquals(message, "1"));
+
+ EXPECT_EQ(OK, node.node().ClosePort(a0));
+ EXPECT_EQ(OK, node.node().ClosePort(a1));
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, GetMessage3) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&a0, &a1));
+
+ const char* kStrings[] = {"1", "2", "3"};
+
+ for (auto& kString : kStrings) {
+ EXPECT_EQ(OK, node.SendStringMessage(a1, kString));
+ }
+
+ ScopedMessage message;
+ for (auto& kString : kStrings) {
+ EXPECT_EQ(OK, node.node().GetMessage(a0, &message, nullptr));
+ ASSERT_TRUE(message);
+ EXPECT_TRUE(MessageEquals(message, kString));
+ }
+
+ EXPECT_EQ(OK, node.node().ClosePort(a0));
+ EXPECT_EQ(OK, node.node().ClosePort(a1));
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, Delegation1) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ // In this test, we send a message to a port that has been moved.
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "a1", a1));
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(x1, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ EXPECT_TRUE(MessageEquals(message, "a1"));
+
+ // This is "a1" from the point of view of node1.
+ PortName a2_name = message->ports()[0];
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(x1, "a2", a2_name));
+ EXPECT_EQ(OK, node0.SendStringMessage(a0, "hello"));
+
+ WaitForIdle();
+
+ ASSERT_TRUE(node0.ReadMessage(x0, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ EXPECT_TRUE(MessageEquals(message, "a2"));
+
+ // This is "a2" from the point of view of node1.
+ PortName a3_name = message->ports()[0];
+
+ PortRef a3;
+ EXPECT_EQ(OK, node0.node().GetPort(a3_name, &a3));
+
+ ASSERT_TRUE(node0.ReadMessage(a3, &message));
+ EXPECT_EQ(0u, message->num_ports());
+ EXPECT_TRUE(MessageEquals(message, "hello"));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a0));
+ EXPECT_EQ(OK, node0.node().ClosePort(a3));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, Delegation2) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ for (int i = 0; i < 100; ++i) {
+ // Setup pipe a<->b between node0 and node1.
+ PortRef A, B;
+ CreatePortPair(&node0, &A, &node1, &B);
+
+ PortRef C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&C, &D));
+
+ PortRef E, F;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&E, &F));
+
+ node1.set_save_messages(true);
+
+ // Pass D over A to B.
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(A, "1", D));
+
+ // Pass F over C to D.
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(C, "1", F));
+
+ // This message should find its way to node1.
+ EXPECT_EQ(OK, node0.SendStringMessage(E, "hello"));
+
+ WaitForIdle();
+
+ EXPECT_EQ(OK, node0.node().ClosePort(C));
+ EXPECT_EQ(OK, node0.node().ClosePort(E));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(B));
+
+ bool got_hello = false;
+ ScopedMessage message;
+ while (node1.GetSavedMessage(&message)) {
+ node1.ClosePortsInEvent(message.get());
+ if (MessageEquals(message, "hello")) {
+ got_hello = true;
+ break;
+ }
+ }
+
+ EXPECT_TRUE(got_hello);
+
+ WaitForIdle(); // Because closing ports may have generated tasks.
+ }
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, SendUninitialized) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef x0;
+ EXPECT_EQ(OK, node.node().CreateUninitializedPort(&x0));
+ EXPECT_EQ(ERROR_PORT_STATE_UNEXPECTED, node.SendStringMessage(x0, "oops"));
+ EXPECT_EQ(OK, node.node().ClosePort(x0));
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, SendFailure) {
+ TestNode node(0);
+ AddNode(&node);
+
+ node.set_save_messages(true);
+
+ PortRef A, B;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+
+ // Try to send A over itself.
+
+ EXPECT_EQ(ERROR_PORT_CANNOT_SEND_SELF,
+ node.SendStringMessageWithPort(A, "oops", A));
+
+ // Try to send B over A.
+
+ EXPECT_EQ(ERROR_PORT_CANNOT_SEND_PEER,
+ node.SendStringMessageWithPort(A, "nope", B));
+
+ // B should be closed immediately.
+ EXPECT_EQ(ERROR_PORT_UNKNOWN, node.node().GetPort(B.name(), &B));
+
+ WaitForIdle();
+
+ // There should have been no messages accepted.
+ ScopedMessage message;
+ EXPECT_FALSE(node.GetSavedMessage(&message));
+
+ EXPECT_EQ(OK, node.node().ClosePort(A));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, DontLeakUnreceivedPorts) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node.node().CreatePortPair(&C, &D));
+
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(A, "foo", D));
+
+ EXPECT_EQ(OK, node.node().ClosePort(C));
+ EXPECT_EQ(OK, node.node().ClosePort(A));
+ EXPECT_EQ(OK, node.node().ClosePort(B));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, AllowShutdownWithLocalPortsOpen) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node.node().CreatePortPair(&C, &D));
+
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(A, "foo", D));
+
+ ScopedMessage message;
+ EXPECT_TRUE(node.ReadMessage(B, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ EXPECT_TRUE(MessageEquals(message, "foo"));
+ PortRef E;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &E));
+
+ EXPECT_TRUE(
+ node.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(
+ node.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+ EXPECT_FALSE(node.node().CanShutdownCleanly());
+
+ EXPECT_EQ(OK, node.node().ClosePort(A));
+ EXPECT_EQ(OK, node.node().ClosePort(B));
+ EXPECT_EQ(OK, node.node().ClosePort(C));
+ EXPECT_EQ(OK, node.node().ClosePort(E));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, ProxyCollapse1) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef A, B;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+
+ PortRef X, Y;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&X, &Y));
+
+ ScopedMessage message;
+
+ // Send B and receive it as C.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", B));
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef C;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &C));
+
+ // Send C and receive it as D.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", C));
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef D;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &D));
+
+ // Send D and receive it as E.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", D));
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef E;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &E));
+
+ EXPECT_EQ(OK, node.node().ClosePort(X));
+ EXPECT_EQ(OK, node.node().ClosePort(Y));
+
+ EXPECT_EQ(OK, node.node().ClosePort(A));
+ EXPECT_EQ(OK, node.node().ClosePort(E));
+
+ // The node should not idle until all proxies are collapsed.
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, ProxyCollapse2) {
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef A, B;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+
+ PortRef X, Y;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&X, &Y));
+
+ ScopedMessage message;
+
+ // Send B and A to create proxies in each direction.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", B));
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", A));
+
+ EXPECT_EQ(OK, node.node().ClosePort(X));
+ EXPECT_EQ(OK, node.node().ClosePort(Y));
+
+ // At this point we have a scenario with:
+ //
+ // D -> [B] -> C -> [A]
+ //
+ // Ensure that the proxies can collapse. The sent ports will be closed
+ // eventually as a result of Y's closure.
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, SendWithClosedPeer) {
+ // This tests that if a port is sent when its peer is already known to be
+ // closed, the newly created port will be aware of that peer closure, and the
+ // proxy will eventually collapse.
+
+ TestNode node(0);
+ AddNode(&node);
+
+ // Send a message from A to B, then close A.
+ PortRef A, B;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node.SendStringMessage(A, "hey"));
+ EXPECT_EQ(OK, node.node().ClosePort(A));
+
+ // Now send B over X-Y as new port C.
+ PortRef X, Y;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&X, &Y));
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", B));
+ ScopedMessage message;
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef C;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &C));
+
+ EXPECT_EQ(OK, node.node().ClosePort(X));
+ EXPECT_EQ(OK, node.node().ClosePort(Y));
+
+ WaitForIdle();
+
+ // C should have received the message originally sent to B, and it should also
+ // be aware of A's closure.
+
+ ASSERT_TRUE(node.ReadMessage(C, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ PortStatus status{};
+ EXPECT_EQ(OK, node.node().GetStatus(C, &status));
+ EXPECT_FALSE(status.receiving_messages);
+ EXPECT_FALSE(status.has_messages);
+ EXPECT_TRUE(status.peer_closed);
+
+ node.node().ClosePort(C);
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, SendWithClosedPeerSent) {
+ // This tests that if a port is closed while some number of proxies are still
+ // routing messages (directly or indirectly) to it, that the peer port is
+ // eventually notified of the closure, and the dead-end proxies will
+ // eventually be removed.
+
+ TestNode node(0);
+ AddNode(&node);
+
+ PortRef X, Y;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&X, &Y));
+
+ PortRef A, B;
+ EXPECT_EQ(OK, node.node().CreatePortPair(&A, &B));
+
+ ScopedMessage message;
+
+ // Send A as new port C.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", A));
+
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef C;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &C));
+
+ // Send C as new port D.
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", C));
+
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef D;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &D));
+
+ // Send a message to B through D, then close D.
+ EXPECT_EQ(OK, node.SendStringMessage(D, "hey"));
+ EXPECT_EQ(OK, node.node().ClosePort(D));
+
+ // Now send B as new port E.
+
+ EXPECT_EQ(OK, node.SendStringMessageWithPort(X, "foo", B));
+ EXPECT_EQ(OK, node.node().ClosePort(X));
+
+ ASSERT_TRUE(node.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef E;
+ ASSERT_EQ(OK, node.node().GetPort(message->ports()[0], &E));
+
+ EXPECT_EQ(OK, node.node().ClosePort(Y));
+
+ WaitForIdle();
+
+ // E should receive the message originally sent to B, and it should also be
+ // aware of D's closure.
+
+ ASSERT_TRUE(node.ReadMessage(E, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ PortStatus status{};
+ EXPECT_EQ(OK, node.node().GetStatus(E, &status));
+ EXPECT_FALSE(status.receiving_messages);
+ EXPECT_FALSE(status.has_messages);
+ EXPECT_TRUE(status.peer_closed);
+
+ EXPECT_EQ(OK, node.node().ClosePort(E));
+
+ WaitForIdle();
+
+ EXPECT_TRUE(node.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePorts) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ // Write a message on A.
+ EXPECT_EQ(OK, node0.SendStringMessage(A, "hey"));
+
+ // Initiate a merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ WaitForIdle();
+
+ // Expect all proxies to be gone once idle.
+ EXPECT_TRUE(
+ node0.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+ EXPECT_TRUE(
+ node1.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+
+ // Expect D to have received the message sent on A.
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(D, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+
+ // No more ports should be open.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePortWithClosedPeer1) {
+ // This tests that the right thing happens when initiating a merge on a port
+ // whose peer has already been closed.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ // Write a message on A.
+ EXPECT_EQ(OK, node0.SendStringMessage(A, "hey"));
+
+ // Close A.
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+
+ // Initiate a merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ WaitForIdle();
+
+ // Expect all proxies to be gone once idle. node0 should have no ports since
+ // A was explicitly closed.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(
+ node1.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+
+ // Expect D to have received the message sent on A.
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(D, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+
+ // No more ports should be open.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePortWithClosedPeer2) {
+ // This tests that the right thing happens when merging into a port whose peer
+ // has already been closed.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ // Write a message on D and close it.
+ EXPECT_EQ(OK, node1.SendStringMessage(D, "hey"));
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+
+ // Initiate a merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ WaitForIdle();
+
+ // Expect all proxies to be gone once idle. node1 should have no ports since
+ // D was explicitly closed.
+ EXPECT_TRUE(
+ node0.node().CanShutdownCleanly(Node::ShutdownPolicy::ALLOW_LOCAL_PORTS));
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+
+ // Expect A to have received the message sent on D.
+ ScopedMessage message;
+ ASSERT_TRUE(node0.ReadMessage(A, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+
+ // No more ports should be open.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePortsWithClosedPeers) {
+ // This tests that no residual ports are left behind if two ports are merged
+ // when both of their peers have been closed.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ // Close A and D.
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+
+ WaitForIdle();
+
+ // Initiate a merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ WaitForIdle();
+
+ // Expect everything to have gone away.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePortsWithMovedPeers) {
+ // This tests that ports can be merged successfully even if their peers are
+ // moved around.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ // Set up another pair X-Y for moving ports on node0.
+ PortRef X, Y;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&X, &Y));
+
+ ScopedMessage message;
+
+ // Move A to new port E.
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(X, "foo", A));
+ ASSERT_TRUE(node0.ReadMessage(Y, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef E;
+ ASSERT_EQ(OK, node0.node().GetPort(message->ports()[0], &E));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(X));
+ EXPECT_EQ(OK, node0.node().ClosePort(Y));
+
+ // Write messages on E and D.
+ EXPECT_EQ(OK, node0.SendStringMessage(E, "hey"));
+ EXPECT_EQ(OK, node1.SendStringMessage(D, "hi"));
+
+ // Initiate a merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ WaitForIdle();
+
+ // Expect to receive D's message on E and E's message on D.
+ ASSERT_TRUE(node0.ReadMessage(E, &message));
+ EXPECT_TRUE(MessageEquals(message, "hi"));
+ ASSERT_TRUE(node1.ReadMessage(D, &message));
+ EXPECT_TRUE(MessageEquals(message, "hey"));
+
+ // Close E and D.
+ EXPECT_EQ(OK, node0.node().ClosePort(E));
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+
+ WaitForIdle();
+
+ // Expect everything to have gone away.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, MergePortsFailsGracefully) {
+ // This tests that the system remains in a well-defined state if something
+ // goes wrong during port merge.
+
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Setup two independent port pairs, A-B on node0 and C-D on node1.
+ PortRef A, B, C, D;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&A, &B));
+ EXPECT_EQ(OK, node1.node().CreatePortPair(&C, &D));
+
+ ScopedMessage message;
+ PortRef X, Y;
+ EXPECT_EQ(OK, node0.node().CreateUninitializedPort(&X));
+ EXPECT_EQ(OK, node1.node().CreateUninitializedPort(&Y));
+ EXPECT_EQ(OK, node0.node().InitializePort(X, node1.name(), Y.name(),
+ node1.name(), Y.name()));
+ EXPECT_EQ(OK, node1.node().InitializePort(Y, node0.name(), X.name(),
+ node0.name(), X.name()));
+
+ // Block the merge from proceeding until we can do something stupid with port
+ // C. This avoids the test logic racing with async merge logic.
+ node1.BlockOnEvent(Event::Type::kMergePort);
+
+ // Initiate the merge between B and C.
+ node1.AllowPortMerge(C);
+ EXPECT_EQ(OK, node0.node().MergePorts(B, node1.name(), C.name()));
+
+ // Move C to a new port E. This is not a sane use of Node's public API but
+ // is still hypothetically possible. It allows us to force a merge failure
+ // because C will be in an invalid state by the time the merge is processed.
+ // As a result, B should be closed.
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(Y, "foo", C));
+
+ node1.Unblock();
+
+ WaitForIdle();
+
+ ASSERT_TRUE(node0.ReadMessage(X, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ PortRef E;
+ ASSERT_EQ(OK, node0.node().GetPort(message->ports()[0], &E));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(X));
+ EXPECT_EQ(OK, node1.node().ClosePort(Y));
+
+ WaitForIdle();
+
+ // C goes away as a result of normal proxy removal. B should have been closed
+ // cleanly by the failed MergePorts.
+ EXPECT_EQ(ERROR_PORT_UNKNOWN, node1.node().GetPort(C.name(), &C));
+ EXPECT_EQ(ERROR_PORT_UNKNOWN, node0.node().GetPort(B.name(), &B));
+
+ // Close A, D, and E.
+ EXPECT_EQ(OK, node0.node().ClosePort(A));
+ EXPECT_EQ(OK, node1.node().ClosePort(D));
+ EXPECT_EQ(OK, node0.node().ClosePort(E));
+
+ WaitForIdle();
+
+ // Expect everything to have gone away.
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, RemotePeerStatus) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Create a local port pair. Neither port should appear to have a remote peer.
+ PortRef a, b;
+ PortStatus status{};
+ node0.node().CreatePortPair(&a, &b);
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(b, &status));
+ EXPECT_FALSE(status.peer_remote);
+
+ // Create a port pair spanning the two nodes. Both spanning ports should
+ // immediately appear to have a remote peer.
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+
+ ASSERT_EQ(OK, node0.node().GetStatus(x0, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(x1, &status));
+ EXPECT_TRUE(status.peer_remote);
+
+ PortRef x2, x3;
+ CreatePortPair(&node0, &x2, &node1, &x3);
+
+ // Transfer |b| to |node1| and |x1| to |node0|. i.e., make the local peers
+ // remote and the remote peers local.
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x2, "foo", b));
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(x3, "bar", x1));
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node0.ReadMessage(x2, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ ASSERT_EQ(OK, node0.node().GetPort(message->ports()[0], &x1));
+
+ ASSERT_TRUE(node1.ReadMessage(x3, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ ASSERT_EQ(OK, node1.node().GetPort(message->ports()[0], &b));
+
+ // Now x0-x1 should be local to node0 and a-b should span the nodes.
+ ASSERT_EQ(OK, node0.node().GetStatus(x0, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(x1, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(b, &status));
+ EXPECT_TRUE(status.peer_remote);
+
+ // And swap them back one more time.
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x2, "foo", x1));
+ EXPECT_EQ(OK, node1.SendStringMessageWithPort(x3, "bar", b));
+ WaitForIdle();
+
+ ASSERT_TRUE(node0.ReadMessage(x2, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ ASSERT_EQ(OK, node0.node().GetPort(message->ports()[0], &b));
+
+ ASSERT_TRUE(node1.ReadMessage(x3, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ ASSERT_EQ(OK, node1.node().GetPort(message->ports()[0], &x1));
+
+ ASSERT_EQ(OK, node0.node().GetStatus(x0, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(x1, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(b, &status));
+ EXPECT_FALSE(status.peer_remote);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+ EXPECT_EQ(OK, node0.node().ClosePort(x2));
+ EXPECT_EQ(OK, node1.node().ClosePort(x3));
+ EXPECT_EQ(OK, node0.node().ClosePort(a));
+ EXPECT_EQ(OK, node0.node().ClosePort(b));
+
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, RemotePeerStatusAfterLocalPortMerge) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Set up a-b on node0 and c-d spanning node0-node1.
+ PortRef a, b, c, d;
+ node0.node().CreatePortPair(&a, &b);
+ CreatePortPair(&node0, &c, &node1, &d);
+
+ PortStatus status{};
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(b, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(c, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(d, &status));
+ EXPECT_TRUE(status.peer_remote);
+
+ EXPECT_EQ(OK, node0.node().MergeLocalPorts(b, c));
+ WaitForIdle();
+
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(d, &status));
+ EXPECT_TRUE(status.peer_remote);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a));
+ EXPECT_EQ(OK, node1.node().ClosePort(d));
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, RemotePeerStatusAfterRemotePortMerge) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Set up a-b on node0 and c-d on node1.
+ PortRef a, b, c, d;
+ node0.node().CreatePortPair(&a, &b);
+ node1.node().CreatePortPair(&c, &d);
+
+ PortStatus status{};
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node0.node().GetStatus(b, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(c, &status));
+ EXPECT_FALSE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(d, &status));
+ EXPECT_FALSE(status.peer_remote);
+
+ node1.AllowPortMerge(c);
+ EXPECT_EQ(OK, node0.node().MergePorts(b, node1.name(), c.name()));
+ WaitForIdle();
+
+ ASSERT_EQ(OK, node0.node().GetStatus(a, &status));
+ EXPECT_TRUE(status.peer_remote);
+ ASSERT_EQ(OK, node1.node().GetStatus(d, &status));
+ EXPECT_TRUE(status.peer_remote);
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a));
+ EXPECT_EQ(OK, node1.node().ClosePort(d));
+ EXPECT_TRUE(node0.node().CanShutdownCleanly());
+ EXPECT_TRUE(node1.node().CanShutdownCleanly());
+}
+
+TEST_F(PortsTest, RetransmitUserMessageEvents) {
+ // Ensures that user message events can be retransmitted properly.
+ TestNode node0(0);
+ AddNode(&node0);
+
+ PortRef a, b;
+ node0.node().CreatePortPair(&a, &b);
+
+ // Ping.
+ const char* kMessage = "hey";
+ ScopedMessage message;
+ EXPECT_EQ(OK, node0.SendStringMessage(a, kMessage));
+ ASSERT_TRUE(node0.ReadMessage(b, &message));
+ EXPECT_TRUE(MessageEquals(message, kMessage));
+
+ // Pong.
+ EXPECT_EQ(OK, node0.node().SendUserMessage(b, std::move(message)));
+ EXPECT_FALSE(message);
+ ASSERT_TRUE(node0.ReadMessage(a, &message));
+ EXPECT_TRUE(MessageEquals(message, kMessage));
+
+ // Ping again.
+ EXPECT_EQ(OK, node0.node().SendUserMessage(a, std::move(message)));
+ EXPECT_FALSE(message);
+ ASSERT_TRUE(node0.ReadMessage(b, &message));
+ EXPECT_TRUE(MessageEquals(message, kMessage));
+
+ // Pong again!
+ EXPECT_EQ(OK, node0.node().SendUserMessage(b, std::move(message)));
+ EXPECT_FALSE(message);
+ ASSERT_TRUE(node0.ReadMessage(a, &message));
+ EXPECT_TRUE(MessageEquals(message, kMessage));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a));
+ EXPECT_EQ(OK, node0.node().ClosePort(b));
+}
+
+TEST_F(PortsTest, SetAcknowledgeRequestInterval) {
+ TestNode node0(0);
+ AddNode(&node0);
+
+ PortRef a0, a1;
+ EXPECT_EQ(OK, node0.node().CreatePortPair(&a0, &a1));
+ EXPECT_EQ(0u, node0.GetUnacknowledgedMessageCount(a0));
+
+ // Send a batch of messages.
+ EXPECT_EQ(OK, node0.SendMultipleMessages(a0, 15));
+ EXPECT_EQ(15u, node0.GetUnacknowledgedMessageCount(a0));
+ EXPECT_TRUE(node0.ReadMultipleMessages(a1, 5));
+ WaitForIdle();
+ EXPECT_EQ(15u, node0.GetUnacknowledgedMessageCount(a0));
+
+ // Set to acknowledge every read message, and validate that already-read
+ // messages are acknowledged.
+ EXPECT_EQ(OK, node0.node().SetAcknowledgeRequestInterval(a0, 1));
+ WaitForIdle();
+ EXPECT_EQ(10u, node0.GetUnacknowledgedMessageCount(a0));
+
+ // Read a third of the messages from the other end.
+ EXPECT_TRUE(node0.ReadMultipleMessages(a1, 5));
+ WaitForIdle();
+
+ EXPECT_EQ(5u, node0.GetUnacknowledgedMessageCount(a0));
+
+ TestNode node1(1);
+ AddNode(&node1);
+
+ // Transfer a1 across to node1.
+ PortRef x0, x1;
+ CreatePortPair(&node0, &x0, &node1, &x1);
+ EXPECT_EQ(OK, node0.SendStringMessageWithPort(x0, "foo", a1));
+ WaitForIdle();
+
+ ScopedMessage message;
+ ASSERT_TRUE(node1.ReadMessage(x1, &message));
+ ASSERT_EQ(1u, message->num_ports());
+ ASSERT_EQ(OK, node1.node().GetPort(message->ports()[0], &a1));
+
+ // Read the last third of the messages from the transferred node, and
+ // validate that the unacknowledge message count updates correctly.
+ EXPECT_TRUE(node1.ReadMultipleMessages(a1, 5));
+ WaitForIdle();
+ EXPECT_EQ(0u, node0.GetUnacknowledgedMessageCount(a0));
+
+ // Turn the acknowledges down and validate that they don't go on indefinitely.
+ EXPECT_EQ(OK, node0.node().SetAcknowledgeRequestInterval(a0, 0));
+ EXPECT_EQ(OK, node0.SendMultipleMessages(a0, 10));
+ WaitForIdle();
+ EXPECT_TRUE(node1.ReadMultipleMessages(a1, 10));
+ WaitForIdle();
+ EXPECT_NE(0u, node0.GetUnacknowledgedMessageCount(a0));
+
+ // Close the far port and validate that the closure updates the unacknowledged
+ // count.
+ EXPECT_EQ(OK, node1.node().ClosePort(a1));
+ WaitForIdle();
+ EXPECT_EQ(0u, node0.GetUnacknowledgedMessageCount(a0));
+
+ EXPECT_EQ(OK, node0.node().ClosePort(a0));
+ EXPECT_EQ(OK, node0.node().ClosePort(x0));
+ EXPECT_EQ(OK, node1.node().ClosePort(x1));
+}
+
+} // namespace test
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/moz.build b/ipc/chromium/moz.build
new file mode 100644
index 0000000000..56f24c24bb
--- /dev/null
+++ b/ipc/chromium/moz.build
@@ -0,0 +1,136 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+libevent_path_prefix = "src/third_party"
+include(libevent_path_prefix + "/libeventcommon.mozbuild")
+
+UNIFIED_SOURCES += [
+ "src/base/at_exit.cc",
+ "src/base/command_line.cc",
+ "src/base/file_path.cc",
+ "src/base/histogram.cc",
+ "src/base/logging.cc",
+ "src/base/message_loop.cc",
+ "src/base/message_pump_default.cc",
+ "src/base/pickle.cc",
+ "src/base/rand_util.cc",
+ "src/base/revocable_store.cc",
+ "src/base/string_piece.cc",
+ "src/base/string_util.cc",
+ "src/base/thread.cc",
+ "src/base/time.cc",
+ "src/base/timer.cc",
+ "src/chrome/common/child_process.cc",
+ "src/chrome/common/child_thread.cc",
+ "src/chrome/common/chrome_switches.cc",
+ "src/chrome/common/ipc_channel_utils.cc",
+ "src/chrome/common/ipc_message.cc",
+ "src/chrome/common/ipc_message_utils.cc",
+ "src/mojo/core/ports/event.cc",
+ "src/mojo/core/ports/message_queue.cc",
+ "src/mojo/core/ports/name.cc",
+ "src/mojo/core/ports/node.cc",
+ "src/mojo/core/ports/port.cc",
+ "src/mojo/core/ports/port_locker.cc",
+ "src/mojo/core/ports/port_ref.cc",
+ "src/mojo/core/ports/user_message.cc",
+]
+
+if os_win:
+ SOURCES += [
+ "src/base/condition_variable_win.cc",
+ "src/base/lock_impl_win.cc",
+ "src/base/message_pump_win.cc",
+ "src/base/object_watcher.cc",
+ "src/base/platform_thread_win.cc",
+ "src/base/process_util_win.cc",
+ "src/base/shared_memory_win.cc",
+ "src/base/sys_string_conversions_win.cc",
+ "src/base/thread_local_win.cc",
+ "src/base/time_win.cc",
+ "src/base/waitable_event_win.cc",
+ "src/base/win_util.cc",
+ "src/chrome/common/ipc_channel_win.cc",
+ "src/chrome/common/process_watcher_win.cc",
+ ]
+
+elif not CONFIG["MOZ_SYSTEM_LIBEVENT"]:
+ DIRS += ["src/third_party"]
+
+if os_posix:
+ UNIFIED_SOURCES += [
+ "src/base/condition_variable_posix.cc",
+ "src/base/lock_impl_posix.cc",
+ "src/base/message_pump_libevent.cc",
+ "src/base/platform_thread_posix.cc",
+ "src/base/process_util_posix.cc",
+ "src/base/shared_memory_posix.cc",
+ "src/base/string16.cc",
+ "src/base/thread_local_posix.cc",
+ "src/base/waitable_event_posix.cc",
+ "src/chrome/common/ipc_channel_posix.cc",
+ "src/chrome/common/process_watcher_posix_sigchld.cc",
+ ]
+
+if os_macosx:
+ UNIFIED_SOURCES += [
+ "src/base/chrome_application_mac.mm",
+ "src/base/mac_util.mm",
+ "src/base/message_pump_mac.mm",
+ "src/base/process_util_mac.mm",
+ "src/base/scoped_nsautorelease_pool.mm",
+ "src/base/sys_string_conversions_mac.mm",
+ "src/base/time_mac.cc",
+ "src/chrome/common/mach_ipc_mac.cc",
+ "src/chrome/common/mach_message_source_mac.cc",
+ ]
+ SOURCES += [
+ # This file cannot be built in unified mode because of the redefinition
+ # of NoOp.
+ "src/base/platform_thread_mac.mm",
+ ]
+
+if os_bsd:
+ SOURCES += [
+ "src/base/process_util_linux.cc",
+ "src/base/time_posix.cc",
+ ]
+
+if os_linux:
+ SOURCES += [
+ "src/base/process_util_linux.cc",
+ "src/base/set_process_title_linux.cc",
+ "src/base/time_posix.cc",
+ ]
+ if CONFIG["OS_TARGET"] == "Android":
+ UNIFIED_SOURCES += [
+ "src/base/message_pump_android.cc",
+ ]
+ DEFINES["ANDROID"] = True
+ DEFINES["_POSIX_MONOTONIC_CLOCK"] = 0
+
+if os_bsd or os_linux:
+ if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
+ SOURCES += [
+ "src/base/message_pump_glib.cc",
+ ]
+
+if os_solaris:
+ SOURCES += [
+ "src/base/process_util_linux.cc",
+ "src/base/time_posix.cc",
+ ]
+
+if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
+ CXXFLAGS += CONFIG["MOZ_GTK3_CFLAGS"]
+
+TEST_DIRS += [
+ "gtest",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
diff --git a/ipc/chromium/src/LICENSE b/ipc/chromium/src/LICENSE
new file mode 100644
index 0000000000..9314092fdc
--- /dev/null
+++ b/ipc/chromium/src/LICENSE
@@ -0,0 +1,27 @@
+// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+// * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+// * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+// * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/ipc/chromium/src/base/at_exit.cc b/ipc/chromium/src/base/at_exit.cc
new file mode 100644
index 0000000000..057d8b2678
--- /dev/null
+++ b/ipc/chromium/src/base/at_exit.cc
@@ -0,0 +1,73 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/at_exit.h"
+#include "base/logging.h"
+
+namespace base {
+
+// Keep a stack of registered AtExitManagers. We always operate on the most
+// recent, and we should never have more than one outside of testing, when we
+// use the shadow version of the constructor. We don't protect this for
+// thread-safe access, since it will only be modified in testing.
+static AtExitManager* g_top_manager = NULL;
+
+AtExitManager::AtExitManager() : lock_("AtExitManager"), next_manager_(NULL) {
+ DCHECK(!g_top_manager);
+ g_top_manager = this;
+}
+
+AtExitManager::AtExitManager(bool shadow)
+ : lock_("AtExitManager"), next_manager_(g_top_manager) {
+ DCHECK(shadow || !g_top_manager);
+ g_top_manager = this;
+}
+
+AtExitManager::~AtExitManager() {
+ if (!g_top_manager) {
+ NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
+ return;
+ }
+ DCHECK(g_top_manager == this);
+
+ ProcessCallbacksNow();
+ g_top_manager = next_manager_;
+}
+
+// static
+void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
+ if (!g_top_manager) {
+ NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
+ return;
+ }
+
+ DCHECK(func);
+
+ mozilla::MutexAutoLock lock(g_top_manager->lock_);
+ g_top_manager->stack_.push(CallbackAndParam(func, param));
+}
+
+// static
+void AtExitManager::ProcessCallbacksNow() {
+ if (!g_top_manager) {
+ NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
+ return;
+ }
+
+ mozilla::MutexAutoLock lock(g_top_manager->lock_);
+
+ while (!g_top_manager->stack_.empty()) {
+ CallbackAndParam callback_and_param = g_top_manager->stack_.top();
+ g_top_manager->stack_.pop();
+
+ callback_and_param.func_(callback_and_param.param_);
+ }
+}
+
+// static
+bool AtExitManager::AlreadyRegistered() { return !!g_top_manager; }
+
+} // namespace base
diff --git a/ipc/chromium/src/base/at_exit.h b/ipc/chromium/src/base/at_exit.h
new file mode 100644
index 0000000000..268d9e0fbe
--- /dev/null
+++ b/ipc/chromium/src/base/at_exit.h
@@ -0,0 +1,76 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_AT_EXIT_H_
+#define BASE_AT_EXIT_H_
+
+#include <stack>
+
+#include "base/basictypes.h"
+
+#include "mozilla/Mutex.h"
+
+namespace base {
+
+// This class provides a facility similar to the CRT atexit(), except that
+// we control when the callbacks are executed. Under Windows for a DLL they
+// happen at a really bad time and under the loader lock. This facility is
+// mostly used by base::Singleton.
+//
+// The usage is simple. Early in the main() or WinMain() scope create an
+// AtExitManager object on the stack:
+// int main(...) {
+// base::AtExitManager exit_manager;
+//
+// }
+// When the exit_manager object goes out of scope, all the registered
+// callbacks and singleton destructors will be called.
+
+class AtExitManager {
+ protected:
+ // This constructor will allow this instance of AtExitManager to be created
+ // even if one already exists. This should only be used for testing!
+ // AtExitManagers are kept on a global stack, and it will be removed during
+ // destruction. This allows you to shadow another AtExitManager.
+ explicit AtExitManager(bool shadow);
+
+ public:
+ typedef void (*AtExitCallbackType)(void*);
+
+ AtExitManager();
+
+ // The dtor calls all the registered callbacks. Do not try to register more
+ // callbacks after this point.
+ ~AtExitManager();
+
+ // Registers the specified function to be called at exit. The prototype of
+ // the callback function is void func().
+ static void RegisterCallback(AtExitCallbackType func, void* param);
+
+ // Calls the functions registered with RegisterCallback in LIFO order. It
+ // is possible to register new callbacks after calling this function.
+ static void ProcessCallbacksNow();
+
+ static bool AlreadyRegistered();
+
+ private:
+ struct CallbackAndParam {
+ CallbackAndParam(AtExitCallbackType func, void* param)
+ : func_(func), param_(param) {}
+ AtExitCallbackType func_;
+ void* param_;
+ };
+
+ mozilla::Mutex lock_;
+ std::stack<CallbackAndParam> stack_ MOZ_GUARDED_BY(lock_);
+ AtExitManager* next_manager_; // Stack of managers to allow shadowing.
+
+ DISALLOW_COPY_AND_ASSIGN(AtExitManager);
+};
+
+} // namespace base
+
+#endif // BASE_AT_EXIT_H_
diff --git a/ipc/chromium/src/base/basictypes.h b/ipc/chromium/src/base/basictypes.h
new file mode 100644
index 0000000000..78dcd8964e
--- /dev/null
+++ b/ipc/chromium/src/base/basictypes.h
@@ -0,0 +1,262 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_BASICTYPES_H_
+#define BASE_BASICTYPES_H_
+
+#include <limits.h> // So we can set the bounds of our types
+#include <stddef.h> // For size_t
+#include <string.h> // for memcpy
+
+#include "base/port.h" // Types that only need exist on certain systems
+
+#include "mozilla/Assertions.h"
+#include "mozilla/IntegerPrintfMacros.h"
+
+// A type to represent a Unicode code-point value. As of Unicode 4.0,
+// such values require up to 21 bits.
+// (For type-checking on pointers, make this explicitly signed,
+// and it should always be the signed version of whatever int32_t is.)
+typedef signed int char32;
+
+const uint8_t kuint8max = ((uint8_t)0xFF);
+const uint16_t kuint16max = ((uint16_t)0xFFFF);
+const uint32_t kuint32max = ((uint32_t)0xFFFFFFFF);
+const uint64_t kuint64max = ((uint64_t)GG_LONGLONG(0xFFFFFFFFFFFFFFFF));
+const int8_t kint8min = ((int8_t)0x80);
+const int8_t kint8max = ((int8_t)0x7F);
+const int16_t kint16min = ((int16_t)0x8000);
+const int16_t kint16max = ((int16_t)0x7FFF);
+const int32_t kint32min = ((int32_t)0x80000000);
+const int32_t kint32max = ((int32_t)0x7FFFFFFF);
+const int64_t kint64min = ((int64_t)GG_LONGLONG(0x8000000000000000));
+const int64_t kint64max = ((int64_t)GG_LONGLONG(0x7FFFFFFFFFFFFFFF));
+
+// Platform- and hardware-dependent printf specifiers
+#if defined(XP_UNIX)
+# define PRId64L "I64d"
+# define PRIu64L "I64u"
+# define PRIx64L "I64x"
+#else
+# define PRId64L L"I64d"
+# define PRIu64L L"I64u"
+# define PRIx64L L"I64x"
+#endif
+
+// A macro to disallow the copy constructor and operator= functions
+// This should be used in the private: declarations for a class
+#undef DISALLOW_COPY_AND_ASSIGN
+#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
+ TypeName(const TypeName&); \
+ void operator=(const TypeName&)
+
+// An older, deprecated, politically incorrect name for the above.
+#undef DISALLOW_EVIL_CONSTRUCTORS
+#define DISALLOW_EVIL_CONSTRUCTORS(TypeName) DISALLOW_COPY_AND_ASSIGN(TypeName)
+
+// A macro to disallow all the implicit constructors, namely the
+// default constructor, copy constructor and operator= functions.
+//
+// This should be used in the private: declarations for a class
+// that wants to prevent anyone from instantiating it. This is
+// especially useful for classes containing only static methods.
+#undef DISALLOW_IMPLICIT_CONSTRUCTORS
+#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
+ TypeName(); \
+ DISALLOW_COPY_AND_ASSIGN(TypeName)
+
+// The arraysize(arr) macro returns the # of elements in an array arr.
+// The expression is a compile-time constant, and therefore can be
+// used in defining new arrays, for example. If you use arraysize on
+// a pointer by mistake, you will get a compile-time error.
+//
+// One caveat is that arraysize() doesn't accept any array of an
+// anonymous type or a type defined inside a function. In these rare
+// cases, you have to use the unsafe ARRAYSIZE_UNSAFE() macro below. This is
+// due to a limitation in C++'s template system. The limitation might
+// eventually be removed, but it hasn't happened yet.
+
+// This template function declaration is used in defining arraysize.
+// Note that the function doesn't need an implementation, as we only
+// use its type.
+template <typename T, size_t N>
+char (&ArraySizeHelper(T (&array)[N]))[N];
+
+// That gcc wants both of these prototypes seems mysterious. VC, for
+// its part, can't decide which to use (another mystery). Matching of
+// template overloads: the final frontier.
+#ifndef _MSC_VER
+template <typename T, size_t N>
+char (&ArraySizeHelper(const T (&array)[N]))[N];
+#endif
+
+#define arraysize(array) (sizeof(ArraySizeHelper(array)))
+
+// ARRAYSIZE_UNSAFE performs essentially the same calculation as arraysize,
+// but can be used on anonymous types or types defined inside
+// functions. It's less safe than arraysize as it accepts some
+// (although not all) pointers. Therefore, you should use arraysize
+// whenever possible.
+//
+// The expression ARRAYSIZE_UNSAFE(a) is a compile-time constant of type
+// size_t.
+//
+// ARRAYSIZE_UNSAFE catches a few type errors. If you see a compiler error
+//
+// "warning: division by zero in ..."
+//
+// when using ARRAYSIZE_UNSAFE, you are (wrongfully) giving it a pointer.
+// You should only use ARRAYSIZE_UNSAFE on statically allocated arrays.
+//
+// The following comments are on the implementation details, and can
+// be ignored by the users.
+//
+// ARRAYSIZE_UNSAFE(arr) works by inspecting sizeof(arr) (the # of bytes in
+// the array) and sizeof(*(arr)) (the # of bytes in one array
+// element). If the former is divisible by the latter, perhaps arr is
+// indeed an array, in which case the division result is the # of
+// elements in the array. Otherwise, arr cannot possibly be an array,
+// and we generate a compiler error to prevent the code from
+// compiling.
+//
+// Since the size of bool is implementation-defined, we need to cast
+// !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final
+// result has type size_t.
+//
+// This macro is not perfect as it wrongfully accepts certain
+// pointers, namely where the pointer size is divisible by the pointee
+// size. Since all our code has to go through a 32-bit compiler,
+// where a pointer is 4 bytes, this means all pointers to a type whose
+// size is 3 or greater than 4 will be (righteously) rejected.
+
+#define ARRAYSIZE_UNSAFE(a) \
+ ((sizeof(a) / sizeof(*(a))) / \
+ static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
+
+// Use implicit_cast as a safe version of static_cast or const_cast
+// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
+// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
+// a const pointer to Foo).
+// When you use implicit_cast, the compiler checks that the cast is safe.
+// Such explicit implicit_casts are necessary in surprisingly many
+// situations where C++ demands an exact type match instead of an
+// argument type convertable to a target type.
+//
+// The From type can be inferred, so the preferred syntax for using
+// implicit_cast is the same as for static_cast etc.:
+//
+// implicit_cast<ToType>(expr)
+//
+// implicit_cast would have been part of the C++ standard library,
+// but the proposal was submitted too late. It will probably make
+// its way into the language in the future.
+template <typename To, typename From>
+inline To implicit_cast(From const& f) {
+ return f;
+}
+
+// The COMPILE_ASSERT macro (below) creates an otherwise-unused typedef. This
+// triggers compiler warnings with gcc 4.8 and higher, so mark the typedef
+// as permissibly-unused to disable the warnings.
+#if defined(__GNUC__)
+# define COMPILE_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
+#else
+# define COMPILE_ASSERT_UNUSED_ATTRIBUTE /* nothing */
+#endif
+
+// The COMPILE_ASSERT macro can be used to verify that a compile time
+// expression is true. For example, you could use it to verify the
+// size of a static array:
+//
+// COMPILE_ASSERT(ARRAYSIZE_UNSAFE(content_type_names) == CONTENT_NUM_TYPES,
+// content_type_names_incorrect_size);
+//
+// or to make sure a struct is smaller than a certain size:
+//
+// COMPILE_ASSERT(sizeof(foo) < 128, foo_too_large);
+//
+// The second argument to the macro is the name of the variable. If
+// the expression is false, most compilers will issue a warning/error
+// containing the name of the variable.
+
+// Avoid multiple definitions for webrtc
+#if !defined(COMPILE_ASSERT)
+template <bool>
+struct CompileAssert {};
+
+# define COMPILE_ASSERT(expr, msg) \
+ typedef CompileAssert<(bool(expr))> \
+ msg[bool(expr) ? 1 : -1] COMPILE_ASSERT_UNUSED_ATTRIBUTE
+#endif
+
+// Implementation details of COMPILE_ASSERT:
+//
+// - COMPILE_ASSERT works by defining an array type that has -1
+// elements (and thus is invalid) when the expression is false.
+//
+// - The simpler definition
+//
+// #define COMPILE_ASSERT(expr, msg) typedef char msg[(expr) ? 1 : -1]
+//
+// does not work, as gcc supports variable-length arrays whose sizes
+// are determined at run-time (this is gcc's extension and not part
+// of the C++ standard). As a result, gcc fails to reject the
+// following code with the simple definition:
+//
+// int foo;
+// COMPILE_ASSERT(foo, msg); // not supposed to compile as foo is
+// // not a compile-time constant.
+//
+// - By using the type CompileAssert<(bool(expr))>, we ensures that
+// expr is a compile-time constant. (Template arguments must be
+// determined at compile-time.)
+//
+// - The outter parentheses in CompileAssert<(bool(expr))> are necessary
+// to work around a bug in gcc 3.4.4 and 4.0.1. If we had written
+//
+// CompileAssert<bool(expr)>
+//
+// instead, these compilers will refuse to compile
+//
+// COMPILE_ASSERT(5 > 0, some_message);
+//
+// (They seem to think the ">" in "5 > 0" marks the end of the
+// template argument list.)
+//
+// - The array size is (bool(expr) ? 1 : -1), instead of simply
+//
+// ((expr) ? 1 : -1).
+//
+// This is to avoid running into a bug in MS VC 7.1, which
+// causes ((0.0) ? 1 : -1) to incorrectly evaluate to 1.
+
+// MetatagId refers to metatag-id that we assign to
+// each metatag <name, value> pair..
+typedef uint32_t MetatagId;
+
+// Argument type used in interfaces that can optionally take ownership
+// of a passed in argument. If TAKE_OWNERSHIP is passed, the called
+// object takes ownership of the argument. Otherwise it does not.
+enum Ownership { DO_NOT_TAKE_OWNERSHIP, TAKE_OWNERSHIP };
+
+// The following enum should be used only as a constructor argument to indicate
+// that the variable has static storage class, and that the constructor should
+// do nothing to its state. It indicates to the reader that it is legal to
+// declare a static instance of the class, provided the constructor is given
+// the base::LINKER_INITIALIZED argument. Normally, it is unsafe to declare a
+// static variable that has a constructor or a destructor because invocation
+// order is undefined. However, IF the type can be initialized by filling with
+// zeroes (which the loader does for static variables), AND the destructor also
+// does nothing to the storage, AND there are no virtual methods, then a
+// constructor declared as
+// explicit MyClass(base::LinkerInitialized x) {}
+// and invoked as
+// static MyClass my_variable_name(base::LINKER_INITIALIZED);
+namespace base {
+enum LinkerInitialized { LINKER_INITIALIZED };
+} // namespace base
+
+#endif // BASE_BASICTYPES_H_
diff --git a/ipc/chromium/src/base/chrome_application_mac.h b/ipc/chromium/src/base/chrome_application_mac.h
new file mode 100644
index 0000000000..8c5bb197f7
--- /dev/null
+++ b/ipc/chromium/src/base/chrome_application_mac.h
@@ -0,0 +1,60 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#ifndef BASE_CHROME_APPLICATION_MAC_H_
+#define BASE_CHROME_APPLICATION_MAC_H_
+
+#import <AppKit/AppKit.h>
+
+#include "base/basictypes.h"
+#include "base/scoped_nsobject.h"
+
+// Event hooks must implement this protocol.
+@protocol CrApplicationEventHookProtocol
+- (void)hookForEvent:(NSEvent*)theEvent;
+@end
+
+@interface CrApplication : NSApplication {
+ @private
+ BOOL handlingSendEvent_;
+ // Array of objects implementing the CrApplicationEventHookProtocol
+ scoped_nsobject<NSMutableArray> eventHooks_;
+}
+@property(readonly, getter=isHandlingSendEvent, nonatomic)
+ BOOL handlingSendEvent;
+
+// Add or remove an event hook to be called for every sendEvent:
+// that the application receives. These handlers are called before
+// the normal [NSApplication sendEvent:] call is made.
+
+// This is not a good alternative to a nested event loop. It should
+// be used only when normal event logic and notification breaks down
+// (e.g. when clicking outside a canBecomeKey:NO window to "switch
+// context" out of it).
+- (void)addEventHook:(id<CrApplicationEventHookProtocol>)hook;
+- (void)removeEventHook:(id<CrApplicationEventHookProtocol>)hook;
+
++ (NSApplication*)sharedApplication;
+@end
+
+namespace chrome_application_mac {
+
+// Controls the state of |handlingSendEvent_| in the event loop so that it is
+// reset properly.
+class ScopedSendingEvent {
+ public:
+ ScopedSendingEvent();
+ ~ScopedSendingEvent();
+
+ private:
+ CrApplication* app_;
+ BOOL handling_;
+ DISALLOW_COPY_AND_ASSIGN(ScopedSendingEvent);
+};
+
+} // namespace chrome_application_mac
+
+#endif // BASE_CHROME_APPLICATION_MAC_H_
diff --git a/ipc/chromium/src/base/chrome_application_mac.mm b/ipc/chromium/src/base/chrome_application_mac.mm
new file mode 100644
index 0000000000..405a02a0e7
--- /dev/null
+++ b/ipc/chromium/src/base/chrome_application_mac.mm
@@ -0,0 +1,68 @@
+// Copyright (c) 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.
+
+#import "chrome_application_mac.h"
+
+#include "base/logging.h"
+
+@interface CrApplication ()
+@property(readwrite, getter=isHandlingSendEvent, nonatomic)
+ BOOL handlingSendEvent;
+@end
+
+@implementation CrApplication
+@synthesize handlingSendEvent = handlingSendEvent_;
+
+// Initialize NSApplication using the custom subclass. Check whether NSApp
+// was already initialized using another class, because that would break
+// some things.
++ (NSApplication*)sharedApplication {
+ NSApplication* app = [super sharedApplication];
+ if (![NSApp isKindOfClass:self]) {
+ CHROMIUM_LOG(ERROR) << "NSApp should be of type "
+ << [[self className] UTF8String] << ", not "
+ << [[NSApp className] UTF8String];
+ DCHECK(false) << "NSApp is of wrong type";
+ }
+ return app;
+}
+
+- (id)init {
+ if ((self = [super init])) {
+ eventHooks_.reset([[NSMutableArray alloc] init]);
+ }
+ return self;
+}
+
+- (void)sendEvent:(NSEvent*)event {
+ chrome_application_mac::ScopedSendingEvent sendingEventScoper;
+ for (id<CrApplicationEventHookProtocol> handler in eventHooks_.get()) {
+ [handler hookForEvent:event];
+ }
+ [super sendEvent:event];
+}
+
+- (void)addEventHook:(id<CrApplicationEventHookProtocol>)handler {
+ [eventHooks_ addObject:handler];
+}
+
+- (void)removeEventHook:(id<CrApplicationEventHookProtocol>)handler {
+ [eventHooks_ removeObject:handler];
+}
+
+@end
+
+namespace chrome_application_mac {
+
+ScopedSendingEvent::ScopedSendingEvent()
+ : app_(static_cast<CrApplication*>([CrApplication sharedApplication])),
+ handling_([app_ isHandlingSendEvent]) {
+ [app_ setHandlingSendEvent:YES];
+}
+
+ScopedSendingEvent::~ScopedSendingEvent() {
+ [app_ setHandlingSendEvent:handling_];
+}
+
+} // namespace chrome_application_mac
diff --git a/ipc/chromium/src/base/command_line.cc b/ipc/chromium/src/base/command_line.cc
new file mode 100644
index 0000000000..b3daa6f104
--- /dev/null
+++ b/ipc/chromium/src/base/command_line.cc
@@ -0,0 +1,389 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/command_line.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+# include <shellapi.h>
+# include "mozilla/DynamicallyLinkedFunctionPtr.h"
+#endif
+
+#include <algorithm>
+
+#include "base/logging.h"
+#include "base/string_piece.h"
+#include "base/string_util.h"
+#include "base/sys_string_conversions.h"
+
+CommandLine* CommandLine::current_process_commandline_ = NULL;
+
+// Since we use a lazy match, make sure that longer versions (like L"--")
+// are listed before shorter versions (like L"-") of similar prefixes.
+#if defined(XP_WIN)
+const wchar_t* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
+const wchar_t kSwitchTerminator[] = L"--";
+const wchar_t kSwitchValueSeparator[] = L"=";
+#else
+// Unixes don't use slash as a switch.
+const char* const kSwitchPrefixes[] = {"--", "-"};
+const char kSwitchTerminator[] = "--";
+const char kSwitchValueSeparator[] = "=";
+#endif
+
+#if defined(XP_WIN)
+// Lowercase a string. This is used to lowercase switch names.
+// Is this what we really want? It seems crazy to me. I've left it in
+// for backwards compatibility on Windows.
+static void Lowercase(std::wstring* parameter) {
+ transform(parameter->begin(), parameter->end(), parameter->begin(), tolower);
+}
+#endif
+
+#if defined(XP_WIN)
+void CommandLine::ParseFromString(const std::wstring& command_line) {
+ TrimWhitespace(command_line, TRIM_ALL, &command_line_string_);
+
+ if (command_line_string_.empty()) return;
+
+ int num_args = 0;
+ wchar_t** args = NULL;
+ // When calling CommandLineToArgvW, use the API set if available.
+ // Doing so will bypass loading shell32.dll on Win8+.
+ mozilla::DynamicallyLinkedFunctionPtr<decltype(&::CommandLineToArgvW)>
+ pCommandLineToArgvW(L"api-ms-win-downlevel-shell32-l1-1-0.dll",
+ "CommandLineToArgvW");
+ if (pCommandLineToArgvW) {
+ args = pCommandLineToArgvW(command_line_string_.c_str(), &num_args);
+ } else {
+ args = CommandLineToArgvW(command_line_string_.c_str(), &num_args);
+ }
+
+ // Populate program_ with the trimmed version of the first arg.
+ TrimWhitespace(args[0], TRIM_ALL, &program_);
+
+ bool parse_switches = true;
+ for (int i = 1; i < num_args; ++i) {
+ std::wstring arg;
+ TrimWhitespace(args[i], TRIM_ALL, &arg);
+
+ if (!parse_switches) {
+ loose_values_.push_back(arg);
+ continue;
+ }
+
+ if (arg == kSwitchTerminator) {
+ parse_switches = false;
+ continue;
+ }
+
+ std::string switch_string;
+ std::wstring switch_value;
+ if (IsSwitch(arg, &switch_string, &switch_value)) {
+ switches_[switch_string] = switch_value;
+ } else {
+ loose_values_.push_back(arg);
+ }
+ }
+
+ if (args) LocalFree(args);
+}
+CommandLine::CommandLine(const std::wstring& program) {
+ if (!program.empty()) {
+ program_ = program;
+ command_line_string_ = L'"' + program + L'"';
+ }
+}
+#else
+CommandLine::CommandLine(int argc, const char* const* argv) {
+ for (int i = 0; i < argc; ++i) argv_.push_back(argv[i]);
+ InitFromArgv();
+}
+CommandLine::CommandLine(const std::vector<std::string>& argv) {
+ argv_ = argv;
+ InitFromArgv();
+}
+
+void CommandLine::InitFromArgv() {
+ bool parse_switches = true;
+ for (size_t i = 1; i < argv_.size(); ++i) {
+ const std::string& arg = argv_[i];
+
+ if (!parse_switches) {
+ loose_values_.push_back(arg);
+ continue;
+ }
+
+ if (arg == kSwitchTerminator) {
+ parse_switches = false;
+ continue;
+ }
+
+ std::string switch_string;
+ std::string switch_value;
+ if (IsSwitch(arg, &switch_string, &switch_value)) {
+ switches_[switch_string] = switch_value;
+ } else {
+ loose_values_.push_back(arg);
+ }
+ }
+}
+
+CommandLine::CommandLine(const std::wstring& program) {
+ argv_.push_back(WideToASCII(program));
+}
+#endif
+
+// static
+bool CommandLine::IsSwitch(const StringType& parameter_string,
+ std::string* switch_string,
+ StringType* switch_value) {
+ switch_string->clear();
+ switch_value->clear();
+
+ for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) {
+ StringType prefix(kSwitchPrefixes[i]);
+ if (parameter_string.find(prefix) != 0) continue;
+
+ const size_t switch_start = prefix.length();
+ const size_t equals_position =
+ parameter_string.find(kSwitchValueSeparator, switch_start);
+ StringType switch_native;
+ if (equals_position == StringType::npos) {
+ switch_native = parameter_string.substr(switch_start);
+ } else {
+ switch_native =
+ parameter_string.substr(switch_start, equals_position - switch_start);
+ *switch_value = parameter_string.substr(equals_position + 1);
+ }
+#if defined(XP_WIN)
+ Lowercase(&switch_native);
+ *switch_string = WideToASCII(switch_native);
+#else
+ *switch_string = switch_native;
+#endif
+
+ return true;
+ }
+
+ return false;
+}
+
+// static
+void CommandLine::Init(int argc, const char* const* argv) {
+ DCHECK(current_process_commandline_ == NULL);
+#if defined(XP_WIN)
+ current_process_commandline_ = new CommandLine;
+ current_process_commandline_->ParseFromString(::GetCommandLineW());
+#else
+ current_process_commandline_ = new CommandLine(argc, argv);
+#endif
+}
+
+void CommandLine::Terminate() {
+ DCHECK(current_process_commandline_ != NULL);
+ delete current_process_commandline_;
+ current_process_commandline_ = NULL;
+}
+
+bool CommandLine::HasSwitch(const std::wstring& switch_string) const {
+ std::wstring lowercased_switch(switch_string);
+#if defined(XP_WIN)
+ Lowercase(&lowercased_switch);
+#endif
+ return switches_.find(WideToASCII(lowercased_switch)) != switches_.end();
+}
+
+std::wstring CommandLine::GetSwitchValue(
+ const std::wstring& switch_string) const {
+ std::wstring lowercased_switch(switch_string);
+#if defined(XP_WIN)
+ Lowercase(&lowercased_switch);
+#endif
+
+ std::map<std::string, StringType>::const_iterator result =
+ switches_.find(WideToASCII(lowercased_switch));
+
+ if (result == switches_.end()) {
+ return L"";
+ } else {
+#if defined(XP_WIN)
+ return result->second;
+#else
+ return ASCIIToWide(result->second);
+#endif
+ }
+}
+
+#if defined(XP_WIN)
+std::vector<std::wstring> CommandLine::GetLooseValues() const {
+ return loose_values_;
+}
+std::wstring CommandLine::program() const { return program_; }
+#else
+std::vector<std::wstring> CommandLine::GetLooseValues() const {
+ std::vector<std::wstring> values;
+ for (size_t i = 0; i < loose_values_.size(); ++i)
+ values.push_back(ASCIIToWide(loose_values_[i]));
+ return values;
+}
+std::wstring CommandLine::program() const {
+ DCHECK(argv_.size() > 0);
+ return ASCIIToWide(argv_[0]);
+}
+#endif
+
+// static
+std::wstring CommandLine::PrefixedSwitchString(
+ const std::wstring& switch_string) {
+ return StringPrintf(L"%ls%ls", kSwitchPrefixes[0], switch_string.c_str());
+}
+
+// static
+std::wstring CommandLine::PrefixedSwitchStringWithValue(
+ const std::wstring& switch_string, const std::wstring& value_string) {
+ if (value_string.empty()) {
+ return PrefixedSwitchString(switch_string);
+ }
+
+ return StringPrintf(L"%ls%ls%ls%ls", kSwitchPrefixes[0],
+ switch_string.c_str(), kSwitchValueSeparator,
+ value_string.c_str());
+}
+
+#if defined(XP_WIN)
+void CommandLine::AppendSwitch(const std::wstring& switch_string) {
+ std::wstring prefixed_switch_string = PrefixedSwitchString(switch_string);
+ command_line_string_.append(L" ");
+ command_line_string_.append(prefixed_switch_string);
+ switches_[WideToASCII(switch_string)] = L"";
+}
+
+// Quote a string if necessary, such that CommandLineToArgvW() will
+// always process it as a single argument.
+static std::wstring WindowsStyleQuote(const std::wstring& arg) {
+ // We follow the quoting rules of CommandLineToArgvW.
+ // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
+ if (arg.find_first_of(L" \\\"\t") == std::wstring::npos) {
+ // No quoting necessary.
+ return arg;
+ }
+
+ std::wstring out;
+ out.push_back(L'"');
+ for (size_t i = 0; i < arg.size(); ++i) {
+ if (arg[i] == '\\') {
+ // Find the extent of this run of backslashes.
+ size_t start = i, end = start + 1;
+ for (; end < arg.size() && arg[end] == '\\'; ++end) /* empty */
+ ;
+ size_t backslash_count = end - start;
+
+ // Backslashes are escapes only if the run is followed by a double quote.
+ // Since we also will end the string with a double quote, we escape for
+ // either a double quote or the end of the string.
+ if (end == arg.size() || arg[end] == '"') {
+ // To quote, we need to output 2x as many backslashes.
+ backslash_count *= 2;
+ }
+ for (size_t j = 0; j < backslash_count; ++j) out.push_back('\\');
+
+ // Advance i to one before the end to balance i++ in loop.
+ i = end - 1;
+ } else if (arg[i] == '"') {
+ out.push_back('\\');
+ out.push_back('"');
+ } else {
+ out.push_back(arg[i]);
+ }
+ }
+ out.push_back('"');
+
+ return out;
+}
+
+void CommandLine::AppendSwitchWithValue(const std::wstring& switch_string,
+ const std::wstring& value_string) {
+ std::wstring quoted_value_string = WindowsStyleQuote(value_string);
+ std::wstring combined_switch_string =
+ PrefixedSwitchStringWithValue(switch_string, quoted_value_string);
+
+ command_line_string_.append(L" ");
+ command_line_string_.append(combined_switch_string);
+
+ switches_[WideToASCII(switch_string)] = value_string;
+}
+
+void CommandLine::AppendLooseValue(const std::wstring& value) {
+ command_line_string_.append(L" ");
+ command_line_string_.append(WindowsStyleQuote(value));
+}
+
+void CommandLine::AppendArguments(const CommandLine& other,
+ bool include_program) {
+ // Verify include_program is used correctly.
+ // Logic could be shorter but this is clearer.
+ DCHECK(include_program ? !other.program().empty() : other.program().empty());
+ command_line_string_ += L" " + other.command_line_string_;
+ std::map<std::string, StringType>::const_iterator i;
+ for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
+ switches_[i->first] = i->second;
+}
+
+void CommandLine::PrependWrapper(const std::wstring& wrapper) {
+ // The wrapper may have embedded arguments (like "gdb --args"). In this case,
+ // we don't pretend to do anything fancy, we just split on spaces.
+ std::vector<std::wstring> wrapper_and_args;
+ SplitString(wrapper, ' ', &wrapper_and_args);
+ program_ = wrapper_and_args[0];
+ command_line_string_ = wrapper + L" " + command_line_string_;
+}
+
+#else
+void CommandLine::AppendSwitch(const std::wstring& switch_string) {
+ std::string ascii_switch = WideToASCII(switch_string);
+ argv_.push_back(kSwitchPrefixes[0] + ascii_switch);
+ switches_[ascii_switch] = "";
+}
+
+void CommandLine::AppendSwitchWithValue(const std::wstring& switch_string,
+ const std::wstring& value_string) {
+ std::string ascii_switch = WideToASCII(switch_string);
+ std::string ascii_value = WideToASCII(value_string);
+
+ argv_.push_back(kSwitchPrefixes[0] + ascii_switch + kSwitchValueSeparator +
+ ascii_value);
+ switches_[ascii_switch] = ascii_value;
+}
+
+void CommandLine::AppendLooseValue(const std::wstring& value) {
+ argv_.push_back(WideToASCII(value));
+}
+
+void CommandLine::AppendArguments(const CommandLine& other,
+ bool include_program) {
+ // Verify include_program is used correctly.
+ // Logic could be shorter but this is clearer.
+ DCHECK(include_program ? !other.program().empty() : other.program().empty());
+
+ size_t first_arg = include_program ? 0 : 1;
+ for (size_t i = first_arg; i < other.argv_.size(); ++i)
+ argv_.push_back(other.argv_[i]);
+ std::map<std::string, StringType>::const_iterator i;
+ for (i = other.switches_.begin(); i != other.switches_.end(); ++i)
+ switches_[i->first] = i->second;
+}
+
+void CommandLine::PrependWrapper(const std::wstring& wrapper_wide) {
+ // The wrapper may have embedded arguments (like "gdb --args"). In this case,
+ // we don't pretend to do anything fancy, we just split on spaces.
+ const std::string wrapper = WideToASCII(wrapper_wide);
+ std::vector<std::string> wrapper_and_args;
+ SplitString(wrapper, ' ', &wrapper_and_args);
+ argv_.insert(argv_.begin(), wrapper_and_args.begin(), wrapper_and_args.end());
+}
+
+#endif
diff --git a/ipc/chromium/src/base/command_line.h b/ipc/chromium/src/base/command_line.h
new file mode 100644
index 0000000000..1aff5eae07
--- /dev/null
+++ b/ipc/chromium/src/base/command_line.h
@@ -0,0 +1,188 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// This class works with command lines: building and parsing.
+// Switches can optionally have a value attached using an equals sign,
+// as in "-switch=value". Arguments that aren't prefixed with a
+// switch prefix are considered "loose parameters". Switch names are
+// case-insensitive. An argument of "--" will terminate switch
+// parsing, causing everything after to be considered as loose
+// parameters.
+
+// There is a singleton read-only CommandLine that represents the command
+// line that the current process was started with. It must be initialized
+// in main() (or whatever the platform's equivalent function is).
+
+#ifndef BASE_COMMAND_LINE_H_
+#define BASE_COMMAND_LINE_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+class InProcessBrowserTest;
+
+class CommandLine {
+ public:
+#if defined(XP_WIN)
+ // Creates a parsed version of the given command-line string.
+ // The program name is assumed to be the first item in the string.
+ void ParseFromString(const std::wstring& command_line);
+#else
+ // Initialize from an argv vector (or directly from main()'s argv).
+ CommandLine(int argc, const char* const* argv);
+ explicit CommandLine(const std::vector<std::string>& argv);
+#endif
+
+ // Construct a new, empty command line.
+ // |program| is the name of the program to run (aka argv[0]).
+ // TODO(port): should be a FilePath.
+ explicit CommandLine(const std::wstring& program);
+
+ // Initialize the current process CommandLine singleton. On Windows,
+ // ignores its arguments (we instead parse GetCommandLineW()
+ // directly) because we don't trust the CRT's parsing of the command
+ // line, but it still must be called to set up the command line.
+ static void Init(int argc, const char* const* argv);
+
+ // Destroys the current process CommandLine singleton. This is necessary if
+ // you want to reset the base library to its initial state (for example in an
+ // outer library that needs to be able to terminate, and be re-initialized).
+ // If Init is called only once, e.g. in main(), calling Terminate() is not
+ // necessary.
+ static void Terminate();
+
+ // Get the singleton CommandLine representing the current process's
+ // command line.
+ static const CommandLine* ForCurrentProcess() {
+ DCHECK(current_process_commandline_);
+ return current_process_commandline_;
+ }
+
+ static bool IsInitialized() { return !!current_process_commandline_; }
+
+ // Returns true if this command line contains the given switch.
+ // (Switch names are case-insensitive.)
+ bool HasSwitch(const std::wstring& switch_string) const;
+
+ // Returns the value associated with the given switch. If the
+ // switch has no value or isn't present, this method returns
+ // the empty string.
+ std::wstring GetSwitchValue(const std::wstring& switch_string) const;
+
+ // Get the remaining arguments to the command.
+ // WARNING: this is incorrect on POSIX; we must do string conversions.
+ std::vector<std::wstring> GetLooseValues() const;
+
+#if defined(XP_WIN)
+ // Returns the original command line string.
+ const std::wstring& command_line_string() const {
+ return command_line_string_;
+ }
+#else
+ // Returns the original command line string as a vector of strings.
+ const std::vector<std::string>& argv() const { return argv_; }
+#endif
+
+ // Returns the program part of the command line string (the first item).
+ std::wstring program() const;
+
+ // Return a copy of the string prefixed with a switch prefix.
+ // Used internally.
+ static std::wstring PrefixedSwitchString(const std::wstring& switch_string);
+
+ // Return a copy of the string prefixed with a switch prefix,
+ // and appended with the given value. Used internally.
+ static std::wstring PrefixedSwitchStringWithValue(
+ const std::wstring& switch_string, const std::wstring& value_string);
+
+ // Appends the given switch string (preceded by a space and a switch
+ // prefix) to the given string.
+ void AppendSwitch(const std::wstring& switch_string);
+
+ // Appends the given switch string (preceded by a space and a switch
+ // prefix) to the given string, with the given value attached.
+ void AppendSwitchWithValue(const std::wstring& switch_string,
+ const std::wstring& value_string);
+
+ // Append a loose value to the command line.
+ void AppendLooseValue(const std::wstring& value);
+
+#if defined(XP_WIN)
+ void AppendLooseValue(const wchar_t* value) {
+ AppendLooseValue(std::wstring(value));
+ }
+#endif
+
+ // Append the arguments from another command line to this one.
+ // If |include_program| is true, include |other|'s program as well.
+ void AppendArguments(const CommandLine& other, bool include_program);
+
+ // On POSIX systems it's common to run processes via a wrapper (like
+ // "valgrind" or "gdb --args").
+ void PrependWrapper(const std::wstring& wrapper);
+
+ private:
+ friend class InProcessBrowserTest;
+
+ CommandLine() {}
+
+ // Used by InProcessBrowserTest.
+ static CommandLine* ForCurrentProcessMutable() {
+ DCHECK(current_process_commandline_);
+ return current_process_commandline_;
+ }
+
+ // The singleton CommandLine instance representing the current process's
+ // command line.
+ static CommandLine* current_process_commandline_;
+
+ // We store a platform-native version of the command line, used when building
+ // up a new command line to be executed. This ifdef delimits that code.
+
+#if defined(XP_WIN)
+ // The quoted, space-separated command-line string.
+ std::wstring command_line_string_;
+
+ // The name of the program.
+ std::wstring program_;
+
+ // The type of native command line arguments.
+ typedef std::wstring StringType;
+
+#else
+ // The argv array, with the program name in argv_[0].
+ std::vector<std::string> argv_;
+
+ // The type of native command line arguments.
+ typedef std::string StringType;
+
+ // Shared by the two POSIX constructor forms. Initalize from argv_.
+ void InitFromArgv();
+#endif
+
+ // Returns true and fills in |switch_string| and |switch_value|
+ // if |parameter_string| represents a switch.
+ static bool IsSwitch(const StringType& parameter_string,
+ std::string* switch_string, StringType* switch_value);
+
+ // Parsed-out values.
+ std::map<std::string, StringType> switches_;
+
+ // Non-switch command-line arguments.
+ std::vector<StringType> loose_values_;
+
+ // We allow copy constructors, because a common pattern is to grab a
+ // copy of the current process's command line and then add some
+ // flags to it. E.g.:
+ // CommandLine cl(*CommandLine::ForCurrentProcess());
+ // cl.AppendSwitch(...);
+};
+
+#endif // BASE_COMMAND_LINE_H_
diff --git a/ipc/chromium/src/base/compiler_specific.h b/ipc/chromium/src/base/compiler_specific.h
new file mode 100644
index 0000000000..9cf749d9f1
--- /dev/null
+++ b/ipc/chromium/src/base/compiler_specific.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_COMPILER_SPECIFIC_H_
+#define BASE_COMPILER_SPECIFIC_H_
+
+#if defined(_MSC_VER)
+
+// Macros for suppressing and disabling warnings on MSVC.
+//
+// Warning numbers are enumerated at:
+// http://msdn.microsoft.com/en-us/library/8x5x43k7(VS.80).aspx
+//
+// The warning pragma:
+// http://msdn.microsoft.com/en-us/library/2c8f766e(VS.80).aspx
+//
+// Using __pragma instead of #pragma inside macros:
+// http://msdn.microsoft.com/en-us/library/d9x1s805.aspx
+
+// MSVC_SUPPRESS_WARNING disables warning |n| for the remainder of the line and
+// for the next line of the source file.
+# define MSVC_SUPPRESS_WARNING(n) __pragma(warning(suppress : n))
+
+// MSVC_PUSH_DISABLE_WARNING pushes |n| onto a stack of warnings to be disabled.
+// The warning remains disabled until popped by MSVC_POP_WARNING.
+# define MSVC_PUSH_DISABLE_WARNING(n) \
+ __pragma(warning(push)) __pragma(warning(disable : n))
+
+// MSVC_PUSH_WARNING_LEVEL pushes |n| as the global warning level. The level
+// remains in effect until popped by MSVC_POP_WARNING(). Use 0 to disable all
+// warnings.
+# define MSVC_PUSH_WARNING_LEVEL(n) __pragma(warning(push, n))
+
+// Pop effects of innermost MSVC_PUSH_* macro.
+# define MSVC_POP_WARNING() __pragma(warning(pop))
+
+# define MSVC_DISABLE_OPTIMIZE() __pragma(optimize("", off))
+# define MSVC_ENABLE_OPTIMIZE() __pragma(optimize("", on))
+
+// Allows |this| to be passed as an argument in constructor initializer lists.
+// This uses push/pop instead of the seemingly simpler suppress feature to avoid
+// having the warning be disabled for more than just |code|.
+//
+// Example usage:
+// Foo::Foo() : x(NULL), ALLOW_THIS_IN_INITIALIZER_LIST(y(this)), z(3) {}
+//
+// Compiler warning C4355: 'this': used in base member initializer list:
+// http://msdn.microsoft.com/en-us/library/3c594ae3(VS.80).aspx
+# define ALLOW_THIS_IN_INITIALIZER_LIST(code) \
+ MSVC_PUSH_DISABLE_WARNING(4355) \
+ code MSVC_POP_WARNING()
+
+#else // Not MSVC
+
+# define MSVC_SUPPRESS_WARNING(n)
+# define MSVC_PUSH_DISABLE_WARNING(n)
+# define MSVC_PUSH_WARNING_LEVEL(n)
+# define MSVC_POP_WARNING()
+# define MSVC_DISABLE_OPTIMIZE()
+# define MSVC_ENABLE_OPTIMIZE()
+# define ALLOW_THIS_IN_INITIALIZER_LIST(code) code
+
+#endif // _MSC_VER
+
+// Annotate a function indicating the caller must examine the return value.
+// Use like:
+// int foo() WARN_UNUSED_RESULT;
+// To explicitly ignore a result, see |ignore_result()| in base/macros.h.
+#undef WARN_UNUSED_RESULT
+#if defined(__GNUC__) || defined(__clang__)
+# define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
+#else
+# define WARN_UNUSED_RESULT
+#endif
+
+#endif // BASE_COMPILER_SPECIFIC_H_
diff --git a/ipc/chromium/src/base/condition_variable.h b/ipc/chromium/src/base/condition_variable.h
new file mode 100644
index 0000000000..0b82824ce6
--- /dev/null
+++ b/ipc/chromium/src/base/condition_variable.h
@@ -0,0 +1,116 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+// ConditionVariable wraps pthreads condition variable synchronization or, on
+// Windows, simulates it. This functionality is very helpful for having
+// several threads wait for an event, as is common with a managed thread pool.
+// The meaning of such an event in the (worker) thread pool scenario is that
+// additional tasks are now available for processing. It is used in Chrome in
+// the DNS prefetching system to notify worker threads that a queue now has
+// items (tasks) which need to be tended to. A related use would have a pool
+// manager waiting on a ConditionVariable, waiting for a thread in the pool to
+// announce (signal) that there is now more room in a (bounded size)
+// communications queue for the manager to deposit tasks, or, as a second
+// example, that the queue of tasks is completely empty and all workers are
+// waiting.
+//
+// USAGE NOTE 1: spurious signal events are possible with this and
+// most implementations of condition variables. As a result, be
+// *sure* to retest your condition before proceeding. The following
+// is a good example of doing this correctly:
+//
+// while (!work_to_be_done()) Wait(...);
+//
+// In contrast do NOT do the following:
+//
+// if (!work_to_be_done()) Wait(...); // Don't do this.
+//
+// Especially avoid the above if you are relying on some other thread only
+// issuing a signal up *if* there is work-to-do. There can/will
+// be spurious signals. Recheck state on waiting thread before
+// assuming the signal was intentional. Caveat caller ;-).
+//
+// USAGE NOTE 2: Broadcast() frees up all waiting threads at once,
+// which leads to contention for the locks they all held when they
+// called Wait(). This results in POOR performance. A much better
+// approach to getting a lot of threads out of Wait() is to have each
+// thread (upon exiting Wait()) call Signal() to free up another
+// Wait'ing thread. Look at condition_variable_unittest.cc for
+// both examples.
+//
+// Broadcast() can be used nicely during teardown, as it gets the job
+// done, and leaves no sleeping threads... and performance is less
+// critical at that point.
+//
+// The semantics of Broadcast() are carefully crafted so that *all*
+// threads that were waiting when the request was made will indeed
+// get signaled. Some implementations mess up, and don't signal them
+// all, while others allow the wait to be effectively turned off (for
+// a while while waiting threads come around). This implementation
+// appears correct, as it will not "lose" any signals, and will guarantee
+// that all threads get signaled by Broadcast().
+//
+// This implementation offers support for "performance" in its selection of
+// which thread to revive. Performance, in direct contrast with "fairness,"
+// assures that the thread that most recently began to Wait() is selected by
+// Signal to revive. Fairness would (if publicly supported) assure that the
+// thread that has Wait()ed the longest is selected. The default policy
+// may improve performance, as the selected thread may have a greater chance of
+// having some of its stack data in various CPU caches.
+//
+// For a discussion of the many very subtle implementation details, see the FAQ
+// at the end of condition_variable_win.cc.
+
+#ifndef BASE_CONDITION_VARIABLE_H_
+#define BASE_CONDITION_VARIABLE_H_
+
+#include "base/basictypes.h"
+#include "base/lock.h"
+
+#if defined(XP_UNIX)
+# include <pthread.h>
+#endif
+
+#if defined(XP_WIN)
+# include <windows.h>
+#endif
+
+namespace base {
+class TimeDelta;
+}
+
+class ConditionVariable {
+ public:
+ // Construct a cv for use with ONLY one user lock.
+ explicit ConditionVariable(Lock* user_lock);
+
+ ~ConditionVariable();
+
+ // Wait() releases the caller's critical section atomically as it starts to
+ // sleep, and the reacquires it when it is signaled. The wait functions are
+ // susceptible to spurious wakeups. (See usage note 1 for more details.)
+ void Wait();
+ void TimedWait(const base::TimeDelta& max_time);
+
+ // Broadcast() revives all waiting threads. (See usage note 2 for more
+ // details.)
+ void Broadcast();
+ // Signal() revives one waiting thread.
+ void Signal();
+
+ private:
+#if defined(XP_WIN)
+ CONDITION_VARIABLE cv_;
+ SRWLOCK* const srwlock_;
+#else
+ pthread_cond_t condition_;
+ pthread_mutex_t* user_mutex_;
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
+};
+
+#endif // BASE_CONDITION_VARIABLE_H_
diff --git a/ipc/chromium/src/base/condition_variable_posix.cc b/ipc/chromium/src/base/condition_variable_posix.cc
new file mode 100644
index 0000000000..be01d3af95
--- /dev/null
+++ b/ipc/chromium/src/base/condition_variable_posix.cc
@@ -0,0 +1,110 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#include "base/condition_variable.h"
+
+#include <errno.h>
+#include <stdint.h>
+#include <sys/time.h>
+
+#include "base/lock.h"
+#include "base/logging.h"
+#include "base/time.h"
+
+ConditionVariable::ConditionVariable(Lock* user_lock)
+ : user_mutex_(user_lock->lock_.native_handle()) {
+ int rv = 0;
+ // http://crbug.com/293736
+ // On older Android platform versions, monotonic clock based absolute
+ // deadlines are supported through the non-standard
+ // pthread_cond_timedwait_monotonic_np. Newer platform versions have
+ // pthread_condattr_setclock.
+ // Mac can use relative time deadlines.
+#if !defined(XP_DARWIN) && \
+ !(defined(ANDROID) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC))
+ pthread_condattr_t attrs;
+ rv = pthread_condattr_init(&attrs);
+ DCHECK_EQ(0, rv);
+ pthread_condattr_setclock(&attrs, CLOCK_MONOTONIC);
+ rv = pthread_cond_init(&condition_, &attrs);
+ pthread_condattr_destroy(&attrs);
+#else
+ rv = pthread_cond_init(&condition_, NULL);
+#endif
+ DCHECK_EQ(0, rv);
+}
+
+ConditionVariable::~ConditionVariable() {
+#if defined(XP_DARWIN)
+ // This hack is necessary to avoid a fatal pthreads subsystem bug in the
+ // Darwin kernel. http://crbug.com/517681.
+ {
+ Lock lock;
+ AutoLock l(lock);
+ struct timespec ts;
+ ts.tv_sec = 0;
+ ts.tv_nsec = 1;
+ pthread_cond_timedwait_relative_np(&condition_, lock.lock_.native_handle(),
+ &ts);
+ }
+#endif
+
+ int rv = pthread_cond_destroy(&condition_);
+ DCHECK_EQ(0, rv);
+}
+
+void ConditionVariable::Wait() {
+ int rv = pthread_cond_wait(&condition_, user_mutex_);
+ DCHECK_EQ(0, rv);
+}
+
+void ConditionVariable::TimedWait(const base::TimeDelta& max_time) {
+ int64_t usecs = max_time.InMicroseconds();
+ struct timespec relative_time;
+ relative_time.tv_sec = usecs / base::Time::kMicrosecondsPerSecond;
+ relative_time.tv_nsec = (usecs % base::Time::kMicrosecondsPerSecond) *
+ base::Time::kNanosecondsPerMicrosecond;
+
+#if defined(XP_DARWIN)
+ int rv = pthread_cond_timedwait_relative_np(&condition_, user_mutex_,
+ &relative_time);
+#else
+ // The timeout argument to pthread_cond_timedwait is in absolute time.
+ struct timespec absolute_time;
+ struct timespec now;
+ clock_gettime(CLOCK_MONOTONIC, &now);
+ absolute_time.tv_sec = now.tv_sec;
+ absolute_time.tv_nsec = now.tv_nsec;
+
+ absolute_time.tv_sec += relative_time.tv_sec;
+ absolute_time.tv_nsec += relative_time.tv_nsec;
+ absolute_time.tv_sec +=
+ absolute_time.tv_nsec / base::Time::kNanosecondsPerSecond;
+ absolute_time.tv_nsec %= base::Time::kNanosecondsPerSecond;
+ DCHECK_GE(absolute_time.tv_sec, now.tv_sec); // Overflow paranoia
+
+# if defined(ANDROID) && defined(HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC)
+ int rv = pthread_cond_timedwait_monotonic_np(&condition_, user_mutex_,
+ &absolute_time);
+# else
+ int rv = pthread_cond_timedwait(&condition_, user_mutex_, &absolute_time);
+# endif // ANDROID && HAVE_PTHREAD_COND_TIMEDWAIT_MONOTONIC
+#endif // XP_DARWIN
+
+ // On failure, we only expect the CV to timeout. Any other error value means
+ // that we've unexpectedly woken up.
+ DCHECK(rv == 0 || rv == ETIMEDOUT);
+}
+
+void ConditionVariable::Broadcast() {
+ int rv = pthread_cond_broadcast(&condition_);
+ DCHECK_EQ(0, rv);
+}
+
+void ConditionVariable::Signal() {
+ int rv = pthread_cond_signal(&condition_);
+ DCHECK_EQ(0, rv);
+}
diff --git a/ipc/chromium/src/base/condition_variable_win.cc b/ipc/chromium/src/base/condition_variable_win.cc
new file mode 100644
index 0000000000..35d79ba2ec
--- /dev/null
+++ b/ipc/chromium/src/base/condition_variable_win.cc
@@ -0,0 +1,40 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#include "base/condition_variable.h"
+
+#include "base/lock.h"
+#include "base/logging.h"
+#include "base/time.h"
+
+ConditionVariable::ConditionVariable(Lock* user_lock)
+ : srwlock_(user_lock->lock_.native_handle()) {
+ DCHECK(user_lock);
+ InitializeConditionVariable(&cv_);
+}
+
+ConditionVariable::~ConditionVariable() = default;
+
+void ConditionVariable::Wait() {
+ TimedWait(base::TimeDelta::FromMilliseconds(INFINITE));
+}
+
+void ConditionVariable::TimedWait(const base::TimeDelta& max_time) {
+ DWORD timeout = static_cast<DWORD>(max_time.InMilliseconds());
+
+ if (!SleepConditionVariableSRW(&cv_, srwlock_, timeout, 0)) {
+ // On failure, we only expect the CV to timeout. Any other error value means
+ // that we've unexpectedly woken up.
+ // Note that WAIT_TIMEOUT != ERROR_TIMEOUT. WAIT_TIMEOUT is used with the
+ // WaitFor* family of functions as a direct return value. ERROR_TIMEOUT is
+ // used with GetLastError().
+ DCHECK_EQ(static_cast<DWORD>(ERROR_TIMEOUT), GetLastError());
+ }
+}
+
+void ConditionVariable::Broadcast() { WakeAllConditionVariable(&cv_); }
+
+void ConditionVariable::Signal() { WakeConditionVariable(&cv_); }
diff --git a/ipc/chromium/src/base/dir_reader_bsd.h b/ipc/chromium/src/base/dir_reader_bsd.h
new file mode 100644
index 0000000000..851f46a006
--- /dev/null
+++ b/ipc/chromium/src/base/dir_reader_bsd.h
@@ -0,0 +1,94 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+// derived from dir_reader_linux.h
+
+#ifndef BASE_DIR_READER_BSD_H_
+#define BASE_DIR_READER_BSD_H_
+#pragma once
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <unistd.h>
+
+#include "base/logging.h"
+#include "base/eintr_wrapper.h"
+
+// See the comments in dir_reader_posix.h about this.
+
+namespace base {
+
+class DirReaderBSD {
+ public:
+ explicit DirReaderBSD(const char* directory_path)
+#ifdef O_DIRECTORY
+ : fd_(open(directory_path, O_RDONLY | O_DIRECTORY)),
+#else
+ : fd_(open(directory_path, O_RDONLY)),
+#endif
+ offset_(0),
+ size_(0) {
+ memset(buf_, 0, sizeof(buf_));
+ }
+
+ ~DirReaderBSD() {
+ if (fd_ >= 0) {
+ if (IGNORE_EINTR(close(fd_)))
+ DLOG(ERROR) << "Failed to close directory handle";
+ }
+ }
+
+ bool IsValid() const { return fd_ >= 0; }
+
+ // Move to the next entry returning false if the iteration is complete.
+ bool Next() {
+ if (size_) {
+ struct dirent* dirent = reinterpret_cast<struct dirent*>(&buf_[offset_]);
+#ifdef __DragonFly__
+ offset_ += _DIRENT_DIRSIZ(dirent);
+#else
+ offset_ += dirent->d_reclen;
+#endif
+ }
+
+ if (offset_ != size_) return true;
+
+ const int r = getdents(fd_, buf_, sizeof(buf_));
+ if (r == 0) return false;
+ if (r == -1) {
+ DLOG(ERROR) << "getdents returned an error: " << errno;
+ return false;
+ }
+ size_ = r;
+ offset_ = 0;
+ return true;
+ }
+
+ const char* name() const {
+ if (!size_) return NULL;
+
+ const struct dirent* dirent =
+ reinterpret_cast<const struct dirent*>(&buf_[offset_]);
+ return dirent->d_name;
+ }
+
+ int fd() const { return fd_; }
+
+ static bool IsFallback() { return false; }
+
+ private:
+ const int fd_;
+ char buf_[512];
+ size_t offset_, size_;
+
+ DISALLOW_COPY_AND_ASSIGN(DirReaderBSD);
+};
+
+} // namespace base
+
+#endif // BASE_DIR_READER_BSD_H_
diff --git a/ipc/chromium/src/base/dir_reader_fallback.h b/ipc/chromium/src/base/dir_reader_fallback.h
new file mode 100644
index 0000000000..5fbf658d49
--- /dev/null
+++ b/ipc/chromium/src/base/dir_reader_fallback.h
@@ -0,0 +1,33 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#ifndef BASE_DIR_READER_FALLBACK_H_
+#define BASE_DIR_READER_FALLBACK_H_
+#pragma once
+
+namespace base {
+
+class DirReaderFallback {
+ public:
+ // Open a directory. If |IsValid| is true, then |Next| can be called to start
+ // the iteration at the beginning of the directory.
+ explicit DirReaderFallback(const char* directory_path) {}
+ // After construction, IsValid returns true iff the directory was
+ // successfully opened.
+ bool IsValid() const { return false; }
+ // Move to the next entry returning false if the iteration is complete.
+ bool Next() { return false; }
+ // Return the name of the current directory entry.
+ const char* name() { return 0; }
+ // Return the file descriptor which is being used.
+ int fd() const { return -1; }
+ // Returns true if this is a no-op fallback class (for testing).
+ static bool IsFallback() { return true; }
+};
+
+} // namespace base
+
+#endif // BASE_DIR_READER_FALLBACK_H_
diff --git a/ipc/chromium/src/base/dir_reader_linux.h b/ipc/chromium/src/base/dir_reader_linux.h
new file mode 100644
index 0000000000..a70ff3bb64
--- /dev/null
+++ b/ipc/chromium/src/base/dir_reader_linux.h
@@ -0,0 +1,95 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#ifndef BASE_DIR_READER_LINUX_H_
+#define BASE_DIR_READER_LINUX_H_
+#pragma once
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <sys/syscall.h>
+#include <unistd.h>
+
+#include "base/logging.h"
+#include "base/eintr_wrapper.h"
+
+// See the comments in dir_reader_posix.h about this.
+
+namespace base {
+
+struct linux_dirent {
+ uint64_t d_ino;
+ int64_t d_off;
+ unsigned short d_reclen;
+ unsigned char d_type;
+ char d_name[0];
+};
+
+class DirReaderLinux {
+ public:
+ explicit DirReaderLinux(const char* directory_path)
+ : fd_(open(directory_path, O_RDONLY | O_DIRECTORY)),
+ offset_(0),
+ size_(0) {
+ memset(buf_, 0, sizeof(buf_));
+ }
+
+ ~DirReaderLinux() {
+ if (fd_ >= 0) {
+ if (IGNORE_EINTR(close(fd_)))
+ DLOG(ERROR) << "Failed to close directory handle";
+ }
+ }
+
+ bool IsValid() const { return fd_ >= 0; }
+
+ // Move to the next entry returning false if the iteration is complete.
+ bool Next() {
+ if (size_) {
+ linux_dirent* dirent = reinterpret_cast<linux_dirent*>(&buf_[offset_]);
+ offset_ += dirent->d_reclen;
+ }
+
+ if (offset_ != size_) return true;
+
+ const int r = syscall(__NR_getdents64, fd_, buf_, sizeof(buf_));
+ if (r == 0) return false;
+ if (r == -1) {
+ DLOG(ERROR) << "getdents64 returned an error: " << errno;
+ return false;
+ }
+ size_ = r;
+ offset_ = 0;
+ return true;
+ }
+
+ const char* name() const {
+ if (!size_) return NULL;
+
+ const linux_dirent* dirent =
+ reinterpret_cast<const linux_dirent*>(&buf_[offset_]);
+ return dirent->d_name;
+ }
+
+ int fd() const { return fd_; }
+
+ static bool IsFallback() { return false; }
+
+ private:
+ const int fd_;
+ union {
+ linux_dirent dirent_;
+ unsigned char buf_[512];
+ };
+ size_t offset_, size_;
+
+ DISALLOW_COPY_AND_ASSIGN(DirReaderLinux);
+};
+
+} // namespace base
+
+#endif // BASE_DIR_READER_LINUX_H_
diff --git a/ipc/chromium/src/base/dir_reader_posix.h b/ipc/chromium/src/base/dir_reader_posix.h
new file mode 100644
index 0000000000..2a2aae1140
--- /dev/null
+++ b/ipc/chromium/src/base/dir_reader_posix.h
@@ -0,0 +1,45 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#ifndef BASE_DIR_READER_POSIX_H_
+#define BASE_DIR_READER_POSIX_H_
+#pragma once
+
+// This header provides a class, DirReaderPosix, which allows one to open and
+// read from directories without allocating memory. For the interface, see
+// the generic fallback in dir_reader_fallback.h.
+
+// Mac note: OS X has getdirentries, but it only works if we restrict Chrome to
+// 32-bit inodes. There is a getdirentries64 syscall in 10.6, but it's not
+// wrapped and the direct syscall interface is unstable. Using an unstable API
+// seems worse than falling back to enumerating all file descriptors so we will
+// probably never implement this on the Mac.
+
+#if defined(XP_LINUX)
+# include "base/dir_reader_linux.h"
+#elif (defined(__DragonFly__) || defined(XP_FREEBSD) || defined(XP_NETBSD) || \
+ defined(XP_OPENBSD)) && \
+ !defined(__GLIBC__)
+# include "base/dir_reader_bsd.h"
+#else
+# include "base/dir_reader_fallback.h"
+#endif
+
+namespace base {
+
+#if defined(XP_LINUX)
+typedef DirReaderLinux DirReaderPosix;
+#elif (defined(__DragonFly__) || defined(XP_FREEBSD) || defined(XP_NETBSD) || \
+ defined(XP_OPENBSD)) && \
+ !defined(__GLIBC__)
+typedef DirReaderBSD DirReaderPosix;
+#else
+typedef DirReaderFallback DirReaderPosix;
+#endif
+
+} // namespace base
+
+#endif // BASE_DIR_READER_POSIX_H_
diff --git a/ipc/chromium/src/base/eintr_wrapper.h b/ipc/chromium/src/base/eintr_wrapper.h
new file mode 100644
index 0000000000..8592efa8ce
--- /dev/null
+++ b/ipc/chromium/src/base/eintr_wrapper.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2012 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.
+
+// This provides a wrapper around system calls which may be interrupted by a
+// signal and return EINTR. See man 7 signal.
+//
+// On Windows, this wrapper macro does nothing because there are no
+// signals.
+//
+// Don't wrap close calls in HANDLE_EINTR. Use IGNORE_EINTR if the return
+// value of close is significant. See http://crbug.com/269623.
+
+#ifndef BASE_EINTR_WRAPPER_H_
+#define BASE_EINTR_WRAPPER_H_
+
+#if defined(XP_UNIX)
+
+# include <errno.h>
+
+# define HANDLE_EINTR(x) \
+ ({ \
+ decltype(x) eintr_wrapper_result; \
+ do { \
+ eintr_wrapper_result = (x); \
+ } while (eintr_wrapper_result == -1 && errno == EINTR); \
+ eintr_wrapper_result; \
+ })
+
+# define IGNORE_EINTR(x) \
+ ({ \
+ decltype(x) eintr_wrapper_result; \
+ do { \
+ eintr_wrapper_result = (x); \
+ if (eintr_wrapper_result == -1 && errno == EINTR) { \
+ eintr_wrapper_result = 0; \
+ } \
+ } while (0); \
+ eintr_wrapper_result; \
+ })
+
+# define HANDLE_RV_EINTR(x) \
+ ({ \
+ decltype(x) eintr_wrapper_result; \
+ do { \
+ eintr_wrapper_result = (x); \
+ } while (eintr_wrapper_result == EINTR); \
+ eintr_wrapper_result; \
+ })
+
+#else
+
+# define HANDLE_EINTR(x) (x)
+# define IGNORE_EINTR(x) (x)
+# define HANDLE_RV_EINTR(x) (x)
+
+#endif // XP_UNIX
+
+#endif // !BASE_EINTR_WRAPPER_H_
diff --git a/ipc/chromium/src/base/file_path.cc b/ipc/chromium/src/base/file_path.cc
new file mode 100644
index 0000000000..6796ad45d0
--- /dev/null
+++ b/ipc/chromium/src/base/file_path.cc
@@ -0,0 +1,313 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include <fstream>
+
+#include "base/file_path.h"
+#include "base/logging.h"
+
+// These includes are just for the *Hack functions, and should be removed
+// when those functions are removed.
+#include "base/string_piece.h"
+#include "base/string_util.h"
+#include "base/sys_string_conversions.h"
+
+#if defined(FILE_PATH_USES_WIN_SEPARATORS)
+const FilePath::CharType FilePath::kSeparators[] = FILE_PATH_LITERAL("\\/");
+#else // FILE_PATH_USES_WIN_SEPARATORS
+const FilePath::CharType FilePath::kSeparators[] = FILE_PATH_LITERAL("/");
+#endif // FILE_PATH_USES_WIN_SEPARATORS
+
+const FilePath::CharType FilePath::kCurrentDirectory[] = FILE_PATH_LITERAL(".");
+const FilePath::CharType FilePath::kParentDirectory[] = FILE_PATH_LITERAL("..");
+
+const FilePath::CharType FilePath::kExtensionSeparator = FILE_PATH_LITERAL('.');
+
+namespace {
+
+// If this FilePath contains a drive letter specification, returns the
+// position of the last character of the drive letter specification,
+// otherwise returns npos. This can only be true on Windows, when a pathname
+// begins with a letter followed by a colon. On other platforms, this always
+// returns npos.
+FilePath::StringType::size_type FindDriveLetter(
+ const FilePath::StringType& path) {
+#if defined(FILE_PATH_USES_DRIVE_LETTERS)
+ // This is dependent on an ASCII-based character set, but that's a
+ // reasonable assumption. iswalpha can be too inclusive here.
+ if (path.length() >= 2 && path[1] == L':' &&
+ ((path[0] >= L'A' && path[0] <= L'Z') ||
+ (path[0] >= L'a' && path[0] <= L'z'))) {
+ return 1;
+ }
+#endif // FILE_PATH_USES_DRIVE_LETTERS
+ return FilePath::StringType::npos;
+}
+
+bool IsPathAbsolute(const FilePath::StringType& path) {
+#if defined(FILE_PATH_USES_DRIVE_LETTERS)
+ FilePath::StringType::size_type letter = FindDriveLetter(path);
+ if (letter != FilePath::StringType::npos) {
+ // Look for a separator right after the drive specification.
+ return path.length() > letter + 1 &&
+ FilePath::IsSeparator(path[letter + 1]);
+ }
+ // Look for a pair of leading separators.
+ return path.length() > 1 && FilePath::IsSeparator(path[0]) &&
+ FilePath::IsSeparator(path[1]);
+#else // FILE_PATH_USES_DRIVE_LETTERS
+ // Look for a separator in the first position.
+ return path.length() > 0 && FilePath::IsSeparator(path[0]);
+#endif // FILE_PATH_USES_DRIVE_LETTERS
+}
+
+} // namespace
+
+bool FilePath::IsSeparator(CharType character) {
+ for (size_t i = 0; i < arraysize(kSeparators) - 1; ++i) {
+ if (character == kSeparators[i]) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// libgen's dirname and basename aren't guaranteed to be thread-safe and aren't
+// guaranteed to not modify their input strings, and in fact are implemented
+// differently in this regard on different platforms. Don't use them, but
+// adhere to their behavior.
+FilePath FilePath::DirName() const {
+ FilePath new_path(path_);
+ new_path.StripTrailingSeparatorsInternal();
+
+ // The drive letter, if any, always needs to remain in the output. If there
+ // is no drive letter, as will always be the case on platforms which do not
+ // support drive letters, letter will be npos, or -1, so the comparisons and
+ // resizes below using letter will still be valid.
+ StringType::size_type letter = FindDriveLetter(new_path.path_);
+
+ StringType::size_type last_separator = new_path.path_.find_last_of(
+ kSeparators, StringType::npos, arraysize(kSeparators) - 1);
+ if (last_separator == StringType::npos) {
+ // path_ is in the current directory.
+ new_path.path_.resize(letter + 1);
+ } else if (last_separator == letter + 1) {
+ // path_ is in the root directory.
+ new_path.path_.resize(letter + 2);
+ } else if (last_separator == letter + 2 &&
+ IsSeparator(new_path.path_[letter + 1])) {
+ // path_ is in "//" (possibly with a drive letter); leave the double
+ // separator intact indicating alternate root.
+ new_path.path_.resize(letter + 3);
+ } else if (last_separator != 0) {
+ // path_ is somewhere else, trim the basename.
+ new_path.path_.resize(last_separator);
+ }
+
+ new_path.StripTrailingSeparatorsInternal();
+ if (!new_path.path_.length()) new_path.path_ = kCurrentDirectory;
+
+ return new_path;
+}
+
+FilePath FilePath::BaseName() const {
+ FilePath new_path(path_);
+ new_path.StripTrailingSeparatorsInternal();
+
+ // The drive letter, if any, is always stripped.
+ StringType::size_type letter = FindDriveLetter(new_path.path_);
+ if (letter != StringType::npos) {
+ new_path.path_.erase(0, letter + 1);
+ }
+
+ // Keep everything after the final separator, but if the pathname is only
+ // one character and it's a separator, leave it alone.
+ StringType::size_type last_separator = new_path.path_.find_last_of(
+ kSeparators, StringType::npos, arraysize(kSeparators) - 1);
+ if (last_separator != StringType::npos &&
+ last_separator < new_path.path_.length() - 1) {
+ new_path.path_.erase(0, last_separator + 1);
+ }
+
+ return new_path;
+}
+
+FilePath::StringType FilePath::Extension() const {
+ // BaseName() calls StripTrailingSeparators, so cases like /foo.baz/// work.
+ StringType base = BaseName().value();
+
+ // Special case "." and ".."
+ if (base == kCurrentDirectory || base == kParentDirectory)
+ return StringType();
+
+ const StringType::size_type last_dot = base.rfind(kExtensionSeparator);
+ if (last_dot == StringType::npos) return StringType();
+ return StringType(base, last_dot);
+}
+
+FilePath FilePath::RemoveExtension() const {
+ StringType ext = Extension();
+ // It's important to check Extension() since that verifies that the
+ // kExtensionSeparator actually appeared in the last path component.
+ if (ext.empty()) return FilePath(path_);
+ // Since Extension() verified that the extension is in fact in the last path
+ // component, this substr will effectively strip trailing separators.
+ const StringType::size_type last_dot = path_.rfind(kExtensionSeparator);
+ return FilePath(path_.substr(0, last_dot));
+}
+
+FilePath FilePath::InsertBeforeExtension(const StringType& suffix) const {
+ if (suffix.empty()) return FilePath(path_);
+
+ if (path_.empty()) return FilePath();
+
+ StringType base = BaseName().value();
+ if (base.empty()) return FilePath();
+ if (*(base.end() - 1) == kExtensionSeparator) {
+ // Special case "." and ".."
+ if (base == kCurrentDirectory || base == kParentDirectory) {
+ return FilePath();
+ }
+ }
+
+ StringType ext = Extension();
+ StringType ret = RemoveExtension().value();
+ ret.append(suffix);
+ ret.append(ext);
+ return FilePath(ret);
+}
+
+FilePath FilePath::ReplaceExtension(const StringType& extension) const {
+ if (path_.empty()) return FilePath();
+
+ StringType base = BaseName().value();
+ if (base.empty()) return FilePath();
+ if (*(base.end() - 1) == kExtensionSeparator) {
+ // Special case "." and ".."
+ if (base == kCurrentDirectory || base == kParentDirectory) {
+ return FilePath();
+ }
+ }
+
+ FilePath no_ext = RemoveExtension();
+ // If the new extension is "" or ".", then just remove the current extension.
+ if (extension.empty() || extension == StringType(1, kExtensionSeparator))
+ return no_ext;
+
+ StringType str = no_ext.value();
+ if (extension[0] != kExtensionSeparator) str.append(1, kExtensionSeparator);
+ str.append(extension);
+ return FilePath(str);
+}
+
+FilePath FilePath::Append(const StringType& component) const {
+ DCHECK(!IsPathAbsolute(component));
+ if (path_.compare(kCurrentDirectory) == 0) {
+ // Append normally doesn't do any normalization, but as a special case,
+ // when appending to kCurrentDirectory, just return a new path for the
+ // component argument. Appending component to kCurrentDirectory would
+ // serve no purpose other than needlessly lengthening the path, and
+ // it's likely in practice to wind up with FilePath objects containing
+ // only kCurrentDirectory when calling DirName on a single relative path
+ // component.
+ return FilePath(component);
+ }
+
+ FilePath new_path(path_);
+ new_path.StripTrailingSeparatorsInternal();
+
+ // Don't append a separator if the path is empty (indicating the current
+ // directory) or if the path component is empty (indicating nothing to
+ // append).
+ if (component.length() > 0 && new_path.path_.length() > 0) {
+ // Don't append a separator if the path still ends with a trailing
+ // separator after stripping (indicating the root directory).
+ if (!IsSeparator(new_path.path_[new_path.path_.length() - 1])) {
+ // Don't append a separator if the path is just a drive letter.
+ if (FindDriveLetter(new_path.path_) + 1 != new_path.path_.length()) {
+ new_path.path_.append(1, kSeparators[0]);
+ }
+ }
+ }
+
+ new_path.path_.append(component);
+ return new_path;
+}
+
+FilePath FilePath::Append(const FilePath& component) const {
+ return Append(component.value());
+}
+
+FilePath FilePath::AppendASCII(const std::string& component) const {
+ DCHECK(IsStringASCII(component));
+#if defined(XP_WIN)
+ return Append(ASCIIToWide(component));
+#else
+ return Append(component);
+#endif
+}
+
+bool FilePath::IsAbsolute() const { return IsPathAbsolute(path_); }
+
+#if defined(XP_UNIX)
+// See file_path.h for a discussion of the encoding of paths on POSIX
+// platforms. These *Hack() functions are not quite correct, but they're
+// only temporary while we fix the remainder of the code.
+// Remember to remove the #includes at the top when you remove these.
+
+// static
+FilePath FilePath::FromWStringHack(const std::wstring& wstring) {
+ return FilePath(base::SysWideToNativeMB(wstring));
+}
+std::wstring FilePath::ToWStringHack() const {
+ return base::SysNativeMBToWide(path_);
+}
+#else
+// static
+FilePath FilePath::FromWStringHack(const std::wstring& wstring) {
+ return FilePath(wstring);
+}
+std::wstring FilePath::ToWStringHack() const { return path_; }
+#endif
+
+void FilePath::OpenInputStream(std::ifstream& stream) const {
+ stream.open(
+#ifndef __MINGW32__
+ path_.c_str(),
+#else
+ base::SysWideToNativeMB(path_).c_str(),
+#endif
+ std::ios::in | std::ios::binary);
+}
+
+FilePath FilePath::StripTrailingSeparators() const {
+ FilePath new_path(path_);
+ new_path.StripTrailingSeparatorsInternal();
+
+ return new_path;
+}
+
+void FilePath::StripTrailingSeparatorsInternal() {
+ // If there is no drive letter, start will be 1, which will prevent stripping
+ // the leading separator if there is only one separator. If there is a drive
+ // letter, start will be set appropriately to prevent stripping the first
+ // separator following the drive letter, if a separator immediately follows
+ // the drive letter.
+ StringType::size_type start = FindDriveLetter(path_) + 2;
+
+ StringType::size_type last_stripped = StringType::npos;
+ for (StringType::size_type pos = path_.length();
+ pos > start && IsSeparator(path_[pos - 1]); --pos) {
+ // If the string only has two separators and they're at the beginning,
+ // don't strip them, unless the string began with more than two separators.
+ if (pos != start + 1 || last_stripped == start + 2 ||
+ !IsSeparator(path_[start - 1])) {
+ path_.resize(pos - 1);
+ last_stripped = pos;
+ }
+ }
+}
diff --git a/ipc/chromium/src/base/file_path.h b/ipc/chromium/src/base/file_path.h
new file mode 100644
index 0000000000..3551fba6a9
--- /dev/null
+++ b/ipc/chromium/src/base/file_path.h
@@ -0,0 +1,248 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+// FilePath is a container for pathnames stored in a platform's native string
+// type, providing containers for manipulation in according with the
+// platform's conventions for pathnames. It supports the following path
+// types:
+//
+// POSIX Windows
+// --------------- ----------------------------------
+// Fundamental type char[] wchar_t[]
+// Encoding unspecified* UTF-16
+// Separator / \, tolerant of /
+// Drive letters no case-insensitive A-Z followed by :
+// Alternate root // (surprise!) \\, for UNC paths
+//
+// * The encoding need not be specified on POSIX systems, although some
+// POSIX-compliant systems do specify an encoding. Mac OS X uses UTF-8.
+// Linux does not specify an encoding, but in practice, the locale's
+// character set may be used.
+//
+// FilePath objects are intended to be used anywhere paths are. An
+// application may pass FilePath objects around internally, masking the
+// underlying differences between systems, only differing in implementation
+// where interfacing directly with the system. For example, a single
+// OpenFile(const FilePath &) function may be made available, allowing all
+// callers to operate without regard to the underlying implementation. On
+// POSIX-like platforms, OpenFile might wrap fopen, and on Windows, it might
+// wrap _wfopen_s, perhaps both by calling file_path.value().c_str(). This
+// allows each platform to pass pathnames around without requiring conversions
+// between encodings, which has an impact on performance, but more imporantly,
+// has an impact on correctness on platforms that do not have well-defined
+// encodings for pathnames.
+//
+// Several methods are available to perform common operations on a FilePath
+// object, such as determining the parent directory (DirName), isolating the
+// final path component (BaseName), and appending a relative pathname string
+// to an existing FilePath object (Append). These methods are highly
+// recommended over attempting to split and concatenate strings directly.
+// These methods are based purely on string manipulation and knowledge of
+// platform-specific pathname conventions, and do not consult the filesystem
+// at all, making them safe to use without fear of blocking on I/O operations.
+// These methods do not function as mutators but instead return distinct
+// instances of FilePath objects, and are therefore safe to use on const
+// objects. The objects themselves are safe to share between threads.
+//
+// To aid in initialization of FilePath objects from string literals, a
+// FILE_PATH_LITERAL macro is provided, which accounts for the difference
+// between char[]-based pathnames on POSIX systems and wchar_t[]-based
+// pathnames on Windows.
+//
+// Because a FilePath object should not be instantiated at the global scope,
+// instead, use a FilePath::CharType[] and initialize it with
+// FILE_PATH_LITERAL. At runtime, a FilePath object can be created from the
+// character array. Example:
+//
+// | const FilePath::CharType kLogFileName[] = FILE_PATH_LITERAL("log.txt");
+// |
+// | void Function() {
+// | FilePath log_file_path(kLogFileName);
+// | [...]
+// | }
+
+#ifndef BASE_FILE_PATH_H_
+#define BASE_FILE_PATH_H_
+
+#include <string>
+
+#include "base/basictypes.h"
+#include "base/compiler_specific.h"
+
+// Windows-style drive letter support and pathname separator characters can be
+// enabled and disabled independently, to aid testing. These #defines are
+// here so that the same setting can be used in both the implementation and
+// in the unit test.
+#if defined(XP_WIN)
+# define FILE_PATH_USES_DRIVE_LETTERS
+# define FILE_PATH_USES_WIN_SEPARATORS
+#endif // XP_WIN
+
+// An abstraction to isolate users from the differences between native
+// pathnames on different platforms.
+class FilePath {
+ public:
+#if defined(XP_UNIX)
+ // On most platforms, native pathnames are char arrays, and the encoding
+ // may or may not be specified. On Mac OS X, native pathnames are encoded
+ // in UTF-8.
+ typedef std::string StringType;
+#else
+ // On Windows, for Unicode-aware applications, native pathnames are wchar_t
+ // arrays encoded in UTF-16.
+ typedef std::wstring StringType;
+#endif
+
+ typedef StringType::value_type CharType;
+
+ // Null-terminated array of separators used to separate components in
+ // hierarchical paths. Each character in this array is a valid separator,
+ // but kSeparators[0] is treated as the canonical separator and will be used
+ // when composing pathnames.
+ static const CharType kSeparators[];
+
+ // A special path component meaning "this directory."
+ static const CharType kCurrentDirectory[];
+
+ // A special path component meaning "the parent directory."
+ static const CharType kParentDirectory[];
+
+ // The character used to identify a file extension.
+ static const CharType kExtensionSeparator;
+
+ FilePath() {}
+ FilePath(const FilePath& that) : path_(that.path_) {}
+ explicit FilePath(const StringType& path) : path_(path) {}
+
+#if defined(XP_WIN)
+ explicit FilePath(const wchar_t* path) : path_(path) {}
+#endif
+
+ FilePath& operator=(const FilePath& that) {
+ path_ = that.path_;
+ return *this;
+ }
+
+ bool operator==(const FilePath& that) const { return path_ == that.path_; }
+
+ bool operator!=(const FilePath& that) const { return path_ != that.path_; }
+
+ // Required for some STL containers and operations
+ bool operator<(const FilePath& that) const { return path_ < that.path_; }
+
+ const StringType& value() const { return path_; }
+
+ bool empty() const { return path_.empty(); }
+
+ // Returns true if |character| is in kSeparators.
+ static bool IsSeparator(CharType character);
+
+ // Returns a FilePath corresponding to the directory containing the path
+ // named by this object, stripping away the file component. If this object
+ // only contains one component, returns a FilePath identifying
+ // kCurrentDirectory. If this object already refers to the root directory,
+ // returns a FilePath identifying the root directory.
+ FilePath DirName() const;
+
+ // Returns a FilePath corresponding to the last path component of this
+ // object, either a file or a directory. If this object already refers to
+ // the root directory, returns a FilePath identifying the root directory;
+ // this is the only situation in which BaseName will return an absolute path.
+ FilePath BaseName() const;
+
+ // Returns ".jpg" for path "C:\pics\jojo.jpg", or an empty string if
+ // the file has no extension. If non-empty, Extension() will always start
+ // with precisely one ".". The following code should always work regardless
+ // of the value of path.
+ // new_path = path.RemoveExtension().value().append(path.Extension());
+ // ASSERT(new_path == path.value());
+ // NOTE: this is different from the original file_util implementation which
+ // returned the extension without a leading "." ("jpg" instead of ".jpg")
+ StringType Extension() const;
+
+ // Returns "C:\pics\jojo" for path "C:\pics\jojo.jpg"
+ // NOTE: this is slightly different from the similar file_util implementation
+ // which returned simply 'jojo'.
+ FilePath RemoveExtension() const;
+
+ // Inserts |suffix| after the file name portion of |path| but before the
+ // extension. Returns "" if BaseName() == "." or "..".
+ // Examples:
+ // path == "C:\pics\jojo.jpg" suffix == " (1)", returns "C:\pics\jojo (1).jpg"
+ // path == "jojo.jpg" suffix == " (1)", returns "jojo (1).jpg"
+ // path == "C:\pics\jojo" suffix == " (1)", returns "C:\pics\jojo (1)"
+ // path == "C:\pics.old\jojo" suffix == " (1)", returns "C:\pics.old\jojo (1)"
+ FilePath InsertBeforeExtension(const StringType& suffix) const;
+
+ // Replaces the extension of |file_name| with |extension|. If |file_name|
+ // does not have an extension, them |extension| is added. If |extension| is
+ // empty, then the extension is removed from |file_name|.
+ // Returns "" if BaseName() == "." or "..".
+ FilePath ReplaceExtension(const StringType& extension) const;
+
+ // Returns a FilePath by appending a separator and the supplied path
+ // component to this object's path. Append takes care to avoid adding
+ // excessive separators if this object's path already ends with a separator.
+ // If this object's path is kCurrentDirectory, a new FilePath corresponding
+ // only to |component| is returned. |component| must be a relative path;
+ // it is an error to pass an absolute path.
+ FilePath Append(const StringType& component) const WARN_UNUSED_RESULT;
+ FilePath Append(const FilePath& component) const WARN_UNUSED_RESULT;
+
+ // Although Windows StringType is std::wstring, since the encoding it uses for
+ // paths is well defined, it can handle ASCII path components as well.
+ // Mac uses UTF8, and since ASCII is a subset of that, it works there as well.
+ // On Linux, although it can use any 8-bit encoding for paths, we assume that
+ // ASCII is a valid subset, regardless of the encoding, since many operating
+ // system paths will always be ASCII.
+ FilePath AppendASCII(const std::string& component) const WARN_UNUSED_RESULT;
+
+ // Returns true if this FilePath contains an absolute path. On Windows, an
+ // absolute path begins with either a drive letter specification followed by
+ // a separator character, or with two separator characters. On POSIX
+ // platforms, an absolute path begins with a separator character.
+ bool IsAbsolute() const;
+
+ // Returns a copy of this FilePath that does not end with a trailing
+ // separator.
+ FilePath StripTrailingSeparators() const;
+
+ // Calls open on given ifstream instance
+ void OpenInputStream(std::ifstream& stream) const;
+
+ // Older Chromium code assumes that paths are always wstrings.
+ // This function converts a wstring to a FilePath, and is useful to smooth
+ // porting that old code to the FilePath API.
+ // It has "Hack" in its name so people feel bad about using it.
+ // TODO(port): remove these functions.
+ static FilePath FromWStringHack(const std::wstring& wstring);
+
+ // Older Chromium code assumes that paths are always wstrings.
+ // This function produces a wstring from a FilePath, and is useful to smooth
+ // porting that old code to the FilePath API.
+ // It has "Hack" in its name so people feel bad about using it.
+ // TODO(port): remove these functions.
+ std::wstring ToWStringHack() const;
+
+ private:
+ // Remove trailing separators from this object. If the path is absolute, it
+ // will never be stripped any more than to refer to the absolute root
+ // directory, so "////" will become "/", not "". A leading pair of
+ // separators is never stripped, to support alternate roots. This is used to
+ // support UNC paths on Windows.
+ void StripTrailingSeparatorsInternal();
+
+ StringType path_;
+};
+
+// Macros for string literal initialization of FilePath::CharType[].
+#if defined(XP_UNIX)
+# define FILE_PATH_LITERAL(x) x
+#else
+# define FILE_PATH_LITERAL(x) L##x
+#endif
+
+#endif // BASE_FILE_PATH_H_
diff --git a/ipc/chromium/src/base/histogram.cc b/ipc/chromium/src/base/histogram.cc
new file mode 100644
index 0000000000..1ddb788b41
--- /dev/null
+++ b/ipc/chromium/src/base/histogram.cc
@@ -0,0 +1,638 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+// Histogram is an object that aggregates statistics, and can summarize them in
+// various forms, including ASCII graphical, HTML, and numerically (as a
+// vector of numbers corresponding to each of the aggregating buckets).
+// See header file for details and examples.
+
+#include "base/histogram.h"
+
+#include <math.h>
+
+#include <algorithm>
+#include <string>
+
+#include "base/logging.h"
+#include "base/pickle.h"
+#include "base/string_util.h"
+#include "base/logging.h"
+
+namespace base {
+
+#define CHECK_GT DCHECK_GT
+#define CHECK_LT DCHECK_LT
+
+// Static table of checksums for all possible 8 bit bytes.
+const uint32_t Histogram::kCrcTable[256] = {
+ 0x0, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x76dc419L,
+ 0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0xedb8832L, 0x79dcb8a4L,
+ 0xe0d5e91eL, 0x97d2d988L, 0x9b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
+ 0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
+ 0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
+ 0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
+ 0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
+ 0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
+ 0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
+ 0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
+ 0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
+ 0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
+ 0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
+ 0x1db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x6b6b51fL,
+ 0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0xf00f934L, 0x9609a88eL,
+ 0xe10e9818L, 0x7f6a0dbbL, 0x86d3d2dL, 0x91646c97L, 0xe6635c01L,
+ 0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
+ 0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
+ 0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
+ 0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
+ 0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
+ 0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
+ 0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
+ 0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
+ 0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
+ 0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
+ 0x3b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x4db2615L,
+ 0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0xd6d6a3eL, 0x7a6a5aa8L,
+ 0xe40ecf0bL, 0x9309ff9dL, 0xa00ae27L, 0x7d079eb1L, 0xf00f9344L,
+ 0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
+ 0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
+ 0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
+ 0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
+ 0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
+ 0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
+ 0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
+ 0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
+ 0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
+ 0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
+ 0x26d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x5005713L,
+ 0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0xcb61b38L, 0x92d28e9bL,
+ 0xe5d5be0dL, 0x7cdcefb7L, 0xbdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
+ 0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
+ 0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
+ 0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
+ 0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
+ 0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
+ 0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
+ 0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
+ 0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
+ 0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
+ 0x2d02ef8dL,
+};
+
+typedef Histogram::Count Count;
+
+// static
+const size_t Histogram::kBucketCount_MAX = 16384u;
+
+Histogram* Histogram::FactoryGet(Sample minimum, Sample maximum,
+ size_t bucket_count, Flags flags,
+ const int* buckets) {
+ DCHECK(buckets);
+ Histogram* histogram(NULL);
+
+ // Defensive code.
+ if (minimum < 1) minimum = 1;
+ if (maximum > kSampleType_MAX - 1) maximum = kSampleType_MAX - 1;
+
+ histogram = new Histogram(minimum, maximum, bucket_count);
+ histogram->InitializeBucketRangeFromData(buckets);
+ histogram->SetFlags(flags);
+
+ DCHECK_EQ(HISTOGRAM, histogram->histogram_type());
+ DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count));
+ return histogram;
+}
+
+void Histogram::Add(int value) {
+ if (value > kSampleType_MAX - 1) value = kSampleType_MAX - 1;
+ if (value < 0) value = 0;
+ size_t index = BucketIndex(value);
+ DCHECK_GE(value, ranges(index));
+ DCHECK_LT(value, ranges(index + 1));
+ Accumulate(value, 1, index);
+}
+
+void Histogram::Subtract(int value) {
+ if (value > kSampleType_MAX - 1) value = kSampleType_MAX - 1;
+ if (value < 0) value = 0;
+ size_t index = BucketIndex(value);
+ DCHECK_GE(value, ranges(index));
+ DCHECK_LT(value, ranges(index + 1));
+ Accumulate(value, -1, index);
+}
+
+void Histogram::AddBoolean(bool value) { DCHECK(false); }
+
+void Histogram::AddSampleSet(const SampleSet& sample) { sample_.Add(sample); }
+
+void Histogram::Clear() { sample_.Clear(); }
+
+void Histogram::SetRangeDescriptions(const DescriptionPair descriptions[]) {
+ DCHECK(false);
+}
+
+//------------------------------------------------------------------------------
+// Methods for the validating a sample and a related histogram.
+//------------------------------------------------------------------------------
+
+Histogram::Inconsistencies Histogram::FindCorruption(
+ const SampleSet& snapshot) const {
+ int inconsistencies = NO_INCONSISTENCIES;
+ Sample previous_range = -1; // Bottom range is always 0.
+ int64_t count = 0;
+ for (size_t index = 0; index < bucket_count(); ++index) {
+ count += snapshot.counts(index);
+ int new_range = ranges(index);
+ if (previous_range >= new_range) inconsistencies |= BUCKET_ORDER_ERROR;
+ previous_range = new_range;
+ }
+
+ if (!HasValidRangeChecksum()) inconsistencies |= RANGE_CHECKSUM_ERROR;
+
+ int64_t delta64 = snapshot.redundant_count() - count;
+ if (delta64 != 0) {
+ int delta = static_cast<int>(delta64);
+ if (delta != delta64) delta = INT_MAX; // Flag all giant errors as INT_MAX.
+ // Since snapshots of histograms are taken asynchronously relative to
+ // sampling (and snapped from different threads), it is pretty likely that
+ // we'll catch a redundant count that doesn't match the sample count. We
+ // allow for a certain amount of slop before flagging this as an
+ // inconsistency. Even with an inconsistency, we'll snapshot it again (for
+ // UMA in about a half hour, so we'll eventually get the data, if it was
+ // not the result of a corruption. If histograms show that 1 is "too tight"
+ // then we may try to use 2 or 3 for this slop value.
+ const int kCommonRaceBasedCountMismatch = 1;
+ if (delta > 0) {
+ if (delta > kCommonRaceBasedCountMismatch)
+ inconsistencies |= COUNT_HIGH_ERROR;
+ } else {
+ DCHECK_GT(0, delta);
+ if (-delta > kCommonRaceBasedCountMismatch)
+ inconsistencies |= COUNT_LOW_ERROR;
+ }
+ }
+ return static_cast<Inconsistencies>(inconsistencies);
+}
+
+Histogram::ClassType Histogram::histogram_type() const { return HISTOGRAM; }
+
+Histogram::Sample Histogram::ranges(size_t i) const { return ranges_[i]; }
+
+size_t Histogram::bucket_count() const { return bucket_count_; }
+
+Histogram::SampleSet Histogram::SnapshotSample() const {
+ return sample_.Clone();
+}
+
+bool Histogram::HasConstructorArguments(Sample minimum, Sample maximum,
+ size_t bucket_count) {
+ return ((minimum == declared_min_) && (maximum == declared_max_) &&
+ (bucket_count == bucket_count_));
+}
+
+bool Histogram::HasConstructorTimeDeltaArguments(TimeDelta minimum,
+ TimeDelta maximum,
+ size_t bucket_count) {
+ return ((minimum.InMilliseconds() == declared_min_) &&
+ (maximum.InMilliseconds() == declared_max_) &&
+ (bucket_count == bucket_count_));
+}
+
+bool Histogram::HasValidRangeChecksum() const {
+ return CalculateRangeChecksum() == range_checksum_;
+}
+
+size_t Histogram::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) {
+ size_t n = 0;
+ n += aMallocSizeOf(this);
+ n += sample_.SizeOfExcludingThis(aMallocSizeOf);
+ return n;
+}
+
+size_t Histogram::SampleSet::SizeOfExcludingThis(
+ mozilla::MallocSizeOf aMallocSizeOf) {
+ return counts_.ShallowSizeOfExcludingThis(aMallocSizeOf);
+}
+
+Histogram::Histogram(Sample minimum, Sample maximum, size_t bucket_count)
+ : declared_min_(minimum),
+ declared_max_(maximum),
+ bucket_count_(bucket_count),
+ flags_(kNoFlags),
+ range_checksum_(0) {
+ Initialize();
+}
+
+Histogram::Histogram(TimeDelta minimum, TimeDelta maximum, size_t bucket_count)
+ : declared_min_(static_cast<int>(minimum.InMilliseconds())),
+ declared_max_(static_cast<int>(maximum.InMilliseconds())),
+ bucket_count_(bucket_count),
+ flags_(kNoFlags),
+ range_checksum_(0) {
+ Initialize();
+}
+
+Histogram::~Histogram() {
+ // Just to make sure most derived class did this properly...
+ DCHECK(ValidateBucketRanges());
+}
+
+void Histogram::InitializeBucketRangeFromData(const int* buckets) {
+ ranges_ = buckets;
+ ResetRangeChecksum();
+ DCHECK(ValidateBucketRanges());
+}
+
+bool Histogram::PrintEmptyBucket(size_t index) const { return true; }
+
+size_t Histogram::BucketIndex(Sample value) const {
+ // Use simple binary search. This is very general, but there are better
+ // approaches if we knew that the buckets were linearly distributed.
+ DCHECK_LE(ranges(0), value);
+ DCHECK_GT(ranges(bucket_count()), value);
+ size_t under = 0;
+ size_t over = bucket_count();
+ size_t mid;
+
+ do {
+ DCHECK_GE(over, under);
+ mid = under + (over - under) / 2;
+ if (mid == under) break;
+ if (ranges(mid) <= value)
+ under = mid;
+ else
+ over = mid;
+ } while (true);
+
+ DCHECK_LE(ranges(mid), value);
+ CHECK_GT(ranges(mid + 1), value);
+ return mid;
+}
+
+// Use the actual bucket widths (like a linear histogram) until the widths get
+// over some transition value, and then use that transition width. Exponentials
+// get so big so fast (and we don't expect to see a lot of entries in the large
+// buckets), so we need this to make it possible to see what is going on and
+// not have 0-graphical-height buckets.
+double Histogram::GetBucketSize(Count current, size_t i) const {
+ DCHECK_GT(ranges(i + 1), ranges(i));
+ static const double kTransitionWidth = 5;
+ double denominator = ranges(i + 1) - ranges(i);
+ if (denominator > kTransitionWidth)
+ denominator = kTransitionWidth; // Stop trying to normalize.
+ return current / denominator;
+}
+
+void Histogram::ResetRangeChecksum() {
+ range_checksum_ = CalculateRangeChecksum();
+}
+
+const std::string Histogram::GetAsciiBucketRange(size_t i) const {
+ std::string result;
+ if (kHexRangePrintingFlag & flags_)
+ StringAppendF(&result, "%#x", ranges(i));
+ else
+ StringAppendF(&result, "%d", ranges(i));
+ return result;
+}
+
+// Update histogram data with new sample.
+void Histogram::Accumulate(Sample value, Count count, size_t index) {
+ sample_.Accumulate(value, count, index);
+}
+
+bool Histogram::ValidateBucketRanges() const {
+ // Standard assertions that all bucket ranges should satisfy.
+ DCHECK_EQ(0, ranges_[bucket_count_ + 1]);
+ DCHECK_EQ(0, ranges_[0]);
+ DCHECK_EQ(declared_min(), ranges_[1]);
+ DCHECK_EQ(declared_max(), ranges_[bucket_count_ - 1]);
+ DCHECK_EQ(kSampleType_MAX, ranges_[bucket_count_]);
+ return true;
+}
+
+uint32_t Histogram::CalculateRangeChecksum() const {
+ DCHECK_EQ(0, ranges_[bucket_count_ + 1]);
+ uint32_t checksum =
+ static_cast<uint32_t>(bucket_count_ + 1); // Seed checksum.
+ for (size_t index = 0; index < bucket_count(); ++index)
+ checksum = Crc32(checksum, ranges(index));
+ return checksum;
+}
+
+void Histogram::Initialize() {
+ sample_.Resize(*this);
+ if (declared_min_ < 1) declared_min_ = 1;
+ if (declared_max_ > kSampleType_MAX - 1) declared_max_ = kSampleType_MAX - 1;
+ DCHECK_LE(declared_min_, declared_max_);
+ DCHECK_GT(bucket_count_, 1u);
+ CHECK_LT(bucket_count_, kBucketCount_MAX);
+ size_t maximal_bucket_count = declared_max_ - declared_min_ + 2;
+ DCHECK_LE(bucket_count_, maximal_bucket_count);
+}
+
+// We generate the CRC-32 using the low order bits to select whether to XOR in
+// the reversed polynomial 0xedb88320L. This is nice and simple, and allows us
+// to keep the quotient in a uint32_t. Since we're not concerned about the
+// nature of corruptions (i.e., we don't care about bit sequencing, since we are
+// handling memory changes, which are more grotesque) so we don't bother to
+// get the CRC correct for big-endian vs little-ending calculations. All we
+// need is a nice hash, that tends to depend on all the bits of the sample, with
+// very little chance of changes in one place impacting changes in another
+// place.
+uint32_t Histogram::Crc32(uint32_t sum, Histogram::Sample range) {
+ const bool kUseRealCrc = true; // TODO(jar): Switch to false and watch stats.
+ if (kUseRealCrc) {
+ union {
+ Histogram::Sample range;
+ unsigned char bytes[sizeof(Histogram::Sample)];
+ } converter;
+ converter.range = range;
+ for (size_t i = 0; i < sizeof(converter); ++i)
+ sum = kCrcTable[(sum & 0xff) ^ converter.bytes[i]] ^ (sum >> 8);
+ } else {
+ // Use hash techniques provided in ReallyFastHash, except we don't care
+ // about "avalanching" (which would worsten the hash, and add collisions),
+ // and we don't care about edge cases since we have an even number of bytes.
+ union {
+ Histogram::Sample range;
+ uint16_t ints[sizeof(Histogram::Sample) / 2];
+ } converter;
+ DCHECK_EQ(sizeof(Histogram::Sample), sizeof(converter));
+ converter.range = range;
+ sum += converter.ints[0];
+ sum = (sum << 16) ^ sum ^ (static_cast<uint32_t>(converter.ints[1]) << 11);
+ sum += sum >> 11;
+ }
+ return sum;
+}
+
+//------------------------------------------------------------------------------
+// Private methods
+
+double Histogram::GetPeakBucketSize(const SampleSet& snapshot) const {
+ double max = 0;
+ for (size_t i = 0; i < bucket_count(); ++i) {
+ double current_size = GetBucketSize(snapshot.counts(i), i);
+ if (current_size > max) max = current_size;
+ }
+ return max;
+}
+
+//------------------------------------------------------------------------------
+// Methods for the Histogram::SampleSet class
+//------------------------------------------------------------------------------
+
+Histogram::SampleSet::SampleSet() : sum_(0), redundant_count_(0) {}
+
+Histogram::SampleSet::~SampleSet() = default;
+
+void Histogram::SampleSet::Resize(const Histogram& histogram) {
+ size_t oldSize = counts_.Length();
+ counts_.SetLength(histogram.bucket_count());
+
+ for (size_t i = oldSize; i < histogram.bucket_count(); ++i) counts_[i] = 0;
+}
+
+void Histogram::SampleSet::Accumulate(Sample value, Count count, size_t index) {
+ DCHECK(count == 1 || count == -1);
+ counts_[index] += count;
+ redundant_count_ += count;
+ sum_ += static_cast<int64_t>(count) * value;
+ DCHECK_GE(counts_[index], 0);
+ DCHECK_GE(sum_, 0);
+ DCHECK_GE(redundant_count_, 0);
+}
+
+Count Histogram::SampleSet::TotalCount() const {
+ Count total = 0;
+ for (Counts::const_iterator it = counts_.begin(); it != counts_.end(); ++it) {
+ total += *it;
+ }
+ return total;
+}
+
+void Histogram::SampleSet::Add(const SampleSet& other) {
+ DCHECK_EQ(counts_.Length(), other.counts_.Length());
+ sum_ += other.sum_;
+ redundant_count_ += other.redundant_count_;
+ for (size_t index = 0; index < counts_.Length(); ++index)
+ counts_[index] += other.counts_[index];
+}
+
+//------------------------------------------------------------------------------
+// LinearHistogram: This histogram uses a traditional set of evenly spaced
+// buckets.
+//------------------------------------------------------------------------------
+
+LinearHistogram::~LinearHistogram() = default;
+
+Histogram* LinearHistogram::FactoryGet(Sample minimum, Sample maximum,
+ size_t bucket_count, Flags flags,
+ const int* buckets) {
+ Histogram* histogram(NULL);
+
+ if (minimum < 1) minimum = 1;
+ if (maximum > kSampleType_MAX - 1) maximum = kSampleType_MAX - 1;
+
+ LinearHistogram* linear_histogram =
+ new LinearHistogram(minimum, maximum, bucket_count);
+ linear_histogram->InitializeBucketRangeFromData(buckets);
+ linear_histogram->SetFlags(flags);
+ histogram = linear_histogram;
+
+ DCHECK_EQ(LINEAR_HISTOGRAM, histogram->histogram_type());
+ DCHECK(histogram->HasConstructorArguments(minimum, maximum, bucket_count));
+ return histogram;
+}
+
+Histogram::ClassType LinearHistogram::histogram_type() const {
+ return LINEAR_HISTOGRAM;
+}
+
+void LinearHistogram::Accumulate(Sample value, Count count, size_t index) {
+ sample_.Accumulate(value, count, index);
+}
+
+void LinearHistogram::SetRangeDescriptions(
+ const DescriptionPair descriptions[]) {
+ for (int i = 0; descriptions[i].description; ++i) {
+ bucket_description_[descriptions[i].sample] = descriptions[i].description;
+ }
+}
+
+LinearHistogram::LinearHistogram(Sample minimum, Sample maximum,
+ size_t bucket_count)
+ : Histogram(minimum >= 1 ? minimum : 1, maximum, bucket_count) {}
+
+LinearHistogram::LinearHistogram(TimeDelta minimum, TimeDelta maximum,
+ size_t bucket_count)
+ : Histogram(minimum >= TimeDelta::FromMilliseconds(1)
+ ? minimum
+ : TimeDelta::FromMilliseconds(1),
+ maximum, bucket_count) {}
+
+double LinearHistogram::GetBucketSize(Count current, size_t i) const {
+ DCHECK_GT(ranges(i + 1), ranges(i));
+ // Adjacent buckets with different widths would have "surprisingly" many (few)
+ // samples in a histogram if we didn't normalize this way.
+ double denominator = ranges(i + 1) - ranges(i);
+ return current / denominator;
+}
+
+const std::string LinearHistogram::GetAsciiBucketRange(size_t i) const {
+ int range = ranges(i);
+ BucketDescriptionMap::const_iterator it = bucket_description_.find(range);
+ if (it == bucket_description_.end()) return Histogram::GetAsciiBucketRange(i);
+ return it->second;
+}
+
+bool LinearHistogram::PrintEmptyBucket(size_t index) const {
+ return bucket_description_.find(ranges(index)) == bucket_description_.end();
+}
+
+//------------------------------------------------------------------------------
+// This section provides implementation for BooleanHistogram.
+//------------------------------------------------------------------------------
+
+Histogram* BooleanHistogram::FactoryGet(Flags flags, const int* buckets) {
+ Histogram* histogram(NULL);
+
+ BooleanHistogram* tentative_histogram = new BooleanHistogram();
+ tentative_histogram->InitializeBucketRangeFromData(buckets);
+ tentative_histogram->SetFlags(flags);
+ histogram = tentative_histogram;
+
+ DCHECK_EQ(BOOLEAN_HISTOGRAM, histogram->histogram_type());
+ return histogram;
+}
+
+Histogram::ClassType BooleanHistogram::histogram_type() const {
+ return BOOLEAN_HISTOGRAM;
+}
+
+void BooleanHistogram::AddBoolean(bool value) { Add(value ? 1 : 0); }
+
+BooleanHistogram::BooleanHistogram() : LinearHistogram(1, 2, 3) {}
+
+void BooleanHistogram::Accumulate(Sample value, Count count, size_t index) {
+ // Callers will have computed index based on the non-booleanified value.
+ // So we need to adjust the index manually.
+ LinearHistogram::Accumulate(!!value, count, value ? 1 : 0);
+}
+
+//------------------------------------------------------------------------------
+// FlagHistogram:
+//------------------------------------------------------------------------------
+
+Histogram* FlagHistogram::FactoryGet(Flags flags, const int* buckets) {
+ Histogram* h(nullptr);
+
+ FlagHistogram* fh = new FlagHistogram();
+ fh->InitializeBucketRangeFromData(buckets);
+ fh->SetFlags(flags);
+ size_t zero_index = fh->BucketIndex(0);
+ fh->LinearHistogram::Accumulate(0, 1, zero_index);
+ h = fh;
+
+ return h;
+}
+
+FlagHistogram::FlagHistogram() : mSwitched(false) {}
+
+Histogram::ClassType FlagHistogram::histogram_type() const {
+ return FLAG_HISTOGRAM;
+}
+
+void FlagHistogram::Accumulate(Sample value, Count count, size_t index) {
+ if (mSwitched) {
+ return;
+ }
+
+ mSwitched = true;
+ DCHECK_EQ(value, 1);
+ LinearHistogram::Accumulate(value, 1, index);
+ size_t zero_index = BucketIndex(0);
+ LinearHistogram::Accumulate(0, -1, zero_index);
+}
+
+void FlagHistogram::AddSampleSet(const SampleSet& sample) {
+ DCHECK_EQ(bucket_count(), sample.size());
+ // We can't be sure the SampleSet provided came from another FlagHistogram,
+ // so we take the following steps:
+ // - If our flag has already been set do nothing.
+ // - Set our flag if the following hold:
+ // - The sum of the counts in the provided SampleSet is 1.
+ // - The bucket index for that single value is the same as the index
+ // where we
+ // would place our set flag.
+ // - Otherwise, take no action.
+
+ if (mSwitched) {
+ return;
+ }
+
+ if (sample.sum() != 1) {
+ return;
+ }
+
+ size_t one_index = BucketIndex(1);
+ if (sample.counts(one_index) == 1) {
+ Accumulate(1, 1, one_index);
+ }
+}
+
+void FlagHistogram::Clear() {
+ Histogram::Clear();
+
+ mSwitched = false;
+ size_t zero_index = BucketIndex(0);
+ LinearHistogram::Accumulate(0, 1, zero_index);
+}
+
+//------------------------------------------------------------------------------
+// CountHistogram:
+//------------------------------------------------------------------------------
+
+Histogram* CountHistogram::FactoryGet(Flags flags, const int* buckets) {
+ Histogram* h(nullptr);
+
+ CountHistogram* fh = new CountHistogram();
+ fh->InitializeBucketRangeFromData(buckets);
+ fh->SetFlags(flags);
+ h = fh;
+
+ return h;
+}
+
+CountHistogram::CountHistogram() : LinearHistogram(1, 2, 3) {}
+
+Histogram::ClassType CountHistogram::histogram_type() const {
+ return COUNT_HISTOGRAM;
+}
+
+void CountHistogram::Accumulate(Sample value, Count count, size_t index) {
+ size_t zero_index = BucketIndex(0);
+ LinearHistogram::Accumulate(value, 1, zero_index);
+}
+
+void CountHistogram::AddSampleSet(const SampleSet& sample) {
+ DCHECK_EQ(bucket_count(), sample.size());
+ // We can't be sure the SampleSet provided came from another CountHistogram,
+ // so we at least check that the unused buckets are empty.
+
+ const size_t indices[] = {BucketIndex(0), BucketIndex(1), BucketIndex(2)};
+
+ if (sample.counts(indices[1]) != 0 || sample.counts(indices[2]) != 0) {
+ return;
+ }
+
+ if (sample.counts(indices[0]) != 0) {
+ Histogram::AddSampleSet(sample);
+ }
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/histogram.h b/ipc/chromium/src/base/histogram.h
new file mode 100644
index 0000000000..f9ea21c8df
--- /dev/null
+++ b/ipc/chromium/src/base/histogram.h
@@ -0,0 +1,432 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+// Histogram is an object that aggregates statistics, and can summarize them in
+// various forms, including ASCII graphical, HTML, and numerically (as a
+// vector of numbers corresponding to each of the aggregating buckets).
+
+// It supports calls to accumulate either time intervals (which are processed
+// as integral number of milliseconds), or arbitrary integral units.
+
+// The default layout of buckets is exponential. For example, buckets might
+// contain (sequentially) the count of values in the following intervals:
+// [0,1), [1,2), [2,4), [4,8), [8,16), [16,32), [32,64), [64,infinity)
+// That bucket allocation would actually result from construction of a histogram
+// for values between 1 and 64, with 8 buckets, such as:
+// Histogram count(L"some name", 1, 64, 8);
+// Note that the underflow bucket [0,1) and the overflow bucket [64,infinity)
+// are not counted by the constructor in the user supplied "bucket_count"
+// argument.
+// The above example has an exponential ratio of 2 (doubling the bucket width
+// in each consecutive bucket. The Histogram class automatically calculates
+// the smallest ratio that it can use to construct the number of buckets
+// selected in the constructor. An another example, if you had 50 buckets,
+// and millisecond time values from 1 to 10000, then the ratio between
+// consecutive bucket widths will be approximately somewhere around the 50th
+// root of 10000. This approach provides very fine grain (narrow) buckets
+// at the low end of the histogram scale, but allows the histogram to cover a
+// gigantic range with the addition of very few buckets.
+
+// Histograms use a pattern involving a function static variable, that is a
+// pointer to a histogram. This static is explicitly initialized on any thread
+// that detects a uninitialized (NULL) pointer. The potentially racy
+// initialization is not a problem as it is always set to point to the same
+// value (i.e., the FactoryGet always returns the same value). FactoryGet
+// is also completely thread safe, which results in a completely thread safe,
+// and relatively fast, set of counters. To avoid races at shutdown, the static
+// pointer is NOT deleted, and we leak the histograms at process termination.
+
+#ifndef BASE_METRICS_HISTOGRAM_H_
+#define BASE_METRICS_HISTOGRAM_H_
+#pragma once
+
+#include "mozilla/Atomics.h"
+#include "mozilla/MemoryReporting.h"
+
+#include <map>
+#include <string>
+
+#include "base/time.h"
+
+#include "nsTArray.h"
+
+namespace base {
+
+//------------------------------------------------------------------------------
+
+class BooleanHistogram;
+class CustomHistogram;
+class Histogram;
+class LinearHistogram;
+
+class Histogram {
+ public:
+ typedef int Sample; // Used for samples (and ranges of samples).
+ typedef int Count; // Used to count samples in a bucket.
+ static const Sample kSampleType_MAX = INT_MAX;
+ // Initialize maximum number of buckets in histograms as 16,384.
+ static const size_t kBucketCount_MAX;
+
+ typedef nsTArray<Count> Counts;
+ typedef const Sample* Ranges;
+
+ // These enums are used to facilitate deserialization of renderer histograms
+ // into the browser.
+ enum ClassType {
+ HISTOGRAM,
+ LINEAR_HISTOGRAM,
+ BOOLEAN_HISTOGRAM,
+ FLAG_HISTOGRAM,
+ COUNT_HISTOGRAM,
+ CUSTOM_HISTOGRAM,
+ NOT_VALID_IN_RENDERER
+ };
+
+ enum BucketLayout { EXPONENTIAL, LINEAR, CUSTOM };
+
+ enum Flags {
+ kNoFlags = 0,
+ kUmaTargetedHistogramFlag = 0x1, // Histogram should be UMA uploaded.
+
+ kHexRangePrintingFlag = 0x8000 // Fancy bucket-naming supported.
+ };
+
+ enum Inconsistencies {
+ NO_INCONSISTENCIES = 0x0,
+ RANGE_CHECKSUM_ERROR = 0x1,
+ BUCKET_ORDER_ERROR = 0x2,
+ COUNT_HIGH_ERROR = 0x4,
+ COUNT_LOW_ERROR = 0x8,
+
+ NEVER_EXCEEDED_VALUE = 0x10
+ };
+
+ struct DescriptionPair {
+ Sample sample;
+ const char* description; // Null means end of a list of pairs.
+ };
+
+ size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf);
+
+ bool is_empty() const {
+ return this->sample_.counts(0) == 0 && this->sample_.sum() == 0;
+ }
+
+ //----------------------------------------------------------------------------
+ // Statistic values, developed over the life of the histogram.
+
+ class SampleSet {
+ public:
+ explicit SampleSet();
+ ~SampleSet();
+ SampleSet(SampleSet&&) = default;
+
+ // None of the methods in this class are thread-safe. Callers
+ // must deal with locking themselves.
+
+ // Adjust size of counts_ for use with given histogram.
+ void Resize(const Histogram& histogram);
+
+ // Accessor for histogram to make routine additions.
+ void Accumulate(Sample value, Count count, size_t index);
+
+ // Arithmetic manipulation of corresponding elements of the set.
+ void Add(const SampleSet& other);
+
+ size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf);
+
+ Count counts(size_t i) const { return counts_[i]; }
+ Count TotalCount() const;
+ int64_t sum() const { return sum_; }
+ int64_t redundant_count() const { return redundant_count_; }
+ size_t size() const { return counts_.Length(); }
+ SampleSet Clone() const {
+ SampleSet result;
+ result.counts_ = counts_.Clone();
+ result.sum_ = sum_;
+ result.redundant_count_ = redundant_count_;
+ return result;
+ }
+ void Clear() {
+ sum_ = 0;
+ redundant_count_ = 0;
+ for (int& i : counts_) {
+ i = 0;
+ }
+ }
+
+ protected:
+ // Actual histogram data is stored in buckets, showing the count of values
+ // that fit into each bucket.
+ Counts counts_;
+
+ // Save simple stats locally. Note that this MIGHT get done in base class
+ // without shared memory at some point.
+ int64_t sum_; // sum of samples.
+
+ // To help identify memory corruption, we reduntantly save the number of
+ // samples we've accumulated into all of our buckets. We can compare this
+ // count to the sum of the counts in all buckets, and detect problems. Note
+ // that due to races in histogram accumulation (if a histogram is indeed
+ // updated on several threads simultaneously), the tallies might mismatch,
+ // and also the snapshotting code may asynchronously get a mismatch (though
+ // generally either race based mismatch cause is VERY rare).
+ int64_t redundant_count_;
+ };
+
+ //----------------------------------------------------------------------------
+ // minimum should start from 1. 0 is invalid as a minimum. 0 is an implicit
+ // default underflow bucket.
+ static Histogram* FactoryGet(Sample minimum, Sample maximum,
+ size_t bucket_count, Flags flags,
+ const int* buckets);
+
+ virtual ~Histogram();
+
+ void Add(int value);
+ void Subtract(int value);
+
+ // This method is an interface, used only by BooleanHistogram.
+ virtual void AddBoolean(bool value);
+
+ // Accept a TimeDelta to increment.
+ void AddTime(TimeDelta time) { Add(static_cast<int>(time.InMilliseconds())); }
+
+ virtual void AddSampleSet(const SampleSet& sample);
+
+ virtual void Clear();
+
+ // This method is an interface, used only by LinearHistogram.
+ virtual void SetRangeDescriptions(const DescriptionPair descriptions[]);
+
+ // Support generic flagging of Histograms.
+ // 0x1 Currently used to mark this histogram to be recorded by UMA..
+ // 0x8000 means print ranges in hex.
+ void SetFlags(Flags flags) { flags_ = static_cast<Flags>(flags_ | flags); }
+ void ClearFlags(Flags flags) { flags_ = static_cast<Flags>(flags_ & ~flags); }
+ int flags() const { return flags_; }
+
+ // Check to see if bucket ranges, counts and tallies in the snapshot are
+ // consistent with the bucket ranges and checksums in our histogram. This can
+ // produce a false-alarm if a race occurred in the reading of the data during
+ // a SnapShot process, but should otherwise be false at all times (unless we
+ // have memory over-writes, or DRAM failures).
+ virtual Inconsistencies FindCorruption(const SampleSet& snapshot) const;
+
+ //----------------------------------------------------------------------------
+ // Accessors for factory constuction, serialization and testing.
+ //----------------------------------------------------------------------------
+ virtual ClassType histogram_type() const;
+ Sample declared_min() const { return declared_min_; }
+ Sample declared_max() const { return declared_max_; }
+ virtual Sample ranges(size_t i) const;
+ uint32_t range_checksum() const { return range_checksum_; }
+ virtual size_t bucket_count() const;
+
+ virtual SampleSet SnapshotSample() const;
+
+ virtual bool HasConstructorArguments(Sample minimum, Sample maximum,
+ size_t bucket_count);
+
+ virtual bool HasConstructorTimeDeltaArguments(TimeDelta minimum,
+ TimeDelta maximum,
+ size_t bucket_count);
+ // Return true iff the range_checksum_ matches current ranges_ vector.
+ bool HasValidRangeChecksum() const;
+
+ protected:
+ Histogram(Sample minimum, Sample maximum, size_t bucket_count);
+ Histogram(TimeDelta minimum, TimeDelta maximum, size_t bucket_count);
+
+ // Initialize ranges_ mapping from raw data.
+ void InitializeBucketRangeFromData(const int* buckets);
+
+ // Method to override to skip the display of the i'th bucket if it's empty.
+ virtual bool PrintEmptyBucket(size_t index) const;
+
+ //----------------------------------------------------------------------------
+ // Methods to override to create histogram with different bucket widths.
+ //----------------------------------------------------------------------------
+ // Find bucket to increment for sample value.
+ virtual size_t BucketIndex(Sample value) const;
+ // Get normalized size, relative to the ranges_[i].
+ virtual double GetBucketSize(Count current, size_t i) const;
+
+ // Recalculate range_checksum_.
+ void ResetRangeChecksum();
+
+ // Return a string description of what goes in a given bucket.
+ // Most commonly this is the numeric value, but in derived classes it may
+ // be a name (or string description) given to the bucket.
+ virtual const std::string GetAsciiBucketRange(size_t it) const;
+
+ //----------------------------------------------------------------------------
+ // Methods to override to create thread safe histogram.
+ //----------------------------------------------------------------------------
+ // Update all our internal data, including histogram
+ virtual void Accumulate(Sample value, Count count, size_t index);
+
+ // Validate that ranges_ was created sensibly (top and bottom range
+ // values relate properly to the declared_min_ and declared_max_)..
+ bool ValidateBucketRanges() const;
+
+ virtual uint32_t CalculateRangeChecksum() const;
+
+ // Finally, provide the state that changes with the addition of each new
+ // sample.
+ SampleSet sample_;
+
+ private:
+ // Post constructor initialization.
+ void Initialize();
+
+ // Checksum function for accumulating range values into a checksum.
+ static uint32_t Crc32(uint32_t sum, Sample range);
+
+ //----------------------------------------------------------------------------
+ // Helpers for emitting Ascii graphic. Each method appends data to output.
+
+ // Find out how large the (graphically) the largest bucket will appear to be.
+ double GetPeakBucketSize(const SampleSet& snapshot) const;
+
+ //----------------------------------------------------------------------------
+ // Table for generating Crc32 values.
+ static const uint32_t kCrcTable[256];
+ //----------------------------------------------------------------------------
+ // Invariant values set at/near construction time
+
+ Sample declared_min_; // Less than this goes into counts_[0]
+ Sample declared_max_; // Over this goes into counts_[bucket_count_ - 1].
+ size_t bucket_count_; // Dimension of counts_[].
+
+ // Flag the histogram for recording by UMA via metric_services.h.
+ Flags flags_;
+
+ // For each index, show the least value that can be stored in the
+ // corresponding bucket. We also append one extra element in this array,
+ // containing kSampleType_MAX, to make calculations easy.
+ // The dimension of ranges_ is bucket_count + 1.
+ Ranges ranges_;
+
+ // For redundancy, we store a checksum of all the sample ranges when ranges
+ // are generated. If ever there is ever a difference, then the histogram must
+ // have been corrupted.
+ uint32_t range_checksum_;
+
+ DISALLOW_COPY_AND_ASSIGN(Histogram);
+};
+
+//------------------------------------------------------------------------------
+
+// LinearHistogram is a more traditional histogram, with evenly spaced
+// buckets.
+class LinearHistogram : public Histogram {
+ public:
+ virtual ~LinearHistogram();
+
+ /* minimum should start from 1. 0 is as minimum is invalid. 0 is an implicit
+ default underflow bucket. */
+ static Histogram* FactoryGet(Sample minimum, Sample maximum,
+ size_t bucket_count, Flags flags,
+ const int* buckets);
+
+ // Overridden from Histogram:
+ virtual ClassType histogram_type() const override;
+
+ virtual void Accumulate(Sample value, Count count, size_t index) override;
+
+ // Store a list of number/text values for use in rendering the histogram.
+ // The last element in the array has a null in its "description" slot.
+ virtual void SetRangeDescriptions(
+ const DescriptionPair descriptions[]) override;
+
+ protected:
+ LinearHistogram(Sample minimum, Sample maximum, size_t bucket_count);
+
+ LinearHistogram(TimeDelta minimum, TimeDelta maximum, size_t bucket_count);
+
+ virtual double GetBucketSize(Count current, size_t i) const override;
+
+ // If we have a description for a bucket, then return that. Otherwise
+ // let parent class provide a (numeric) description.
+ virtual const std::string GetAsciiBucketRange(size_t i) const override;
+
+ // Skip printing of name for numeric range if we have a name (and if this is
+ // an empty bucket).
+ virtual bool PrintEmptyBucket(size_t index) const override;
+
+ private:
+ // For some ranges, we store a printable description of a bucket range.
+ // If there is no desciption, then GetAsciiBucketRange() uses parent class
+ // to provide a description.
+ typedef std::map<Sample, std::string> BucketDescriptionMap;
+ BucketDescriptionMap bucket_description_;
+
+ DISALLOW_COPY_AND_ASSIGN(LinearHistogram);
+};
+
+//------------------------------------------------------------------------------
+
+// BooleanHistogram is a histogram for booleans.
+class BooleanHistogram : public LinearHistogram {
+ public:
+ static Histogram* FactoryGet(Flags flags, const int* buckets);
+
+ virtual ClassType histogram_type() const override;
+
+ virtual void AddBoolean(bool value) override;
+
+ virtual void Accumulate(Sample value, Count count, size_t index) override;
+
+ protected:
+ explicit BooleanHistogram();
+
+ DISALLOW_COPY_AND_ASSIGN(BooleanHistogram);
+};
+
+//------------------------------------------------------------------------------
+
+// FlagHistogram is like boolean histogram, but only allows a single off/on
+// value.
+class FlagHistogram : public BooleanHistogram {
+ public:
+ static Histogram* FactoryGet(Flags flags, const int* buckets);
+
+ virtual ClassType histogram_type() const override;
+
+ virtual void Accumulate(Sample value, Count count, size_t index) override;
+
+ virtual void AddSampleSet(const SampleSet& sample) override;
+
+ virtual void Clear() override;
+
+ private:
+ explicit FlagHistogram();
+ bool mSwitched;
+
+ DISALLOW_COPY_AND_ASSIGN(FlagHistogram);
+};
+
+// CountHistogram only allows a single monotic counter value.
+class CountHistogram : public LinearHistogram {
+ public:
+ static Histogram* FactoryGet(Flags flags, const int* buckets);
+
+ virtual ClassType histogram_type() const override;
+
+ virtual void Accumulate(Sample value, Count count, size_t index) override;
+
+ virtual void AddSampleSet(const SampleSet& sample) override;
+
+ private:
+ explicit CountHistogram();
+
+ DISALLOW_COPY_AND_ASSIGN(CountHistogram);
+};
+
+} // namespace base
+
+#endif // BASE_METRICS_HISTOGRAM_H_
diff --git a/ipc/chromium/src/base/linked_ptr.h b/ipc/chromium/src/base/linked_ptr.h
new file mode 100644
index 0000000000..7b428312b8
--- /dev/null
+++ b/ipc/chromium/src/base/linked_ptr.h
@@ -0,0 +1,185 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+//
+// A "smart" pointer type with reference tracking. Every pointer to a
+// particular object is kept on a circular linked list. When the last pointer
+// to an object is destroyed or reassigned, the object is deleted.
+//
+// Used properly, this deletes the object when the last reference goes away.
+// There are several caveats:
+// - Like all reference counting schemes, cycles lead to leaks.
+// - Each smart pointer is actually two pointers (8 bytes instead of 4).
+// - Every time a pointer is released, the entire list of pointers to that
+// object is traversed. This class is therefore NOT SUITABLE when there
+// will often be more than two or three pointers to a particular object.
+// - References are only tracked as long as linked_ptr<> objects are copied.
+// If a linked_ptr<> is converted to a raw pointer and back, BAD THINGS
+// will happen (double deletion).
+//
+// A good use of this class is storing object references in STL containers.
+// You can safely put linked_ptr<> in a vector<>.
+// Other uses may not be as good.
+//
+// Note: If you use an incomplete type with linked_ptr<>, the class
+// *containing* linked_ptr<> must have a constructor and destructor (even
+// if they do nothing!).
+//
+// Thread Safety:
+// A linked_ptr is NOT thread safe. Copying a linked_ptr object is
+// effectively a read-write operation.
+//
+// Alternative: to linked_ptr is shared_ptr, which
+// - is also two pointers in size (8 bytes for 32 bit addresses)
+// - is thread safe for copying and deletion
+// - supports weak_ptrs
+
+#ifndef BASE_LINKED_PTR_H_
+#define BASE_LINKED_PTR_H_
+
+#include "base/logging.h" // for CHECK macros
+
+// This is used internally by all instances of linked_ptr<>. It needs to be
+// a non-template class because different types of linked_ptr<> can refer to
+// the same object (linked_ptr<Superclass>(obj) vs linked_ptr<Subclass>(obj)).
+// So, it needs to be possible for different types of linked_ptr to participate
+// in the same circular linked list, so we need a single class type here.
+//
+// DO NOT USE THIS CLASS DIRECTLY YOURSELF. Use linked_ptr<T>.
+class linked_ptr_internal {
+ public:
+ // Create a new circle that includes only this instance.
+ void join_new() { next_ = this; }
+
+ // Join an existing circle.
+ void join(linked_ptr_internal const* ptr) {
+ next_ = ptr->next_;
+ ptr->next_ = this;
+ }
+
+ // Leave whatever circle we're part of. Returns true iff we were the
+ // last member of the circle. Once this is done, you can join() another.
+ bool depart() {
+ if (next_ == this) return true;
+ linked_ptr_internal const* p = next_;
+ while (p->next_ != this) p = p->next_;
+ p->next_ = next_;
+ return false;
+ }
+
+ private:
+ mutable linked_ptr_internal const* next_;
+};
+
+template <typename T>
+class linked_ptr {
+ public:
+ typedef T element_type;
+
+ // Take over ownership of a raw pointer. This should happen as soon as
+ // possible after the object is created.
+ explicit linked_ptr(T* ptr = NULL) { capture(ptr); }
+ ~linked_ptr() { depart(); }
+
+ // Copy an existing linked_ptr<>, adding ourselves to the list of references.
+ template <typename U>
+ linked_ptr(linked_ptr<U> const& ptr) {
+ copy(&ptr);
+ }
+ linked_ptr(linked_ptr const& ptr) {
+ DCHECK_NE(&ptr, this);
+ copy(&ptr);
+ }
+
+ // Assignment releases the old value and acquires the new.
+ template <typename U>
+ linked_ptr& operator=(linked_ptr<U> const& ptr) {
+ depart();
+ copy(&ptr);
+ return *this;
+ }
+
+ linked_ptr& operator=(linked_ptr const& ptr) {
+ if (&ptr != this) {
+ depart();
+ copy(&ptr);
+ }
+ return *this;
+ }
+
+ // Smart pointer members.
+ void reset(T* ptr = NULL) {
+ depart();
+ capture(ptr);
+ }
+ T* get() const { return value_; }
+ T* operator->() const { return value_; }
+ T& operator*() const { return *value_; }
+ // Release ownership of the pointed object and returns it.
+ // Sole ownership by this linked_ptr object is required.
+ T* release() {
+ bool last = link_.depart();
+ CHECK(last);
+ T* v = value_;
+ value_ = NULL;
+ return v;
+ }
+
+ bool operator==(const T* p) const { return value_ == p; }
+ bool operator!=(const T* p) const { return value_ != p; }
+ template <typename U>
+ bool operator==(linked_ptr<U> const& ptr) const {
+ return value_ == ptr.get();
+ }
+ template <typename U>
+ bool operator!=(linked_ptr<U> const& ptr) const {
+ return value_ != ptr.get();
+ }
+
+ private:
+ template <typename U>
+ friend class linked_ptr;
+
+ T* value_;
+ linked_ptr_internal link_;
+
+ void depart() {
+ if (link_.depart()) delete value_;
+ }
+
+ void capture(T* ptr) {
+ value_ = ptr;
+ link_.join_new();
+ }
+
+ template <typename U>
+ void copy(linked_ptr<U> const* ptr) {
+ value_ = ptr->get();
+ if (value_)
+ link_.join(&ptr->link_);
+ else
+ link_.join_new();
+ }
+};
+
+template <typename T>
+inline bool operator==(T* ptr, const linked_ptr<T>& x) {
+ return ptr == x.get();
+}
+
+template <typename T>
+inline bool operator!=(T* ptr, const linked_ptr<T>& x) {
+ return ptr != x.get();
+}
+
+// A function to convert T* into linked_ptr<T>
+// Doing e.g. make_linked_ptr(new FooBarBaz<type>(arg)) is a shorter notation
+// for linked_ptr<FooBarBaz<type> >(new FooBarBaz<type>(arg))
+template <typename T>
+linked_ptr<T> make_linked_ptr(T* ptr) {
+ return linked_ptr<T>(ptr);
+}
+
+#endif // BASE_LINKED_PTR_H_
diff --git a/ipc/chromium/src/base/linux_memfd_defs.h b/ipc/chromium/src/base/linux_memfd_defs.h
new file mode 100644
index 0000000000..f5b0de1de8
--- /dev/null
+++ b/ipc/chromium/src/base/linux_memfd_defs.h
@@ -0,0 +1,69 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef BASE_LINUX_MEMFD_DEFS_H
+#define BASE_LINUX_MEMFD_DEFS_H
+
+#include <sys/syscall.h>
+
+// glibc before 2.27 didn't have a memfd_create wrapper, and if the
+// build system is old enough then it won't have the syscall number
+// and various related constants either.
+
+#if defined(__x86_64__)
+# define MEMFD_CREATE_NR 319
+#elif defined(__i386__)
+# define MEMFD_CREATE_NR 356
+#elif defined(__aarch64__)
+# define MEMFD_CREATE_NR 279
+#elif defined(__arm__)
+# define MEMFD_CREATE_NR 385
+#elif defined(__powerpc__)
+# define MEMFD_CREATE_NR 360
+#elif defined(__s390__)
+# define MEMFD_CREATE_NR 350
+#elif defined(__mips__)
+# include <sgidefs.h>
+# if _MIPS_SIM == _MIPS_SIM_ABI32
+# define MEMFD_CREATE_NR 4354
+# elif _MIPS_SIM == _MIPS_SIM_ABI64
+# define MEMFD_CREATE_NR 5314
+# elif _MIPS_SIM == _MIPS_SIM_NABI32
+# define MEMFD_CREATE_NR 6318
+# endif // mips subarch
+#endif // arch
+
+#ifdef MEMFD_CREATE_NR
+# ifdef SYS_memfd_create
+static_assert(MEMFD_CREATE_NR == SYS_memfd_create,
+ "MEMFD_CREATE_NR should match the actual SYS_memfd_create value");
+# else // defined here but not in system headers
+# define SYS_memfd_create MEMFD_CREATE_NR
+# endif
+#endif
+
+#ifndef MFD_CLOEXEC
+# define MFD_CLOEXEC 0x0001U
+# define MFD_ALLOW_SEALING 0x0002U
+#endif
+
+#ifndef F_ADD_SEALS
+# ifndef F_LINUX_SPECIFIC_BASE
+# define F_LINUX_SPECIFIC_BASE 1024
+# endif
+# define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
+# define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
+# define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
+# define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
+# define F_SEAL_GROW 0x0004 /* prevent file from growing */
+# define F_SEAL_WRITE 0x0008 /* prevent writes */
+#endif
+
+#ifndef F_SEAL_FUTURE_WRITE
+# define F_SEAL_FUTURE_WRITE 0x0010
+#endif
+
+#endif // BASE_LINUX_MEMFD_DEFS_H
diff --git a/ipc/chromium/src/base/lock.h b/ipc/chromium/src/base/lock.h
new file mode 100644
index 0000000000..085e70e725
--- /dev/null
+++ b/ipc/chromium/src/base/lock.h
@@ -0,0 +1,97 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#ifndef BASE_LOCK_H_
+#define BASE_LOCK_H_
+
+#include "base/basictypes.h"
+#include "base/lock_impl.h"
+#include "base/platform_thread.h"
+
+// A convenient wrapper for an OS specific critical section.
+class Lock {
+ public:
+ // Optimized wrapper implementation
+ Lock() = default;
+ ~Lock() = default;
+ void Acquire() { lock_.Lock(); }
+ void Release() { lock_.Unlock(); }
+
+ // If the lock is not held, take it and return true. If the lock is already
+ // held by another thread, immediately return false. This must not be called
+ // by a thread already holding the lock (what happens is undefined and an
+ // assertion may fail).
+ bool Try() { return lock_.Try(); }
+
+ // Null implementation if not debug.
+ void AssertAcquired() const {}
+
+ // Whether Lock mitigates priority inversion when used from different thread
+ // priorities.
+ static bool HandlesMultipleThreadPriorities() {
+#if defined(XP_UNIX)
+ // POSIX mitigates priority inversion by setting the priority of a thread
+ // holding a Lock to the maximum priority of any other thread waiting on it.
+ return base::internal::LockImpl::PriorityInheritanceAvailable();
+#else
+ // Windows mitigates priority inversion by randomly boosting the priority of
+ // ready threads.
+ // https://msdn.microsoft.com/library/windows/desktop/ms684831.aspx
+ return true;
+#endif
+ }
+
+ // Both Windows and POSIX implementations of ConditionVariable need to be
+ // able to see our lock and tweak our debugging counters, as they release and
+ // acquire locks inside of their condition variable APIs.
+ friend class ConditionVariable;
+
+ private:
+ // Platform specific underlying lock implementation.
+ ::base::internal::LockImpl lock_;
+
+ DISALLOW_COPY_AND_ASSIGN(Lock);
+};
+
+// A helper class that acquires the given Lock while the AutoLock is in scope.
+class AutoLock {
+ public:
+ struct AlreadyAcquired {};
+
+ explicit AutoLock(Lock& lock) : lock_(lock) { lock_.Acquire(); }
+
+ AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(lock) {
+ lock_.AssertAcquired();
+ }
+
+ ~AutoLock() {
+ lock_.AssertAcquired();
+ lock_.Release();
+ }
+
+ private:
+ Lock& lock_;
+ DISALLOW_COPY_AND_ASSIGN(AutoLock);
+};
+
+// AutoUnlock is a helper that will Release() the |lock| argument in the
+// constructor, and re-Acquire() it in the destructor.
+class AutoUnlock {
+ public:
+ explicit AutoUnlock(Lock& lock) : lock_(lock) {
+ // We require our caller to have the lock.
+ lock_.AssertAcquired();
+ lock_.Release();
+ }
+
+ ~AutoUnlock() { lock_.Acquire(); }
+
+ private:
+ Lock& lock_;
+ DISALLOW_COPY_AND_ASSIGN(AutoUnlock);
+};
+
+#endif // BASE_LOCK_H_
diff --git a/ipc/chromium/src/base/lock_impl.h b/ipc/chromium/src/base/lock_impl.h
new file mode 100644
index 0000000000..95588bcca2
--- /dev/null
+++ b/ipc/chromium/src/base/lock_impl.h
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#ifndef BASE_LOCK_IMPL_H_
+#define BASE_LOCK_IMPL_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+#else
+# include <pthread.h>
+#endif
+
+namespace base {
+namespace internal {
+
+// This class implements the underlying platform-specific spin-lock mechanism
+// used for the Lock class. Most users should not use LockImpl directly, but
+// should instead use Lock.
+class LockImpl {
+ public:
+#if defined(XP_WIN)
+ using NativeHandle = SRWLOCK;
+#else
+ using NativeHandle = pthread_mutex_t;
+#endif
+
+ LockImpl();
+ ~LockImpl();
+
+ // If the lock is not held, take it and return true. If the lock is already
+ // held by something else, immediately return false.
+ bool Try();
+
+ // Take the lock, blocking until it is available if necessary.
+ void Lock();
+
+ // Release the lock. This must only be called by the lock's holder: after
+ // a successful call to Try, or a call to Lock.
+ void Unlock();
+
+ // Return the native underlying lock.
+ // TODO(awalker): refactor lock and condition variables so that this is
+ // unnecessary.
+ NativeHandle* native_handle() { return &native_handle_; }
+
+#if defined(XP_UNIX)
+ // Whether this lock will attempt to use priority inheritance.
+ static bool PriorityInheritanceAvailable();
+#endif
+
+ private:
+ NativeHandle native_handle_;
+
+ DISALLOW_COPY_AND_ASSIGN(LockImpl);
+};
+
+} // namespace internal
+} // namespace base
+
+#endif // BASE_LOCK_IMPL_H_
diff --git a/ipc/chromium/src/base/lock_impl_posix.cc b/ipc/chromium/src/base/lock_impl_posix.cc
new file mode 100644
index 0000000000..a4a2ce87b6
--- /dev/null
+++ b/ipc/chromium/src/base/lock_impl_posix.cc
@@ -0,0 +1,98 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#include "base/lock_impl.h"
+
+#include <errno.h>
+#include <string.h>
+
+#include "base/logging.h"
+#include "base/lock.h"
+
+namespace base {
+namespace internal {
+
+// Determines which platforms can consider using priority inheritance locks. Use
+// this define for platform code that may not compile if priority inheritance
+// locks aren't available. For this platform code,
+// PRIORITY_INHERITANCE_LOCKS_POSSIBLE() is a necessary but insufficient check.
+// Lock::PriorityInheritanceAvailable still must be checked as the code may
+// compile but the underlying platform still may not correctly support priority
+// inheritance locks.
+#if defined(ANDROID)
+# define PRIORITY_INHERITANCE_LOCKS_POSSIBLE() 0
+#else
+# define PRIORITY_INHERITANCE_LOCKS_POSSIBLE() 1
+#endif
+
+LockImpl::LockImpl() {
+ pthread_mutexattr_t mta;
+ int rv = pthread_mutexattr_init(&mta);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+#if PRIORITY_INHERITANCE_LOCKS_POSSIBLE()
+ if (PriorityInheritanceAvailable()) {
+ rv = pthread_mutexattr_setprotocol(&mta, PTHREAD_PRIO_INHERIT);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+ }
+#endif
+#ifndef NDEBUG
+ // In debug, setup attributes for lock error checking.
+ rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+#endif
+ rv = pthread_mutex_init(&native_handle_, &mta);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+ rv = pthread_mutexattr_destroy(&mta);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+}
+
+LockImpl::~LockImpl() {
+ int rv = pthread_mutex_destroy(&native_handle_);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+}
+
+bool LockImpl::Try() {
+ int rv = pthread_mutex_trylock(&native_handle_);
+ DCHECK(rv == 0 || rv == EBUSY) << ". " << strerror(rv);
+ return rv == 0;
+}
+
+void LockImpl::Lock() {
+ int rv = pthread_mutex_lock(&native_handle_);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+}
+
+void LockImpl::Unlock() {
+ int rv = pthread_mutex_unlock(&native_handle_);
+ DCHECK_EQ(rv, 0) << ". " << strerror(rv);
+}
+
+// static
+bool LockImpl::PriorityInheritanceAvailable() {
+#if PRIORITY_INHERITANCE_LOCKS_POSSIBLE() && defined(XP_DARWIN)
+ return true;
+#else
+ // Security concerns prevent the use of priority inheritance mutexes on Linux.
+ // * CVE-2010-0622 - wake_futex_pi unlocks incorrect, possible DoS.
+ // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2010-0622
+ // * CVE-2012-6647 - Linux < 3.5.1, futex_wait_requeue_pi possible DoS.
+ // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-6647
+ // * CVE-2014-3153 - Linux <= 3.14.5, futex_requeue, privilege escalation.
+ // https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-3153
+ //
+ // If the above were all addressed, we still need a runtime check to deal with
+ // the bug below.
+ // * glibc Bug 14652: https://sourceware.org/bugzilla/show_bug.cgi?id=14652
+ // Fixed in glibc 2.17.
+ // Priority inheritance mutexes may deadlock with condition variables
+ // during recacquisition of the mutex after the condition variable is
+ // signalled.
+ return false;
+#endif
+}
+
+} // namespace internal
+} // namespace base
diff --git a/ipc/chromium/src/base/lock_impl_win.cc b/ipc/chromium/src/base/lock_impl_win.cc
new file mode 100644
index 0000000000..fc16b3a464
--- /dev/null
+++ b/ipc/chromium/src/base/lock_impl_win.cc
@@ -0,0 +1,23 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#include "base/lock_impl.h"
+
+namespace base {
+namespace internal {
+
+LockImpl::LockImpl() : native_handle_(SRWLOCK_INIT) {}
+
+LockImpl::~LockImpl() = default;
+
+bool LockImpl::Try() { return !!::TryAcquireSRWLockExclusive(&native_handle_); }
+
+void LockImpl::Lock() { ::AcquireSRWLockExclusive(&native_handle_); }
+
+void LockImpl::Unlock() { ::ReleaseSRWLockExclusive(&native_handle_); }
+
+} // namespace internal
+} // namespace base
diff --git a/ipc/chromium/src/base/logging.cc b/ipc/chromium/src/base/logging.cc
new file mode 100644
index 0000000000..217ae80844
--- /dev/null
+++ b/ipc/chromium/src/base/logging.cc
@@ -0,0 +1,87 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// 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.
+
+#include "base/logging.h"
+
+#include <utility>
+
+#include "base/string_util.h"
+#include "nsXPCOM.h"
+
+namespace mozilla {
+
+Logger::~Logger() {
+ LogLevel prlevel = LogLevel::Debug;
+ int xpcomlevel = -1;
+
+ switch (mSeverity) {
+ case LOG_INFO:
+ prlevel = LogLevel::Debug;
+ xpcomlevel = -1;
+ break;
+
+ case LOG_WARNING:
+ prlevel = LogLevel::Warning;
+ xpcomlevel = NS_DEBUG_WARNING;
+ break;
+
+ case LOG_ERROR:
+ prlevel = LogLevel::Error;
+ xpcomlevel = NS_DEBUG_WARNING;
+ break;
+
+ case LOG_ERROR_REPORT:
+ prlevel = LogLevel::Error;
+ xpcomlevel = NS_DEBUG_ASSERTION;
+ break;
+
+ case LOG_FATAL:
+ prlevel = LogLevel::Error;
+ xpcomlevel = NS_DEBUG_ABORT;
+ break;
+ }
+
+ MOZ_LOG(gChromiumPRLog, prlevel,
+ ("%s:%i: %s", mFile, mLine, mMsg ? mMsg.get() : "<no message>"));
+ if (xpcomlevel != -1)
+ NS_DebugBreak(xpcomlevel, mMsg.get(), NULL, mFile, mLine);
+}
+
+void Logger::printf(const char* fmt, ...) {
+ va_list args;
+ va_start(args, fmt);
+ mMsg = mozilla::VsmprintfAppend(std::move(mMsg), fmt, args);
+ va_end(args);
+}
+
+LazyLogModule Logger::gChromiumPRLog("chromium");
+
+mozilla::Logger& operator<<(mozilla::Logger& log, const char* s) {
+ log.printf("%s", s);
+ return log;
+}
+
+mozilla::Logger& operator<<(mozilla::Logger& log, const std::string& s) {
+ log.printf("%s", s.c_str());
+ return log;
+}
+
+mozilla::Logger& operator<<(mozilla::Logger& log, int i) {
+ log.printf("%i", i);
+ return log;
+}
+
+mozilla::Logger& operator<<(mozilla::Logger& log, const std::wstring& s) {
+ log.printf("%s", WideToASCII(s).c_str());
+ return log;
+}
+
+mozilla::Logger& operator<<(mozilla::Logger& log, void* p) {
+ log.printf("%p", p);
+ return log;
+}
+
+} // namespace mozilla
diff --git a/ipc/chromium/src/base/logging.h b/ipc/chromium/src/base/logging.h
new file mode 100644
index 0000000000..4313f131b3
--- /dev/null
+++ b/ipc/chromium/src/base/logging.h
@@ -0,0 +1,132 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_LOGGING_H_
+#define BASE_LOGGING_H_
+
+#include <string>
+#include <cstring>
+
+#include "base/basictypes.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Logging.h"
+#include "mozilla/Printf.h"
+
+#ifdef NO_CHROMIUM_LOGGING
+# include <sstream>
+#endif
+
+// Replace the Chromium logging code with NSPR-based logging code and
+// some C++ wrappers to emulate std::ostream
+
+namespace mozilla {
+
+enum LogSeverity {
+ LOG_INFO,
+ LOG_WARNING,
+ LOG_ERROR,
+ LOG_ERROR_REPORT,
+ LOG_FATAL,
+ LOG_0 = LOG_ERROR
+};
+
+class Logger {
+ public:
+ Logger(LogSeverity severity, const char* file, int line)
+ : mSeverity(severity), mFile(file), mLine(line) {}
+
+ ~Logger();
+
+ // not private so that the operator<< overloads can get to it
+ void printf(const char* fmt, ...) MOZ_FORMAT_PRINTF(2, 3);
+
+ private:
+ static mozilla::LazyLogModule gChromiumPRLog;
+ // static PRLogModuleInfo* GetLog();
+
+ LogSeverity mSeverity;
+ const char* mFile;
+ int mLine;
+ SmprintfPointer mMsg;
+
+ DISALLOW_EVIL_CONSTRUCTORS(Logger);
+};
+
+class LogWrapper {
+ public:
+ LogWrapper(LogSeverity severity, const char* file, int line)
+ : log(severity, file, line) {}
+
+ operator Logger&() const { return log; }
+
+ private:
+ mutable Logger log;
+
+ DISALLOW_EVIL_CONSTRUCTORS(LogWrapper);
+};
+
+struct EmptyLog {};
+
+mozilla::Logger& operator<<(mozilla::Logger& log, const char* s);
+mozilla::Logger& operator<<(mozilla::Logger& log, const std::string& s);
+mozilla::Logger& operator<<(mozilla::Logger& log, int i);
+mozilla::Logger& operator<<(mozilla::Logger& log, const std::wstring& s);
+mozilla::Logger& operator<<(mozilla::Logger& log, void* p);
+
+template <class T>
+const mozilla::EmptyLog& operator<<(const mozilla::EmptyLog& log, const T&) {
+ return log;
+}
+
+} // namespace mozilla
+
+#ifdef NO_CHROMIUM_LOGGING
+# define CHROMIUM_LOG(info) std::stringstream()
+# define LOG_IF(info, condition) \
+ if (!(condition)) std::stringstream()
+#else
+# define CHROMIUM_LOG(info) \
+ mozilla::LogWrapper(mozilla::LOG_##info, __FILE__, __LINE__)
+# define LOG_IF(info, condition) \
+ if (!(condition)) \
+ mozilla::LogWrapper(mozilla::LOG_##info, __FILE__, __LINE__)
+#endif
+
+#ifdef DEBUG
+# define DLOG(info) CHROMIUM_LOG(info)
+# define DLOG_IF(info, condition) LOG_IF(info, condition)
+# define DCHECK(condition) CHECK(condition)
+#else
+# define DLOG(info) mozilla::EmptyLog()
+# define DLOG_IF(info, condition) mozilla::EmptyLog()
+# define DCHECK(condition) \
+ while (false && (condition)) mozilla::EmptyLog()
+#endif
+
+#define DVLOG(level) DLOG(INFO)
+
+#undef LOG_ASSERT
+#define LOG_ASSERT(cond) CHECK(0)
+#define DLOG_ASSERT(cond) DCHECK(0)
+
+#define NOTREACHED() CHROMIUM_LOG(ERROR)
+#define NOTIMPLEMENTED() CHROMIUM_LOG(ERROR)
+
+#undef CHECK
+#ifdef FUZZING
+# define CHECK(condition) LOG_IF(WARNING, condition)
+#else
+# define CHECK(condition) LOG_IF(FATAL, condition)
+#endif
+
+#define DCHECK_EQ(v1, v2) DCHECK((v1) == (v2))
+#define DCHECK_NE(v1, v2) DCHECK((v1) != (v2))
+#define DCHECK_LE(v1, v2) DCHECK((v1) <= (v2))
+#define DCHECK_LT(v1, v2) DCHECK((v1) < (v2))
+#define DCHECK_GE(v1, v2) DCHECK((v1) >= (v2))
+#define DCHECK_GT(v1, v2) DCHECK((v1) > (v2))
+
+#endif // BASE_LOGGING_H_
diff --git a/ipc/chromium/src/base/mac_util.h b/ipc/chromium/src/base/mac_util.h
new file mode 100644
index 0000000000..6af2bd7032
--- /dev/null
+++ b/ipc/chromium/src/base/mac_util.h
@@ -0,0 +1,17 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef BASE_MAC_UTIL_H_
+#define BASE_MAC_UTIL_H_
+
+namespace mac_util {
+
+// Returns true if the application is running from a bundle
+bool AmIBundled();
+
+} // namespace mac_util
+
+#endif // BASE_MAC_UTIL_H_
diff --git a/ipc/chromium/src/base/mac_util.mm b/ipc/chromium/src/base/mac_util.mm
new file mode 100644
index 0000000000..dde8d9a273
--- /dev/null
+++ b/ipc/chromium/src/base/mac_util.mm
@@ -0,0 +1,33 @@
+// Copyright (c) 2008 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.
+
+#include "base/mac_util.h"
+
+#include <Carbon/Carbon.h>
+#import <Cocoa/Cocoa.h>
+
+#include "base/file_path.h"
+#include "base/logging.h"
+#include "base/scoped_cftyperef.h"
+#include "base/sys_string_conversions.h"
+
+namespace mac_util {
+
+// Adapted from http://developer.apple.com/carbon/tipsandtricks.html#AmIBundled
+bool AmIBundled() {
+ ProcessSerialNumber psn = {0, kCurrentProcess};
+
+ FSRef fsref;
+ if (GetProcessBundleLocation(&psn, &fsref) != noErr) return false;
+
+ FSCatalogInfo info;
+ if (FSGetCatalogInfo(&fsref, kFSCatInfoNodeFlags, &info, NULL, NULL, NULL) !=
+ noErr) {
+ return false;
+ }
+
+ return info.nodeFlags & kFSNodeIsDirectoryMask;
+}
+
+} // namespace mac_util
diff --git a/ipc/chromium/src/base/message_loop.cc b/ipc/chromium/src/base/message_loop.cc
new file mode 100644
index 0000000000..c82d555ee5
--- /dev/null
+++ b/ipc/chromium/src/base/message_loop.cc
@@ -0,0 +1,725 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#include "base/message_loop.h"
+
+#include <algorithm>
+
+#include "base/compiler_specific.h"
+#include "base/logging.h"
+#include "base/message_pump_default.h"
+#include "base/string_util.h"
+#include "base/thread_local.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/ProfilerRunnable.h"
+#include "nsIEventTarget.h"
+#include "nsITargetShutdownTask.h"
+#include "nsThreadUtils.h"
+
+#if defined(XP_DARWIN)
+# include "base/message_pump_mac.h"
+#endif
+#if defined(XP_UNIX)
+# include "base/message_pump_libevent.h"
+#endif
+#if defined(XP_LINUX) || defined(__DragonFly__) || defined(XP_FREEBSD) || \
+ defined(XP_NETBSD) || defined(XP_OPENBSD)
+# if defined(MOZ_WIDGET_GTK)
+# include "base/message_pump_glib.h"
+# endif
+#endif
+#ifdef ANDROID
+# include "base/message_pump_android.h"
+#endif
+#include "nsISerialEventTarget.h"
+
+#include "mozilla/ipc/MessagePump.h"
+#include "nsThreadUtils.h"
+
+using base::Time;
+using base::TimeDelta;
+using base::TimeTicks;
+
+using mozilla::Runnable;
+
+static base::ThreadLocalPointer<MessageLoop>& get_tls_ptr() {
+ static base::ThreadLocalPointer<MessageLoop> tls_ptr;
+ return tls_ptr;
+}
+
+//------------------------------------------------------------------------------
+
+#if defined(XP_WIN)
+
+// Upon a SEH exception in this thread, it restores the original unhandled
+// exception filter.
+static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
+ ::SetUnhandledExceptionFilter(old_filter);
+ return EXCEPTION_CONTINUE_SEARCH;
+}
+
+// Retrieves a pointer to the current unhandled exception filter. There
+// is no standalone getter method.
+static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
+ LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
+ top_filter = ::SetUnhandledExceptionFilter(0);
+ ::SetUnhandledExceptionFilter(top_filter);
+ return top_filter;
+}
+
+#endif // defined(XP_WIN)
+
+//------------------------------------------------------------------------------
+
+class MessageLoop::EventTarget : public nsISerialEventTarget,
+ public nsITargetShutdownTask,
+ public MessageLoop::DestructionObserver {
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+ NS_DECL_NSIEVENTTARGET_FULL
+
+ void TargetShutdown() override {
+ nsTArray<nsCOMPtr<nsITargetShutdownTask>> shutdownTasks;
+ {
+ mozilla::MutexAutoLock lock(mMutex);
+ if (mShutdownTasksRun) {
+ return;
+ }
+ mShutdownTasksRun = true;
+ shutdownTasks = std::move(mShutdownTasks);
+ mShutdownTasks.Clear();
+ }
+
+ for (auto& task : shutdownTasks) {
+ task->TargetShutdown();
+ }
+ }
+
+ explicit EventTarget(MessageLoop* aLoop)
+ : mMutex("MessageLoop::EventTarget"), mLoop(aLoop) {
+ aLoop->AddDestructionObserver(this);
+ }
+
+ private:
+ virtual ~EventTarget() {
+ if (mLoop) {
+ mLoop->RemoveDestructionObserver(this);
+ }
+ MOZ_ASSERT(mShutdownTasks.IsEmpty());
+ }
+
+ void WillDestroyCurrentMessageLoop() override {
+ {
+ mozilla::MutexAutoLock lock(mMutex);
+ // The MessageLoop is being destroyed and we are called from its
+ // destructor There's no real need to remove ourselves from the
+ // destruction observer list. But it makes things look tidier.
+ mLoop->RemoveDestructionObserver(this);
+ mLoop = nullptr;
+ }
+
+ TargetShutdown();
+ }
+
+ mozilla::Mutex mMutex;
+ bool mShutdownTasksRun MOZ_GUARDED_BY(mMutex) = false;
+ nsTArray<nsCOMPtr<nsITargetShutdownTask>> mShutdownTasks
+ MOZ_GUARDED_BY(mMutex);
+ MessageLoop* mLoop MOZ_GUARDED_BY(mMutex);
+};
+
+NS_IMPL_ISUPPORTS(MessageLoop::EventTarget, nsIEventTarget,
+ nsISerialEventTarget)
+
+NS_IMETHODIMP_(bool)
+MessageLoop::EventTarget::IsOnCurrentThreadInfallible() {
+ mozilla::MutexAutoLock lock(mMutex);
+ return mLoop == MessageLoop::current();
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::IsOnCurrentThread(bool* aResult) {
+ *aResult = IsOnCurrentThreadInfallible();
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::DispatchFromScript(nsIRunnable* aEvent,
+ uint32_t aFlags) {
+ nsCOMPtr<nsIRunnable> event(aEvent);
+ return Dispatch(event.forget(), aFlags);
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::Dispatch(already_AddRefed<nsIRunnable> aEvent,
+ uint32_t aFlags) {
+ mozilla::MutexAutoLock lock(mMutex);
+ if (!mLoop) {
+ return NS_ERROR_NOT_INITIALIZED;
+ }
+
+ if (aFlags != NS_DISPATCH_NORMAL) {
+ return NS_ERROR_NOT_IMPLEMENTED;
+ }
+
+ mLoop->PostTask(std::move(aEvent));
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::DelayedDispatch(already_AddRefed<nsIRunnable> aEvent,
+ uint32_t aDelayMs) {
+ mozilla::MutexAutoLock lock(mMutex);
+ if (!mLoop) {
+ return NS_ERROR_NOT_INITIALIZED;
+ }
+
+ mLoop->PostDelayedTask(std::move(aEvent), aDelayMs);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::RegisterShutdownTask(nsITargetShutdownTask* aTask) {
+ mozilla::MutexAutoLock lock(mMutex);
+ if (!mLoop || mShutdownTasksRun) {
+ return NS_ERROR_UNEXPECTED;
+ }
+ MOZ_ASSERT(!mShutdownTasks.Contains(aTask));
+ mShutdownTasks.AppendElement(aTask);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessageLoop::EventTarget::UnregisterShutdownTask(nsITargetShutdownTask* aTask) {
+ mozilla::MutexAutoLock lock(mMutex);
+ if (!mLoop || mShutdownTasksRun) {
+ return NS_ERROR_UNEXPECTED;
+ }
+ return mShutdownTasks.RemoveElement(aTask) ? NS_OK : NS_ERROR_UNEXPECTED;
+}
+
+//------------------------------------------------------------------------------
+
+// static
+MessageLoop* MessageLoop::current() { return get_tls_ptr().Get(); }
+
+// static
+void MessageLoop::set_current(MessageLoop* loop) { get_tls_ptr().Set(loop); }
+
+static mozilla::Atomic<int32_t> message_loop_id_seq(0);
+
+MessageLoop::MessageLoop(Type type, nsISerialEventTarget* aEventTarget)
+ : type_(type),
+ id_(++message_loop_id_seq),
+ nestable_tasks_allowed_(true),
+ exception_restoration_(false),
+ incoming_queue_lock_("MessageLoop Incoming Queue Lock"),
+ state_(NULL),
+ run_depth_base_(1),
+ shutting_down_(false),
+#ifdef XP_WIN
+ os_modal_loop_(false),
+#endif // XP_WIN
+ transient_hang_timeout_(0),
+ permanent_hang_timeout_(0),
+ next_sequence_num_(0) {
+ DCHECK(!current()) << "should only have one message loop per thread";
+ get_tls_ptr().Set(this);
+
+ // Must initialize after current() is initialized.
+ mEventTarget = new EventTarget(this);
+
+ switch (type_) {
+ case TYPE_MOZILLA_PARENT:
+ MOZ_RELEASE_ASSERT(!aEventTarget);
+ pump_ = new mozilla::ipc::MessagePump(aEventTarget);
+ return;
+ case TYPE_MOZILLA_CHILD:
+ MOZ_RELEASE_ASSERT(!aEventTarget);
+ pump_ = new mozilla::ipc::MessagePumpForChildProcess();
+ // There is a MessageLoop Run call from XRE_InitChildProcess
+ // and another one from MessagePumpForChildProcess. The one
+ // from MessagePumpForChildProcess becomes the base, so we need
+ // to set run_depth_base_ to 2 or we'll never be able to process
+ // Idle tasks.
+ run_depth_base_ = 2;
+ return;
+ case TYPE_MOZILLA_NONMAINTHREAD:
+ pump_ = new mozilla::ipc::MessagePumpForNonMainThreads(aEventTarget);
+ return;
+#if defined(XP_WIN) || defined(XP_DARWIN)
+ case TYPE_MOZILLA_NONMAINUITHREAD:
+ pump_ = new mozilla::ipc::MessagePumpForNonMainUIThreads(aEventTarget);
+ return;
+#elif defined(MOZ_WIDGET_ANDROID)
+ case TYPE_MOZILLA_ANDROID_UI:
+ MOZ_RELEASE_ASSERT(aEventTarget);
+ pump_ = new mozilla::ipc::MessagePumpForAndroidUI(aEventTarget);
+ return;
+#endif // defined(MOZ_WIDGET_ANDROID)
+ default:
+ // Create one of Chromium's standard MessageLoop types below.
+ break;
+ }
+
+#if defined(XP_WIN)
+ // TODO(rvargas): Get rid of the OS guards.
+ if (type_ == TYPE_DEFAULT) {
+ pump_ = new base::MessagePumpDefault();
+ } else if (type_ == TYPE_IO) {
+ pump_ = new base::MessagePumpForIO();
+ } else {
+ DCHECK(type_ == TYPE_UI);
+ pump_ = new base::MessagePumpForUI();
+ }
+#else
+ if (type_ == TYPE_UI) {
+# if defined(XP_DARWIN)
+ pump_ = base::MessagePumpMac::Create();
+# elif defined(XP_LINUX) || defined(__DragonFly__) || defined(XP_FREEBSD) || \
+ defined(XP_NETBSD) || defined(XP_OPENBSD)
+ pump_ = new base::MessagePumpForUI();
+# endif // XP_LINUX
+ } else if (type_ == TYPE_IO) {
+ pump_ = new base::MessagePumpLibevent();
+ } else {
+ pump_ = new base::MessagePumpDefault();
+ }
+#endif
+
+ // We want GetCurrentSerialEventTarget() to return the real nsThread if it
+ // will be used to dispatch tasks. However, under all other cases; we'll want
+ // it to return this MessageLoop's EventTarget.
+ if (nsISerialEventTarget* thread = pump_->GetXPCOMThread()) {
+ MOZ_ALWAYS_SUCCEEDS(thread->RegisterShutdownTask(mEventTarget));
+ } else {
+ mozilla::SerialEventTargetGuard::Set(mEventTarget);
+ }
+}
+
+MessageLoop::~MessageLoop() {
+ DCHECK(this == current());
+
+ // Let interested parties have one last shot at accessing this.
+ FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
+ WillDestroyCurrentMessageLoop());
+
+ DCHECK(!state_);
+
+ // Clean up any unprocessed tasks, but take care: deleting a task could
+ // result in the addition of more tasks (e.g., via DeleteSoon). We set a
+ // limit on the number of times we will allow a deleted task to generate more
+ // tasks. Normally, we should only pass through this loop once or twice. If
+ // we end up hitting the loop limit, then it is probably due to one task that
+ // is being stubborn. Inspect the queues to see who is left.
+ bool did_work;
+ for (int i = 0; i < 100; ++i) {
+ DeletePendingTasks();
+ ReloadWorkQueue();
+ // If we end up with empty queues, then break out of the loop.
+ did_work = DeletePendingTasks();
+ if (!did_work) break;
+ }
+ DCHECK(!did_work);
+
+ // OK, now make it so that no one can find us.
+ get_tls_ptr().Set(NULL);
+}
+
+void MessageLoop::AddDestructionObserver(DestructionObserver* obs) {
+ DCHECK(this == current());
+ destruction_observers_.AddObserver(obs);
+}
+
+void MessageLoop::RemoveDestructionObserver(DestructionObserver* obs) {
+ DCHECK(this == current());
+ destruction_observers_.RemoveObserver(obs);
+}
+
+void MessageLoop::Run() {
+ AutoRunState save_state(this);
+ RunHandler();
+}
+
+// Runs the loop in two different SEH modes:
+// enable_SEH_restoration_ = false : any unhandled exception goes to the last
+// one that calls SetUnhandledExceptionFilter().
+// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
+// that was existed before the loop was run.
+void MessageLoop::RunHandler() {
+#if defined(XP_WIN)
+ if (exception_restoration_) {
+ LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
+ MOZ_SEH_TRY { RunInternal(); }
+ MOZ_SEH_EXCEPT(SEHFilter(current_filter)) {}
+ return;
+ }
+#endif
+
+ RunInternal();
+}
+
+//------------------------------------------------------------------------------
+
+void MessageLoop::RunInternal() {
+ DCHECK(this == current());
+ pump_->Run(this);
+}
+
+//------------------------------------------------------------------------------
+// Wrapper functions for use in above message loop framework.
+
+bool MessageLoop::ProcessNextDelayedNonNestableTask() {
+ if (state_->run_depth > run_depth_base_) return false;
+
+ if (deferred_non_nestable_work_queue_.empty()) return false;
+
+ nsCOMPtr<nsIRunnable> task =
+ std::move(deferred_non_nestable_work_queue_.front().task);
+ deferred_non_nestable_work_queue_.pop();
+
+ RunTask(task.forget());
+ return true;
+}
+
+//------------------------------------------------------------------------------
+
+void MessageLoop::Quit() {
+ DCHECK(current() == this);
+ if (state_) {
+ state_->quit_received = true;
+ } else {
+ NOTREACHED() << "Must be inside Run to call Quit";
+ }
+}
+
+void MessageLoop::PostTask(already_AddRefed<nsIRunnable> task) {
+ PostTask_Helper(std::move(task), 0);
+}
+
+void MessageLoop::PostDelayedTask(already_AddRefed<nsIRunnable> task,
+ int delay_ms) {
+ PostTask_Helper(std::move(task), delay_ms);
+}
+
+void MessageLoop::PostIdleTask(already_AddRefed<nsIRunnable> task) {
+ DCHECK(current() == this);
+ MOZ_ASSERT(NS_IsMainThread());
+
+ PendingTask pending_task(std::move(task), false);
+ mozilla::LogRunnable::LogDispatch(pending_task.task.get());
+ deferred_non_nestable_work_queue_.push(std::move(pending_task));
+}
+
+// Possibly called on a background thread!
+void MessageLoop::PostTask_Helper(already_AddRefed<nsIRunnable> task,
+ int delay_ms) {
+ if (nsISerialEventTarget* target = pump_->GetXPCOMThread()) {
+ nsresult rv;
+ if (delay_ms) {
+ rv = target->DelayedDispatch(std::move(task), delay_ms);
+ } else {
+ rv = target->Dispatch(std::move(task), 0);
+ }
+ MOZ_ALWAYS_SUCCEEDS(rv);
+ return;
+ }
+
+ // Tasks should only be queued before or during the Run loop, not after.
+ MOZ_ASSERT(!shutting_down_);
+
+ PendingTask pending_task(std::move(task), true);
+
+ if (delay_ms > 0) {
+ pending_task.delayed_run_time =
+ TimeTicks::Now() + TimeDelta::FromMilliseconds(delay_ms);
+ } else {
+ DCHECK(delay_ms == 0) << "delay should not be negative";
+ }
+
+ // Warning: Don't try to short-circuit, and handle this thread's tasks more
+ // directly, as it could starve handling of foreign threads. Put every task
+ // into this queue.
+
+ RefPtr<base::MessagePump> pump;
+ {
+ mozilla::MutexAutoLock locked(incoming_queue_lock_);
+ mozilla::LogRunnable::LogDispatch(pending_task.task.get());
+ incoming_queue_.push(std::move(pending_task));
+ pump = pump_;
+ }
+ // Since the incoming_queue_ may contain a task that destroys this message
+ // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
+ // We use a stack-based reference to the message pump so that we can call
+ // ScheduleWork outside of incoming_queue_lock_.
+
+ pump->ScheduleWork();
+}
+
+void MessageLoop::SetNestableTasksAllowed(bool allowed) {
+ if (nestable_tasks_allowed_ != allowed) {
+ nestable_tasks_allowed_ = allowed;
+ if (!nestable_tasks_allowed_) return;
+ // Start the native pump if we are not already pumping.
+ pump_->ScheduleWorkForNestedLoop();
+ }
+}
+
+void MessageLoop::ScheduleWork() {
+ // Start the native pump if we are not already pumping.
+ pump_->ScheduleWork();
+}
+
+bool MessageLoop::NestableTasksAllowed() const {
+ return nestable_tasks_allowed_;
+}
+
+//------------------------------------------------------------------------------
+
+void MessageLoop::RunTask(already_AddRefed<nsIRunnable> aTask) {
+ DCHECK(nestable_tasks_allowed_);
+ // Execute the task and assume the worst: It is probably not reentrant.
+ nestable_tasks_allowed_ = false;
+
+ nsCOMPtr<nsIRunnable> task = aTask;
+
+ {
+ mozilla::LogRunnable::Run log(task.get());
+ AUTO_PROFILE_FOLLOWING_RUNNABLE(task);
+ task->Run();
+ task = nullptr;
+ }
+
+ nestable_tasks_allowed_ = true;
+}
+
+bool MessageLoop::DeferOrRunPendingTask(PendingTask&& pending_task) {
+ if (pending_task.nestable || state_->run_depth <= run_depth_base_) {
+ RunTask(pending_task.task.forget());
+ // Show that we ran a task (Note: a new one might arrive as a
+ // consequence!).
+ return true;
+ }
+
+ // We couldn't run the task now because we're in a nested message loop
+ // and the task isn't nestable.
+ mozilla::LogRunnable::LogDispatch(pending_task.task.get());
+ deferred_non_nestable_work_queue_.push(std::move(pending_task));
+ return false;
+}
+
+void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
+ // Move to the delayed work queue. Initialize the sequence number
+ // before inserting into the delayed_work_queue_. The sequence number
+ // is used to faciliate FIFO sorting when two tasks have the same
+ // delayed_run_time value.
+ PendingTask new_pending_task(pending_task);
+ new_pending_task.sequence_num = next_sequence_num_++;
+ mozilla::LogRunnable::LogDispatch(new_pending_task.task.get());
+ delayed_work_queue_.push(std::move(new_pending_task));
+}
+
+void MessageLoop::ReloadWorkQueue() {
+ // We can improve performance of our loading tasks from incoming_queue_ to
+ // work_queue_ by waiting until the last minute (work_queue_ is empty) to
+ // load. That reduces the number of locks-per-task significantly when our
+ // queues get large.
+ if (!work_queue_.empty())
+ return; // Wait till we *really* need to lock and load.
+
+ // Acquire all we can from the inter-thread queue with one lock acquisition.
+ {
+ mozilla::MutexAutoLock lock(incoming_queue_lock_);
+ if (incoming_queue_.empty()) return;
+ std::swap(incoming_queue_, work_queue_);
+ DCHECK(incoming_queue_.empty());
+ }
+}
+
+bool MessageLoop::DeletePendingTasks() {
+ MOZ_ASSERT(work_queue_.empty());
+ bool did_work = !deferred_non_nestable_work_queue_.empty();
+ while (!deferred_non_nestable_work_queue_.empty()) {
+ deferred_non_nestable_work_queue_.pop();
+ }
+ did_work |= !delayed_work_queue_.empty();
+ while (!delayed_work_queue_.empty()) {
+ delayed_work_queue_.pop();
+ }
+ return did_work;
+}
+
+bool MessageLoop::DoWork() {
+ if (!nestable_tasks_allowed_) {
+ // Task can't be executed right now.
+ return false;
+ }
+
+ for (;;) {
+ ReloadWorkQueue();
+ if (work_queue_.empty()) break;
+
+ // Execute oldest task.
+ do {
+ PendingTask pending_task = std::move(work_queue_.front());
+ work_queue_.pop();
+ if (!pending_task.delayed_run_time.is_null()) {
+ // NB: Don't move, because we use this later!
+ AddToDelayedWorkQueue(pending_task);
+ // If we changed the topmost task, then it is time to re-schedule.
+ if (delayed_work_queue_.top().task == pending_task.task)
+ pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
+ } else {
+ if (DeferOrRunPendingTask(std::move(pending_task))) return true;
+ }
+ } while (!work_queue_.empty());
+ }
+
+ // Nothing happened.
+ return false;
+}
+
+bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
+ if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
+ *next_delayed_work_time = TimeTicks();
+ return false;
+ }
+
+ if (delayed_work_queue_.top().delayed_run_time > TimeTicks::Now()) {
+ *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
+ return false;
+ }
+
+ PendingTask pending_task = delayed_work_queue_.top();
+ delayed_work_queue_.pop();
+
+ if (!delayed_work_queue_.empty())
+ *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
+
+ return DeferOrRunPendingTask(std::move(pending_task));
+}
+
+bool MessageLoop::DoIdleWork() {
+ if (ProcessNextDelayedNonNestableTask()) return true;
+
+ if (state_->quit_received) pump_->Quit();
+
+ return false;
+}
+
+//------------------------------------------------------------------------------
+// MessageLoop::AutoRunState
+
+MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
+ // Top-level Run should only get called once.
+ MOZ_ASSERT(!loop_->shutting_down_);
+
+ // Make the loop reference us.
+ previous_state_ = loop_->state_;
+ if (previous_state_) {
+ run_depth = previous_state_->run_depth + 1;
+ } else {
+ run_depth = 1;
+ }
+ loop_->state_ = this;
+
+ // Initialize the other fields:
+ quit_received = false;
+#if defined(XP_WIN)
+ dispatcher = NULL;
+#endif
+}
+
+MessageLoop::AutoRunState::~AutoRunState() {
+ loop_->state_ = previous_state_;
+
+ // If exiting a top-level Run, then we're shutting down.
+ loop_->shutting_down_ = !previous_state_;
+}
+
+//------------------------------------------------------------------------------
+// MessageLoop::PendingTask
+
+bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
+ // Since the top of a priority queue is defined as the "greatest" element, we
+ // need to invert the comparison here. We want the smaller time to be at the
+ // top of the heap.
+
+ if (delayed_run_time < other.delayed_run_time) return false;
+
+ if (delayed_run_time > other.delayed_run_time) return true;
+
+ // If the times happen to match, then we use the sequence number to decide.
+ // Compare the difference to support integer roll-over.
+ return (sequence_num - other.sequence_num) > 0;
+}
+
+//------------------------------------------------------------------------------
+// MessageLoop::SerialEventTarget
+
+nsISerialEventTarget* MessageLoop::SerialEventTarget() { return mEventTarget; }
+
+//------------------------------------------------------------------------------
+// MessageLoopForUI
+
+#if defined(XP_WIN)
+
+void MessageLoopForUI::Run(Dispatcher* dispatcher) {
+ AutoRunState save_state(this);
+ state_->dispatcher = dispatcher;
+ RunHandler();
+}
+
+void MessageLoopForUI::AddObserver(Observer* observer) {
+ pump_win()->AddObserver(observer);
+}
+
+void MessageLoopForUI::RemoveObserver(Observer* observer) {
+ pump_win()->RemoveObserver(observer);
+}
+
+void MessageLoopForUI::WillProcessMessage(const MSG& message) {
+ pump_win()->WillProcessMessage(message);
+}
+void MessageLoopForUI::DidProcessMessage(const MSG& message) {
+ pump_win()->DidProcessMessage(message);
+}
+void MessageLoopForUI::PumpOutPendingPaintMessages() {
+ pump_ui()->PumpOutPendingPaintMessages();
+}
+
+#endif // defined(XP_WIN)
+
+//------------------------------------------------------------------------------
+// MessageLoopForIO
+
+#if defined(XP_WIN)
+
+void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
+ pump_io()->RegisterIOHandler(file, handler);
+}
+
+bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
+ return pump_io()->WaitForIOCompletion(timeout, filter);
+}
+
+#else
+
+bool MessageLoopForIO::WatchFileDescriptor(int fd, bool persistent, Mode mode,
+ FileDescriptorWatcher* controller,
+ Watcher* delegate) {
+ return pump_libevent()->WatchFileDescriptor(
+ fd, persistent, static_cast<base::MessagePumpLibevent::Mode>(mode),
+ controller, delegate);
+}
+
+bool MessageLoopForIO::CatchSignal(int sig, SignalEvent* sigevent,
+ SignalWatcher* delegate) {
+ return pump_libevent()->CatchSignal(sig, sigevent, delegate);
+}
+
+#endif
diff --git a/ipc/chromium/src/base/message_loop.h b/ipc/chromium/src/base/message_loop.h
new file mode 100644
index 0000000000..ee3f118ac3
--- /dev/null
+++ b/ipc/chromium/src/base/message_loop.h
@@ -0,0 +1,559 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MESSAGE_LOOP_H_
+#define BASE_MESSAGE_LOOP_H_
+
+#include <deque>
+#include <queue>
+#include <string>
+#include <vector>
+#include <map>
+
+#include "base/message_pump.h"
+#include "base/observer_list.h"
+
+#include "mozilla/Mutex.h"
+
+#if defined(XP_WIN)
+// We need this to declare base::MessagePumpWin::Dispatcher, which we should
+// really just eliminate.
+# include "base/message_pump_win.h"
+#else
+# include "base/message_pump_libevent.h"
+#endif
+
+#include "nsCOMPtr.h"
+#include "nsIRunnable.h"
+#include "nsThreadUtils.h"
+
+class nsISerialEventTarget;
+
+namespace mozilla {
+namespace ipc {
+
+class DoWorkRunnable;
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+// A MessageLoop is used to process events for a particular thread. There is
+// at most one MessageLoop instance per thread.
+//
+// Events include at a minimum Task instances submitted to PostTask or those
+// managed by TimerManager. Depending on the type of message pump used by the
+// MessageLoop other events such as UI messages may be processed. On Windows
+// APC calls (as time permits) and signals sent to a registered set of HANDLEs
+// may also be processed.
+//
+// NOTE: Unless otherwise specified, a MessageLoop's methods may only be called
+// on the thread where the MessageLoop's Run method executes.
+//
+// NOTE: MessageLoop has task reentrancy protection. This means that if a
+// task is being processed, a second task cannot start until the first task is
+// finished. Reentrancy can happen when processing a task, and an inner
+// message pump is created. That inner pump then processes native messages
+// which could implicitly start an inner task. Inner message pumps are created
+// with dialogs (DialogBox), common dialogs (GetOpenFileName), OLE functions
+// (DoDragDrop), printer functions (StartDoc) and *many* others.
+//
+// Sample workaround when inner task processing is needed:
+// bool old_state = MessageLoop::current()->NestableTasksAllowed();
+// MessageLoop::current()->SetNestableTasksAllowed(true);
+// HRESULT hr = DoDragDrop(...); // Implicitly runs a modal message loop here.
+// MessageLoop::current()->SetNestableTasksAllowed(old_state);
+// // Process hr (the result returned by DoDragDrop().
+//
+// Please be SURE your task is reentrant (nestable) and all global variables
+// are stable and accessible before calling SetNestableTasksAllowed(true).
+//
+class MessageLoop : public base::MessagePump::Delegate {
+ friend class mozilla::ipc::DoWorkRunnable;
+
+ public:
+ // A DestructionObserver is notified when the current MessageLoop is being
+ // destroyed. These obsevers are notified prior to MessageLoop::current()
+ // being changed to return NULL. This gives interested parties the chance to
+ // do final cleanup that depends on the MessageLoop.
+ //
+ // NOTE: Any tasks posted to the MessageLoop during this notification will
+ // not be run. Instead, they will be deleted.
+ //
+ class DestructionObserver {
+ public:
+ virtual ~DestructionObserver() {}
+ virtual void WillDestroyCurrentMessageLoop() = 0;
+ };
+
+ // Add a DestructionObserver, which will start receiving notifications
+ // immediately.
+ void AddDestructionObserver(DestructionObserver* destruction_observer);
+
+ // Remove a DestructionObserver. It is safe to call this method while a
+ // DestructionObserver is receiving a notification callback.
+ void RemoveDestructionObserver(DestructionObserver* destruction_observer);
+
+ // The "PostTask" family of methods call the task's Run method asynchronously
+ // from within a message loop at some point in the future.
+ //
+ // With the PostTask variant, tasks are invoked in FIFO order, inter-mixed
+ // with normal UI or IO event processing. With the PostDelayedTask variant,
+ // tasks are called after at least approximately 'delay_ms' have elapsed.
+ //
+ // The NonNestable variants work similarly except that they promise never to
+ // dispatch the task from a nested invocation of MessageLoop::Run. Instead,
+ // such tasks get deferred until the top-most MessageLoop::Run is executing.
+ //
+ // The MessageLoop takes ownership of the Task, and deletes it after it has
+ // been Run().
+ //
+ // New tasks should not be posted after the invocation of a MessageLoop's
+ // Run method. Otherwise, they may fail to actually run. Callers should check
+ // if the MessageLoop is processing tasks if necessary by calling
+ // IsAcceptingTasks().
+ //
+ // NOTE: These methods may be called on any thread. The Task will be invoked
+ // on the thread that executes MessageLoop::Run().
+
+ bool IsAcceptingTasks() const { return !shutting_down_; }
+
+ void PostTask(already_AddRefed<nsIRunnable> task);
+
+ void PostDelayedTask(already_AddRefed<nsIRunnable> task, int delay_ms);
+
+ // PostIdleTask is not thread safe and should be called on this thread
+ void PostIdleTask(already_AddRefed<nsIRunnable> task);
+
+ // Run the message loop.
+ void Run();
+
+ // Signals the Run method to return after it is done processing all pending
+ // messages. This method may only be called on the same thread that called
+ // Run, and Run must still be on the call stack.
+ //
+ // Use QuitTask if you need to Quit another thread's MessageLoop, but note
+ // that doing so is fairly dangerous if the target thread makes nested calls
+ // to MessageLoop::Run. The problem being that you won't know which nested
+ // run loop you are quiting, so be careful!
+ //
+ void Quit();
+
+ // Invokes Quit on the current MessageLoop when run. Useful to schedule an
+ // arbitrary MessageLoop to Quit.
+ class QuitTask : public mozilla::Runnable {
+ public:
+ QuitTask() : mozilla::Runnable("QuitTask") {}
+ NS_IMETHOD Run() override {
+ MessageLoop::current()->Quit();
+ return NS_OK;
+ }
+ };
+
+ // Return an XPCOM-compatible event target for this thread.
+ nsISerialEventTarget* SerialEventTarget();
+
+ // A MessageLoop has a particular type, which indicates the set of
+ // asynchronous events it may process in addition to tasks and timers.
+ //
+ // TYPE_DEFAULT
+ // This type of ML only supports tasks and timers.
+ //
+ // TYPE_UI
+ // This type of ML also supports native UI events (e.g., Windows messages).
+ // See also MessageLoopForUI.
+ //
+ // TYPE_IO
+ // This type of ML also supports asynchronous IO. See also
+ // MessageLoopForIO.
+ //
+ // TYPE_MOZILLA_CHILD
+ // This type of ML is used in Mozilla child processes which initialize
+ // XPCOM and use the gecko event loop.
+ //
+ // TYPE_MOZILLA_PARENT
+ // This type of ML is used in Mozilla parent processes which initialize
+ // XPCOM and use the gecko event loop.
+ //
+ // TYPE_MOZILLA_NONMAINTHREAD
+ // This type of ML is used in Mozilla parent processes which initialize
+ // XPCOM and use the nsThread event loop.
+ //
+ // TYPE_MOZILLA_NONMAINUITHREAD
+ // This type of ML is used in Mozilla processes which initialize XPCOM
+ // and use TYPE_UI loop logic.
+ //
+ enum Type {
+ TYPE_DEFAULT,
+ TYPE_UI,
+ TYPE_IO,
+ TYPE_MOZILLA_CHILD,
+ TYPE_MOZILLA_PARENT,
+ TYPE_MOZILLA_NONMAINTHREAD,
+ TYPE_MOZILLA_NONMAINUITHREAD,
+ TYPE_MOZILLA_ANDROID_UI
+ };
+
+ // Normally, it is not necessary to instantiate a MessageLoop. Instead, it
+ // is typical to make use of the current thread's MessageLoop instance.
+ explicit MessageLoop(Type type = TYPE_DEFAULT,
+ nsISerialEventTarget* aEventTarget = nullptr);
+ ~MessageLoop();
+
+ // Returns the type passed to the constructor.
+ Type type() const { return type_; }
+
+ // Unique, non-repeating ID for this message loop.
+ int32_t id() const { return id_; }
+
+ // Optional call to connect the thread name with this loop.
+ void set_thread_name(const std::string& aThreadName) {
+ DCHECK(thread_name_.empty()) << "Should not rename this thread!";
+ thread_name_ = aThreadName;
+ }
+ const std::string& thread_name() const { return thread_name_; }
+
+ // Returns the MessageLoop object for the current thread, or null if none.
+ static MessageLoop* current();
+
+ static void set_current(MessageLoop* loop);
+
+ // Enables or disables the recursive task processing. This happens in the case
+ // of recursive message loops. Some unwanted message loop may occurs when
+ // using common controls or printer functions. By default, recursive task
+ // processing is disabled.
+ //
+ // The specific case where tasks get queued is:
+ // - The thread is running a message loop.
+ // - It receives a task #1 and execute it.
+ // - The task #1 implicitly start a message loop, like a MessageBox in the
+ // unit test. This can also be StartDoc or GetSaveFileName.
+ // - The thread receives a task #2 before or while in this second message
+ // loop.
+ // - With NestableTasksAllowed set to true, the task #2 will run right away.
+ // Otherwise, it will get executed right after task #1 completes at "thread
+ // message loop level".
+ void SetNestableTasksAllowed(bool allowed);
+ void ScheduleWork();
+ bool NestableTasksAllowed() const;
+
+ // Enables or disables the restoration during an exception of the unhandled
+ // exception filter that was active when Run() was called. This can happen
+ // if some third party code call SetUnhandledExceptionFilter() and never
+ // restores the previous filter.
+ void set_exception_restoration(bool restore) {
+ exception_restoration_ = restore;
+ }
+
+#if defined(XP_WIN)
+ void set_os_modal_loop(bool os_modal_loop) { os_modal_loop_ = os_modal_loop; }
+
+ bool& os_modal_loop() { return os_modal_loop_; }
+#endif // XP_WIN
+
+ // Set the timeouts for background hang monitoring.
+ // A value of 0 indicates there is no timeout.
+ void set_hang_timeouts(uint32_t transient_timeout_ms,
+ uint32_t permanent_timeout_ms) {
+ transient_hang_timeout_ = transient_timeout_ms;
+ permanent_hang_timeout_ = permanent_timeout_ms;
+ }
+ uint32_t transient_hang_timeout() const { return transient_hang_timeout_; }
+ uint32_t permanent_hang_timeout() const { return permanent_hang_timeout_; }
+
+ //----------------------------------------------------------------------------
+ protected:
+ struct RunState {
+ // Used to count how many Run() invocations are on the stack.
+ int run_depth;
+
+ // Used to record that Quit() was called, or that we should quit the pump
+ // once it becomes idle.
+ bool quit_received;
+
+#if defined(XP_WIN)
+ base::MessagePumpWin::Dispatcher* dispatcher;
+#endif
+ };
+
+ class AutoRunState : RunState {
+ public:
+ explicit AutoRunState(MessageLoop* loop);
+ ~AutoRunState();
+
+ private:
+ MessageLoop* loop_;
+ RunState* previous_state_;
+ };
+
+ // This structure is copied around by value.
+ struct PendingTask {
+ nsCOMPtr<nsIRunnable> task; // The task to run.
+ base::TimeTicks delayed_run_time; // The time when the task should be run.
+ int sequence_num; // Secondary sort key for run time.
+ bool nestable; // OK to dispatch from a nested loop.
+
+ PendingTask(already_AddRefed<nsIRunnable> aTask, bool aNestable)
+ : task(aTask), sequence_num(0), nestable(aNestable) {}
+
+ PendingTask(PendingTask&& aOther)
+ : task(std::move(aOther.task)),
+ delayed_run_time(aOther.delayed_run_time),
+ sequence_num(aOther.sequence_num),
+ nestable(aOther.nestable) {}
+
+ // std::priority_queue<T>::top is dumb, so we have to have this.
+ PendingTask(const PendingTask& aOther)
+ : task(aOther.task),
+ delayed_run_time(aOther.delayed_run_time),
+ sequence_num(aOther.sequence_num),
+ nestable(aOther.nestable) {}
+ PendingTask& operator=(const PendingTask& aOther) {
+ task = aOther.task;
+ delayed_run_time = aOther.delayed_run_time;
+ sequence_num = aOther.sequence_num;
+ nestable = aOther.nestable;
+ return *this;
+ }
+
+ // Used to support sorting.
+ bool operator<(const PendingTask& other) const;
+ };
+
+ typedef std::queue<PendingTask> TaskQueue;
+ typedef std::priority_queue<PendingTask> DelayedTaskQueue;
+
+#if defined(XP_WIN)
+ base::MessagePumpWin* pump_win() {
+ return static_cast<base::MessagePumpWin*>(pump_.get());
+ }
+#else
+ base::MessagePumpLibevent* pump_libevent() {
+ return static_cast<base::MessagePumpLibevent*>(pump_.get());
+ }
+#endif
+
+ // A function to encapsulate all the exception handling capability in the
+ // stacks around the running of a main message loop. It will run the message
+ // loop in a SEH try block or not depending on the set_SEH_restoration()
+ // flag.
+ void RunHandler();
+
+ // A surrounding stack frame around the running of the message loop that
+ // supports all saving and restoring of state, as is needed for any/all (ugly)
+ // recursive calls.
+ void RunInternal();
+
+ // Called to process any delayed non-nestable tasks.
+ bool ProcessNextDelayedNonNestableTask();
+
+ //----------------------------------------------------------------------------
+ // Run a work_queue_ task or new_task, and delete it (if it was processed by
+ // PostTask). If there are queued tasks, the oldest one is executed and
+ // new_task is queued. new_task is optional and can be NULL. In this NULL
+ // case, the method will run one pending task (if any exist). Returns true if
+ // it executes a task. Queued tasks accumulate only when there is a
+ // non-nestable task currently processing, in which case the new_task is
+ // appended to the list work_queue_. Such re-entrancy generally happens when
+ // an unrequested message pump (typical of a native dialog) is executing in
+ // the context of a task.
+ bool QueueOrRunTask(already_AddRefed<nsIRunnable> new_task);
+
+ // Runs the specified task and deletes it.
+ void RunTask(already_AddRefed<nsIRunnable> task);
+
+ // Calls RunTask or queues the pending_task on the deferred task list if it
+ // cannot be run right now. Returns true if the task was run.
+ bool DeferOrRunPendingTask(PendingTask&& pending_task);
+
+ // Adds the pending task to delayed_work_queue_.
+ void AddToDelayedWorkQueue(const PendingTask& pending_task);
+
+ // Load tasks from the incoming_queue_ into work_queue_ if the latter is
+ // empty. The former requires a lock to access, while the latter is directly
+ // accessible on this thread.
+ void ReloadWorkQueue();
+
+ // Delete tasks that haven't run yet without running them. Used in the
+ // destructor to make sure all the task's destructors get called. Returns
+ // true if some work was done.
+ bool DeletePendingTasks();
+
+ // Post a task to our incomming queue.
+ void PostTask_Helper(already_AddRefed<nsIRunnable> task, int delay_ms);
+
+ // base::MessagePump::Delegate methods:
+ virtual bool DoWork() override;
+ virtual bool DoDelayedWork(base::TimeTicks* next_delayed_work_time) override;
+ virtual bool DoIdleWork() override;
+
+ Type type_;
+ int32_t id_;
+
+ // A list of tasks that need to be processed by this instance. Note that
+ // this queue is only accessed (push/pop) by our current thread.
+ TaskQueue work_queue_;
+
+ // Contains delayed tasks, sorted by their 'delayed_run_time' property.
+ DelayedTaskQueue delayed_work_queue_;
+
+ // A queue of non-nestable tasks that we had to defer because when it came
+ // time to execute them we were in a nested message loop. They will execute
+ // once we're out of nested message loops.
+ TaskQueue deferred_non_nestable_work_queue_;
+
+ RefPtr<base::MessagePump> pump_;
+
+ base::ObserverList<DestructionObserver> destruction_observers_;
+
+ // A recursion block that prevents accidentally running additonal tasks when
+ // insider a (accidentally induced?) nested message pump.
+ bool nestable_tasks_allowed_;
+
+ bool exception_restoration_;
+
+ std::string thread_name_;
+
+ // A null terminated list which creates an incoming_queue of tasks that are
+ // aquired under a mutex for processing on this instance's thread. These tasks
+ // have not yet been sorted out into items for our work_queue_ vs items that
+ // will be handled by the TimerManager.
+ TaskQueue incoming_queue_ MOZ_GUARDED_BY(incoming_queue_lock_);
+ // Protect access to incoming_queue_.
+ mozilla::Mutex incoming_queue_lock_;
+
+ RunState* state_;
+ int run_depth_base_;
+ bool shutting_down_;
+
+#if defined(XP_WIN)
+ // Should be set to true before calling Windows APIs like TrackPopupMenu, etc
+ // which enter a modal message loop.
+ bool os_modal_loop_;
+#endif
+
+ // Timeout values for hang monitoring
+ uint32_t transient_hang_timeout_;
+ uint32_t permanent_hang_timeout_;
+
+ // The next sequence number to use for delayed tasks.
+ int next_sequence_num_;
+
+ class EventTarget;
+ RefPtr<EventTarget> mEventTarget;
+
+ DISALLOW_COPY_AND_ASSIGN(MessageLoop);
+};
+
+//-----------------------------------------------------------------------------
+// MessageLoopForUI extends MessageLoop with methods that are particular to a
+// MessageLoop instantiated with TYPE_UI.
+//
+// This class is typically used like so:
+// MessageLoopForUI::current()->...call some method...
+//
+class MessageLoopForUI : public MessageLoop {
+ public:
+ explicit MessageLoopForUI(Type aType = TYPE_UI) : MessageLoop(aType) {}
+
+ // Returns the MessageLoopForUI of the current thread.
+ static MessageLoopForUI* current() {
+ MessageLoop* loop = MessageLoop::current();
+ if (!loop) return NULL;
+ Type type = loop->type();
+ DCHECK(type == MessageLoop::TYPE_UI ||
+ type == MessageLoop::TYPE_MOZILLA_PARENT ||
+ type == MessageLoop::TYPE_MOZILLA_CHILD);
+ return static_cast<MessageLoopForUI*>(loop);
+ }
+
+#if defined(XP_WIN)
+ typedef base::MessagePumpWin::Dispatcher Dispatcher;
+ typedef base::MessagePumpWin::Observer Observer;
+
+ // Please see MessagePumpWin for definitions of these methods.
+ void Run(Dispatcher* dispatcher);
+ void AddObserver(Observer* observer);
+ void RemoveObserver(Observer* observer);
+ void WillProcessMessage(const MSG& message);
+ void DidProcessMessage(const MSG& message);
+ void PumpOutPendingPaintMessages();
+
+ protected:
+ // TODO(rvargas): Make this platform independent.
+ base::MessagePumpForUI* pump_ui() {
+ return static_cast<base::MessagePumpForUI*>(pump_.get());
+ }
+#endif // defined(XP_WIN)
+};
+
+// Do not add any member variables to MessageLoopForUI! This is important b/c
+// MessageLoopForUI is often allocated via MessageLoop(TYPE_UI). Any extra
+// data that you need should be stored on the MessageLoop's pump_ instance.
+COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForUI),
+ MessageLoopForUI_should_not_have_extra_member_variables);
+
+//-----------------------------------------------------------------------------
+// MessageLoopForIO extends MessageLoop with methods that are particular to a
+// MessageLoop instantiated with TYPE_IO.
+//
+// This class is typically used like so:
+// MessageLoopForIO::current()->...call some method...
+//
+class MessageLoopForIO : public MessageLoop {
+ public:
+ MessageLoopForIO() : MessageLoop(TYPE_IO) {}
+
+ // Returns the MessageLoopForIO of the current thread.
+ static MessageLoopForIO* current() {
+ MessageLoop* loop = MessageLoop::current();
+ DCHECK_EQ(MessageLoop::TYPE_IO, loop->type());
+ return static_cast<MessageLoopForIO*>(loop);
+ }
+
+#if defined(XP_WIN)
+ typedef base::MessagePumpForIO::IOHandler IOHandler;
+ typedef base::MessagePumpForIO::IOContext IOContext;
+
+ // Please see MessagePumpWin for definitions of these methods.
+ void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
+ bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
+
+ protected:
+ // TODO(rvargas): Make this platform independent.
+ base::MessagePumpForIO* pump_io() {
+ return static_cast<base::MessagePumpForIO*>(pump_.get());
+ }
+
+#else
+ typedef base::MessagePumpLibevent::Watcher Watcher;
+ typedef base::MessagePumpLibevent::FileDescriptorWatcher
+ FileDescriptorWatcher;
+
+ enum Mode {
+ WATCH_READ = base::MessagePumpLibevent::WATCH_READ,
+ WATCH_WRITE = base::MessagePumpLibevent::WATCH_WRITE,
+ WATCH_READ_WRITE = base::MessagePumpLibevent::WATCH_READ_WRITE
+ };
+
+ // Please see MessagePumpLibevent for definition.
+ bool WatchFileDescriptor(int fd, bool persistent, Mode mode,
+ FileDescriptorWatcher* controller,
+ Watcher* delegate);
+
+ typedef base::MessagePumpLibevent::SignalEvent SignalEvent;
+ typedef base::MessagePumpLibevent::SignalWatcher SignalWatcher;
+ bool CatchSignal(int sig, SignalEvent* sigevent, SignalWatcher* delegate);
+
+#endif
+};
+
+// Do not add any member variables to MessageLoopForIO! This is important b/c
+// MessageLoopForIO is often allocated via MessageLoop(TYPE_IO). Any extra
+// data that you need should be stored on the MessageLoop's pump_ instance.
+COMPILE_ASSERT(sizeof(MessageLoop) == sizeof(MessageLoopForIO),
+ MessageLoopForIO_should_not_have_extra_member_variables);
+
+#endif // BASE_MESSAGE_LOOP_H_
diff --git a/ipc/chromium/src/base/message_pump.h b/ipc/chromium/src/base/message_pump.h
new file mode 100644
index 0000000000..884c016d20
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump.h
@@ -0,0 +1,140 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MESSAGE_PUMP_H_
+#define BASE_MESSAGE_PUMP_H_
+
+#include "nsISupportsImpl.h"
+
+class nsISerialEventTarget;
+
+namespace base {
+
+class TimeTicks;
+
+class MessagePump {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(MessagePump)
+
+ // Please see the comments above the Run method for an illustration of how
+ // these delegate methods are used.
+ class Delegate {
+ public:
+ virtual ~Delegate() {}
+
+ // Called from within Run in response to ScheduleWork or when the message
+ // pump would otherwise call DoDelayedWork. Returns true to indicate that
+ // work was done. DoDelayedWork will not be called if DoWork returns true.
+ virtual bool DoWork() = 0;
+
+ // Called from within Run in response to ScheduleDelayedWork or when the
+ // message pump would otherwise sleep waiting for more work. Returns true
+ // to indicate that delayed work was done. DoIdleWork will not be called
+ // if DoDelayedWork returns true. Upon return |next_delayed_work_time|
+ // indicates the time when DoDelayedWork should be called again. If
+ // |next_delayed_work_time| is null (per Time::is_null), then the queue of
+ // future delayed work (timer events) is currently empty, and no additional
+ // calls to this function need to be scheduled.
+ virtual bool DoDelayedWork(TimeTicks* next_delayed_work_time) = 0;
+
+ // Called from within Run just before the message pump goes to sleep.
+ // Returns true to indicate that idle work was done.
+ virtual bool DoIdleWork() = 0;
+ };
+
+ // The Run method is called to enter the message pump's run loop.
+ //
+ // Within the method, the message pump is responsible for processing native
+ // messages as well as for giving cycles to the delegate periodically. The
+ // message pump should take care to mix delegate callbacks with native
+ // message processing so neither type of event starves the other of cycles.
+ //
+ // The anatomy of a typical run loop:
+ //
+ // for (;;) {
+ // bool did_work = DoInternalWork();
+ // if (should_quit_)
+ // break;
+ //
+ // did_work |= delegate_->DoWork();
+ // if (should_quit_)
+ // break;
+ //
+ // did_work |= delegate_->DoDelayedWork();
+ // if (should_quit_)
+ // break;
+ //
+ // if (did_work)
+ // continue;
+ //
+ // did_work = delegate_->DoIdleWork();
+ // if (should_quit_)
+ // break;
+ //
+ // if (did_work)
+ // continue;
+ //
+ // WaitForWork();
+ // }
+ //
+ // Here, DoInternalWork is some private method of the message pump that is
+ // responsible for dispatching the next UI message or notifying the next IO
+ // completion (for example). WaitForWork is a private method that simply
+ // blocks until there is more work of any type to do.
+ //
+ // Notice that the run loop cycles between calling DoInternalWork, DoWork,
+ // and DoDelayedWork methods. This helps ensure that neither work queue
+ // starves the other. This is important for message pumps that are used to
+ // drive animations, for example.
+ //
+ // Notice also that after each callout to foreign code, the run loop checks
+ // to see if it should quit. The Quit method is responsible for setting this
+ // flag. No further work is done once the quit flag is set.
+ //
+ // NOTE: Care must be taken to handle Run being called again from within any
+ // of the callouts to foreign code. Native message pumps may also need to
+ // deal with other native message pumps being run outside their control
+ // (e.g., the MessageBox API on Windows pumps UI messages!). To be specific,
+ // the callouts (DoWork and DoDelayedWork) MUST still be provided even in
+ // nested sub-loops that are "seemingly" outside the control of this message
+ // pump. DoWork in particular must never be starved for time slices unless
+ // it returns false (meaning it has run out of things to do).
+ //
+ virtual void Run(Delegate* delegate) = 0;
+
+ // Quit immediately from the most recently entered run loop. This method may
+ // only be used on the thread that called Run.
+ virtual void Quit() = 0;
+
+ // Schedule a DoWork callback to happen reasonably soon. Does nothing if a
+ // DoWork callback is already scheduled. This method may be called from any
+ // thread. Once this call is made, DoWork should not be "starved" at least
+ // until it returns a value of false.
+ virtual void ScheduleWork() = 0;
+
+ // This method may only called from the thread that called Run.
+ //
+ // Ensure that DoWork will be called if a nested loop is entered.
+ // If a MessagePump can already guarantee that DoWork will be called
+ // "reasonably soon", this method can be a no-op to avoid expensive
+ // atomic tests and/or syscalls required for ScheduleWork().
+ virtual void ScheduleWorkForNestedLoop() { ScheduleWork(); };
+
+ // Schedule a DoDelayedWork callback to happen at the specified time,
+ // cancelling any pending DoDelayedWork callback. This method may only be
+ // used on the thread that called Run.
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) = 0;
+
+ // If returned, just use the nsThread.
+ virtual nsISerialEventTarget* GetXPCOMThread() { return nullptr; }
+
+ protected:
+ virtual ~MessagePump(){};
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_H_
diff --git a/ipc/chromium/src/base/message_pump_android.cc b/ipc/chromium/src/base/message_pump_android.cc
new file mode 100644
index 0000000000..6d35534e5c
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_android.cc
@@ -0,0 +1,104 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#include "base/message_pump_android.h"
+
+#include <fcntl.h>
+#include <math.h>
+
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/platform_thread.h"
+
+namespace mozilla {
+bool ProcessNextEvent();
+void NotifyEvent();
+} // namespace mozilla
+
+namespace base {
+
+MessagePumpForUI::MessagePumpForUI() : state_(NULL) {}
+
+MessagePumpForUI::~MessagePumpForUI() {}
+
+void MessagePumpForUI::Run(Delegate* delegate) {
+ RunState state;
+ state.delegate = delegate;
+ state.should_quit = false;
+ state.run_depth = state_ ? state_->run_depth + 1 : 1;
+ // We really only do a single task for each iteration of the loop. If we
+ // have done something, assume there is likely something more to do. This
+ // will mean that we don't block on the message pump until there was nothing
+ // more to do. We also set this to true to make sure not to block on the
+ // first iteration of the loop, so RunAllPending() works correctly.
+ state.more_work_is_plausible = true;
+
+ RunState* previous_state = state_;
+ state_ = &state;
+
+ // We run our own loop instead of using g_main_loop_quit in one of the
+ // callbacks. This is so we only quit our own loops, and we don't quit
+ // nested loops run by others. TODO(deanm): Is this what we want?
+
+ while (!state_->should_quit) {
+ mozilla::ProcessNextEvent();
+ if (work_scheduled) {
+ work_scheduled = false;
+ HandleDispatch();
+ }
+ }
+
+ state_ = previous_state;
+}
+
+void MessagePumpForUI::HandleDispatch() {
+ // We should only ever have a single message on the wakeup pipe, since we
+ // are only signaled when the queue went from empty to non-empty. The qApp
+ // poll will tell us whether there was data, so this read shouldn't block.
+ if (state_->should_quit) return;
+
+ state_->more_work_is_plausible = false;
+
+ if (state_->delegate->DoWork()) state_->more_work_is_plausible = true;
+
+ if (state_->should_quit) return;
+
+ if (state_->delegate->DoDelayedWork(&delayed_work_time_))
+ state_->more_work_is_plausible = true;
+ if (state_->should_quit) return;
+
+ // Don't do idle work if we think there are more important things
+ // that we could be doing.
+ if (state_->more_work_is_plausible) return;
+
+ if (state_->delegate->DoIdleWork()) state_->more_work_is_plausible = true;
+ if (state_->should_quit) return;
+}
+
+void MessagePumpForUI::Quit() {
+ if (state_) {
+ state_->should_quit = true;
+ } else {
+ NOTREACHED() << "Quit called outside Run!";
+ }
+}
+
+void MessagePumpForUI::ScheduleWork() {
+ // This can be called on any thread, so we don't want to touch any state
+ // variables as we would then need locks all over. This ensures that if
+ // we are sleeping in a poll that we will wake up.
+ work_scheduled = true;
+ mozilla::NotifyEvent();
+}
+
+void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
+ // We need to wake up the loop in case the poll timeout needs to be
+ // adjusted. This will cause us to try to do work, but that's ok.
+ delayed_work_time_ = delayed_work_time;
+ ScheduleWork();
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_android.h b/ipc/chromium/src/base/message_pump_android.h
new file mode 100644
index 0000000000..8dd3fdac86
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_android.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#ifndef BASE_MESSAGE_PUMP_ANDROID_H_
+#define BASE_MESSAGE_PUMP_ANDROID_H_
+
+#include "base/message_pump.h"
+#include "base/time.h"
+
+namespace base {
+
+// This class implements a MessagePump needed for TYPE_UI MessageLoops on
+// Android
+class MessagePumpForUI : public MessagePump {
+ public:
+ MessagePumpForUI();
+ ~MessagePumpForUI();
+
+ virtual void Run(Delegate* delegate);
+ virtual void Quit();
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
+
+ // Internal methods used for processing the pump callbacks. They are
+ // public for simplicity but should not be used directly.
+ // HandleDispatch is called after the poll has completed.
+ void HandleDispatch();
+
+ private:
+ // We may make recursive calls to Run, so we save state that needs to be
+ // separate between them in this structure type.
+ struct RunState {
+ Delegate* delegate;
+
+ // Used to flag that the current Run() invocation should return ASAP.
+ bool should_quit;
+
+ // Used to count how many Run() invocations are on the stack.
+ int run_depth;
+
+ // Used internally for controlling whether we want a message pump
+ // iteration to be blocking or not.
+ bool more_work_is_plausible;
+ };
+
+ RunState* state_;
+
+ // This is the time when we need to do delayed work.
+ TimeTicks delayed_work_time_;
+
+ bool work_scheduled;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpForUI);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_ANDROID_H_
diff --git a/ipc/chromium/src/base/message_pump_default.cc b/ipc/chromium/src/base/message_pump_default.cc
new file mode 100644
index 0000000000..9db5789f1a
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_default.cc
@@ -0,0 +1,96 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/message_pump_default.h"
+
+#include "base/logging.h"
+#include "base/message_loop.h"
+#include "base/scoped_nsautorelease_pool.h"
+
+#include "mozilla/BackgroundHangMonitor.h"
+#include "mozilla/ProfilerLabels.h"
+#include "mozilla/ProfilerThreadSleep.h"
+
+namespace base {
+
+MessagePumpDefault::MessagePumpDefault()
+ : keep_running_(true), event_(false, false) {}
+
+void MessagePumpDefault::Run(Delegate* delegate) {
+ AUTO_PROFILER_LABEL("MessagePumpDefault::Run", OTHER);
+
+ DCHECK(keep_running_) << "Quit must have been called outside of Run!";
+
+ const MessageLoop* const loop = MessageLoop::current();
+ mozilla::BackgroundHangMonitor hangMonitor(loop->thread_name().c_str(),
+ loop->transient_hang_timeout(),
+ loop->permanent_hang_timeout());
+
+ for (;;) {
+ ScopedNSAutoreleasePool autorelease_pool;
+
+ hangMonitor.NotifyActivity();
+ bool did_work = delegate->DoWork();
+ if (!keep_running_) break;
+
+ hangMonitor.NotifyActivity();
+ did_work |= delegate->DoDelayedWork(&delayed_work_time_);
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ hangMonitor.NotifyActivity();
+ did_work = delegate->DoIdleWork();
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ if (delayed_work_time_.is_null()) {
+ hangMonitor.NotifyWait();
+ AUTO_PROFILER_LABEL("MessagePumpDefault::Run:Wait", IDLE);
+ {
+ AUTO_PROFILER_THREAD_SLEEP;
+ event_.Wait();
+ }
+ } else {
+ TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
+ if (delay > TimeDelta()) {
+ hangMonitor.NotifyWait();
+ AUTO_PROFILER_LABEL("MessagePumpDefault::Run:Wait", IDLE);
+ {
+ AUTO_PROFILER_THREAD_SLEEP;
+ event_.TimedWait(delay);
+ }
+ } else {
+ // It looks like delayed_work_time_ indicates a time in the past, so we
+ // need to call DoDelayedWork now.
+ delayed_work_time_ = TimeTicks();
+ }
+ }
+ // Since event_ is auto-reset, we don't need to do anything special here
+ // other than service each delegate method.
+ }
+
+ keep_running_ = true;
+}
+
+void MessagePumpDefault::Quit() { keep_running_ = false; }
+
+void MessagePumpDefault::ScheduleWork() {
+ // Since this can be called on any thread, we need to ensure that our Run
+ // loop wakes up.
+ event_.Signal();
+}
+
+void MessagePumpDefault::ScheduleDelayedWork(
+ const TimeTicks& delayed_work_time) {
+ // We know that we can't be blocked on Wait right now since this method can
+ // only be called on the same thread as Run, so we only need to update our
+ // record of how long to sleep when we do sleep.
+ delayed_work_time_ = delayed_work_time;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_default.h b/ipc/chromium/src/base/message_pump_default.h
new file mode 100644
index 0000000000..99abaf6580
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_default.h
@@ -0,0 +1,43 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MESSAGE_PUMP_DEFAULT_H_
+#define BASE_MESSAGE_PUMP_DEFAULT_H_
+
+#include "base/message_pump.h"
+#include "base/time.h"
+#include "base/waitable_event.h"
+
+namespace base {
+
+class MessagePumpDefault : public MessagePump {
+ public:
+ MessagePumpDefault();
+ ~MessagePumpDefault() {}
+
+ // MessagePump methods:
+ virtual void Run(Delegate* delegate) override;
+ virtual void Quit() override;
+ virtual void ScheduleWork() override;
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
+
+ protected:
+ // This flag is set to false when Run should return.
+ bool keep_running_;
+
+ // Used to sleep until there is more work to do.
+ WaitableEvent event_;
+
+ // The time at which we should call DoDelayedWork.
+ TimeTicks delayed_work_time_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpDefault);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_DEFAULT_H_
diff --git a/ipc/chromium/src/base/message_pump_glib.cc b/ipc/chromium/src/base/message_pump_glib.cc
new file mode 100644
index 0000000000..7f3dc0f965
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_glib.cc
@@ -0,0 +1,291 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/message_pump_glib.h"
+
+#include <unistd.h>
+#include <math.h>
+
+#include <gtk/gtk.h>
+#include <glib.h>
+
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/platform_thread.h"
+
+namespace {
+
+// Return a timeout suitable for the glib loop, -1 to block forever,
+// 0 to return right away, or a timeout in milliseconds from now.
+int GetTimeIntervalMilliseconds(const base::TimeTicks& from) {
+ if (from.is_null()) return -1;
+
+ // Be careful here. TimeDelta has a precision of microseconds, but we want a
+ // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
+ // 6? It should be 6 to avoid executing delayed work too early.
+ int delay =
+ static_cast<int>(ceil((from - base::TimeTicks::Now()).InMillisecondsF()));
+
+ // If this value is negative, then we need to run delayed work soon.
+ return delay < 0 ? 0 : delay;
+}
+
+// A brief refresher on GLib:
+// GLib sources have four callbacks: Prepare, Check, Dispatch and Finalize.
+// On each iteration of the GLib pump, it calls each source's Prepare function.
+// This function should return TRUE if it wants GLib to call its Dispatch, and
+// FALSE otherwise. It can also set a timeout in this case for the next time
+// Prepare should be called again (it may be called sooner).
+// After the Prepare calls, GLib does a poll to check for events from the
+// system. File descriptors can be attached to the sources. The poll may block
+// if none of the Prepare calls returned TRUE. It will block indefinitely, or
+// by the minimum time returned by a source in Prepare.
+// After the poll, GLib calls Check for each source that returned FALSE
+// from Prepare. The return value of Check has the same meaning as for Prepare,
+// making Check a second chance to tell GLib we are ready for Dispatch.
+// Finally, GLib calls Dispatch for each source that is ready. If Dispatch
+// returns FALSE, GLib will destroy the source. Dispatch calls may be recursive
+// (i.e., you can call Run from them), but Prepare and Check cannot.
+// Finalize is called when the source is destroyed.
+// NOTE: It is common for subsytems to want to process pending events while
+// doing intensive work, for example the flash plugin. They usually use the
+// following pattern (recommended by the GTK docs):
+// while (gtk_events_pending()) {
+// gtk_main_iteration();
+// }
+//
+// gtk_events_pending just calls g_main_context_pending, which does the
+// following:
+// - Call prepare on all the sources.
+// - Do the poll with a timeout of 0 (not blocking).
+// - Call check on all the sources.
+// - *Does not* call dispatch on the sources.
+// - Return true if any of prepare() or check() returned true.
+//
+// gtk_main_iteration just calls g_main_context_iteration, which does the whole
+// thing, respecting the timeout for the poll (and block, although it is
+// expected not to if gtk_events_pending returned true), and call dispatch.
+//
+// Thus it is important to only return true from prepare or check if we
+// actually have events or work to do. We also need to make sure we keep
+// internal state consistent so that if prepare/check return true when called
+// from gtk_events_pending, they will still return true when called right
+// after, from gtk_main_iteration.
+//
+// For the GLib pump we try to follow the Windows UI pump model:
+// - Whenever we receive a wakeup event or the timer for delayed work expires,
+// we run DoWork and/or DoDelayedWork. That part will also run in the other
+// event pumps.
+// - We also run DoWork, DoDelayedWork, and possibly DoIdleWork in the main
+// loop, around event handling.
+
+struct WorkSource : public GSource {
+ base::MessagePumpForUI* pump;
+};
+
+gboolean WorkSourcePrepare(GSource* source, gint* timeout_ms) {
+ *timeout_ms = static_cast<WorkSource*>(source)->pump->HandlePrepare();
+ // We always return FALSE, so that our timeout is honored. If we were
+ // to return TRUE, the timeout would be considered to be 0 and the poll
+ // would never block. Once the poll is finished, Check will be called.
+ return FALSE;
+}
+
+gboolean WorkSourceCheck(GSource* source) {
+ // Only return TRUE if Dispatch should be called.
+ return static_cast<WorkSource*>(source)->pump->HandleCheck();
+}
+
+gboolean WorkSourceDispatch(GSource* source, GSourceFunc unused_func,
+ gpointer unused_data) {
+ static_cast<WorkSource*>(source)->pump->HandleDispatch();
+ // Always return TRUE so our source stays registered.
+ return TRUE;
+}
+
+// I wish these could be const, but g_source_new wants non-const.
+GSourceFuncs WorkSourceFuncs = {WorkSourcePrepare, WorkSourceCheck,
+ WorkSourceDispatch, NULL};
+
+} // namespace
+
+namespace base {
+
+MessagePumpForUI::MessagePumpForUI()
+ : state_(NULL),
+ context_(g_main_context_default()),
+ wakeup_gpollfd_(new GPollFD),
+ pipe_full_(false) {
+ // Create our wakeup pipe, which is used to flag when work was scheduled.
+ int fds[2];
+ CHECK(pipe(fds) == 0);
+ wakeup_pipe_read_ = fds[0];
+ wakeup_pipe_write_ = fds[1];
+ wakeup_gpollfd_->fd = wakeup_pipe_read_;
+ wakeup_gpollfd_->events = G_IO_IN;
+
+ work_source_ = g_source_new(&WorkSourceFuncs, sizeof(WorkSource));
+ static_cast<WorkSource*>(work_source_)->pump = this;
+ g_source_add_poll(work_source_, wakeup_gpollfd_.get());
+ // Use a low priority so that we let other events in the queue go first.
+ g_source_set_priority(work_source_, G_PRIORITY_DEFAULT_IDLE);
+ // This is needed to allow Run calls inside Dispatch.
+ g_source_set_can_recurse(work_source_, TRUE);
+ g_source_attach(work_source_, context_);
+}
+
+MessagePumpForUI::~MessagePumpForUI() {
+ gdk_event_handler_set(reinterpret_cast<GdkEventFunc>(gtk_main_do_event), this,
+ NULL);
+ g_source_destroy(work_source_);
+ g_source_unref(work_source_);
+ close(wakeup_pipe_read_);
+ close(wakeup_pipe_write_);
+}
+
+void MessagePumpForUI::Run(Delegate* delegate) {
+#ifndef NDEBUG
+ // Make sure we only run this on one thread. GTK only has one message pump
+ // so we can only have one UI loop per process.
+ static PlatformThreadId thread_id = PlatformThread::CurrentId();
+ DCHECK(thread_id == PlatformThread::CurrentId())
+ << "Running MessagePumpForUI on two different threads; "
+ "this is unsupported by GLib!";
+#endif
+
+ RunState state;
+ state.delegate = delegate;
+ state.should_quit = false;
+ state.run_depth = state_ ? state_->run_depth + 1 : 1;
+ state.has_work = false;
+
+ RunState* previous_state = state_;
+ state_ = &state;
+
+ // We really only do a single task for each iteration of the loop. If we
+ // have done something, assume there is likely something more to do. This
+ // will mean that we don't block on the message pump until there was nothing
+ // more to do. We also set this to true to make sure not to block on the
+ // first iteration of the loop, so RunAllPending() works correctly.
+ bool more_work_is_plausible = true;
+
+ // We run our own loop instead of using g_main_loop_quit in one of the
+ // callbacks. This is so we only quit our own loops, and we don't quit
+ // nested loops run by others. TODO(deanm): Is this what we want?
+ for (;;) {
+ // Don't block if we think we have more work to do.
+ bool block = !more_work_is_plausible;
+
+ // g_main_context_iteration returns true if events have been dispatched.
+ more_work_is_plausible = g_main_context_iteration(context_, block);
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |= state_->delegate->DoWork();
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |=
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ if (state_->should_quit) break;
+
+ if (more_work_is_plausible) continue;
+
+ more_work_is_plausible = state_->delegate->DoIdleWork();
+ if (state_->should_quit) break;
+ }
+
+ state_ = previous_state;
+}
+
+// Return the timeout we want passed to poll.
+int MessagePumpForUI::HandlePrepare() {
+ // We know we have work, but we haven't called HandleDispatch yet. Don't let
+ // the pump block so that we can do some processing.
+ if (state_ && // state_ may be null during tests.
+ state_->has_work)
+ return 0;
+
+ // We don't think we have work to do, but make sure not to block
+ // longer than the next time we need to run delayed work.
+ return GetTimeIntervalMilliseconds(delayed_work_time_);
+}
+
+bool MessagePumpForUI::HandleCheck() {
+ if (!state_) // state_ may be null during tests.
+ return false;
+
+ // We should only ever have a single message on the wakeup pipe since we only
+ // write to the pipe when pipe_full_ is false. The glib poll will tell us
+ // whether there was data, so this read shouldn't block.
+ if (wakeup_gpollfd_->revents & G_IO_IN) {
+ pipe_full_ = false;
+
+ char msg;
+ if (HANDLE_EINTR(read(wakeup_pipe_read_, &msg, 1)) != 1 || msg != '!') {
+ NOTREACHED() << "Error reading from the wakeup pipe.";
+ }
+ // Since we ate the message, we need to record that we have more work,
+ // because HandleCheck() may be called without HandleDispatch being called
+ // afterwards.
+ state_->has_work = true;
+ }
+
+ if (state_->has_work) return true;
+
+ if (GetTimeIntervalMilliseconds(delayed_work_time_) == 0) {
+ // The timer has expired. That condition will stay true until we process
+ // that delayed work, so we don't need to record this differently.
+ return true;
+ }
+
+ return false;
+}
+
+void MessagePumpForUI::HandleDispatch() {
+ state_->has_work = false;
+ if (state_->delegate->DoWork()) {
+ // NOTE: on Windows at this point we would call ScheduleWork (see
+ // MessagePumpForUI::HandleWorkMessage in message_pump_win.cc). But here,
+ // instead of posting a message on the wakeup pipe, we can avoid the
+ // syscalls and just signal that we have more work.
+ state_->has_work = true;
+ }
+
+ if (state_->should_quit) return;
+
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+}
+
+void MessagePumpForUI::Quit() {
+ if (state_) {
+ state_->should_quit = true;
+ } else {
+ NOTREACHED() << "Quit called outside Run!";
+ }
+}
+
+void MessagePumpForUI::ScheduleWork() {
+ bool was_full = pipe_full_.exchange(true);
+ if (was_full) {
+ return;
+ }
+
+ // This can be called on any thread, so we don't want to touch any state
+ // variables as we would then need locks all over. This ensures that if
+ // we are sleeping in a poll that we will wake up.
+ char msg = '!';
+ if (HANDLE_EINTR(write(wakeup_pipe_write_, &msg, 1)) != 1) {
+ NOTREACHED() << "Could not write to the UI message loop wakeup pipe!";
+ }
+}
+
+void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
+ // We need to wake up the loop in case the poll timeout needs to be
+ // adjusted. This will cause us to try to do work, but that's ok.
+ delayed_work_time_ = delayed_work_time;
+ ScheduleWork();
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_glib.h b/ipc/chromium/src/base/message_pump_glib.h
new file mode 100644
index 0000000000..c7888b25b9
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_glib.h
@@ -0,0 +1,92 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef BASE_MESSAGE_PUMP_GLIB_H_
+#define BASE_MESSAGE_PUMP_GLIB_H_
+
+#include "base/message_pump.h"
+#include "base/observer_list.h"
+#include "base/time.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Atomics.h"
+
+typedef struct _GMainContext GMainContext;
+typedef struct _GPollFD GPollFD;
+typedef struct _GSource GSource;
+
+namespace base {
+
+// This class implements a MessagePump needed for TYPE_UI MessageLoops on
+// XP_LINUX platforms using GLib.
+class MessagePumpForUI : public MessagePump {
+ public:
+ MessagePumpForUI();
+ virtual ~MessagePumpForUI();
+
+ void Run(Delegate* delegate) override;
+ void Quit() override;
+ void ScheduleWork() override;
+ void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
+
+ // Internal methods used for processing the pump callbacks. They are
+ // public for simplicity but should not be used directly. HandlePrepare
+ // is called during the prepare step of glib, and returns a timeout that
+ // will be passed to the poll. HandleCheck is called after the poll
+ // has completed, and returns whether or not HandleDispatch should be called.
+ // HandleDispatch is called if HandleCheck returned true.
+ int HandlePrepare();
+ bool HandleCheck();
+ void HandleDispatch();
+
+ private:
+ // We may make recursive calls to Run, so we save state that needs to be
+ // separate between them in this structure type.
+ struct RunState {
+ Delegate* delegate;
+
+ // Used to flag that the current Run() invocation should return ASAP.
+ bool should_quit;
+
+ // Used to count how many Run() invocations are on the stack.
+ int run_depth;
+
+ // This keeps the state of whether the pump got signaled that there was new
+ // work to be done. Since we eat the message on the wake up pipe as soon as
+ // we get it, we keep that state here to stay consistent.
+ bool has_work;
+ };
+
+ RunState* state_;
+
+ // This is a GLib structure that we can add event sources to. We use the
+ // default GLib context, which is the one to which all GTK events are
+ // dispatched.
+ GMainContext* context_;
+
+ // This is the time when we need to do delayed work.
+ TimeTicks delayed_work_time_;
+
+ // The work source. It is shared by all calls to Run and destroyed when
+ // the message pump is destroyed.
+ GSource* work_source_;
+
+ // We use a wakeup pipe to make sure we'll get out of the glib polling phase
+ // when another thread has scheduled us to do some work. There is a glib
+ // mechanism g_main_context_wakeup, but this won't guarantee that our event's
+ // Dispatch() will be called.
+ int wakeup_pipe_read_;
+ int wakeup_pipe_write_;
+ // Use an autoptr to avoid needing the definition of GPollFD in the header.
+ mozilla::UniquePtr<GPollFD> wakeup_gpollfd_;
+
+ mozilla::Atomic<bool> pipe_full_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpForUI);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_GLIB_H_
diff --git a/ipc/chromium/src/base/message_pump_libevent.cc b/ipc/chromium/src/base/message_pump_libevent.cc
new file mode 100644
index 0000000000..004001fddd
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_libevent.cc
@@ -0,0 +1,410 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/message_pump_libevent.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#if defined(ANDROID) || defined(XP_UNIX)
+# include <unistd.h>
+#endif
+
+#include "eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/scoped_nsautorelease_pool.h"
+#include "base/time.h"
+#include "event.h"
+#include "mozilla/ProfilerLabels.h"
+#include "mozilla/ProfilerThreadSleep.h"
+#include "mozilla/UniquePtr.h"
+
+// This macro checks that the _EVENT_SIZEOF_* constants defined in
+// ipc/chromiume/src/third_party/<platform>/event2/event-config.h are correct.
+#if defined(_EVENT_SIZEOF_SHORT)
+# define CHECK_EVENT_SIZEOF(TYPE, type) \
+ static_assert(_EVENT_SIZEOF_##TYPE == sizeof(type), \
+ "bad _EVENT_SIZEOF_" #TYPE);
+#elif defined(EVENT__SIZEOF_SHORT)
+# define CHECK_EVENT_SIZEOF(TYPE, type) \
+ static_assert(EVENT__SIZEOF_##TYPE == sizeof(type), \
+ "bad EVENT__SIZEOF_" #TYPE);
+#else
+# error Cannot find libevent type sizes
+#endif
+
+CHECK_EVENT_SIZEOF(LONG, long);
+CHECK_EVENT_SIZEOF(LONG_LONG, long long);
+CHECK_EVENT_SIZEOF(OFF_T, ev_off_t);
+CHECK_EVENT_SIZEOF(PTHREAD_T, pthread_t);
+CHECK_EVENT_SIZEOF(SHORT, short);
+CHECK_EVENT_SIZEOF(SIZE_T, size_t);
+CHECK_EVENT_SIZEOF(TIME_T, time_t);
+CHECK_EVENT_SIZEOF(VOID_P, void*);
+
+// Lifecycle of struct event
+// Libevent uses two main data structures:
+// struct event_base (of which there is one per message pump), and
+// struct event (of which there is roughly one per socket).
+// The socket's struct event is created in
+// MessagePumpLibevent::WatchFileDescriptor(),
+// is owned by the FileDescriptorWatcher, and is destroyed in
+// StopWatchingFileDescriptor().
+// It is moved into and out of lists in struct event_base by
+// the libevent functions event_add() and event_del().
+//
+// TODO(dkegel):
+// At the moment bad things happen if a FileDescriptorWatcher
+// is active after its MessagePumpLibevent has been destroyed.
+// See MessageLoopTest.FileDescriptorWatcherOutlivesMessageLoop
+// Not clear yet whether that situation occurs in practice,
+// but if it does, we need to fix it.
+
+namespace base {
+
+// Return 0 on success
+// Too small a function to bother putting in a library?
+static int SetNonBlocking(int fd) {
+ int flags = fcntl(fd, F_GETFL, 0);
+ if (flags == -1) flags = 0;
+ return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
+}
+
+MessagePumpLibevent::FileDescriptorWatcher::FileDescriptorWatcher()
+ : is_persistent_(false), event_(NULL) {}
+
+MessagePumpLibevent::FileDescriptorWatcher::~FileDescriptorWatcher() {
+ if (event_) {
+ StopWatchingFileDescriptor();
+ }
+}
+
+void MessagePumpLibevent::FileDescriptorWatcher::Init(event* e,
+ bool is_persistent) {
+ DCHECK(e);
+ DCHECK(event_ == NULL);
+
+ is_persistent_ = is_persistent;
+ event_ = e;
+}
+
+event* MessagePumpLibevent::FileDescriptorWatcher::ReleaseEvent() {
+ struct event* e = event_;
+ event_ = NULL;
+ return e;
+}
+
+bool MessagePumpLibevent::FileDescriptorWatcher::StopWatchingFileDescriptor() {
+ event* e = ReleaseEvent();
+ if (e == NULL) return true;
+
+ // event_del() is a no-op if the event isn't active.
+ int rv = event_del(e);
+ delete e;
+ return (rv == 0);
+}
+
+bool MessagePumpLibevent::awake_ = false;
+
+// Called if a byte is received on the wakeup pipe.
+void MessagePumpLibevent::OnWakeup(int socket, short flags, void* context) {
+ if (!awake_) {
+ profiler_thread_wake();
+ awake_ = true;
+ }
+
+ AUTO_PROFILER_LABEL("MessagePumpLibevent::OnWakeup", OTHER);
+
+ base::MessagePumpLibevent* that =
+ static_cast<base::MessagePumpLibevent*>(context);
+ DCHECK(that->wakeup_pipe_out_ == socket);
+
+ // Remove and discard the wakeup byte.
+ char buf;
+ int nread = HANDLE_EINTR(read(socket, &buf, 1));
+ DCHECK_EQ(nread, 1);
+ // Tell libevent to break out of inner loop.
+ event_base_loopbreak(that->event_base_);
+}
+
+MessagePumpLibevent::MessagePumpLibevent()
+ : keep_running_(true),
+ in_run_(false),
+ event_base_(event_base_new()),
+ wakeup_pipe_in_(-1),
+ wakeup_pipe_out_(-1) {
+ if (!Init()) NOTREACHED();
+}
+
+bool MessagePumpLibevent::Init() {
+ int fds[2];
+ if (pipe(fds)) {
+ DLOG(ERROR) << "pipe() failed, errno: " << errno;
+ return false;
+ }
+ if (SetNonBlocking(fds[0])) {
+ DLOG(ERROR) << "SetNonBlocking for pipe fd[0] failed, errno: " << errno;
+ return false;
+ }
+ if (SetNonBlocking(fds[1])) {
+ DLOG(ERROR) << "SetNonBlocking for pipe fd[1] failed, errno: " << errno;
+ return false;
+ }
+ wakeup_pipe_out_ = fds[0];
+ wakeup_pipe_in_ = fds[1];
+
+ wakeup_event_ = new event;
+ event_set(wakeup_event_, wakeup_pipe_out_, EV_READ | EV_PERSIST, OnWakeup,
+ this);
+ event_base_set(event_base_, wakeup_event_);
+
+ if (event_add(wakeup_event_, 0)) return false;
+ return true;
+}
+
+MessagePumpLibevent::~MessagePumpLibevent() {
+ DCHECK(wakeup_event_);
+ DCHECK(event_base_);
+ event_del(wakeup_event_);
+ delete wakeup_event_;
+ if (wakeup_pipe_in_ >= 0) close(wakeup_pipe_in_);
+ if (wakeup_pipe_out_ >= 0) close(wakeup_pipe_out_);
+ event_base_free(event_base_);
+}
+
+bool MessagePumpLibevent::WatchFileDescriptor(int fd, bool persistent,
+ Mode mode,
+ FileDescriptorWatcher* controller,
+ Watcher* delegate) {
+ DCHECK(fd > 0);
+ DCHECK(controller);
+ DCHECK(delegate);
+ DCHECK(mode == WATCH_READ || mode == WATCH_WRITE || mode == WATCH_READ_WRITE);
+
+ int event_mask = persistent ? EV_PERSIST : 0;
+ if ((mode & WATCH_READ) != 0) {
+ event_mask |= EV_READ;
+ }
+ if ((mode & WATCH_WRITE) != 0) {
+ event_mask |= EV_WRITE;
+ }
+
+ // |should_delete_event| is true if we're modifying an event that's currently
+ // active in |controller|.
+ // If we're modifying an existing event and there's an error then we need to
+ // tell libevent to clean it up via event_delete() before returning.
+ bool should_delete_event = true;
+ mozilla::UniquePtr<event> evt(controller->ReleaseEvent());
+ if (evt.get() == NULL) {
+ should_delete_event = false;
+ // Ownership is transferred to the controller.
+ evt = mozilla::MakeUnique<event>();
+ } else {
+ // It's illegal to use this function to listen on 2 separate fds with the
+ // same |controller|.
+ if (EVENT_FD(evt.get()) != fd) {
+ NOTREACHED() << "FDs don't match" << EVENT_FD(evt.get()) << "!=" << fd;
+ return false;
+ }
+
+ // Make sure we don't pick up any funky internal libevent masks.
+ int old_interest_mask =
+ evt.get()->ev_events & (EV_READ | EV_WRITE | EV_PERSIST);
+
+ // Combine old/new event masks.
+ event_mask |= old_interest_mask;
+
+ // Must disarm the event before we can reuse it.
+ event_del(evt.get());
+ }
+
+ // Set current interest mask and message pump for this event.
+ event_set(evt.get(), fd, event_mask, OnLibeventNotification, delegate);
+
+ // Tell libevent which message pump this socket will belong to when we add it.
+ if (event_base_set(event_base_, evt.get()) != 0) {
+ if (should_delete_event) {
+ event_del(evt.get());
+ }
+ return false;
+ }
+
+ // Add this socket to the list of monitored sockets.
+ if (event_add(evt.get(), NULL) != 0) {
+ if (should_delete_event) {
+ event_del(evt.get());
+ }
+ return false;
+ }
+
+ // Transfer ownership of evt to controller.
+ controller->Init(evt.release(), persistent);
+ return true;
+}
+
+void MessagePumpLibevent::OnLibeventNotification(int fd, short flags,
+ void* context) {
+ if (!awake_) {
+ profiler_thread_wake();
+ awake_ = true;
+ }
+ AUTO_PROFILER_LABEL("MessagePumpLibevent::OnLibeventNotification", OTHER);
+
+ Watcher* watcher = static_cast<Watcher*>(context);
+
+ if (flags & EV_WRITE) {
+ watcher->OnFileCanWriteWithoutBlocking(fd);
+ }
+ if (flags & EV_READ) {
+ watcher->OnFileCanReadWithoutBlocking(fd);
+ }
+}
+
+MessagePumpLibevent::SignalEvent::SignalEvent() : event_(NULL) {}
+
+MessagePumpLibevent::SignalEvent::~SignalEvent() {
+ if (event_) {
+ StopCatching();
+ }
+}
+
+void MessagePumpLibevent::SignalEvent::Init(event* e) {
+ DCHECK(e);
+ DCHECK(event_ == NULL);
+ event_ = e;
+}
+
+bool MessagePumpLibevent::SignalEvent::StopCatching() {
+ // XXX/cjones: this code could be shared with
+ // FileDescriptorWatcher. ironic that libevent is "more"
+ // object-oriented than this C++
+ event* e = ReleaseEvent();
+ if (e == NULL) return true;
+
+ // event_del() is a no-op if the event isn't active.
+ int rv = event_del(e);
+ delete e;
+ return (rv == 0);
+}
+
+event* MessagePumpLibevent::SignalEvent::ReleaseEvent() {
+ event* e = event_;
+ event_ = NULL;
+ return e;
+}
+
+bool MessagePumpLibevent::CatchSignal(int sig, SignalEvent* sigevent,
+ SignalWatcher* delegate) {
+ DCHECK(sig > 0);
+ DCHECK(sigevent);
+ DCHECK(delegate);
+ // TODO if we want to support re-using SignalEvents, this code needs
+ // to jump through the same hoops as WatchFileDescriptor(). Not
+ // needed at present
+ DCHECK(NULL == sigevent->event_);
+
+ mozilla::UniquePtr<event> evt = mozilla::MakeUnique<event>();
+ signal_set(evt.get(), sig, OnLibeventSignalNotification, delegate);
+
+ if (event_base_set(event_base_, evt.get())) return false;
+
+ if (signal_add(evt.get(), NULL)) return false;
+
+ // Transfer ownership of evt to controller.
+ sigevent->Init(evt.release());
+ return true;
+}
+
+void MessagePumpLibevent::OnLibeventSignalNotification(int sig, short flags,
+ void* context) {
+ if (!awake_) {
+ profiler_thread_wake();
+ awake_ = true;
+ }
+ AUTO_PROFILER_LABEL("MessagePumpLibevent::OnLibeventSignalNotification",
+ OTHER);
+
+ DCHECK(sig > 0);
+ DCHECK(EV_SIGNAL == flags);
+ DCHECK(context);
+ reinterpret_cast<SignalWatcher*>(context)->OnSignal(sig);
+}
+
+// Reentrant!
+void MessagePumpLibevent::Run(Delegate* delegate) {
+ DCHECK(keep_running_) << "Quit must have been called outside of Run!";
+
+ bool old_in_run = in_run_;
+ in_run_ = true;
+
+ for (;;) {
+ ScopedNSAutoreleasePool autorelease_pool;
+
+ bool did_work = delegate->DoWork();
+ if (!keep_running_) break;
+
+ did_work |= delegate->DoDelayedWork(&delayed_work_time_);
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ did_work = delegate->DoIdleWork();
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ // EVLOOP_ONCE tells libevent to only block once,
+ // but to service all pending events when it wakes up.
+ AUTO_PROFILER_LABEL("MessagePumpLibevent::Run::Wait", IDLE);
+ if (delayed_work_time_.is_null()) {
+ profiler_thread_sleep();
+ awake_ = false;
+ event_base_loop(event_base_, EVLOOP_ONCE);
+ } else {
+ TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
+ if (delay > TimeDelta()) {
+ struct timeval poll_tv;
+ poll_tv.tv_sec = delay.InSeconds();
+ poll_tv.tv_usec = delay.InMicroseconds() % Time::kMicrosecondsPerSecond;
+ event_base_loopexit(event_base_, &poll_tv);
+ profiler_thread_sleep();
+ awake_ = false;
+ event_base_loop(event_base_, EVLOOP_ONCE);
+ } else {
+ // It looks like delayed_work_time_ indicates a time in the past, so we
+ // need to call DoDelayedWork now.
+ delayed_work_time_ = TimeTicks();
+ }
+ }
+ }
+
+ keep_running_ = true;
+ in_run_ = old_in_run;
+}
+
+void MessagePumpLibevent::Quit() {
+ DCHECK(in_run_);
+ // Tell both libevent and Run that they should break out of their loops.
+ keep_running_ = false;
+ ScheduleWork();
+}
+
+void MessagePumpLibevent::ScheduleWork() {
+ // Tell libevent (in a threadsafe way) that it should break out of its loop.
+ char buf = 0;
+ int nwrite = HANDLE_EINTR(write(wakeup_pipe_in_, &buf, 1));
+ DCHECK(nwrite == 1 || errno == EAGAIN)
+ << "[nwrite:" << nwrite << "] [errno:" << errno << "]";
+}
+
+void MessagePumpLibevent::ScheduleDelayedWork(
+ const TimeTicks& delayed_work_time) {
+ // We know that we can't be blocked on Wait right now since this method can
+ // only be called on the same thread as Run, so we only need to update our
+ // record of how long to sleep when we do sleep.
+ delayed_work_time_ = delayed_work_time;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_libevent.h b/ipc/chromium/src/base/message_pump_libevent.h
new file mode 100644
index 0000000000..b1a7d474b3
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_libevent.h
@@ -0,0 +1,181 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MESSAGE_PUMP_LIBEVENT_H_
+#define BASE_MESSAGE_PUMP_LIBEVENT_H_
+
+#include "base/message_pump.h"
+#include "base/time.h"
+
+// Declare structs we need from libevent.h rather than including it
+struct event_base;
+struct event;
+
+namespace base {
+
+// Class to monitor sockets and issue callbacks when sockets are ready for I/O
+// TODO(dkegel): add support for background file IO somehow
+class MessagePumpLibevent : public MessagePump {
+ public:
+ // Object returned by WatchFileDescriptor to manage further watching.
+ class FileDescriptorWatcher {
+ public:
+ FileDescriptorWatcher();
+ ~FileDescriptorWatcher(); // Implicitly calls StopWatchingFileDescriptor.
+
+ // NOTE: These methods aren't called StartWatching()/StopWatching() to
+ // avoid confusion with the win32 ObjectWatcher class.
+
+ // Stop watching the FD, always safe to call. No-op if there's nothing
+ // to do.
+ bool StopWatchingFileDescriptor();
+
+ private:
+ // Called by MessagePumpLibevent, ownership of |e| is transferred to this
+ // object.
+ void Init(event* e, bool is_persistent);
+
+ // Used by MessagePumpLibevent to take ownership of event_.
+ event* ReleaseEvent();
+ friend class MessagePumpLibevent;
+
+ private:
+ bool is_persistent_; // false if this event is one-shot.
+ event* event_;
+ DISALLOW_COPY_AND_ASSIGN(FileDescriptorWatcher);
+ };
+
+ // Used with WatchFileDescptor to asynchronously monitor the I/O readiness of
+ // a File Descriptor.
+ class Watcher {
+ public:
+ virtual ~Watcher() {}
+ // Called from MessageLoop::Run when an FD can be read from/written to
+ // without blocking
+ virtual void OnFileCanReadWithoutBlocking(int fd) = 0;
+ virtual void OnFileCanWriteWithoutBlocking(int fd) = 0;
+ };
+
+ MessagePumpLibevent();
+
+ enum Mode {
+ WATCH_READ = 1 << 0,
+ WATCH_WRITE = 1 << 1,
+ WATCH_READ_WRITE = WATCH_READ | WATCH_WRITE
+ };
+
+ // Have the current thread's message loop watch for a a situation in which
+ // reading/writing to the FD can be performed without Blocking.
+ // Callers must provide a preallocated FileDescriptorWatcher object which
+ // can later be used to manage the Lifetime of this event.
+ // If a FileDescriptorWatcher is passed in which is already attached to
+ // an event, then the effect is cumulative i.e. after the call |controller|
+ // will watch both the previous event and the new one.
+ // If an error occurs while calling this method in a cumulative fashion, the
+ // event previously attached to |controller| is aborted.
+ // Returns true on success.
+ // TODO(dkegel): switch to edge-triggered readiness notification
+ bool WatchFileDescriptor(int fd, bool persistent, Mode mode,
+ FileDescriptorWatcher* controller,
+ Watcher* delegate);
+
+ // This is analagous to FileDescriptorWatcher above, which really is
+ // just a wrapper around libevent's |struct event|. This class acts
+ // as a sort of "scoped event watcher" in that it guarantees that
+ // when this class is out of scope, the signal-event it wraps is
+ // removed from libevent's guts.
+ //
+ // XXX/cjones: this isn't my favorite API, but preserving it in
+ // order to match code above
+ class SignalEvent {
+ friend class MessagePumpLibevent;
+
+ public:
+ SignalEvent();
+ ~SignalEvent(); // implicitly calls StopCatching()
+
+ // Have libevent forget this event.
+ bool StopCatching();
+
+ private:
+ void Init(event* e);
+ event* ReleaseEvent();
+
+ event* event_;
+
+ DISALLOW_COPY_AND_ASSIGN(SignalEvent);
+ };
+
+ class SignalWatcher {
+ public:
+ virtual ~SignalWatcher() {}
+ // Called from MessageLoop::Run when |sig| has been delivered to
+ // this process
+ virtual void OnSignal(int sig) = 0;
+ };
+
+ // Have the current thread's message loop catch the signal |sig|.
+ // Multiple watchers can catch the same signal; they're all notified
+ // upon its delivery. Callers must provide a preallocated
+ // SignalEvent object which can be used to manage the lifetime of
+ // this event. Returns true on success.
+ bool CatchSignal(int sig, SignalEvent* sigevent, SignalWatcher* delegate);
+
+ // MessagePump methods:
+ virtual void Run(Delegate* delegate) override;
+ virtual void Quit() override;
+ virtual void ScheduleWork() override;
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time) override;
+
+ protected:
+ virtual ~MessagePumpLibevent();
+
+ private:
+ // Risky part of constructor. Returns true on success.
+ bool Init();
+
+ // This flag is set to false when Run should return.
+ bool keep_running_;
+
+ // This flag is set when inside Run.
+ bool in_run_;
+
+ // The time at which we should call DoDelayedWork.
+ TimeTicks delayed_work_time_;
+
+ // Libevent dispatcher. Watches all sockets registered with it, and sends
+ // readiness callbacks when a socket is ready for I/O.
+ event_base* event_base_;
+
+ // Called by libevent to tell us a registered FD can be read/written to.
+ static void OnLibeventNotification(int fd, short flags, void* context);
+
+ // Called by libevent upon receiving a signal
+ static void OnLibeventSignalNotification(int sig, short flags, void* context);
+
+ // Unix pipe used to implement ScheduleWork()
+ // ... callback; called by libevent inside Run() when pipe is ready to read
+ static void OnWakeup(int socket, short flags, void* context);
+ // ... write end; ScheduleWork() writes a single byte to it
+ int wakeup_pipe_in_;
+ // ... read end; OnWakeup reads it and then breaks Run() out of its sleep
+ int wakeup_pipe_out_;
+ // ... libevent wrapper for read end
+ event* wakeup_event_;
+
+ // Set to false when calling event_base_loop and to true when either of the
+ // OnWakeup, OnLibeventNotification or OnLibeventSignalNotification callbacks
+ // is called.
+ // Used to ensure our calls to profiler_thread_sleep and profiler_thread_wake
+ // are paired correctly.
+ static bool awake_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpLibevent);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_LIBEVENT_H_
diff --git a/ipc/chromium/src/base/message_pump_mac.h b/ipc/chromium/src/base/message_pump_mac.h
new file mode 100644
index 0000000000..13902bbf3e
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_mac.h
@@ -0,0 +1,280 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+// The basis for all native run loops on the Mac is the CFRunLoop. It can be
+// used directly, it can be used as the driving force behind the similar
+// Foundation NSRunLoop, and it can be used to implement higher-level event
+// loops such as the NSApplication event loop.
+//
+// This file introduces a basic CFRunLoop-based implementation of the
+// MessagePump interface called CFRunLoopBase. CFRunLoopBase contains all
+// of the machinery necessary to dispatch events to a delegate, but does not
+// implement the specific run loop. Concrete subclasses must provide their
+// own DoRun and Quit implementations.
+//
+// A concrete subclass that just runs a CFRunLoop loop is provided in
+// MessagePumpCFRunLoop. For an NSRunLoop, the similar MessagePumpNSRunLoop
+// is provided.
+//
+// For the application's event loop, an implementation based on AppKit's
+// NSApplication event system is provided in MessagePumpNSApplication.
+//
+// Typically, MessagePumpNSApplication only makes sense on a Cocoa
+// application's main thread. If a CFRunLoop-based message pump is needed on
+// any other thread, one of the other concrete subclasses is preferrable.
+// MessagePumpMac::Create is defined, which returns a new NSApplication-based
+// or NSRunLoop-based MessagePump subclass depending on which thread it is
+// called on.
+
+#ifndef BASE_MESSAGE_PUMP_MAC_H_
+#define BASE_MESSAGE_PUMP_MAC_H_
+
+#include "base/message_pump.h"
+
+#include "base/basictypes.h"
+
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOKit/IOKitLib.h>
+
+#if defined(__OBJC__)
+@class NSAutoreleasePool;
+#else // defined(__OBJC__)
+class NSAutoreleasePool;
+#endif // defined(__OBJC__)
+
+namespace base {
+
+class TimeTicks;
+
+class MessagePumpCFRunLoopBase : public MessagePump {
+ // Needs access to CreateAutoreleasePool.
+ friend class MessagePumpScopedAutoreleasePool;
+
+ public:
+ MessagePumpCFRunLoopBase();
+ virtual ~MessagePumpCFRunLoopBase();
+
+ // Subclasses should implement the work they need to do in MessagePump::Run
+ // in the DoRun method. MessagePumpCFRunLoopBase::Run calls DoRun directly.
+ // This arrangement is used because MessagePumpCFRunLoopBase needs to set
+ // up and tear down things before and after the "meat" of DoRun.
+ virtual void Run(Delegate* delegate);
+ virtual void DoRun(Delegate* delegate) = 0;
+
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
+
+ protected:
+ // Accessors for private data members to be used by subclasses.
+ CFRunLoopRef run_loop() const { return run_loop_; }
+ int nesting_level() const { return nesting_level_; }
+ int run_nesting_level() const { return run_nesting_level_; }
+
+ // Return an autorelease pool to wrap around any work being performed.
+ // In some cases, CreateAutoreleasePool may return nil intentionally to
+ // preventing an autorelease pool from being created, allowing any
+ // objects autoreleased by work to fall into the current autorelease pool.
+ virtual NSAutoreleasePool* CreateAutoreleasePool();
+
+ private:
+ // Timer callback scheduled by ScheduleDelayedWork. This does not do any
+ // work, but it signals delayed_work_source_ so that delayed work can be
+ // performed within the appropriate priority constraints.
+ static void RunDelayedWorkTimer(CFRunLoopTimerRef timer, void* info);
+
+ // Perform highest-priority work. This is associated with work_source_
+ // signalled by ScheduleWork. The static method calls the instance method;
+ // the instance method returns true if work was done.
+ static void RunWorkSource(void* info);
+ bool RunWork();
+
+ // Perform delayed-priority work. This is associated with
+ // delayed_work_source_ signalled by RunDelayedWorkTimer, and is responsible
+ // for calling ScheduleDelayedWork again if appropriate. The static method
+ // calls the instance method; the instance method returns true if more
+ // delayed work is available.
+ static void RunDelayedWorkSource(void* info);
+ bool RunDelayedWork();
+
+ // Perform idle-priority work. This is normally called by PreWaitObserver,
+ // but is also associated with idle_work_source_. When this function
+ // actually does perform idle work, it will resignal that source. The
+ // static method calls the instance method; the instance method returns
+ // true if idle work was done.
+ static void RunIdleWorkSource(void* info);
+ bool RunIdleWork();
+
+ // Perform work that may have been deferred because it was not runnable
+ // within a nested run loop. This is associated with
+ // nesting_deferred_work_source_ and is signalled by
+ // MaybeScheduleNestingDeferredWork when returning from a nested loop,
+ // so that an outer loop will be able to perform the necessary tasks if it
+ // permits nestable tasks.
+ static void RunNestingDeferredWorkSource(void* info);
+ bool RunNestingDeferredWork();
+
+ // Schedules possible nesting-deferred work to be processed before the run
+ // loop goes to sleep, exits, or begins processing sources at the top of its
+ // loop. If this function detects that a nested loop had run since the
+ // previous attempt to schedule nesting-deferred work, it will schedule a
+ // call to RunNestingDeferredWorkSource.
+ void MaybeScheduleNestingDeferredWork();
+
+ // Observer callback responsible for performing idle-priority work, before
+ // the run loop goes to sleep. Associated with idle_work_observer_.
+ static void PreWaitObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity, void* info);
+
+ // Observer callback called before the run loop processes any sources.
+ // Associated with pre_source_observer_.
+ static void PreSourceObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity, void* info);
+
+ // Observer callback called when the run loop starts and stops, at the
+ // beginning and end of calls to CFRunLoopRun. This is used to maintain
+ // nesting_level_. Associated with enter_exit_observer_.
+ static void EnterExitObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity, void* info);
+
+ // Called by EnterExitObserver after performing maintenance on nesting_level_.
+ // This allows subclasses an opportunity to perform additional processing on
+ // the basis of run loops starting and stopping.
+ virtual void EnterExitRunLoop(CFRunLoopActivity activity);
+
+ // IOKit power state change notification callback, called when the system
+ // enters and leaves the sleep state.
+ static void PowerStateNotification(void* info, io_service_t service,
+ uint32_t message_type,
+ void* message_argument);
+
+ // The thread's run loop.
+ CFRunLoopRef run_loop_;
+
+ // The timer, sources, and observers are described above alongside their
+ // callbacks.
+ CFRunLoopTimerRef delayed_work_timer_;
+ CFRunLoopSourceRef work_source_;
+ CFRunLoopSourceRef delayed_work_source_;
+ CFRunLoopSourceRef idle_work_source_;
+ CFRunLoopSourceRef nesting_deferred_work_source_;
+ CFRunLoopObserverRef pre_wait_observer_;
+ CFRunLoopObserverRef pre_source_observer_;
+ CFRunLoopObserverRef enter_exit_observer_;
+
+ // Objects used for power state notification. See PowerStateNotification.
+ io_connect_t root_power_domain_;
+ IONotificationPortRef power_notification_port_;
+ io_object_t power_notification_object_;
+
+ // (weak) Delegate passed as an argument to the innermost Run call.
+ Delegate* delegate_;
+
+ // The time that delayed_work_timer_ is scheduled to fire. This is tracked
+ // independently of CFRunLoopTimerGetNextFireDate(delayed_work_timer_)
+ // to be able to reset the timer properly after waking from system sleep.
+ // See PowerStateNotification.
+ CFAbsoluteTime delayed_work_fire_time_;
+
+ // The recursion depth of the currently-executing CFRunLoopRun loop on the
+ // run loop's thread. 0 if no run loops are running inside of whatever scope
+ // the object was created in.
+ int nesting_level_;
+
+ // The recursion depth (calculated in the same way as nesting_level_) of the
+ // innermost executing CFRunLoopRun loop started by a call to Run.
+ int run_nesting_level_;
+
+ // The deepest (numerically highest) recursion depth encountered since the
+ // most recent attempt to run nesting-deferred work.
+ int deepest_nesting_level_;
+
+ // "Delegateless" work flags are set when work is ready to be performed but
+ // must wait until a delegate is available to process it. This can happen
+ // when a MessagePumpCFRunLoopBase is instantiated and work arrives without
+ // any call to Run on the stack. The Run method will check for delegateless
+ // work on entry and redispatch it as needed once a delegate is available.
+ bool delegateless_work_;
+ bool delegateless_delayed_work_;
+ bool delegateless_idle_work_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoopBase);
+};
+
+class MessagePumpCFRunLoop : public MessagePumpCFRunLoopBase {
+ public:
+ MessagePumpCFRunLoop();
+
+ virtual void DoRun(Delegate* delegate);
+ virtual void Quit();
+
+ private:
+ virtual void EnterExitRunLoop(CFRunLoopActivity activity);
+
+ // True if Quit is called to stop the innermost MessagePump
+ // (innermost_quittable_) but some other CFRunLoopRun loop (nesting_level_)
+ // is running inside the MessagePump's innermost Run call.
+ bool quit_pending_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpCFRunLoop);
+};
+
+class MessagePumpNSRunLoop : public MessagePumpCFRunLoopBase {
+ public:
+ MessagePumpNSRunLoop();
+ virtual ~MessagePumpNSRunLoop();
+
+ virtual void DoRun(Delegate* delegate);
+ virtual void Quit();
+
+ private:
+ // A source that doesn't do anything but provide something signalable
+ // attached to the run loop. This source will be signalled when Quit
+ // is called, to cause the loop to wake up so that it can stop.
+ CFRunLoopSourceRef quit_source_;
+
+ // False after Quit is called.
+ bool keep_running_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpNSRunLoop);
+};
+
+class MessagePumpNSApplication : public MessagePumpCFRunLoopBase {
+ public:
+ MessagePumpNSApplication();
+
+ virtual void DoRun(Delegate* delegate);
+ virtual void Quit();
+
+ protected:
+ // Returns nil if NSApp is currently in the middle of calling -sendEvent.
+ virtual NSAutoreleasePool* CreateAutoreleasePool();
+
+ private:
+ // False after Quit is called.
+ bool keep_running_;
+
+ // True if DoRun is managing its own run loop as opposed to letting
+ // -[NSApplication run] handle it. The outermost run loop in the application
+ // is managed by -[NSApplication run], inner run loops are handled by a loop
+ // in DoRun.
+ bool running_own_loop_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpNSApplication);
+};
+
+class MessagePumpMac {
+ public:
+ // Returns a new instance of MessagePumpNSApplication if called on the main
+ // thread. Otherwise, returns a new instance of MessagePumpNSRunLoop.
+ static MessagePump* Create();
+
+ private:
+ DISALLOW_IMPLICIT_CONSTRUCTORS(MessagePumpMac);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_MAC_H_
diff --git a/ipc/chromium/src/base/message_pump_mac.mm b/ipc/chromium/src/base/message_pump_mac.mm
new file mode 100644
index 0000000000..1382e2a0dc
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_mac.mm
@@ -0,0 +1,735 @@
+// Copyright (c) 2008 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.
+
+#include "base/message_pump_mac.h"
+
+#import <AppKit/AppKit.h>
+#import <Foundation/Foundation.h>
+#include <IOKit/IOMessage.h>
+#include <IOKit/pwr_mgt/IOPMLib.h>
+
+#include <limits>
+
+#import "base/chrome_application_mac.h"
+#include "base/logging.h"
+#include "base/time.h"
+
+namespace {
+
+void NoOp(void* info) {}
+
+const CFTimeInterval kCFTimeIntervalMax =
+ std::numeric_limits<CFTimeInterval>::max();
+
+} // namespace
+
+namespace base {
+
+// A scoper for autorelease pools created from message pump run loops.
+// Avoids dirtying up the ScopedNSAutoreleasePool interface for the rare
+// case where an autorelease pool needs to be passed in.
+class MessagePumpScopedAutoreleasePool {
+ public:
+ explicit MessagePumpScopedAutoreleasePool(MessagePumpCFRunLoopBase* pump)
+ : pool_(pump->CreateAutoreleasePool()) {}
+ ~MessagePumpScopedAutoreleasePool() { [pool_ drain]; }
+
+ private:
+ NSAutoreleasePool* pool_;
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpScopedAutoreleasePool);
+};
+
+// Must be called on the run loop thread.
+MessagePumpCFRunLoopBase::MessagePumpCFRunLoopBase()
+ : delegate_(NULL),
+ delayed_work_fire_time_(kCFTimeIntervalMax),
+ nesting_level_(0),
+ run_nesting_level_(0),
+ deepest_nesting_level_(0),
+ delegateless_work_(false),
+ delegateless_delayed_work_(false),
+ delegateless_idle_work_(false) {
+ run_loop_ = CFRunLoopGetCurrent();
+ CFRetain(run_loop_);
+
+ // Set a repeating timer with a preposterous firing time and interval. The
+ // timer will effectively never fire as-is. The firing time will be adjusted
+ // as needed when ScheduleDelayedWork is called.
+ CFRunLoopTimerContext timer_context = CFRunLoopTimerContext();
+ timer_context.info = this;
+ delayed_work_timer_ =
+ CFRunLoopTimerCreate(NULL, // allocator
+ kCFTimeIntervalMax, // fire time
+ kCFTimeIntervalMax, // interval
+ 0, // flags
+ 0, // priority
+ RunDelayedWorkTimer, &timer_context);
+ CFRunLoopAddTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
+
+ CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
+ source_context.info = this;
+ source_context.perform = RunWorkSource;
+ work_source_ = CFRunLoopSourceCreate(NULL, // allocator
+ 1, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop_, work_source_, kCFRunLoopCommonModes);
+
+ source_context.perform = RunDelayedWorkSource;
+ delayed_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
+ 2, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop_, delayed_work_source_, kCFRunLoopCommonModes);
+
+ source_context.perform = RunIdleWorkSource;
+ idle_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
+ 3, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
+
+ source_context.perform = RunNestingDeferredWorkSource;
+ nesting_deferred_work_source_ = CFRunLoopSourceCreate(NULL, // allocator
+ 0, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop_, nesting_deferred_work_source_,
+ kCFRunLoopCommonModes);
+
+ CFRunLoopObserverContext observer_context = CFRunLoopObserverContext();
+ observer_context.info = this;
+ pre_wait_observer_ =
+ CFRunLoopObserverCreate(NULL, // allocator
+ kCFRunLoopBeforeWaiting,
+ true, // repeat
+ 0, // priority
+ PreWaitObserver, &observer_context);
+ CFRunLoopAddObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes);
+
+ pre_source_observer_ =
+ CFRunLoopObserverCreate(NULL, // allocator
+ kCFRunLoopBeforeSources,
+ true, // repeat
+ 0, // priority
+ PreSourceObserver, &observer_context);
+ CFRunLoopAddObserver(run_loop_, pre_source_observer_, kCFRunLoopCommonModes);
+
+ enter_exit_observer_ =
+ CFRunLoopObserverCreate(NULL, // allocator
+ kCFRunLoopEntry | kCFRunLoopExit,
+ true, // repeat
+ 0, // priority
+ EnterExitObserver, &observer_context);
+ CFRunLoopAddObserver(run_loop_, enter_exit_observer_, kCFRunLoopCommonModes);
+
+ root_power_domain_ = IORegisterForSystemPower(this, &power_notification_port_,
+ PowerStateNotification,
+ &power_notification_object_);
+ if (root_power_domain_ != MACH_PORT_NULL) {
+ CFRunLoopAddSource(
+ run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_),
+ kCFRunLoopCommonModes);
+ }
+}
+
+// Ideally called on the run loop thread. If other run loops were running
+// lower on the run loop thread's stack when this object was created, the
+// same number of run loops must be running when this object is destroyed.
+MessagePumpCFRunLoopBase::~MessagePumpCFRunLoopBase() {
+ if (root_power_domain_ != MACH_PORT_NULL) {
+ CFRunLoopRemoveSource(
+ run_loop_, IONotificationPortGetRunLoopSource(power_notification_port_),
+ kCFRunLoopCommonModes);
+ IODeregisterForSystemPower(&power_notification_object_);
+ IOServiceClose(root_power_domain_);
+ IONotificationPortDestroy(power_notification_port_);
+ }
+
+ CFRunLoopRemoveObserver(run_loop_, enter_exit_observer_,
+ kCFRunLoopCommonModes);
+ CFRelease(enter_exit_observer_);
+
+ CFRunLoopRemoveObserver(run_loop_, pre_source_observer_,
+ kCFRunLoopCommonModes);
+ CFRelease(pre_source_observer_);
+
+ CFRunLoopRemoveObserver(run_loop_, pre_wait_observer_, kCFRunLoopCommonModes);
+ CFRelease(pre_wait_observer_);
+
+ CFRunLoopRemoveSource(run_loop_, nesting_deferred_work_source_,
+ kCFRunLoopCommonModes);
+ CFRelease(nesting_deferred_work_source_);
+
+ CFRunLoopRemoveSource(run_loop_, idle_work_source_, kCFRunLoopCommonModes);
+ CFRelease(idle_work_source_);
+
+ CFRunLoopRemoveSource(run_loop_, delayed_work_source_, kCFRunLoopCommonModes);
+ CFRelease(delayed_work_source_);
+
+ CFRunLoopRemoveSource(run_loop_, work_source_, kCFRunLoopCommonModes);
+ CFRelease(work_source_);
+
+ CFRunLoopRemoveTimer(run_loop_, delayed_work_timer_, kCFRunLoopCommonModes);
+ CFRelease(delayed_work_timer_);
+
+ CFRelease(run_loop_);
+}
+
+// Must be called on the run loop thread.
+void MessagePumpCFRunLoopBase::Run(Delegate* delegate) {
+ // nesting_level_ will be incremented in EnterExitRunLoop, so set
+ // run_nesting_level_ accordingly.
+ int last_run_nesting_level = run_nesting_level_;
+ run_nesting_level_ = nesting_level_ + 1;
+
+ Delegate* last_delegate = delegate_;
+ delegate_ = delegate;
+
+ if (delegate) {
+ // If any work showed up but could not be dispatched for want of a
+ // delegate, set it up for dispatch again now that a delegate is
+ // available.
+ if (delegateless_work_) {
+ CFRunLoopSourceSignal(work_source_);
+ delegateless_work_ = false;
+ }
+ if (delegateless_delayed_work_) {
+ CFRunLoopSourceSignal(delayed_work_source_);
+ delegateless_delayed_work_ = false;
+ }
+ if (delegateless_idle_work_) {
+ CFRunLoopSourceSignal(idle_work_source_);
+ delegateless_idle_work_ = false;
+ }
+ }
+
+ DoRun(delegate);
+
+ // Restore the previous state of the object.
+ delegate_ = last_delegate;
+ run_nesting_level_ = last_run_nesting_level;
+}
+
+// May be called on any thread.
+void MessagePumpCFRunLoopBase::ScheduleWork() {
+ CFRunLoopSourceSignal(work_source_);
+ CFRunLoopWakeUp(run_loop_);
+}
+
+// Must be called on the run loop thread.
+void MessagePumpCFRunLoopBase::ScheduleDelayedWork(
+ const TimeTicks& delayed_work_time) {
+ TimeDelta delta = delayed_work_time - TimeTicks::Now();
+ delayed_work_fire_time_ = CFAbsoluteTimeGetCurrent() + delta.InSecondsF();
+ CFRunLoopTimerSetNextFireDate(delayed_work_timer_, delayed_work_fire_time_);
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::RunDelayedWorkTimer(CFRunLoopTimerRef timer,
+ void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+
+ // The timer won't fire again until it's reset.
+ self->delayed_work_fire_time_ = kCFTimeIntervalMax;
+
+ // CFRunLoopTimers fire outside of the priority scheme for CFRunLoopSources.
+ // In order to establish the proper priority where delegate_->DoDelayedWork
+ // can only be called if delegate_->DoWork returns false, the timer used
+ // to schedule delayed work must signal a CFRunLoopSource set at a lower
+ // priority than the one used for delegate_->DoWork.
+ CFRunLoopSourceSignal(self->delayed_work_source_);
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::RunWorkSource(void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+ self->RunWork();
+}
+
+// Called by MessagePumpCFRunLoopBase::RunWorkSource.
+bool MessagePumpCFRunLoopBase::RunWork() {
+ if (!delegate_) {
+ // This point can be reached with a NULL delegate_ if Run is not on the
+ // stack but foreign code is spinning the CFRunLoop. Arrange to come back
+ // here when a delegate is available.
+ delegateless_work_ = true;
+ return false;
+ }
+
+ // The NSApplication-based run loop only drains the autorelease pool at each
+ // UI event (NSEvent). The autorelease pool is not drained for each
+ // CFRunLoopSource target that's run. Use a local pool for any autoreleased
+ // objects if the app is not currently handling a UI event to ensure they're
+ // released promptly even in the absence of UI events.
+ MessagePumpScopedAutoreleasePool autorelease_pool(this);
+
+ // Call DoWork once, and if something was done, arrange to come back here
+ // again as long as the loop is still running.
+ bool did_work = delegate_->DoWork();
+ if (did_work) {
+ CFRunLoopSourceSignal(work_source_);
+ }
+
+ return did_work;
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::RunDelayedWorkSource(void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+ self->RunDelayedWork();
+}
+
+// Called by MessagePumpCFRunLoopBase::RunDelayedWorkSource.
+bool MessagePumpCFRunLoopBase::RunDelayedWork() {
+ if (!delegate_) {
+ // This point can be reached with a NULL delegate_ if Run is not on the
+ // stack but foreign code is spinning the CFRunLoop. Arrange to come back
+ // here when a delegate is available.
+ delegateless_delayed_work_ = true;
+ return false;
+ }
+
+ // The NSApplication-based run loop only drains the autorelease pool at each
+ // UI event (NSEvent). The autorelease pool is not drained for each
+ // CFRunLoopSource target that's run. Use a local pool for any autoreleased
+ // objects if the app is not currently handling a UI event to ensure they're
+ // released promptly even in the absence of UI events.
+ MessagePumpScopedAutoreleasePool autorelease_pool(this);
+
+ TimeTicks next_time;
+ delegate_->DoDelayedWork(&next_time);
+
+ bool more_work = !next_time.is_null();
+ if (more_work) {
+ TimeDelta delay = next_time - TimeTicks::Now();
+ if (delay > TimeDelta()) {
+ // There's more delayed work to be done in the future.
+ ScheduleDelayedWork(next_time);
+ } else {
+ // There's more delayed work to be done, and its time is in the past.
+ // Arrange to come back here directly as long as the loop is still
+ // running.
+ CFRunLoopSourceSignal(delayed_work_source_);
+ }
+ }
+
+ return more_work;
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::RunIdleWorkSource(void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+ self->RunIdleWork();
+}
+
+// Called by MessagePumpCFRunLoopBase::RunIdleWorkSource.
+bool MessagePumpCFRunLoopBase::RunIdleWork() {
+ if (!delegate_) {
+ // This point can be reached with a NULL delegate_ if Run is not on the
+ // stack but foreign code is spinning the CFRunLoop. Arrange to come back
+ // here when a delegate is available.
+ delegateless_idle_work_ = true;
+ return false;
+ }
+
+ // The NSApplication-based run loop only drains the autorelease pool at each
+ // UI event (NSEvent). The autorelease pool is not drained for each
+ // CFRunLoopSource target that's run. Use a local pool for any autoreleased
+ // objects if the app is not currently handling a UI event to ensure they're
+ // released promptly even in the absence of UI events.
+ MessagePumpScopedAutoreleasePool autorelease_pool(this);
+
+ // Call DoIdleWork once, and if something was done, arrange to come back here
+ // again as long as the loop is still running.
+ bool did_work = delegate_->DoIdleWork();
+ if (did_work) {
+ CFRunLoopSourceSignal(idle_work_source_);
+ }
+
+ return did_work;
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource(void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+ self->RunNestingDeferredWork();
+}
+
+// Called by MessagePumpCFRunLoopBase::RunNestingDeferredWorkSource.
+bool MessagePumpCFRunLoopBase::RunNestingDeferredWork() {
+ if (!delegate_) {
+ // This point can be reached with a NULL delegate_ if Run is not on the
+ // stack but foreign code is spinning the CFRunLoop. There's no sense in
+ // attempting to do any work or signalling the work sources because
+ // without a delegate, work is not possible.
+ return false;
+ }
+
+ // Immediately try work in priority order.
+ if (!RunWork()) {
+ if (!RunDelayedWork()) {
+ if (!RunIdleWork()) {
+ return false;
+ }
+ } else {
+ // There was no work, and delayed work was done. Arrange for the loop
+ // to try non-nestable idle work on a subsequent pass.
+ CFRunLoopSourceSignal(idle_work_source_);
+ }
+ } else {
+ // Work was done. Arrange for the loop to try non-nestable delayed and
+ // idle work on a subsequent pass.
+ CFRunLoopSourceSignal(delayed_work_source_);
+ CFRunLoopSourceSignal(idle_work_source_);
+ }
+
+ return true;
+}
+
+// Called before the run loop goes to sleep or exits, or processes sources.
+void MessagePumpCFRunLoopBase::MaybeScheduleNestingDeferredWork() {
+ // deepest_nesting_level_ is set as run loops are entered. If the deepest
+ // level encountered is deeper than the current level, a nested loop
+ // (relative to the current level) ran since the last time nesting-deferred
+ // work was scheduled. When that situation is encountered, schedule
+ // nesting-deferred work in case any work was deferred because nested work
+ // was disallowed.
+ if (deepest_nesting_level_ > nesting_level_) {
+ deepest_nesting_level_ = nesting_level_;
+ CFRunLoopSourceSignal(nesting_deferred_work_source_);
+ }
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::PreWaitObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity,
+ void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+
+ // Attempt to do some idle work before going to sleep.
+ self->RunIdleWork();
+
+ // The run loop is about to go to sleep. If any of the work done since it
+ // started or woke up resulted in a nested run loop running,
+ // nesting-deferred work may have accumulated. Schedule it for processing
+ // if appropriate.
+ self->MaybeScheduleNestingDeferredWork();
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::PreSourceObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity,
+ void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+
+ // The run loop has reached the top of the loop and is about to begin
+ // processing sources. If the last iteration of the loop at this nesting
+ // level did not sleep or exit, nesting-deferred work may have accumulated
+ // if a nested loop ran. Schedule nesting-deferred work for processing if
+ // appropriate.
+ self->MaybeScheduleNestingDeferredWork();
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::EnterExitObserver(CFRunLoopObserverRef observer,
+ CFRunLoopActivity activity,
+ void* info) {
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+
+ switch (activity) {
+ case kCFRunLoopEntry:
+ ++self->nesting_level_;
+ if (self->nesting_level_ > self->deepest_nesting_level_) {
+ self->deepest_nesting_level_ = self->nesting_level_;
+ }
+ break;
+
+ case kCFRunLoopExit:
+ // Not all run loops go to sleep. If a run loop is stopped before it
+ // goes to sleep due to a CFRunLoopStop call, or if the timeout passed
+ // to CFRunLoopRunInMode expires, the run loop may proceed directly from
+ // handling sources to exiting without any sleep. This most commonly
+ // occurs when CFRunLoopRunInMode is passed a timeout of 0, causing it
+ // to make a single pass through the loop and exit without sleep. Some
+ // native loops use CFRunLoop in this way. Because PreWaitObserver will
+ // not be called in these case, MaybeScheduleNestingDeferredWork needs
+ // to be called here, as the run loop exits.
+ //
+ // MaybeScheduleNestingDeferredWork consults self->nesting_level_
+ // to determine whether to schedule nesting-deferred work. It expects
+ // the nesting level to be set to the depth of the loop that is going
+ // to sleep or exiting. It must be called before decrementing the
+ // value so that the value still corresponds to the level of the exiting
+ // loop.
+ self->MaybeScheduleNestingDeferredWork();
+ --self->nesting_level_;
+ break;
+
+ default:
+ break;
+ }
+
+ self->EnterExitRunLoop(activity);
+}
+
+// Called from the run loop.
+// static
+void MessagePumpCFRunLoopBase::PowerStateNotification(void* info,
+ io_service_t service,
+ uint32_t message_type,
+ void* message_argument) {
+ // CFRunLoopTimer (NSTimer) is scheduled in terms of CFAbsoluteTime, which
+ // measures the number of seconds since 2001-01-01 00:00:00.0 Z. It is
+ // implemented in terms of kernel ticks, as in mach_absolute_time. While an
+ // offset and scale factor can be applied to convert between the two time
+ // bases at any time after boot, the kernel clock stops while the system is
+ // asleep, altering the offset. (The offset will also change when the
+ // real-time clock is adjusted.) CFRunLoopTimers are not readjusted to take
+ // this into account when the system wakes up, so any timers that were
+ // pending while the system was asleep will be delayed by the sleep
+ // duration.
+ //
+ // The MessagePump interface assumes that scheduled delayed work will be
+ // performed at the time ScheduleDelayedWork was asked to perform it. The
+ // delay caused by the CFRunLoopTimer not firing at the appropriate time
+ // results in a stall of queued delayed work when the system wakes up.
+ // With this limitation, scheduled work would not be performed until
+ // (system wake time + scheduled work time - system sleep time), while it
+ // would be expected to be performed at (scheduled work time).
+ //
+ // To work around this problem, when the system wakes up from sleep, if a
+ // delayed work timer is pending, it is rescheduled to fire at the original
+ // time that it was scheduled to fire.
+ //
+ // This mechanism is not resilient if the real-time clock does not maintain
+ // stable time while the system is sleeping, but it matches the behavior of
+ // the various other MessagePump implementations, and MessageLoop seems to
+ // be limited in the same way.
+ //
+ // References
+ // - Chris Kane, "NSTimer and deep sleep," cocoa-dev@lists.apple.com,
+ // http://lists.apple.com/archives/Cocoa-dev/2002/May/msg01547.html
+ // - Apple Technical Q&A QA1340, "Registering and unregistering for sleep
+ // and wake notifications,"
+ // http://developer.apple.com/mac/library/qa/qa2004/qa1340.html
+ // - Core Foundation source code, CF-550/CFRunLoop.c and CF-550/CFDate.c,
+ // http://www.opensource.apple.com/
+
+ MessagePumpCFRunLoopBase* self = static_cast<MessagePumpCFRunLoopBase*>(info);
+
+ switch (message_type) {
+ case kIOMessageSystemWillPowerOn:
+ if (self->delayed_work_fire_time_ != kCFTimeIntervalMax) {
+ CFRunLoopTimerSetNextFireDate(self->delayed_work_timer_,
+ self->delayed_work_fire_time_);
+ }
+ break;
+
+ case kIOMessageSystemWillSleep:
+ case kIOMessageCanSystemSleep:
+ // The system will wait for 30 seconds before entering sleep if neither
+ // IOAllowPowerChange nor IOCancelPowerChange are called. That would be
+ // pretty antisocial.
+ IOAllowPowerChange(self->root_power_domain_,
+ reinterpret_cast<long>(message_argument));
+ break;
+
+ default:
+ break;
+ }
+}
+
+// Called by MessagePumpCFRunLoopBase::EnterExitRunLoop. The default
+// implementation is a no-op.
+void MessagePumpCFRunLoopBase::EnterExitRunLoop(CFRunLoopActivity activity) {}
+
+// Base version returns a standard NSAutoreleasePool.
+NSAutoreleasePool* MessagePumpCFRunLoopBase::CreateAutoreleasePool() {
+ return [[NSAutoreleasePool alloc] init];
+}
+
+MessagePumpCFRunLoop::MessagePumpCFRunLoop() : quit_pending_(false) {}
+
+// Called by MessagePumpCFRunLoopBase::DoRun. If other CFRunLoopRun loops were
+// running lower on the run loop thread's stack when this object was created,
+// the same number of CFRunLoopRun loops must be running for the outermost call
+// to Run. Run/DoRun are reentrant after that point.
+void MessagePumpCFRunLoop::DoRun(Delegate* delegate) {
+ // This is completely identical to calling CFRunLoopRun(), except autorelease
+ // pool management is introduced.
+ int result;
+ do {
+ MessagePumpScopedAutoreleasePool autorelease_pool(this);
+ result =
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, kCFTimeIntervalMax, false);
+ } while (result != kCFRunLoopRunStopped && result != kCFRunLoopRunFinished);
+}
+
+// Must be called on the run loop thread.
+void MessagePumpCFRunLoop::Quit() {
+ // Stop the innermost run loop managed by this MessagePumpCFRunLoop object.
+ if (nesting_level() == run_nesting_level()) {
+ // This object is running the innermost loop, just stop it.
+ CFRunLoopStop(run_loop());
+ } else {
+ // There's another loop running inside the loop managed by this object.
+ // In other words, someone else called CFRunLoopRunInMode on the same
+ // thread, deeper on the stack than the deepest Run call. Don't preempt
+ // other run loops, just mark this object to quit the innermost Run as
+ // soon as the other inner loops not managed by Run are done.
+ quit_pending_ = true;
+ }
+}
+
+// Called by MessagePumpCFRunLoopBase::EnterExitObserver.
+void MessagePumpCFRunLoop::EnterExitRunLoop(CFRunLoopActivity activity) {
+ if (activity == kCFRunLoopExit && nesting_level() == run_nesting_level() &&
+ quit_pending_) {
+ // Quit was called while loops other than those managed by this object
+ // were running further inside a run loop managed by this object. Now
+ // that all unmanaged inner run loops are gone, stop the loop running
+ // just inside Run.
+ CFRunLoopStop(run_loop());
+ quit_pending_ = false;
+ }
+}
+
+MessagePumpNSRunLoop::MessagePumpNSRunLoop() : keep_running_(true) {
+ CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
+ source_context.perform = NoOp;
+ quit_source_ = CFRunLoopSourceCreate(NULL, // allocator
+ 0, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
+}
+
+MessagePumpNSRunLoop::~MessagePumpNSRunLoop() {
+ CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
+ CFRelease(quit_source_);
+}
+
+void MessagePumpNSRunLoop::DoRun(Delegate* delegate) {
+ while (keep_running_) {
+ // NSRunLoop manages autorelease pools itself.
+ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
+ beforeDate:[NSDate distantFuture]];
+ }
+
+ keep_running_ = true;
+}
+
+void MessagePumpNSRunLoop::Quit() {
+ keep_running_ = false;
+ CFRunLoopSourceSignal(quit_source_);
+ CFRunLoopWakeUp(run_loop());
+}
+
+MessagePumpNSApplication::MessagePumpNSApplication()
+ : keep_running_(true), running_own_loop_(false) {}
+
+void MessagePumpNSApplication::DoRun(Delegate* delegate) {
+ bool last_running_own_loop_ = running_own_loop_;
+
+ // TODO(dmaclach): Get rid of this gratuitous sharedApplication.
+ // Tests should be setting up their applications on their own.
+ [CrApplication sharedApplication];
+
+ if (![NSApp isRunning]) {
+ running_own_loop_ = false;
+ // NSApplication manages autorelease pools itself when run this way.
+ [NSApp run];
+ } else {
+ running_own_loop_ = true;
+ NSDate* distant_future = [NSDate distantFuture];
+ while (keep_running_) {
+ MessagePumpScopedAutoreleasePool autorelease_pool(this);
+ NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
+ untilDate:distant_future
+ inMode:NSDefaultRunLoopMode
+ dequeue:YES];
+ if (event) {
+ [NSApp sendEvent:event];
+ }
+ }
+ keep_running_ = true;
+ }
+
+ running_own_loop_ = last_running_own_loop_;
+}
+
+void MessagePumpNSApplication::Quit() {
+ if (!running_own_loop_) {
+ [NSApp stop:nil];
+ } else {
+ keep_running_ = false;
+ }
+
+ // Send a fake event to wake the loop up.
+ [NSApp postEvent:[NSEvent otherEventWithType:NSEventTypeApplicationDefined
+ location:NSMakePoint(0, 0)
+ modifierFlags:0
+ timestamp:0
+ windowNumber:0
+ context:NULL
+ subtype:0
+ data1:0
+ data2:0]
+ atStart:NO];
+}
+
+// Prevents an autorelease pool from being created if the app is in the midst of
+// handling a UI event because various parts of AppKit depend on objects that
+// are created while handling a UI event to be autoreleased in the event loop.
+// An example of this is NSWindowController. When a window with a window
+// controller is closed it goes through a stack like this:
+// (Several stack frames elided for clarity)
+//
+// #0 [NSWindowController autorelease]
+// #1 DoAClose
+// #2 MessagePumpCFRunLoopBase::DoWork()
+// #3 [NSRunLoop run]
+// #4 [NSButton performClick:]
+// #5 [NSWindow sendEvent:]
+// #6 [NSApp sendEvent:]
+// #7 [NSApp run]
+//
+// -performClick: spins a nested run loop. If the pool created in DoWork was a
+// standard NSAutoreleasePool, it would release the objects that were
+// autoreleased into it once DoWork released it. This would cause the window
+// controller, which autoreleased itself in frame #0, to release itself, and
+// possibly free itself. Unfortunately this window controller controls the
+// window in frame #5. When the stack is unwound to frame #5, the window would
+// no longer exists and crashes may occur. Apple gets around this by never
+// releasing the pool it creates in frame #4, and letting frame #7 clean it up
+// when it cleans up the pool that wraps frame #7. When an autorelease pool is
+// released it releases all other pools that were created after it on the
+// autorelease pool stack.
+//
+// CrApplication is responsible for setting handlingSendEvent to true just
+// before it sends the event throught the event handling mechanism, and
+// returning it to its previous value once the event has been sent.
+NSAutoreleasePool* MessagePumpNSApplication::CreateAutoreleasePool() {
+ NSAutoreleasePool* pool = nil;
+ DCHECK([NSApp isKindOfClass:[CrApplication class]]);
+ if (![static_cast<CrApplication*>(NSApp) isHandlingSendEvent]) {
+ pool = MessagePumpCFRunLoopBase::CreateAutoreleasePool();
+ }
+ return pool;
+}
+
+// static
+MessagePump* MessagePumpMac::Create() {
+ if ([NSThread isMainThread]) {
+ return new MessagePumpNSApplication;
+ }
+
+ return new MessagePumpNSRunLoop;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_qt.cc b/ipc/chromium/src/base/message_pump_qt.cc
new file mode 100644
index 0000000000..d96e2c5e62
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_qt.cc
@@ -0,0 +1,177 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#include <qabstracteventdispatcher.h>
+#include <qevent.h>
+#include <QCoreApplication>
+#include <QThread>
+#include <qtimer.h>
+
+#include "base/message_pump_qt.h"
+
+#include <fcntl.h>
+#include <limits>
+#include <math.h>
+
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/platform_thread.h"
+
+namespace {
+// Cached QEvent user type, registered for our event system
+static int sPokeEvent;
+} // namespace
+
+namespace base {
+
+MessagePumpForUI::MessagePumpForUI() : state_(NULL), qt_pump(*this) {}
+
+MessagePumpForUI::~MessagePumpForUI() {}
+
+MessagePumpQt::MessagePumpQt(MessagePumpForUI& aPump)
+ : pump(aPump), mTimer(new QTimer(this)) {
+ // Register our custom event type, to use in qApp event loop
+ sPokeEvent = QEvent::registerEventType();
+ connect(mTimer, SIGNAL(timeout()), this, SLOT(dispatchDelayed()));
+ mTimer->setSingleShot(true);
+}
+
+MessagePumpQt::~MessagePumpQt() {
+ mTimer->stop();
+ delete mTimer;
+}
+
+bool MessagePumpQt::event(QEvent* e) {
+ if (e->type() == sPokeEvent) {
+ pump.HandleDispatch();
+ return true;
+ }
+ return false;
+}
+
+void MessagePumpQt::scheduleDelayedIfNeeded(
+ const TimeTicks& delayed_work_time) {
+ if (delayed_work_time.is_null()) {
+ return;
+ }
+
+ if (mTimer->isActive()) {
+ mTimer->stop();
+ }
+
+ TimeDelta later = delayed_work_time - TimeTicks::Now();
+ // later.InMilliseconds() returns an int64_t, QTimer only accepts int's for
+ // start(), std::min only works on exact same types.
+ int laterMsecs = later.InMilliseconds() > std::numeric_limits<int>::max()
+ ? std::numeric_limits<int>::max()
+ : later.InMilliseconds();
+ mTimer->start(laterMsecs > 0 ? laterMsecs : 0);
+}
+
+void MessagePumpQt::dispatchDelayed() { pump.HandleDispatch(); }
+
+void MessagePumpForUI::Run(Delegate* delegate) {
+ RunState state;
+ state.delegate = delegate;
+ state.should_quit = false;
+ state.run_depth = state_ ? state_->run_depth + 1 : 1;
+ // We really only do a single task for each iteration of the loop. If we
+ // have done something, assume there is likely something more to do. This
+ // will mean that we don't block on the message pump until there was nothing
+ // more to do. We also set this to true to make sure not to block on the
+ // first iteration of the loop, so RunAllPending() works correctly.
+ bool more_work_is_plausible = true;
+
+ RunState* previous_state = state_;
+ state_ = &state;
+
+ for (;;) {
+ QEventLoop::ProcessEventsFlags block = QEventLoop::AllEvents;
+ if (!more_work_is_plausible) {
+ block |= QEventLoop::WaitForMoreEvents;
+ }
+
+ QAbstractEventDispatcher* dispatcher =
+ QAbstractEventDispatcher::instance(QThread::currentThread());
+ // An assertion seems too much here, as during startup,
+ // the dispatcher might not be ready yet.
+ if (!dispatcher) {
+ return;
+ }
+
+ // processEvent's returns true if an event has been processed.
+ more_work_is_plausible = dispatcher->processEvents(block);
+
+ if (state_->should_quit) {
+ break;
+ }
+
+ more_work_is_plausible |= state_->delegate->DoWork();
+ if (state_->should_quit) {
+ break;
+ }
+
+ more_work_is_plausible |=
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ if (state_->should_quit) {
+ break;
+ }
+
+ qt_pump.scheduleDelayedIfNeeded(delayed_work_time_);
+
+ if (more_work_is_plausible) {
+ continue;
+ }
+
+ more_work_is_plausible = state_->delegate->DoIdleWork();
+ if (state_->should_quit) {
+ break;
+ }
+ }
+
+ state_ = previous_state;
+}
+
+void MessagePumpForUI::HandleDispatch() {
+ if (state_->should_quit) {
+ return;
+ }
+
+ if (state_->delegate->DoWork()) {
+ // there might be more, see more_work_is_plausible
+ // variable above, that's why we ScheduleWork() to keep going.
+ ScheduleWork();
+ }
+
+ if (state_->should_quit) {
+ return;
+ }
+
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ qt_pump.scheduleDelayedIfNeeded(delayed_work_time_);
+}
+
+void MessagePumpForUI::Quit() {
+ if (state_) {
+ state_->should_quit = true;
+ } else {
+ NOTREACHED() << "Quit called outside Run!";
+ }
+}
+
+void MessagePumpForUI::ScheduleWork() {
+ QCoreApplication::postEvent(&qt_pump, new QEvent((QEvent::Type)sPokeEvent));
+}
+
+void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
+ // On GLib implementation, a work source is defined which explicitly checks
+ // the time that has passed. Here, on Qt we can use a QTimer that enqueues our
+ // event signal in an event queue.
+ delayed_work_time_ = delayed_work_time;
+ qt_pump.scheduleDelayedIfNeeded(delayed_work_time_);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_qt.h b/ipc/chromium/src/base/message_pump_qt.h
new file mode 100644
index 0000000000..476c9757ac
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_qt.h
@@ -0,0 +1,84 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2010 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.
+
+#ifndef BASE_MESSAGE_PUMP_QT_H_
+#define BASE_MESSAGE_PUMP_QT_H_
+
+#include <qobject.h>
+
+#include "base/message_pump.h"
+#include "base/time.h"
+
+class QTimer;
+
+namespace base {
+
+class MessagePumpForUI;
+
+class MessagePumpQt : public QObject {
+ Q_OBJECT
+
+ public:
+ MessagePumpQt(MessagePumpForUI& pump);
+ ~MessagePumpQt();
+
+ virtual bool event(QEvent* e);
+ void scheduleDelayedIfNeeded(const TimeTicks& delayed_work_time);
+
+ public Q_SLOTS:
+ void dispatchDelayed();
+
+ private:
+ base::MessagePumpForUI& pump;
+ QTimer* mTimer;
+};
+
+// This class implements a MessagePump needed for TYPE_UI MessageLoops on
+// XP_LINUX platforms using QApplication event loop
+class MessagePumpForUI : public MessagePump {
+ public:
+ MessagePumpForUI();
+ ~MessagePumpForUI();
+
+ virtual void Run(Delegate* delegate);
+ virtual void Quit();
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
+
+ // Internal methods used for processing the pump callbacks. They are
+ // public for simplicity but should not be used directly.
+ // HandleDispatch is called after the poll has completed.
+ void HandleDispatch();
+
+ private:
+ // We may make recursive calls to Run, so we save state that needs to be
+ // separate between them in this structure type.
+ struct RunState {
+ Delegate* delegate;
+
+ // Used to flag that the current Run() invocation should return ASAP.
+ bool should_quit;
+
+ // Used to count how many Run() invocations are on the stack.
+ int run_depth;
+ };
+
+ RunState* state_;
+
+ // This is the time when we need to do delayed work.
+ TimeTicks delayed_work_time_;
+
+ // MessagePump implementation for Qt based on the GLib implement.
+ // On Qt we use a QObject base class and the
+ // default qApp in order to process events through QEventLoop.
+ MessagePumpQt qt_pump;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpForUI);
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_QT_H_
diff --git a/ipc/chromium/src/base/message_pump_win.cc b/ipc/chromium/src/base/message_pump_win.cc
new file mode 100644
index 0000000000..f0caa1db6c
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_win.cc
@@ -0,0 +1,553 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#include "base/message_pump_win.h"
+
+#include <math.h>
+
+#include "base/message_loop.h"
+#include "base/histogram.h"
+#include "base/win_util.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/ProfilerLabels.h"
+#include "mozilla/ProfilerThreadSleep.h"
+#include "WinUtils.h"
+
+using base::Time;
+
+namespace base {
+
+static const wchar_t kWndClass[] = L"Chrome_MessagePumpWindow";
+
+// Message sent to get an additional time slice for pumping (processing) another
+// task (a series of such messages creates a continuous task pump).
+static const int kMsgHaveWork = WM_USER + 1;
+
+//-----------------------------------------------------------------------------
+// MessagePumpWin public:
+
+void MessagePumpWin::AddObserver(Observer* observer) {
+ observers_.AddObserver(observer);
+}
+
+void MessagePumpWin::RemoveObserver(Observer* observer) {
+ observers_.RemoveObserver(observer);
+}
+
+void MessagePumpWin::WillProcessMessage(const MSG& msg) {
+ FOR_EACH_OBSERVER(Observer, observers_, WillProcessMessage(msg));
+}
+
+void MessagePumpWin::DidProcessMessage(const MSG& msg) {
+ FOR_EACH_OBSERVER(Observer, observers_, DidProcessMessage(msg));
+}
+
+void MessagePumpWin::RunWithDispatcher(Delegate* delegate,
+ Dispatcher* dispatcher) {
+ RunState s;
+ s.delegate = delegate;
+ s.dispatcher = dispatcher;
+ s.should_quit = false;
+ s.run_depth = state_ ? state_->run_depth + 1 : 1;
+
+ RunState* previous_state = state_;
+ state_ = &s;
+
+ DoRunLoop();
+
+ state_ = previous_state;
+}
+
+void MessagePumpWin::Quit() {
+ DCHECK(state_);
+ state_->should_quit = true;
+}
+
+//-----------------------------------------------------------------------------
+// MessagePumpWin protected:
+
+int MessagePumpWin::GetCurrentDelay() const {
+ if (delayed_work_time_.is_null()) return -1;
+
+ // Be careful here. TimeDelta has a precision of microseconds, but we want a
+ // value in milliseconds. If there are 5.5ms left, should the delay be 5 or
+ // 6? It should be 6 to avoid executing delayed work too early.
+ double timeout =
+ ceil((delayed_work_time_ - TimeTicks::Now()).InMillisecondsF());
+
+ // If this value is negative, then we need to run delayed work soon.
+ int delay = static_cast<int>(timeout);
+ if (delay < 0) delay = 0;
+
+ return delay;
+}
+
+//-----------------------------------------------------------------------------
+// MessagePumpForUI public:
+
+MessagePumpForUI::MessagePumpForUI() { InitMessageWnd(); }
+
+MessagePumpForUI::~MessagePumpForUI() {
+ DestroyWindow(message_hwnd_);
+ UnregisterClass(kWndClass, GetModuleHandle(NULL));
+}
+
+void MessagePumpForUI::ScheduleWork() {
+ if (InterlockedExchange(&have_work_, 1))
+ return; // Someone else continued the pumping.
+
+ // Make sure the MessagePump does some work for us.
+ PostMessage(message_hwnd_, kMsgHaveWork, reinterpret_cast<WPARAM>(this), 0);
+
+ // In order to wake up any cross-process COM calls which may currently be
+ // pending on the main thread, we also have to post a UI message.
+ PostMessage(message_hwnd_, WM_NULL, 0, 0);
+}
+
+void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
+ //
+ // We would *like* to provide high resolution timers. Windows timers using
+ // SetTimer() have a 10ms granularity. We have to use WM_TIMER as a wakeup
+ // mechanism because the application can enter modal windows loops where it
+ // is not running our MessageLoop; the only way to have our timers fire in
+ // these cases is to post messages there.
+ //
+ // To provide sub-10ms timers, we process timers directly from our run loop.
+ // For the common case, timers will be processed there as the run loop does
+ // its normal work. However, we *also* set the system timer so that WM_TIMER
+ // events fire. This mops up the case of timers not being able to work in
+ // modal message loops. It is possible for the SetTimer to pop and have no
+ // pending timers, because they could have already been processed by the
+ // run loop itself.
+ //
+ // We use a single SetTimer corresponding to the timer that will expire
+ // soonest. As new timers are created and destroyed, we update SetTimer.
+ // Getting a spurrious SetTimer event firing is benign, as we'll just be
+ // processing an empty timer queue.
+ //
+ delayed_work_time_ = delayed_work_time;
+
+ int delay_msec = GetCurrentDelay();
+ DCHECK(delay_msec >= 0);
+ if (delay_msec < USER_TIMER_MINIMUM) delay_msec = USER_TIMER_MINIMUM;
+
+ // Create a WM_TIMER event that will wake us up to check for any pending
+ // timers (in case we are running within a nested, external sub-pump).
+ SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this), delay_msec, NULL);
+}
+
+void MessagePumpForUI::PumpOutPendingPaintMessages() {
+ // If we are being called outside of the context of Run, then don't try to do
+ // any work.
+ if (!state_) return;
+
+ // Create a mini-message-pump to force immediate processing of only Windows
+ // WM_PAINT messages. Don't provide an infinite loop, but do enough peeking
+ // to get the job done. Actual common max is 4 peeks, but we'll be a little
+ // safe here.
+ const int kMaxPeekCount = 20;
+ int peek_count;
+ for (peek_count = 0; peek_count < kMaxPeekCount; ++peek_count) {
+ MSG msg;
+ if (!PeekMessage(&msg, NULL, 0, 0, PM_REMOVE | PM_QS_PAINT)) break;
+ ProcessMessageHelper(msg);
+ if (state_->should_quit) break;
+ }
+}
+
+//-----------------------------------------------------------------------------
+// MessagePumpForUI private:
+
+// static
+LRESULT CALLBACK MessagePumpForUI::WndProcThunk(HWND hwnd, UINT message,
+ WPARAM wparam, LPARAM lparam) {
+ switch (message) {
+ case kMsgHaveWork:
+ reinterpret_cast<MessagePumpForUI*>(wparam)->HandleWorkMessage();
+ break;
+ case WM_TIMER:
+ reinterpret_cast<MessagePumpForUI*>(wparam)->HandleTimerMessage();
+ break;
+ }
+ return DefWindowProc(hwnd, message, wparam, lparam);
+}
+
+void MessagePumpForUI::DoRunLoop() {
+ // IF this was just a simple PeekMessage() loop (servicing all possible work
+ // queues), then Windows would try to achieve the following order according
+ // to MSDN documentation about PeekMessage with no filter):
+ // * Sent messages
+ // * Posted messages
+ // * Sent messages (again)
+ // * WM_PAINT messages
+ // * WM_TIMER messages
+ //
+ // Summary: none of the above classes is starved, and sent messages has twice
+ // the chance of being processed (i.e., reduced service time).
+
+ for (;;) {
+ // If we do any work, we may create more messages etc., and more work may
+ // possibly be waiting in another task group. When we (for example)
+ // ProcessNextWindowsMessage(), there is a good chance there are still more
+ // messages waiting. On the other hand, when any of these methods return
+ // having done no work, then it is pretty unlikely that calling them again
+ // quickly will find any work to do. Finally, if they all say they had no
+ // work, then it is a good time to consider sleeping (waiting) for more
+ // work.
+
+ bool more_work_is_plausible = ProcessNextWindowsMessage();
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |= state_->delegate->DoWork();
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |=
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ // If we did not process any delayed work, then we can assume that our
+ // existing WM_TIMER if any will fire when delayed work should run. We
+ // don't want to disturb that timer if it is already in flight. However,
+ // if we did do all remaining delayed work, then lets kill the WM_TIMER.
+ if (more_work_is_plausible && delayed_work_time_.is_null())
+ KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
+ if (state_->should_quit) break;
+
+ if (more_work_is_plausible) continue;
+
+ more_work_is_plausible = state_->delegate->DoIdleWork();
+ if (state_->should_quit) break;
+
+ if (more_work_is_plausible) continue;
+
+ WaitForWork(); // Wait (sleep) until we have work to do again.
+ }
+}
+
+void MessagePumpForUI::InitMessageWnd() {
+ HINSTANCE hinst = GetModuleHandle(NULL);
+
+ WNDCLASSEX wc = {0};
+ wc.cbSize = sizeof(wc);
+ wc.lpfnWndProc = WndProcThunk;
+ wc.hInstance = hinst;
+ wc.lpszClassName = kWndClass;
+ RegisterClassEx(&wc);
+
+ message_hwnd_ =
+ CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0);
+ DCHECK(message_hwnd_);
+}
+
+void MessagePumpForUI::WaitForWork() {
+ AUTO_PROFILER_LABEL("MessagePumpForUI::WaitForWork", IDLE);
+
+ // Wait until a message is available, up to the time needed by the timer
+ // manager to fire the next set of timers.
+ int delay = GetCurrentDelay();
+ if (delay < 0) // Negative value means no timers waiting.
+ delay = INFINITE;
+
+ mozilla::widget::WinUtils::WaitForMessage(delay);
+}
+
+void MessagePumpForUI::HandleWorkMessage() {
+ // If we are being called outside of the context of Run, then don't try to do
+ // any work. This could correspond to a MessageBox call or something of that
+ // sort.
+ if (!state_) {
+ // Since we handled a kMsgHaveWork message, we must still update this flag.
+ InterlockedExchange(&have_work_, 0);
+ return;
+ }
+
+ // Let whatever would have run had we not been putting messages in the queue
+ // run now. This is an attempt to make our dummy message not starve other
+ // messages that may be in the Windows message queue.
+ ProcessPumpReplacementMessage();
+
+ // Now give the delegate a chance to do some work. He'll let us know if he
+ // needs to do more work.
+ if (state_->delegate->DoWork()) ScheduleWork();
+}
+
+void MessagePumpForUI::HandleTimerMessage() {
+ KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
+
+ // If we are being called outside of the context of Run, then don't do
+ // anything. This could correspond to a MessageBox call or something of
+ // that sort.
+ if (!state_) return;
+
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ if (!delayed_work_time_.is_null()) {
+ // A bit gratuitous to set delayed_work_time_ again, but oh well.
+ ScheduleDelayedWork(delayed_work_time_);
+ }
+}
+
+bool MessagePumpForUI::ProcessNextWindowsMessage() {
+ // If there are sent messages in the queue then PeekMessage internally
+ // dispatches the message and returns false. We return true in this
+ // case to ensure that the message loop peeks again instead of calling
+ // MsgWaitForMultipleObjectsEx again.
+ bool sent_messages_in_queue = false;
+ DWORD queue_status = ::GetQueueStatus(QS_SENDMESSAGE);
+ if (HIWORD(queue_status) & QS_SENDMESSAGE) sent_messages_in_queue = true;
+
+ MSG msg;
+ if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
+ return ProcessMessageHelper(msg);
+
+ return sent_messages_in_queue;
+}
+
+bool MessagePumpForUI::ProcessMessageHelper(const MSG& msg) {
+ if (WM_QUIT == msg.message) {
+ // WM_QUIT is the standard way to exit a ::GetMessage() loop. Our
+ // MessageLoop has its own quit mechanism, so WM_QUIT is unexpected and
+ // should be ignored.
+ return true;
+ }
+
+ // While running our main message pump, we discard kMsgHaveWork messages.
+ if (msg.message == kMsgHaveWork && msg.hwnd == message_hwnd_)
+ return ProcessPumpReplacementMessage();
+
+ WillProcessMessage(msg);
+
+ if (state_->dispatcher) {
+ if (!state_->dispatcher->Dispatch(msg)) state_->should_quit = true;
+ } else {
+ ::TranslateMessage(&msg);
+ ::DispatchMessage(&msg);
+ }
+
+ DidProcessMessage(msg);
+ return true;
+}
+
+bool MessagePumpForUI::ProcessPumpReplacementMessage() {
+ // When we encounter a kMsgHaveWork message, this method is called to peek
+ // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
+ // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
+ // a continuous stream of such messages are posted. This method carefully
+ // peeks a message while there is no chance for a kMsgHaveWork to be pending,
+ // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
+ // possibly be posted), and finally dispatches that peeked replacement. Note
+ // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
+
+ MSG msg;
+ bool have_message = false;
+ if (MessageLoop::current()->os_modal_loop()) {
+ // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
+ have_message = ::PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
+ ::PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
+ } else {
+ have_message = (0 != ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
+
+ if (have_message && msg.message == WM_NULL)
+ have_message = (0 != ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
+ }
+
+ DCHECK(!have_message || kMsgHaveWork != msg.message ||
+ msg.hwnd != message_hwnd_);
+
+ // Since we discarded a kMsgHaveWork message, we must update the flag.
+ int old_have_work = InterlockedExchange(&have_work_, 0);
+ DCHECK(old_have_work);
+
+ // We don't need a special time slice if we didn't have_message to process.
+ if (!have_message) return false;
+
+ if (WM_QUIT == msg.message) {
+ // If we're in a nested ::GetMessage() loop then we must let that loop see
+ // the WM_QUIT in order for it to exit. If we're in DoRunLoop then the re-
+ // posted WM_QUIT will be either ignored, or handled, by
+ // ProcessMessageHelper() called directly from ProcessNextWindowsMessage().
+ ::PostQuitMessage(static_cast<int>(msg.wParam));
+ // Note: we *must not* ScheduleWork() here as WM_QUIT is a low-priority
+ // message on Windows (it is only returned by ::PeekMessage() when idle) :
+ // https://blogs.msdn.microsoft.com/oldnewthing/20051104-33/?p=33453. As
+ // such posting a kMsgHaveWork message via ScheduleWork() would cause an
+ // infinite loop (kMsgHaveWork message handled first means we end up here
+ // again and repost WM_QUIT+ScheduleWork() again, etc.). Not leaving a
+ // kMsgHaveWork message behind however is also problematic as unwinding
+ // multiple layers of nested ::GetMessage() loops can result in starving
+ // application tasks. TODO(https://crbug.com/890016) : Fix this.
+
+ // The return value is mostly irrelevant but return true like we would after
+ // processing a QuitClosure() task.
+ return true;
+ }
+
+ // Guarantee we'll get another time slice in the case where we go into native
+ // windows code. This ScheduleWork() may hurt performance a tiny bit when
+ // tasks appear very infrequently, but when the event queue is busy, the
+ // kMsgHaveWork events get (percentage wise) rarer and rarer.
+ ScheduleWork();
+ return ProcessMessageHelper(msg);
+}
+
+//-----------------------------------------------------------------------------
+// MessagePumpForIO public:
+
+MessagePumpForIO::MessagePumpForIO() {
+ port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1));
+ DCHECK(port_.IsValid());
+}
+
+void MessagePumpForIO::ScheduleWork() {
+ if (InterlockedExchange(&have_work_, 1))
+ return; // Someone else continued the pumping.
+
+ // Make sure the MessagePump does some work for us.
+ BOOL ret =
+ PostQueuedCompletionStatus(port_, 0, reinterpret_cast<ULONG_PTR>(this),
+ reinterpret_cast<OVERLAPPED*>(this));
+ DCHECK(ret);
+}
+
+void MessagePumpForIO::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
+ // We know that we can't be blocked right now since this method can only be
+ // called on the same thread as Run, so we only need to update our record of
+ // how long to sleep when we do sleep.
+ delayed_work_time_ = delayed_work_time;
+}
+
+void MessagePumpForIO::RegisterIOHandler(HANDLE file_handle,
+ IOHandler* handler) {
+ ULONG_PTR key = reinterpret_cast<ULONG_PTR>(handler);
+ HANDLE port = CreateIoCompletionPort(file_handle, port_, key, 1);
+ DCHECK(port == port_.Get());
+}
+
+//-----------------------------------------------------------------------------
+// MessagePumpForIO private:
+
+void MessagePumpForIO::DoRunLoop() {
+ for (;;) {
+ // If we do any work, we may create more messages etc., and more work may
+ // possibly be waiting in another task group. When we (for example)
+ // WaitForIOCompletion(), there is a good chance there are still more
+ // messages waiting. On the other hand, when any of these methods return
+ // having done no work, then it is pretty unlikely that calling them
+ // again quickly will find any work to do. Finally, if they all say they
+ // had no work, then it is a good time to consider sleeping (waiting) for
+ // more work.
+
+ bool more_work_is_plausible = state_->delegate->DoWork();
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |= WaitForIOCompletion(0, NULL);
+ if (state_->should_quit) break;
+
+ more_work_is_plausible |=
+ state_->delegate->DoDelayedWork(&delayed_work_time_);
+ if (state_->should_quit) break;
+
+ if (more_work_is_plausible) continue;
+
+ more_work_is_plausible = state_->delegate->DoIdleWork();
+ if (state_->should_quit) break;
+
+ if (more_work_is_plausible) continue;
+
+ WaitForWork(); // Wait (sleep) until we have work to do again.
+ }
+}
+
+// Wait until IO completes, up to the time needed by the timer manager to fire
+// the next set of timers.
+void MessagePumpForIO::WaitForWork() {
+ // We do not support nested IO message loops. This is to avoid messy
+ // recursion problems.
+ DCHECK(state_->run_depth == 1) << "Cannot nest an IO message loop!";
+
+ int timeout = GetCurrentDelay();
+ if (timeout < 0) // Negative value means no timers waiting.
+ timeout = INFINITE;
+
+ WaitForIOCompletion(timeout, NULL);
+}
+
+bool MessagePumpForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
+ IOItem item;
+ if (completed_io_.empty() || !MatchCompletedIOItem(filter, &item)) {
+ // We have to ask the system for another IO completion.
+ if (!GetIOItem(timeout, &item)) return false;
+
+ if (ProcessInternalIOItem(item)) return true;
+ }
+
+ if (item.context->handler) {
+ if (filter && item.handler != filter) {
+ // Save this item for later
+ completed_io_.push_back(item);
+ } else {
+ DCHECK(item.context->handler == item.handler);
+ item.handler->OnIOCompleted(item.context, item.bytes_transfered,
+ item.error);
+ }
+ } else {
+ // The handler must be gone by now, just cleanup the mess.
+ delete item.context;
+ }
+ return true;
+}
+
+// Asks the OS for another IO completion result.
+bool MessagePumpForIO::GetIOItem(DWORD timeout, IOItem* item) {
+ memset(item, 0, sizeof(*item));
+ ULONG_PTR key = 0;
+ OVERLAPPED* overlapped = NULL;
+ BOOL success;
+ {
+ AUTO_PROFILER_LABEL("MessagePumpForIO::GetIOItem::Wait", IDLE);
+#ifdef MOZ_GECKO_PROFILER
+ mozilla::Maybe<mozilla::AutoProfilerThreadSleep> profilerThreadSleep;
+ if (timeout != 0) {
+ profilerThreadSleep.emplace();
+ }
+#endif
+ success = GetQueuedCompletionStatus(port_.Get(), &item->bytes_transfered,
+ &key, &overlapped, timeout);
+ }
+ if (!success) {
+ if (!overlapped) return false; // Nothing in the queue.
+ item->error = GetLastError();
+ item->bytes_transfered = 0;
+ }
+
+ item->handler = reinterpret_cast<IOHandler*>(key);
+ item->context = reinterpret_cast<IOContext*>(overlapped);
+ return true;
+}
+
+bool MessagePumpForIO::ProcessInternalIOItem(const IOItem& item) {
+ if (this == reinterpret_cast<MessagePumpForIO*>(item.context) &&
+ this == reinterpret_cast<MessagePumpForIO*>(item.handler)) {
+ // This is our internal completion.
+ DCHECK(!item.bytes_transfered);
+ InterlockedExchange(&have_work_, 0);
+ return true;
+ }
+ return false;
+}
+
+// Returns a completion item that was previously received.
+bool MessagePumpForIO::MatchCompletedIOItem(IOHandler* filter, IOItem* item) {
+ DCHECK(!completed_io_.empty());
+ for (std::list<IOItem>::iterator it = completed_io_.begin();
+ it != completed_io_.end(); ++it) {
+ if (!filter || it->handler == filter) {
+ *item = *it;
+ completed_io_.erase(it);
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/message_pump_win.h b/ipc/chromium/src/base/message_pump_win.h
new file mode 100644
index 0000000000..585a4d3ff5
--- /dev/null
+++ b/ipc/chromium/src/base/message_pump_win.h
@@ -0,0 +1,347 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MESSAGE_PUMP_WIN_H_
+#define BASE_MESSAGE_PUMP_WIN_H_
+
+#include <windows.h>
+
+#include <list>
+
+#include "base/message_pump.h"
+#include "base/observer_list.h"
+#include "base/scoped_handle.h"
+#include "base/time.h"
+
+namespace base {
+
+// MessagePumpWin serves as the base for specialized versions of the MessagePump
+// for Windows. It provides basic functionality like handling of observers and
+// controlling the lifetime of the message pump.
+class MessagePumpWin : public MessagePump {
+ public:
+ // An Observer is an object that receives global notifications from the
+ // MessageLoop.
+ //
+ // NOTE: An Observer implementation should be extremely fast!
+ //
+ class Observer {
+ public:
+ virtual ~Observer() {}
+
+ // This method is called before processing a message.
+ // The message may be undefined in which case msg.message is 0
+ virtual void WillProcessMessage(const MSG& msg) = 0;
+
+ // This method is called when control returns from processing a UI message.
+ // The message may be undefined in which case msg.message is 0
+ virtual void DidProcessMessage(const MSG& msg) = 0;
+ };
+
+ // Dispatcher is used during a nested invocation of Run to dispatch events.
+ // If Run is invoked with a non-NULL Dispatcher, MessageLoop does not
+ // dispatch events (or invoke TranslateMessage), rather every message is
+ // passed to Dispatcher's Dispatch method for dispatch. It is up to the
+ // Dispatcher to dispatch, or not, the event.
+ //
+ // The nested loop is exited by either posting a quit, or returning false
+ // from Dispatch.
+ class Dispatcher {
+ public:
+ virtual ~Dispatcher() {}
+ // Dispatches the event. If true is returned processing continues as
+ // normal. If false is returned, the nested loop exits immediately.
+ virtual bool Dispatch(const MSG& msg) = 0;
+ };
+
+ MessagePumpWin() : have_work_(0), state_(NULL) {}
+ virtual ~MessagePumpWin() {}
+
+ // Add an Observer, which will start receiving notifications immediately.
+ void AddObserver(Observer* observer);
+
+ // Remove an Observer. It is safe to call this method while an Observer is
+ // receiving a notification callback.
+ void RemoveObserver(Observer* observer);
+
+ // Give a chance to code processing additional messages to notify the
+ // message loop observers that another message has been processed.
+ void WillProcessMessage(const MSG& msg);
+ void DidProcessMessage(const MSG& msg);
+
+ // Like MessagePump::Run, but MSG objects are routed through dispatcher.
+ void RunWithDispatcher(Delegate* delegate, Dispatcher* dispatcher);
+
+ // MessagePump methods:
+ virtual void Run(Delegate* delegate) { RunWithDispatcher(delegate, NULL); }
+ virtual void Quit();
+
+ protected:
+ struct RunState {
+ Delegate* delegate;
+ Dispatcher* dispatcher;
+
+ // Used to flag that the current Run() invocation should return ASAP.
+ bool should_quit;
+
+ // Used to count how many Run() invocations are on the stack.
+ int run_depth;
+ };
+
+ virtual void DoRunLoop() = 0;
+ int GetCurrentDelay() const;
+
+ ObserverList<Observer> observers_;
+
+ // The time at which delayed work should run.
+ TimeTicks delayed_work_time_;
+
+ // A boolean value used to indicate if there is a kMsgDoWork message pending
+ // in the Windows Message queue. There is at most one such message, and it
+ // can drive execution of tasks when a native message pump is running.
+ LONG have_work_;
+
+ // State for the current invocation of Run.
+ RunState* state_;
+};
+
+//-----------------------------------------------------------------------------
+// MessagePumpForUI extends MessagePumpWin with methods that are particular to a
+// MessageLoop instantiated with TYPE_UI.
+//
+// MessagePumpForUI implements a "traditional" Windows message pump. It contains
+// a nearly infinite loop that peeks out messages, and then dispatches them.
+// Intermixed with those peeks are callouts to DoWork for pending tasks, and
+// DoDelayedWork for pending timers. When there are no events to be serviced,
+// this pump goes into a wait state. In most cases, this message pump handles
+// all processing.
+//
+// However, when a task, or windows event, invokes on the stack a native dialog
+// box or such, that window typically provides a bare bones (native?) message
+// pump. That bare-bones message pump generally supports little more than a
+// peek of the Windows message queue, followed by a dispatch of the peeked
+// message. MessageLoop extends that bare-bones message pump to also service
+// Tasks, at the cost of some complexity.
+//
+// The basic structure of the extension (refered to as a sub-pump) is that a
+// special message, kMsgHaveWork, is repeatedly injected into the Windows
+// Message queue. Each time the kMsgHaveWork message is peeked, checks are
+// made for an extended set of events, including the availability of Tasks to
+// run.
+//
+// After running a task, the special message kMsgHaveWork is again posted to
+// the Windows Message queue, ensuring a future time slice for processing a
+// future event. To prevent flooding the Windows Message queue, care is taken
+// to be sure that at most one kMsgHaveWork message is EVER pending in the
+// Window's Message queue.
+//
+// There are a few additional complexities in this system where, when there are
+// no Tasks to run, this otherwise infinite stream of messages which drives the
+// sub-pump is halted. The pump is automatically re-started when Tasks are
+// queued.
+//
+// A second complexity is that the presence of this stream of posted tasks may
+// prevent a bare-bones message pump from ever peeking a WM_PAINT or WM_TIMER.
+// Such paint and timer events always give priority to a posted message, such as
+// kMsgHaveWork messages. As a result, care is taken to do some peeking in
+// between the posting of each kMsgHaveWork message (i.e., after kMsgHaveWork
+// is peeked, and before a replacement kMsgHaveWork is posted).
+//
+// NOTE: Although it may seem odd that messages are used to start and stop this
+// flow (as opposed to signaling objects, etc.), it should be understood that
+// the native message pump will *only* respond to messages. As a result, it is
+// an excellent choice. It is also helpful that the starter messages that are
+// placed in the queue when new task arrive also awakens DoRunLoop.
+//
+class MessagePumpForUI : public MessagePumpWin {
+ public:
+ MessagePumpForUI();
+ virtual ~MessagePumpForUI();
+
+ // MessagePump methods:
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
+
+ // Applications can call this to encourage us to process all pending WM_PAINT
+ // messages. This method will process all paint messages the Windows Message
+ // queue can provide, up to some fixed number (to avoid any infinite loops).
+ void PumpOutPendingPaintMessages();
+
+ protected:
+ virtual void DoRunLoop();
+
+ bool ProcessNextWindowsMessage();
+ void InitMessageWnd();
+ void WaitForWork();
+ void HandleWorkMessage();
+ void HandleTimerMessage();
+ bool ProcessMessageHelper(const MSG& msg);
+ bool ProcessPumpReplacementMessage();
+
+ // A hidden message-only window.
+ HWND message_hwnd_;
+
+ private:
+ static LRESULT CALLBACK WndProcThunk(HWND hwnd, UINT message, WPARAM wparam,
+ LPARAM lparam);
+};
+
+//-----------------------------------------------------------------------------
+// MessagePumpForIO extends MessagePumpWin with methods that are particular to a
+// MessageLoop instantiated with TYPE_IO. This version of MessagePump does not
+// deal with Windows mesagges, and instead has a Run loop based on Completion
+// Ports so it is better suited for IO operations.
+//
+class MessagePumpForIO : public MessagePumpWin {
+ public:
+ struct IOContext;
+
+ // Clients interested in receiving OS notifications when asynchronous IO
+ // operations complete should implement this interface and register themselves
+ // with the message pump.
+ //
+ // Typical use #1:
+ // // Use only when there are no user's buffers involved on the actual IO,
+ // // so that all the cleanup can be done by the message pump.
+ // class MyFile : public IOHandler {
+ // MyFile() {
+ // ...
+ // context_ = new IOContext;
+ // context_->handler = this;
+ // message_pump->RegisterIOHandler(file_, this);
+ // }
+ // ~MyFile() {
+ // if (pending_) {
+ // // By setting the handler to NULL, we're asking for this context
+ // // to be deleted when received, without calling back to us.
+ // context_->handler = NULL;
+ // } else {
+ // delete context_;
+ // }
+ // }
+ // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
+ // DWORD error) {
+ // pending_ = false;
+ // }
+ // void DoSomeIo() {
+ // ...
+ // // The only buffer required for this operation is the overlapped
+ // // structure.
+ // ConnectNamedPipe(file_, &context_->overlapped);
+ // pending_ = true;
+ // }
+ // bool pending_;
+ // IOContext* context_;
+ // HANDLE file_;
+ // };
+ //
+ // Typical use #2:
+ // class MyFile : public IOHandler {
+ // MyFile() {
+ // ...
+ // message_pump->RegisterIOHandler(file_, this);
+ // }
+ // // Plus some code to make sure that this destructor is not called
+ // // while there are pending IO operations.
+ // ~MyFile() {
+ // }
+ // virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
+ // DWORD error) {
+ // ...
+ // delete context;
+ // }
+ // void DoSomeIo() {
+ // ...
+ // IOContext* context = new IOContext;
+ // // This is not used for anything. It just prevents the context from
+ // // being considered "abandoned".
+ // context->handler = this;
+ // ReadFile(file_, buffer, num_bytes, &read, &context->overlapped);
+ // }
+ // HANDLE file_;
+ // };
+ //
+ // Typical use #3:
+ // Same as the previous example, except that in order to deal with the
+ // requirement stated for the destructor, the class calls WaitForIOCompletion
+ // from the destructor to block until all IO finishes.
+ // ~MyFile() {
+ // while(pending_)
+ // message_pump->WaitForIOCompletion(INFINITE, this);
+ // }
+ //
+ class IOHandler {
+ public:
+ virtual ~IOHandler() {}
+ // This will be called once the pending IO operation associated with
+ // |context| completes. |error| is the Win32 error code of the IO operation
+ // (ERROR_SUCCESS if there was no error). |bytes_transfered| will be zero
+ // on error.
+ virtual void OnIOCompleted(IOContext* context, DWORD bytes_transfered,
+ DWORD error) = 0;
+ };
+
+ // The extended context that should be used as the base structure on every
+ // overlapped IO operation. |handler| must be set to the registered IOHandler
+ // for the given file when the operation is started, and it can be set to NULL
+ // before the operation completes to indicate that the handler should not be
+ // called anymore, and instead, the IOContext should be deleted when the OS
+ // notifies the completion of this operation. Please remember that any buffers
+ // involved with an IO operation should be around until the callback is
+ // received, so this technique can only be used for IO that do not involve
+ // additional buffers (other than the overlapped structure itself).
+ struct IOContext {
+ OVERLAPPED overlapped;
+ IOHandler* handler;
+ };
+
+ MessagePumpForIO();
+ virtual ~MessagePumpForIO() {}
+
+ // MessagePump methods:
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const TimeTicks& delayed_work_time);
+
+ // Register the handler to be used when asynchronous IO for the given file
+ // completes. The registration persists as long as |file_handle| is valid, so
+ // |handler| must be valid as long as there is pending IO for the given file.
+ void RegisterIOHandler(HANDLE file_handle, IOHandler* handler);
+
+ // Waits for the next IO completion that should be processed by |filter|, for
+ // up to |timeout| milliseconds. Return true if any IO operation completed,
+ // regardless of the involved handler, and false if the timeout expired. If
+ // the completion port received any message and the involved IO handler
+ // matches |filter|, the callback is called before returning from this code;
+ // if the handler is not the one that we are looking for, the callback will
+ // be postponed for another time, so reentrancy problems can be avoided.
+ // External use of this method should be reserved for the rare case when the
+ // caller is willing to allow pausing regular task dispatching on this thread.
+ bool WaitForIOCompletion(DWORD timeout, IOHandler* filter);
+
+ private:
+ struct IOItem {
+ IOHandler* handler;
+ IOContext* context;
+ DWORD bytes_transfered;
+ DWORD error;
+ };
+
+ virtual void DoRunLoop();
+ void WaitForWork();
+ bool MatchCompletedIOItem(IOHandler* filter, IOItem* item);
+ bool GetIOItem(DWORD timeout, IOItem* item);
+ bool ProcessInternalIOItem(const IOItem& item);
+
+ // The completion port associated with this thread.
+ ScopedHandle port_;
+ // This list will be empty almost always. It stores IO completions that have
+ // not been delivered yet because somebody was doing cleanup.
+ std::list<IOItem> completed_io_;
+};
+
+} // namespace base
+
+#endif // BASE_MESSAGE_PUMP_WIN_H_
diff --git a/ipc/chromium/src/base/object_watcher.cc b/ipc/chromium/src/base/object_watcher.cc
new file mode 100644
index 0000000000..b749829a0e
--- /dev/null
+++ b/ipc/chromium/src/base/object_watcher.cc
@@ -0,0 +1,135 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/object_watcher.h"
+
+#include "base/logging.h"
+
+namespace base {
+
+//-----------------------------------------------------------------------------
+
+class ObjectWatcher::Watch : public mozilla::Runnable {
+ public:
+ ObjectWatcher* watcher; // The associated ObjectWatcher instance
+ HANDLE object; // The object being watched
+ HANDLE wait_object; // Returned by RegisterWaitForSingleObject
+ MessageLoop* origin_loop; // Used to get back to the origin thread
+ Delegate* delegate; // Delegate to notify when signaled
+ bool did_signal; // DoneWaiting was called
+
+ Watch() : mozilla::Runnable("ObjectWatcher::Watch") {}
+
+ NS_IMETHOD Run() override {
+ // The watcher may have already been torn down, in which case we need to
+ // just get out of dodge.
+ if (!watcher) return NS_OK;
+
+ DCHECK(did_signal);
+ watcher->StopWatching();
+
+ delegate->OnObjectSignaled(object);
+
+ return NS_OK;
+ }
+};
+
+//-----------------------------------------------------------------------------
+
+ObjectWatcher::ObjectWatcher() : watch_(nullptr) {}
+
+ObjectWatcher::~ObjectWatcher() { StopWatching(); }
+
+bool ObjectWatcher::StartWatching(HANDLE object, Delegate* delegate) {
+ if (watch_) {
+ NOTREACHED() << "Already watching an object";
+ return false;
+ }
+
+ RefPtr<Watch> watch = new Watch;
+ watch->watcher = this;
+ watch->object = object;
+ watch->origin_loop = MessageLoop::current();
+ watch->delegate = delegate;
+ watch->did_signal = false;
+
+ // Since our job is to just notice when an object is signaled and report the
+ // result back to this thread, we can just run on a Windows wait thread.
+ DWORD wait_flags = WT_EXECUTEDEFAULT | WT_EXECUTEONLYONCE;
+
+ if (!RegisterWaitForSingleObject(&watch->wait_object, object, DoneWaiting,
+ watch.get(), INFINITE, wait_flags)) {
+ NOTREACHED() << "RegisterWaitForSingleObject failed: " << GetLastError();
+ return false;
+ }
+
+ watch_ = watch.forget();
+
+ // We need to know if the current message loop is going away so we can
+ // prevent the wait thread from trying to access a dead message loop.
+ MessageLoop::current()->AddDestructionObserver(this);
+ return true;
+}
+
+bool ObjectWatcher::StopWatching() {
+ if (!watch_) return false;
+
+ // Make sure ObjectWatcher is used in a single-threaded fashion.
+ DCHECK(watch_->origin_loop == MessageLoop::current());
+
+ // If DoneWaiting is in progress, we wait for it to finish. We know whether
+ // DoneWaiting happened or not by inspecting the did_signal flag.
+ if (!UnregisterWaitEx(watch_->wait_object, INVALID_HANDLE_VALUE)) {
+ NOTREACHED() << "UnregisterWaitEx failed: " << GetLastError();
+ return false;
+ }
+
+ // Make sure that we see any mutation to did_signal. This should be a no-op
+ // since we expect that UnregisterWaitEx resulted in a memory barrier, but
+ // just to be sure, we're going to be explicit.
+ MemoryBarrier();
+
+ // If the watch has been posted, then we need to make sure it knows not to do
+ // anything once it is run.
+ watch_->watcher = NULL;
+
+ watch_ = nullptr;
+
+ MessageLoop::current()->RemoveDestructionObserver(this);
+ return true;
+}
+
+HANDLE ObjectWatcher::GetWatchedObject() {
+ if (!watch_) return NULL;
+
+ return watch_->object;
+}
+
+// static
+void CALLBACK ObjectWatcher::DoneWaiting(void* param, BOOLEAN timed_out) {
+ DCHECK(!timed_out);
+
+ Watch* watch = static_cast<Watch*>(param);
+ RefPtr<Watch> addrefedWatch = watch;
+
+ // Record that we ran this function.
+ watch->did_signal = true;
+
+ // We rely on the locking in PostTask() to ensure that a memory barrier is
+ // provided, which in turn ensures our change to did_signal can be observed
+ // on the target thread.
+ if (watch->origin_loop->IsAcceptingTasks()) {
+ watch->origin_loop->PostTask(addrefedWatch.forget());
+ }
+}
+
+void ObjectWatcher::WillDestroyCurrentMessageLoop() {
+ // Need to shutdown the watch so that we don't try to access the MessageLoop
+ // after this point.
+ StopWatching();
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/object_watcher.h b/ipc/chromium/src/base/object_watcher.h
new file mode 100644
index 0000000000..1e1b27aa46
--- /dev/null
+++ b/ipc/chromium/src/base/object_watcher.h
@@ -0,0 +1,115 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_OBJECT_WATCHER_H_
+#define BASE_OBJECT_WATCHER_H_
+
+#include <windows.h>
+#ifdef GetClassName
+# undef GetClassName
+#endif
+
+#include "base/message_loop.h"
+
+namespace base {
+
+// A class that provides a means to asynchronously wait for a Windows object to
+// become signaled. It is an abstraction around RegisterWaitForSingleObject
+// that provides a notification callback, OnObjectSignaled, that runs back on
+// the origin thread (i.e., the thread that called StartWatching).
+//
+// This class acts like a smart pointer such that when it goes out-of-scope,
+// UnregisterWaitEx is automatically called, and any in-flight notification is
+// suppressed.
+//
+// Typical usage:
+//
+// ```
+// class MyClass : public base::ObjectWatcher::Delegate {
+// public:
+// void DoStuffWhenSignaled(HANDLE object) {
+// watcher_.StartWatching(object, this);
+// }
+// virtual void OnObjectSignaled(HANDLE object) {
+// // OK, time to do stuff!
+// }
+// private:
+// base::ObjectWatcher watcher_;
+// };
+// ```
+//
+// In the above example, MyClass wants to "do stuff" when object becomes
+// signaled. ObjectWatcher makes this task easy. When MyClass goes out of
+// scope, the watcher_ will be destroyed, and there is no need to worry about
+// OnObjectSignaled being called on a deleted MyClass pointer. Easy!
+//
+//////
+//
+// Mozilla/Gecko addendum:
+//
+// An undocumented (but runtime-asserted) requirement for the above is that
+// `MyClass` must be strictly thread-affine. In particular, `StartWatching()`
+// and `StopWatching()` -- including the implicit `StopWatching()` call in
+// `~ObjectWatcher()` -- must always be called on the same thread and from
+// within the same `MessageLoop`.
+//
+// (If this did not hold, `OnObjectSignaled()` might be called on one thread
+// while `MyClass` is in the middle of being destroyed on another.)
+//
+// This condition cannot be guaranteed for potentially-asynchronously-destroyed
+// classes, nor for their owned or shared subobjects, nor for anything which
+// might be sent to a non-thread-affine task queue.
+//
+class ObjectWatcher : public MessageLoop::DestructionObserver {
+ public:
+ class Delegate {
+ public:
+ virtual ~Delegate() {}
+ // Called from the MessageLoop when a signaled object is detected. To
+ // continue watching the object, AddWatch must be called again.
+ virtual void OnObjectSignaled(HANDLE object) = 0;
+ };
+
+ ObjectWatcher();
+ ~ObjectWatcher();
+
+ // When the object is signaled, the given delegate is notified on the thread
+ // where StartWatching is called. The ObjectWatcher is not responsible for
+ // deleting the delegate.
+ //
+ // Returns true if the watch was started. Otherwise, false is returned.
+ //
+ bool StartWatching(HANDLE object, Delegate* delegate);
+
+ // Stops watching. Does nothing if the watch has already completed. If the
+ // watch is still active, then it is canceled, and the associated delegate is
+ // not notified.
+ //
+ // Returns true if the watch was canceled. Otherwise, false is returned.
+ //
+ bool StopWatching();
+
+ // Returns the handle of the object being watched, or NULL if the object
+ // watcher is stopped.
+ HANDLE GetWatchedObject();
+
+ private:
+ // Called on a background thread when done waiting.
+ static void CALLBACK DoneWaiting(void* param, BOOLEAN timed_out);
+
+ // MessageLoop::DestructionObserver implementation:
+ virtual void WillDestroyCurrentMessageLoop();
+
+ // Internal state.
+ class Watch;
+ RefPtr<Watch> watch_;
+
+ DISALLOW_COPY_AND_ASSIGN(ObjectWatcher);
+};
+
+} // namespace base
+
+#endif // BASE_OBJECT_WATCHER_H_
diff --git a/ipc/chromium/src/base/observer_list.h b/ipc/chromium/src/base/observer_list.h
new file mode 100644
index 0000000000..52b88329eb
--- /dev/null
+++ b/ipc/chromium/src/base/observer_list.h
@@ -0,0 +1,180 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_OBSERVER_LIST_H__
+#define BASE_OBSERVER_LIST_H__
+
+#include <algorithm>
+#include <limits>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+#if defined(ANDROID) && defined(_STLP_STD_NAME)
+using _STLP_STD_NAME::find;
+#endif
+
+namespace base {
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// OVERVIEW:
+//
+// A container for a list of observers. Unlike a normal STL vector or list,
+// this container can be modified during iteration without invalidating the
+// iterator. So, it safely handles the case of an observer removing itself
+// or other observers from the list while observers are being notified.
+//
+// TYPICAL USAGE:
+//
+// class MyWidget {
+// public:
+// ...
+//
+// class Observer {
+// public:
+// virtual void OnFoo(MyWidget* w) = 0;
+// virtual void OnBar(MyWidget* w, int x, int y) = 0;
+// };
+//
+// void AddObserver(Observer* obs) {
+// observer_list_.AddObserver(obs);
+// }
+//
+// void RemoveObserver(Observer* obs) {
+// observer_list_.RemoveObserver(obs);
+// }
+//
+// void NotifyFoo() {
+// FOR_EACH_OBSERVER(Observer, observer_list_, OnFoo(this));
+// }
+//
+// void NotifyBar(int x, int y) {
+// FOR_EACH_OBSERVER(Observer, observer_list_, OnBar(this, x, y));
+// }
+//
+// private:
+// ObserverList<Observer> observer_list_;
+// };
+//
+//
+///////////////////////////////////////////////////////////////////////////////
+
+template <class ObserverType, bool check_empty = false>
+class ObserverList {
+ public:
+ // Enumeration of which observers are notified.
+ enum NotificationType {
+ // Specifies that any observers added during notification are notified.
+ // This is the default type if non type is provided to the constructor.
+ NOTIFY_ALL,
+
+ // Specifies that observers added while sending out notification are not
+ // notified.
+ NOTIFY_EXISTING_ONLY
+ };
+
+ ObserverList() : notify_depth_(0), type_(NOTIFY_ALL) {}
+ explicit ObserverList(NotificationType type)
+ : notify_depth_(0), type_(type) {}
+ ~ObserverList() {
+ // When check_empty is true, assert that the list is empty on destruction.
+ if (check_empty) {
+ Compact();
+ DCHECK_EQ(observers_.size(), 0U);
+ }
+ }
+
+ // Add an observer to the list.
+ void AddObserver(ObserverType* obs) {
+ DCHECK(find(observers_.begin(), observers_.end(), obs) == observers_.end())
+ << "Observers can only be added once!";
+ observers_.push_back(obs);
+ }
+
+ // Remove an observer from the list.
+ void RemoveObserver(ObserverType* obs) {
+ typename ListType::iterator it =
+ std::find(observers_.begin(), observers_.end(), obs);
+ if (it != observers_.end()) {
+ if (notify_depth_) {
+ *it = 0;
+ } else {
+ observers_.erase(it);
+ }
+ }
+ }
+
+ size_t size() const { return observers_.size(); }
+
+ ObserverType* GetElementAt(int index) const { return observers_[index]; }
+
+ // An iterator class that can be used to access the list of observers. See
+ // also the FOREACH_OBSERVER macro defined below.
+ class Iterator {
+ public:
+ explicit Iterator(const ObserverList<ObserverType>& list)
+ : list_(list),
+ index_(0),
+ max_index_(list.type_ == NOTIFY_ALL
+ ? std::numeric_limits<size_t>::max()
+ : list.observers_.size()) {
+ ++list_.notify_depth_;
+ }
+
+ ~Iterator() {
+ if (--list_.notify_depth_ == 0) list_.Compact();
+ }
+
+ ObserverType* GetNext() {
+ ListType& observers = list_.observers_;
+ // Advance if the current element is null
+ size_t max_index = std::min(max_index_, observers.size());
+ while (index_ < max_index && !observers[index_]) ++index_;
+ return index_ < max_index ? observers[index_++] : NULL;
+ }
+
+ private:
+ const ObserverList<ObserverType>& list_;
+ size_t index_;
+ size_t max_index_;
+ };
+
+ private:
+ typedef std::vector<ObserverType*> ListType;
+
+ void Compact() const {
+ typename ListType::iterator it = observers_.begin();
+ while (it != observers_.end()) {
+ if (*it) {
+ ++it;
+ } else {
+ it = observers_.erase(it);
+ }
+ }
+ }
+
+ // These are marked mutable to facilitate having NotifyAll be const.
+ mutable ListType observers_;
+ mutable int notify_depth_;
+ NotificationType type_;
+
+ friend class ObserverList::Iterator;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ObserverList);
+};
+
+} // namespace base
+
+#define FOR_EACH_OBSERVER(ObserverType, observer_list, func) \
+ do { \
+ base::ObserverList<ObserverType>::Iterator it(observer_list); \
+ ObserverType* obs; \
+ while ((obs = it.GetNext()) != NULL) obs->func; \
+ } while (0)
+
+#endif // BASE_OBSERVER_LIST_H__
diff --git a/ipc/chromium/src/base/pickle.cc b/ipc/chromium/src/base/pickle.cc
new file mode 100644
index 0000000000..fa72edca20
--- /dev/null
+++ b/ipc/chromium/src/base/pickle.cc
@@ -0,0 +1,525 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/pickle.h"
+
+#include "mozilla/Alignment.h"
+#include "mozilla/CheckedInt.h"
+#include "mozilla/EndianUtils.h"
+#include "mozilla/Telemetry.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+#include <stdlib.h>
+
+#include <limits>
+#include <string>
+#include <algorithm>
+#include <type_traits>
+
+#include "nsDebug.h"
+
+//------------------------------------------------------------------------------
+
+static_assert(MOZ_ALIGNOF(Pickle::memberAlignmentType) >= MOZ_ALIGNOF(uint32_t),
+ "Insufficient alignment");
+
+static const uint32_t kHeaderSegmentCapacity = 64;
+
+static const uint32_t kDefaultSegmentCapacity = 4096;
+
+static const char kBytePaddingMarker = char(0xbf);
+
+namespace {
+
+// We want to copy data to our payload as efficiently as possible.
+// memcpy fits the bill for copying, but not all compilers or
+// architectures support inlining memcpy from void*, which has unknown
+// static alignment. However, we know that all the members of our
+// payload will be aligned on memberAlignmentType boundaries. We
+// therefore use that knowledge to construct a copier that will copy
+// efficiently (via standard C++ assignment mechanisms) if the datatype
+// needs that alignment or less, and memcpy otherwise. (The compiler
+// may still inline memcpy, of course.)
+
+template <typename T, size_t size, bool hasSufficientAlignment>
+struct Copier {
+ static void Copy(T* dest, const char* iter) { memcpy(dest, iter, sizeof(T)); }
+};
+
+// Copying 64-bit quantities happens often enough and can easily be made
+// worthwhile on 32-bit platforms, so handle it specially. Only do it
+// if 64-bit types aren't sufficiently aligned; the alignment
+// requirements for them vary between 32-bit platforms.
+#ifndef HAVE_64BIT_BUILD
+template <typename T>
+struct Copier<T, sizeof(uint64_t), false> {
+ static void Copy(T* dest, const char* iter) {
+# if MOZ_LITTLE_ENDIAN
+ static const int loIndex = 0, hiIndex = 1;
+# else
+ static const int loIndex = 1, hiIndex = 0;
+# endif
+ static_assert(MOZ_ALIGNOF(uint32_t*) == MOZ_ALIGNOF(void*),
+ "Pointers have different alignments");
+ const uint32_t* src = reinterpret_cast<const uint32_t*>(iter);
+ uint32_t* uint32dest = reinterpret_cast<uint32_t*>(dest);
+ uint32dest[loIndex] = src[loIndex];
+ uint32dest[hiIndex] = src[hiIndex];
+ }
+};
+#endif
+
+template <typename T, size_t size>
+struct Copier<T, size, true> {
+ static void Copy(T* dest, const char* iter) {
+ // The pointer ought to be properly aligned.
+ DCHECK_EQ((((uintptr_t)iter) & (MOZ_ALIGNOF(T) - 1)), 0);
+ *dest = *reinterpret_cast<const T*>(iter);
+ }
+};
+
+} // anonymous namespace
+
+PickleIterator::PickleIterator(const Pickle& pickle)
+ : iter_(pickle.buffers_.Iter()) {
+ iter_.Advance(pickle.buffers_, pickle.header_size_);
+}
+
+template <typename T>
+void PickleIterator::CopyInto(T* dest) {
+ static_assert(std::is_trivially_copyable<T>::value,
+ "Copied type must be a POD type");
+ Copier<T, sizeof(T),
+ (MOZ_ALIGNOF(T) <=
+ sizeof(Pickle::memberAlignmentType))>::Copy(dest, iter_.Data());
+}
+
+bool Pickle::IteratorHasRoomFor(const PickleIterator& iter,
+ uint32_t len) const {
+ // Make sure we don't get into trouble where AlignInt(len) == 0.
+ MOZ_RELEASE_ASSERT(len < 64);
+
+ return iter.iter_.HasRoomFor(AlignInt(len));
+}
+
+bool Pickle::HasBytesAvailable(const PickleIterator* iter, uint32_t len) const {
+ return iter->iter_.HasBytesAvailable(buffers_, len);
+}
+
+void Pickle::UpdateIter(PickleIterator* iter, uint32_t bytes) const {
+ // Make sure we don't get into trouble where AlignInt(bytes) == 0.
+ MOZ_RELEASE_ASSERT(bytes < 64);
+
+ iter->iter_.Advance(buffers_, AlignInt(bytes));
+}
+
+// Payload is sizeof(Pickle::memberAlignmentType) aligned.
+
+Pickle::Pickle(uint32_t header_size, size_t segment_capacity)
+ : buffers_(AlignInt(header_size),
+ segment_capacity ? segment_capacity : kHeaderSegmentCapacity,
+ segment_capacity ? segment_capacity : kDefaultSegmentCapacity),
+ header_(nullptr),
+ header_size_(AlignInt(header_size)) {
+ DCHECK(static_cast<memberAlignmentType>(header_size) >= sizeof(Header));
+ DCHECK(header_size_ <= kHeaderSegmentCapacity);
+ header_ = reinterpret_cast<Header*>(buffers_.Start());
+ header_->payload_size = 0;
+}
+
+Pickle::Pickle(uint32_t header_size, const char* data, uint32_t length)
+ : buffers_(length, AlignCapacity(length), kDefaultSegmentCapacity),
+ header_(nullptr),
+ header_size_(AlignInt(header_size)) {
+ DCHECK(static_cast<memberAlignmentType>(header_size) >= sizeof(Header));
+ DCHECK(header_size <= kHeaderSegmentCapacity);
+ MOZ_RELEASE_ASSERT(header_size <= length);
+
+ header_ = reinterpret_cast<Header*>(buffers_.Start());
+ memcpy(header_, data, length);
+}
+
+Pickle::Pickle(Pickle&& other)
+ : buffers_(std::move(other.buffers_)),
+ header_(other.header_),
+ header_size_(other.header_size_) {
+ other.header_ = nullptr;
+}
+
+Pickle::~Pickle() {}
+
+Pickle& Pickle::operator=(Pickle&& other) {
+ BufferList tmp = std::move(other.buffers_);
+ other.buffers_ = std::move(buffers_);
+ buffers_ = std::move(tmp);
+
+ // std::swap(buffers_, other.buffers_);
+ std::swap(header_, other.header_);
+ std::swap(header_size_, other.header_size_);
+ return *this;
+}
+
+void Pickle::CopyFrom(const Pickle& other) {
+ MOZ_ALWAYS_TRUE(buffers_.CopyFrom(other.buffers_));
+ MOZ_ASSERT(other.header_ ==
+ reinterpret_cast<const Header*>(other.buffers_.Start()));
+
+ header_ = reinterpret_cast<Header*>(buffers_.Start());
+ header_size_ = other.header_size_;
+}
+
+bool Pickle::ReadBool(PickleIterator* iter, bool* result) const {
+ int tmp;
+ if (!ReadScalar(iter, &tmp)) return false;
+
+ DCHECK(0 == tmp || 1 == tmp);
+ *result = tmp ? true : false;
+
+ return true;
+}
+
+bool Pickle::ReadInt16(PickleIterator* iter, int16_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadUInt16(PickleIterator* iter, uint16_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadInt(PickleIterator* iter, int* result) const {
+ return ReadScalar(iter, result);
+}
+
+// Always written as a 64-bit value since the size for this type can
+// differ between architectures.
+bool Pickle::ReadLong(PickleIterator* iter, long* result) const {
+ int64_t big_result;
+ if (!ReadScalar(iter, &big_result)) return false;
+
+ DCHECK(big_result <= LONG_MAX && big_result >= LONG_MIN);
+ *result = static_cast<long>(big_result);
+
+ return true;
+}
+
+// Always written as a 64-bit value since the size for this type can
+// differ between architectures.
+bool Pickle::ReadULong(PickleIterator* iter, unsigned long* result) const {
+ uint64_t big_result;
+ if (!ReadScalar(iter, &big_result)) return false;
+ DCHECK(big_result <= ULONG_MAX);
+ *result = static_cast<unsigned long>(big_result);
+
+ return true;
+}
+
+bool Pickle::ReadLength(PickleIterator* iter, int* result) const {
+ if (!ReadScalar(iter, result)) return false;
+ return ((*result) >= 0);
+}
+
+bool Pickle::ReadInt32(PickleIterator* iter, int32_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadUInt32(PickleIterator* iter, uint32_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadInt64(PickleIterator* iter, int64_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadUInt64(PickleIterator* iter, uint64_t* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadDouble(PickleIterator* iter, double* result) const {
+ return ReadScalar(iter, result);
+}
+
+// Always written as a 64-bit value since the size for this type can
+// differ between architectures.
+bool Pickle::ReadIntPtr(PickleIterator* iter, intptr_t* result) const {
+ DCHECK(iter);
+
+ int64_t big_result;
+ if (!ReadScalar(iter, &big_result)) return false;
+
+ DCHECK(big_result <= std::numeric_limits<intptr_t>::max() &&
+ big_result >= std::numeric_limits<intptr_t>::min());
+ *result = static_cast<intptr_t>(big_result);
+
+ return true;
+}
+
+bool Pickle::ReadUnsignedChar(PickleIterator* iter,
+ unsigned char* result) const {
+ return ReadScalar(iter, result);
+}
+
+bool Pickle::ReadString(PickleIterator* iter, std::string* result) const {
+ DCHECK(iter);
+
+ int len;
+ if (!ReadLength(iter, &len)) return false;
+
+ auto chars = mozilla::MakeUnique<char[]>(len);
+ if (!ReadBytesInto(iter, chars.get(), len)) {
+ return false;
+ }
+ result->assign(chars.get(), len);
+
+ return true;
+}
+
+bool Pickle::ReadWString(PickleIterator* iter, std::wstring* result) const {
+ DCHECK(iter);
+
+ int len;
+ if (!ReadLength(iter, &len)) return false;
+ // Avoid integer multiplication overflow.
+ if (len > INT_MAX / static_cast<int>(sizeof(wchar_t))) return false;
+
+ auto chars = mozilla::MakeUnique<wchar_t[]>(len);
+ if (!ReadBytesInto(iter, chars.get(), len * sizeof(wchar_t))) {
+ return false;
+ }
+ result->assign(chars.get(), len);
+
+ return true;
+}
+
+bool Pickle::ReadBytesInto(PickleIterator* iter, void* data,
+ uint32_t length) const {
+ if (AlignInt(length) < length) {
+ return false;
+ }
+
+ if (!buffers_.ReadBytes(iter->iter_, reinterpret_cast<char*>(data), length)) {
+ return false;
+ }
+
+ return iter->iter_.AdvanceAcrossSegments(buffers_, AlignInt(length) - length);
+}
+
+bool Pickle::IgnoreBytes(PickleIterator* iter, uint32_t length) const {
+ if (AlignInt(length) < length) {
+ return false;
+ }
+
+ return iter->iter_.AdvanceAcrossSegments(buffers_, AlignInt(length));
+}
+
+#ifdef MOZ_PICKLE_SENTINEL_CHECKING
+MOZ_NEVER_INLINE
+bool Pickle::ReadSentinel(PickleIterator* iter, uint32_t sentinel) const {
+ uint32_t found;
+ if (!ReadScalar(iter, &found)) {
+ return false;
+ }
+ return found == sentinel;
+}
+
+bool Pickle::IgnoreSentinel(PickleIterator* iter) const {
+ uint32_t found;
+ return ReadUInt32(iter, &found);
+}
+
+bool Pickle::WriteSentinel(uint32_t sentinel) { return WriteUInt32(sentinel); }
+#endif
+
+void Pickle::EndRead(PickleIterator& iter, uint32_t ipcMsgType) const {
+ // FIXME: Deal with the footer somehow...
+ // DCHECK(iter.iter_.Done());
+}
+
+void Pickle::Truncate(PickleIterator* iter) {
+ size_t dropped = buffers_.Truncate(iter->iter_);
+ header_->payload_size -= dropped;
+}
+
+static const char kBytePaddingData[4] = {
+ kBytePaddingMarker,
+ kBytePaddingMarker,
+ kBytePaddingMarker,
+ kBytePaddingMarker,
+};
+
+static void WritePadding(Pickle::BufferList& buffers, uint32_t padding) {
+ MOZ_RELEASE_ASSERT(padding <= 4);
+ if (padding) {
+ MOZ_ALWAYS_TRUE(buffers.WriteBytes(kBytePaddingData, padding));
+ }
+}
+
+void Pickle::BeginWrite(uint32_t length) {
+ // write at an alignment-aligned offset from the beginning of the header
+ uint32_t offset = AlignInt(header_->payload_size);
+ uint32_t padding = (header_size_ + offset) % sizeof(memberAlignmentType);
+ uint32_t new_size = offset + padding + AlignInt(length);
+ MOZ_RELEASE_ASSERT(new_size >= header_->payload_size);
+
+ DCHECK(intptr_t(header_) % sizeof(memberAlignmentType) == 0);
+
+#ifdef HAVE_64BIT_BUILD
+ DCHECK_LE(length, std::numeric_limits<uint32_t>::max());
+#endif
+
+ WritePadding(buffers_, padding);
+
+ DCHECK((header_size_ + header_->payload_size + padding) %
+ sizeof(memberAlignmentType) ==
+ 0);
+
+ header_->payload_size = new_size;
+}
+
+void Pickle::EndWrite(uint32_t length) {
+ uint32_t padding = AlignInt(length) - length;
+ WritePadding(buffers_, padding);
+}
+
+bool Pickle::WriteBool(bool value) { return WriteInt(value ? 1 : 0); }
+
+bool Pickle::WriteInt16(int16_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteUInt16(uint16_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteInt(int value) { return WriteBytes(&value, sizeof(value)); }
+
+bool Pickle::WriteLong(long value) {
+ // Always written as a 64-bit value since the size for this type can
+ // differ between architectures.
+ return WriteInt64(int64_t(value));
+}
+
+bool Pickle::WriteULong(unsigned long value) {
+ // Always written as a 64-bit value since the size for this type can
+ // differ between architectures.
+ return WriteUInt64(uint64_t(value));
+}
+
+bool Pickle::WriteInt32(int32_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteUInt32(uint32_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteInt64(int64_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteUInt64(uint64_t value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteDouble(double value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteIntPtr(intptr_t value) {
+ // Always written as a 64-bit value since the size for this type can
+ // differ between architectures.
+ return WriteInt64(int64_t(value));
+}
+
+bool Pickle::WriteUnsignedChar(unsigned char value) {
+ return WriteBytes(&value, sizeof(value));
+}
+
+bool Pickle::WriteBytesZeroCopy(void* data, uint32_t data_len,
+ uint32_t capacity) {
+ BeginWrite(data_len);
+
+ uint32_t new_capacity = AlignInt(capacity);
+#ifndef MOZ_MEMORY
+ if (new_capacity > capacity) {
+ // If the buffer we were given is not large enough to contain padding
+ // after the data, reallocate it to make it so. When using jemalloc,
+ // we're guaranteed the buffer size is going to be at least 4-bytes
+ // aligned, so we skip realloc altogether. Even with other allocators,
+ // the realloc is likely not necessary, but we don't take chances.
+ // At least with ASan, it does matter to realloc to inform ASan we're
+ // going to use more data from the buffer (and let it actually realloc
+ // if it needs to).
+ data = realloc(data, new_capacity);
+ }
+#endif
+
+ // Shouldn't fail, because we're using InfallibleAllocPolicy.
+ MOZ_ALWAYS_TRUE(buffers_.WriteBytesZeroCopy(reinterpret_cast<char*>(data),
+ data_len, new_capacity));
+
+ EndWrite(data_len);
+ return true;
+}
+
+bool Pickle::WriteBytes(const void* data, uint32_t data_len) {
+ BeginWrite(data_len);
+
+ MOZ_ALWAYS_TRUE(
+ buffers_.WriteBytes(reinterpret_cast<const char*>(data), data_len));
+
+ EndWrite(data_len);
+ return true;
+}
+
+bool Pickle::WriteString(const std::string& value) {
+ if (!WriteInt(static_cast<int>(value.size()))) return false;
+
+ return WriteBytes(value.data(), static_cast<int>(value.size()));
+}
+
+bool Pickle::WriteWString(const std::wstring& value) {
+ if (!WriteInt(static_cast<int>(value.size()))) return false;
+
+ return WriteBytes(value.data(),
+ static_cast<int>(value.size() * sizeof(wchar_t)));
+}
+
+bool Pickle::WriteData(const char* data, uint32_t length) {
+ return WriteInt(length) && WriteBytes(data, length);
+}
+
+void Pickle::InputBytes(const char* data, uint32_t length) {
+ MOZ_ALWAYS_TRUE(buffers_.WriteBytes(data, length));
+}
+
+int32_t* Pickle::GetInt32PtrForTest(uint32_t offset) {
+ size_t pos = buffers_.Size() - offset;
+ BufferList::IterImpl iter(buffers_);
+ MOZ_RELEASE_ASSERT(iter.AdvanceAcrossSegments(buffers_, pos));
+ return reinterpret_cast<int32_t*>(iter.Data());
+}
+
+// static
+uint32_t Pickle::MessageSize(uint32_t header_size, const char* start,
+ const char* end) {
+ DCHECK(header_size == AlignInt(header_size));
+ DCHECK(header_size <=
+ static_cast<memberAlignmentType>(kHeaderSegmentCapacity));
+
+ if (end < start) return 0;
+ size_t length = static_cast<size_t>(end - start);
+ if (length < sizeof(Header)) return 0;
+
+ const Header* hdr = reinterpret_cast<const Header*>(start);
+ if (length < header_size) return 0;
+
+ mozilla::CheckedInt<uint32_t> sum(header_size);
+ sum += hdr->payload_size;
+
+ if (!sum.isValid()) return 0;
+
+ return sum.value();
+}
diff --git a/ipc/chromium/src/base/pickle.h b/ipc/chromium/src/base/pickle.h
new file mode 100644
index 0000000000..5f64880848
--- /dev/null
+++ b/ipc/chromium/src/base/pickle.h
@@ -0,0 +1,284 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_PICKLE_H__
+#define BASE_PICKLE_H__
+
+#include <string>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/string16.h"
+
+#include "mozilla/Attributes.h"
+#include "mozilla/BufferList.h"
+#include "mozilla/mozalloc.h"
+#include "mozilla/TimeStamp.h"
+#if !defined(FUZZING) && (!defined(RELEASE_OR_BETA) || defined(DEBUG))
+# define MOZ_PICKLE_SENTINEL_CHECKING
+#endif
+class Pickle;
+class PickleIterator {
+ public:
+ explicit PickleIterator(const Pickle& pickle);
+
+ private:
+ friend class Pickle;
+
+ mozilla::BufferList<InfallibleAllocPolicy>::IterImpl iter_;
+
+ template <typename T>
+ void CopyInto(T* dest);
+};
+
+// This class provides facilities for basic binary value packing and unpacking.
+//
+// The Pickle class supports appending primitive values (ints, strings, etc.)
+// to a pickle instance. The Pickle instance grows its internal memory buffer
+// dynamically to hold the sequence of primitive values. The internal memory
+// buffer is exposed as the "data" of the Pickle. This "data" can be passed
+// to a Pickle object to initialize it for reading.
+//
+// When reading from a Pickle object, it is important for the consumer to know
+// what value types to read and in what order to read them as the Pickle does
+// not keep track of the type of data written to it.
+//
+// The Pickle's data has a header which contains the size of the Pickle's
+// payload. It can optionally support additional space in the header. That
+// space is controlled by the header_size parameter passed to the Pickle
+// constructor.
+//
+class Pickle {
+ public:
+ ~Pickle();
+
+ Pickle() = delete;
+
+ // Initialize a Pickle object with the specified header size in bytes, which
+ // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size
+ // will be rounded up to ensure that the header size is 32bit-aligned.
+ explicit Pickle(uint32_t header_size, size_t segment_capacity = 0);
+
+ Pickle(uint32_t header_size, const char* data, uint32_t length);
+
+ Pickle(const Pickle& other) = delete;
+
+ Pickle(Pickle&& other);
+
+ // Performs a deep copy.
+ Pickle& operator=(const Pickle& other) = delete;
+
+ Pickle& operator=(Pickle&& other);
+
+ void CopyFrom(const Pickle& other);
+
+ // Returns the size of the Pickle's data.
+ uint32_t size() const { return header_size_ + header_->payload_size; }
+
+ typedef mozilla::BufferList<InfallibleAllocPolicy> BufferList;
+
+ const BufferList& Buffers() const { return buffers_; }
+
+ uint32_t CurrentSize() const { return buffers_.Size(); }
+
+ // Methods for reading the payload of the Pickle. To read from the start of
+ // the Pickle, initialize *iter to NULL. If successful, these methods return
+ // true. Otherwise, false is returned to indicate that the result could not
+ // be extracted.
+ [[nodiscard]] bool ReadBool(PickleIterator* iter, bool* result) const;
+ [[nodiscard]] bool ReadInt16(PickleIterator* iter, int16_t* result) const;
+ [[nodiscard]] bool ReadUInt16(PickleIterator* iter, uint16_t* result) const;
+ [[nodiscard]] bool ReadShort(PickleIterator* iter, short* result) const;
+ [[nodiscard]] bool ReadInt(PickleIterator* iter, int* result) const;
+ [[nodiscard]] bool ReadLong(PickleIterator* iter, long* result) const;
+ [[nodiscard]] bool ReadULong(PickleIterator* iter,
+ unsigned long* result) const;
+ [[nodiscard]] bool ReadInt32(PickleIterator* iter, int32_t* result) const;
+ [[nodiscard]] bool ReadUInt32(PickleIterator* iter, uint32_t* result) const;
+ [[nodiscard]] bool ReadInt64(PickleIterator* iter, int64_t* result) const;
+ [[nodiscard]] bool ReadUInt64(PickleIterator* iter, uint64_t* result) const;
+ [[nodiscard]] bool ReadDouble(PickleIterator* iter, double* result) const;
+ [[nodiscard]] bool ReadIntPtr(PickleIterator* iter, intptr_t* result) const;
+ [[nodiscard]] bool ReadUnsignedChar(PickleIterator* iter,
+ unsigned char* result) const;
+ [[nodiscard]] bool ReadString(PickleIterator* iter,
+ std::string* result) const;
+ [[nodiscard]] bool ReadWString(PickleIterator* iter,
+ std::wstring* result) const;
+ [[nodiscard]] bool ReadBytesInto(PickleIterator* iter, void* data,
+ uint32_t length) const;
+
+ // Safer version of ReadInt() checks for the result not being negative.
+ // Use it for reading the object sizes.
+ [[nodiscard]] bool ReadLength(PickleIterator* iter, int* result) const;
+
+ [[nodiscard]] bool IgnoreBytes(PickleIterator* iter, uint32_t length) const;
+
+ [[nodiscard]] bool ReadSentinel(PickleIterator* iter, uint32_t sentinel) const
+#ifdef MOZ_PICKLE_SENTINEL_CHECKING
+ ;
+#else
+ {
+ return true;
+ }
+#endif
+
+ template <class T>
+ [[nodiscard]] bool ReadScalar(PickleIterator* iter, T* result) const {
+ DCHECK(iter);
+
+ if (!IteratorHasRoomFor(*iter, sizeof(*result)))
+ return ReadBytesInto(iter, result, sizeof(*result));
+
+ iter->CopyInto(result);
+
+ UpdateIter(iter, sizeof(*result));
+ return true;
+ }
+
+ bool IgnoreSentinel(PickleIterator* iter) const
+#ifdef MOZ_PICKLE_SENTINEL_CHECKING
+ ;
+#else
+ {
+ return true;
+ }
+#endif
+
+ // NOTE: The message type optional parameter should _only_ be called from
+ // generated IPDL code, as it is used to trigger the IPC_READ_LATENCY_MS
+ // telemetry probe.
+ void EndRead(PickleIterator& iter, uint32_t ipcMessageType = 0) const;
+
+ // Returns true if the given iterator has at least |len| bytes remaining it,
+ // across all segments. If there is not that much data available, returns
+ // false. Generally used when reading a (len, data) pair from the message,
+ // before allocating |len| bytes of space, to ensure that reading |len| bytes
+ // will succeed.
+ bool HasBytesAvailable(const PickleIterator* iter, uint32_t len) const;
+
+ // Truncate the message at the current point, discarding any data after this
+ // point in the message.
+ void Truncate(PickleIterator* iter);
+
+ // Methods for adding to the payload of the Pickle. These values are
+ // appended to the end of the Pickle's payload. When reading values from a
+ // Pickle, it is important to read them in the order in which they were added
+ // to the Pickle.
+ bool WriteBool(bool value);
+ bool WriteInt16(int16_t value);
+ bool WriteUInt16(uint16_t value);
+ bool WriteInt(int value);
+ bool WriteLong(long value);
+ bool WriteULong(unsigned long value);
+ bool WriteInt32(int32_t value);
+ bool WriteUInt32(uint32_t value);
+ bool WriteInt64(int64_t value);
+ bool WriteUInt64(uint64_t value);
+ bool WriteDouble(double value);
+ bool WriteIntPtr(intptr_t value);
+ bool WriteUnsignedChar(unsigned char value);
+ bool WriteString(const std::string& value);
+ bool WriteWString(const std::wstring& value);
+ bool WriteData(const char* data, uint32_t length);
+ bool WriteBytes(const void* data, uint32_t data_len);
+ // Takes ownership of data
+ bool WriteBytesZeroCopy(void* data, uint32_t data_len, uint32_t capacity);
+
+ bool WriteSentinel(uint32_t sentinel)
+#ifdef MOZ_PICKLE_SENTINEL_CHECKING
+ ;
+#else
+ {
+ return true;
+ }
+#endif
+
+ int32_t* GetInt32PtrForTest(uint32_t offset);
+
+ void InputBytes(const char* data, uint32_t length);
+
+ // Payload follows after allocation of Header (header size is customizable).
+ struct Header {
+ uint32_t payload_size; // Specifies the size of the payload.
+ };
+
+ // Returns the header, cast to a user-specified type T. The type T must be a
+ // subclass of Header and its size must correspond to the header_size passed
+ // to the Pickle constructor.
+ template <class T>
+ T* headerT() {
+ DCHECK(sizeof(T) == header_size_);
+ return static_cast<T*>(header_);
+ }
+ template <class T>
+ const T* headerT() const {
+ DCHECK(sizeof(T) == header_size_);
+ return static_cast<const T*>(header_);
+ }
+
+ typedef uint32_t memberAlignmentType;
+
+ protected:
+ uint32_t payload_size() const { return header_->payload_size; }
+
+ // Resizes the buffer for use when writing the specified amount of data. Call
+ // EndWrite with the given length to pad out for the next write.
+ void BeginWrite(uint32_t length);
+
+ // Completes the write operation by padding the data with poison bytes. Should
+ // be paired with BeginWrite, but it does not necessarily have to be called
+ // after the data is written.
+ void EndWrite(uint32_t length);
+
+ // Round 'bytes' up to the next multiple of 'alignment'. 'alignment' must be
+ // a power of 2.
+ template <uint32_t alignment>
+ struct ConstantAligner {
+ static uint32_t align(int bytes) {
+ static_assert((alignment & (alignment - 1)) == 0,
+ "alignment must be a power of two");
+ return (bytes + (alignment - 1)) & ~static_cast<uint32_t>(alignment - 1);
+ }
+ };
+
+ static uint32_t AlignInt(int bytes) {
+ return ConstantAligner<sizeof(memberAlignmentType)>::align(bytes);
+ }
+
+ static uint32_t AlignCapacity(int bytes) {
+ return ConstantAligner<kSegmentAlignment>::align(bytes);
+ }
+
+ // Returns true if the given iterator could point to data with the given
+ // length. If there is no room for the given data before the end of the
+ // payload, returns false.
+ bool IteratorHasRoomFor(const PickleIterator& iter, uint32_t len) const;
+
+ // Moves the iterator by the given number of bytes, making sure it is aligned.
+ // Pointer (iterator) is NOT aligned, but the change in the pointer
+ // is guaranteed to be a multiple of sizeof(memberAlignmentType).
+ void UpdateIter(PickleIterator* iter, uint32_t bytes) const;
+
+ // Figure out how big the message starting at range_start is. Returns 0 if
+ // there's no enough data to determine (i.e., if [range_start, range_end) does
+ // not contain enough of the message header to know the size).
+ static uint32_t MessageSize(uint32_t header_size, const char* range_start,
+ const char* range_end);
+
+ // Segments capacities are aligned to 8 bytes to ensure that all reads/writes
+ // at 8-byte aligned offsets will be on 8-byte aligned pointers.
+ static const uint32_t kSegmentAlignment = 8;
+
+ private:
+ friend class PickleIterator;
+
+ BufferList buffers_;
+ Header* header_;
+ uint32_t header_size_;
+};
+
+#endif // BASE_PICKLE_H__
diff --git a/ipc/chromium/src/base/platform_file.h b/ipc/chromium/src/base/platform_file.h
new file mode 100644
index 0000000000..2c03821539
--- /dev/null
+++ b/ipc/chromium/src/base/platform_file.h
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_PLATFORM_FILE_H_
+#define BASE_PLATFORM_FILE_H_
+
+#if defined(XP_WIN)
+# include <windows.h>
+#endif
+
+#include <string>
+
+namespace base {
+
+#if defined(XP_WIN)
+typedef HANDLE PlatformFile;
+const PlatformFile kInvalidPlatformFileValue = INVALID_HANDLE_VALUE;
+#else
+typedef int PlatformFile;
+const PlatformFile kInvalidPlatformFileValue = -1;
+#endif
+
+enum PlatformFileFlags {
+ PLATFORM_FILE_OPEN = 1,
+ PLATFORM_FILE_CREATE = 2,
+ PLATFORM_FILE_OPEN_ALWAYS = 4, // May create a new file.
+ PLATFORM_FILE_CREATE_ALWAYS = 8, // May overwrite an old file.
+ PLATFORM_FILE_READ = 16,
+ PLATFORM_FILE_WRITE = 32,
+ PLATFORM_FILE_EXCLUSIVE_READ = 64, // EXCLUSIVE is opposite of Windows SHARE
+ PLATFORM_FILE_EXCLUSIVE_WRITE = 128,
+ PLATFORM_FILE_ASYNC = 256
+};
+
+// Creates or open the given file. If PLATFORM_FILE_OPEN_ALWAYS is used, and
+// |created| is provided, |created| will be set to true if the file was created
+// or to false in case the file was just opened.
+PlatformFile CreatePlatformFile(const std::wstring& name, int flags,
+ bool* created);
+
+} // namespace base
+
+#endif // BASE_PLATFORM_FILE_H_
diff --git a/ipc/chromium/src/base/platform_thread.h b/ipc/chromium/src/base/platform_thread.h
new file mode 100644
index 0000000000..f3a65e8797
--- /dev/null
+++ b/ipc/chromium/src/base/platform_thread.h
@@ -0,0 +1,88 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// WARNING: You should *NOT* be using this class directly. PlatformThread is
+// the low-level platform-specific abstraction to the OS's threading interface.
+// You should instead be using a message-loop driven Thread, see thread.h.
+
+#ifndef BASE_PLATFORM_THREAD_H_
+#define BASE_PLATFORM_THREAD_H_
+
+#include "base/basictypes.h"
+
+// PlatformThreadHandle should not be assumed to be a numeric type, since the
+// standard intends to allow pthread_t to be a structure. This means you
+// should not initialize it to a value, like 0. If it's a member variable, the
+// constructor can safely "value initialize" using () in the initializer list.
+#if defined(XP_WIN)
+# include <windows.h>
+typedef DWORD PlatformThreadId;
+typedef void* PlatformThreadHandle; // HANDLE
+#else
+# include <pthread.h>
+typedef pthread_t PlatformThreadHandle;
+# if defined(XP_LINUX) || defined(XP_OPENBSD) || defined(XP_SOLARIS) || \
+ defined(__GLIBC__)
+# include <unistd.h>
+typedef pid_t PlatformThreadId;
+# elif defined(__DragonFly__) || defined(XP_FREEBSD) || defined(XP_NETBSD)
+# include <sys/types.h>
+typedef lwpid_t PlatformThreadId;
+# elif defined(XP_DARWIN)
+# include <mach/mach.h>
+typedef mach_port_t PlatformThreadId;
+# endif
+#endif
+
+// A namespace for low-level thread functions.
+class PlatformThread {
+ public:
+ // Gets the current thread id, which may be useful for logging purposes.
+ static PlatformThreadId CurrentId();
+
+ // Yield the current thread so another thread can be scheduled.
+ static void YieldCurrentThread();
+
+ // Sleeps for the specified duration (units are milliseconds).
+ static void Sleep(int duration_ms);
+
+ // Sets the thread name visible to a debugger. This has no effect otherwise.
+ static void SetName(const char* name);
+
+ // Implement this interface to run code on a background thread. Your
+ // ThreadMain method will be called on the newly created thread.
+ class Delegate {
+ public:
+ virtual ~Delegate() {}
+ virtual void ThreadMain() = 0;
+ };
+
+ // Creates a new thread. The |stack_size| parameter can be 0 to indicate
+ // that the default stack size should be used. Upon success,
+ // |*thread_handle| will be assigned a handle to the newly created thread,
+ // and |delegate|'s ThreadMain method will be executed on the newly created
+ // thread.
+ // NOTE: When you are done with the thread handle, you must call Join to
+ // release system resources associated with the thread. You must ensure that
+ // the Delegate object outlives the thread.
+ static bool Create(size_t stack_size, Delegate* delegate,
+ PlatformThreadHandle* thread_handle);
+
+ // CreateNonJoinable() does the same thing as Create() except the thread
+ // cannot be Join()'d. Therefore, it also does not output a
+ // PlatformThreadHandle.
+ static bool CreateNonJoinable(size_t stack_size, Delegate* delegate);
+
+ // Joins with a thread created via the Create function. This function blocks
+ // the caller until the designated thread exits. This will invalidate
+ // |thread_handle|.
+ static void Join(PlatformThreadHandle thread_handle);
+
+ private:
+ DISALLOW_IMPLICIT_CONSTRUCTORS(PlatformThread);
+};
+
+#endif // BASE_PLATFORM_THREAD_H_
diff --git a/ipc/chromium/src/base/platform_thread_mac.mm b/ipc/chromium/src/base/platform_thread_mac.mm
new file mode 100644
index 0000000000..32917ff11e
--- /dev/null
+++ b/ipc/chromium/src/base/platform_thread_mac.mm
@@ -0,0 +1,75 @@
+// Copyright (c) 2006-2008 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.
+
+#include "base/platform_thread.h"
+
+#import <Foundation/Foundation.h>
+#include <dlfcn.h>
+
+#include "base/logging.h"
+#include "base/scoped_nsautorelease_pool.h"
+
+// A simple class that demonstrates our impressive ability to do nothing.
+@interface NoOp : NSObject
+
+// Does the deed. Or does it?
++ (void)noOp;
+
+@end
+
+@implementation NoOp
+
++ (void)noOp {
+}
+
+@end
+
+namespace base {
+
+// If Cocoa is to be used on more than one thread, it must know that the
+// application is multithreaded. Since it's possible to enter Cocoa code
+// from threads created by pthread_thread_create, Cocoa won't necessarily
+// be aware that the application is multithreaded. Spawning an NSThread is
+// enough to get Cocoa to set up for multithreaded operation, so this is done
+// if necessary before pthread_thread_create spawns any threads.
+//
+// http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/chapter_4_section_4.html
+void InitThreading() {
+ // this is called early in startup, before the event loop, so provide
+ // an autorelease pool to prevent leaks here
+ ScopedNSAutoreleasePool pool;
+
+ static BOOL multithreaded = [NSThread isMultiThreaded];
+ if (!multithreaded) {
+ [NSThread detachNewThreadSelector:@selector(noOp)
+ toTarget:[NoOp class]
+ withObject:nil];
+ multithreaded = YES;
+
+ DCHECK([NSThread isMultiThreaded]);
+ }
+}
+
+} // namespace base
+
+// static
+void PlatformThread::SetName(const char* name) {
+ // pthread_setname_np is only available in 10.6 or later, so test
+ // for it at runtime.
+ int (*dynamic_pthread_setname_np)(const char*);
+ *reinterpret_cast<void**>(&dynamic_pthread_setname_np) =
+ dlsym(RTLD_DEFAULT, "pthread_setname_np");
+ if (!dynamic_pthread_setname_np) return;
+
+ // Mac OS X does not expose the length limit of the name, so
+ // hardcode it.
+ const int kMaxNameLength = 63;
+ std::string shortened_name = std::string(name).substr(0, kMaxNameLength);
+ // pthread_setname() fails (harmlessly) in the sandbox, ignore when it does.
+ // See http://crbug.com/47058
+
+ // The name parameter is copied thus it's safe to release it after calling.
+ // Checked against the bionic implementation in bionic/libc/bionic/pthread.c
+ dynamic_pthread_setname_np(shortened_name.c_str());
+}
diff --git a/ipc/chromium/src/base/platform_thread_posix.cc b/ipc/chromium/src/base/platform_thread_posix.cc
new file mode 100644
index 0000000000..d28abbc91f
--- /dev/null
+++ b/ipc/chromium/src/base/platform_thread_posix.cc
@@ -0,0 +1,151 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/platform_thread.h"
+
+#include <errno.h>
+#include <sched.h>
+
+#if defined(XP_DARWIN)
+# include <mach/mach.h>
+#elif defined(XP_NETBSD)
+# include <lwp.h>
+#elif defined(XP_LINUX)
+# include <sys/syscall.h>
+# include <sys/prctl.h>
+#endif
+
+#if !defined(XP_DARWIN)
+# include <unistd.h>
+#endif
+
+#if (defined(__DragonFly__) || defined(XP_FREEBSD) || defined(XP_OPENBSD)) && \
+ !defined(__GLIBC__)
+# include <pthread_np.h>
+#endif
+
+#include "nsThreadUtils.h"
+
+#if defined(XP_DARWIN)
+namespace base {
+void InitThreading();
+} // namespace base
+#endif
+
+static void* ThreadFunc(void* closure) {
+ PlatformThread::Delegate* delegate =
+ static_cast<PlatformThread::Delegate*>(closure);
+ delegate->ThreadMain();
+ return NULL;
+}
+
+// static
+PlatformThreadId PlatformThread::CurrentId() {
+ // Pthreads doesn't have the concept of a thread ID, so we have to reach down
+ // into the kernel.
+#if defined(XP_DARWIN)
+ mach_port_t port = mach_thread_self();
+ mach_port_deallocate(mach_task_self(), port);
+ return port;
+#elif defined(XP_LINUX)
+ return syscall(__NR_gettid);
+#elif defined(XP_OPENBSD) || defined(XP_SOLARIS) || defined(__GLIBC__)
+ return (intptr_t)(pthread_self());
+#elif defined(XP_NETBSD)
+ return _lwp_self();
+#elif defined(__DragonFly__)
+ return lwp_gettid();
+#elif defined(XP_FREEBSD)
+ return pthread_getthreadid_np();
+#endif
+}
+
+// static
+void PlatformThread::YieldCurrentThread() { sched_yield(); }
+
+// static
+void PlatformThread::Sleep(int duration_ms) {
+ struct timespec sleep_time, remaining;
+
+ // Contains the portion of duration_ms >= 1 sec.
+ sleep_time.tv_sec = duration_ms / 1000;
+ duration_ms -= sleep_time.tv_sec * 1000;
+
+ // Contains the portion of duration_ms < 1 sec.
+ sleep_time.tv_nsec = duration_ms * 1000 * 1000; // nanoseconds.
+
+ while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR)
+ sleep_time = remaining;
+}
+
+#ifndef XP_DARWIN
+// Mac is implemented in platform_thread_mac.mm.
+
+// static
+void PlatformThread::SetName(const char* name) {
+ // On linux we can get the thread names to show up in the debugger by setting
+ // the process name for the LWP. We don't want to do this for the main
+ // thread because that would rename the process, causing tools like killall
+ // to stop working.
+ if (PlatformThread::CurrentId() == getpid()) return;
+
+ // Using NS_SetCurrentThreadName, as opposed to using platform APIs directly,
+ // also sets the thread name on the PRThread wrapper, and allows us to
+ // retrieve it using PR_GetThreadName.
+ NS_SetCurrentThreadName(name);
+}
+#endif // !XP_DARWIN
+
+namespace {
+
+bool CreateThread(size_t stack_size, bool joinable,
+ PlatformThread::Delegate* delegate,
+ PlatformThreadHandle* thread_handle) {
+#if defined(XP_DARWIN)
+ base::InitThreading();
+#endif // XP_DARWIN
+
+ bool success = false;
+ pthread_attr_t attributes;
+ pthread_attr_init(&attributes);
+
+ // Pthreads are joinable by default, so only specify the detached attribute if
+ // the thread should be non-joinable.
+ if (!joinable) {
+ pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
+ }
+
+ if (stack_size == 0) stack_size = nsIThreadManager::DEFAULT_STACK_SIZE;
+ pthread_attr_setstacksize(&attributes, stack_size);
+
+ success = !pthread_create(thread_handle, &attributes, ThreadFunc, delegate);
+
+ pthread_attr_destroy(&attributes);
+ return success;
+}
+
+} // anonymous namespace
+
+// static
+bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
+ PlatformThreadHandle* thread_handle) {
+ return CreateThread(stack_size, true /* joinable thread */, delegate,
+ thread_handle);
+}
+
+// static
+bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
+ PlatformThreadHandle unused;
+
+ bool result = CreateThread(stack_size, false /* non-joinable thread */,
+ delegate, &unused);
+ return result;
+}
+
+// static
+void PlatformThread::Join(PlatformThreadHandle thread_handle) {
+ pthread_join(thread_handle, NULL);
+}
diff --git a/ipc/chromium/src/base/platform_thread_win.cc b/ipc/chromium/src/base/platform_thread_win.cc
new file mode 100644
index 0000000000..59eb45aff6
--- /dev/null
+++ b/ipc/chromium/src/base/platform_thread_win.cc
@@ -0,0 +1,80 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/platform_thread.h"
+
+#include "base/logging.h"
+#include "base/win_util.h"
+
+#include "nsThreadUtils.h"
+
+namespace {
+
+DWORD __stdcall ThreadFunc(void* closure) {
+ PlatformThread::Delegate* delegate =
+ static_cast<PlatformThread::Delegate*>(closure);
+ delegate->ThreadMain();
+ return 0;
+}
+
+} // namespace
+
+// static
+PlatformThreadId PlatformThread::CurrentId() { return GetCurrentThreadId(); }
+
+// static
+void PlatformThread::YieldCurrentThread() { ::Sleep(0); }
+
+// static
+void PlatformThread::Sleep(int duration_ms) { ::Sleep(duration_ms); }
+
+// static
+void PlatformThread::SetName(const char* name) {
+ // Using NS_SetCurrentThreadName, as opposed to using platform APIs directly,
+ // also sets the thread name on the PRThread wrapper, and allows us to
+ // retrieve it using PR_GetThreadName.
+ NS_SetCurrentThreadName(name);
+}
+
+// static
+bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
+ PlatformThreadHandle* thread_handle) {
+ unsigned int flags = 0;
+ if (stack_size > 0) {
+ flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
+ } else {
+ stack_size = 0;
+ }
+
+ // Using CreateThread here vs _beginthreadex makes thread creation a bit
+ // faster and doesn't require the loader lock to be available. Our code will
+ // have to work running on CreateThread() threads anyway, since we run code
+ // on the Windows thread pool, etc. For some background on the difference:
+ // http://www.microsoft.com/msj/1099/win32/win321099.aspx
+ *thread_handle =
+ CreateThread(NULL, stack_size, ThreadFunc, delegate, flags, NULL);
+ return *thread_handle != NULL;
+}
+
+// static
+bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
+ PlatformThreadHandle thread_handle;
+ bool result = Create(stack_size, delegate, &thread_handle);
+ CloseHandle(thread_handle);
+ return result;
+}
+
+// static
+void PlatformThread::Join(PlatformThreadHandle thread_handle) {
+ DCHECK(thread_handle);
+
+ // Wait for the thread to exit. It should already have terminated but make
+ // sure this assumption is valid.
+ DWORD result = WaitForSingleObject(thread_handle, INFINITE);
+ DCHECK_EQ(WAIT_OBJECT_0, result);
+
+ CloseHandle(thread_handle);
+}
diff --git a/ipc/chromium/src/base/port.h b/ipc/chromium/src/base/port.h
new file mode 100644
index 0000000000..6006b56792
--- /dev/null
+++ b/ipc/chromium/src/base/port.h
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_PORT_H_
+#define BASE_PORT_H_
+
+#include <stdarg.h>
+
+#ifdef _MSC_VER
+# define GG_LONGLONG(x) x##I64
+# define GG_ULONGLONG(x) x##UI64
+#else
+# define GG_LONGLONG(x) x##LL
+# define GG_ULONGLONG(x) x##ULL
+#endif
+
+// Per C99 7.8.14, define __STDC_CONSTANT_MACROS before including <stdint.h>
+// to get the INTn_C and UINTn_C macros for integer constants. It's difficult
+// to guarantee any specific ordering of header includes, so it's difficult to
+// guarantee that the INTn_C macros can be defined by including <stdint.h> at
+// any specific point. Provide GG_INTn_C macros instead.
+
+#define GG_INT8_C(x) (x)
+#define GG_INT16_C(x) (x)
+#define GG_INT32_C(x) (x)
+#define GG_INT64_C(x) GG_LONGLONG(x)
+
+#define GG_UINT8_C(x) (x##U)
+#define GG_UINT16_C(x) (x##U)
+#define GG_UINT32_C(x) (x##U)
+#define GG_UINT64_C(x) GG_ULONGLONG(x)
+
+namespace base {
+
+// It's possible for functions that use a va_list, such as StringPrintf, to
+// invalidate the data in it upon use. The fix is to make a copy of the
+// structure before using it and use that copy instead. va_copy is provided
+// for this purpose. MSVC does not provide va_copy, so define an
+// implementation here. It is not guaranteed that assignment is a copy, so the
+// StringUtil.VariableArgsFunc unit test tests this capability.
+
+// The C standard says that va_copy is a "macro", not a function. Trying to
+// use va_list as ref args to a function, as above, breaks some machines.
+#if defined(__GNUC__)
+# define base_va_copy(_a, _b) ::va_copy(_a, _b)
+#elif defined(_MSC_VER)
+# define base_va_copy(_a, _b) (_a = _b)
+#else
+# error No va_copy for your compiler
+#endif
+
+} // namespace base
+
+// Define an OS-neutral wrapper for shared library entry points
+#if defined(XP_WIN)
+# define API_CALL __stdcall
+#elif defined(XP_LINUX) || defined(XP_DARWIN)
+# define API_CALL
+#endif
+
+#endif // BASE_PORT_H_
diff --git a/ipc/chromium/src/base/process.h b/ipc/chromium/src/base/process.h
new file mode 100644
index 0000000000..006afc1d3f
--- /dev/null
+++ b/ipc/chromium/src/base/process.h
@@ -0,0 +1,50 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_PROCESS_H_
+#define BASE_PROCESS_H_
+
+#include "base/basictypes.h"
+
+#include <sys/types.h>
+#ifdef XP_WIN
+# include <windows.h>
+#endif
+
+namespace base {
+
+// ProcessHandle is a platform specific type which represents the underlying OS
+// handle to a process.
+// ProcessId is a number which identifies the process in the OS.
+#if defined(XP_WIN)
+typedef HANDLE ProcessHandle;
+typedef DWORD ProcessId;
+// inttypes.h-like macro for ProcessId formatting.
+# define PRIPID "lu"
+
+const ProcessHandle kInvalidProcessHandle = INVALID_HANDLE_VALUE;
+
+// In theory, on Windows, this is a valid process ID, but in practice they are
+// currently divisible by four. Process IDs share the kernel handle allocation
+// code and they are guaranteed to be divisible by four.
+// As this could change for process IDs we shouldn't generally rely on this
+// property, however even if that were to change, it seems safe to rely on this
+// particular value never being used.
+const ProcessId kInvalidProcessId = kuint32max;
+#else
+// On POSIX, our ProcessHandle will just be the PID.
+typedef pid_t ProcessHandle;
+typedef pid_t ProcessId;
+// inttypes.h-like macro for ProcessId formatting.
+# define PRIPID "d"
+
+const ProcessHandle kInvalidProcessHandle = -1;
+const ProcessId kInvalidProcessId = -1;
+#endif
+
+} // namespace base
+
+#endif // BASE_PROCESS_H_
diff --git a/ipc/chromium/src/base/process_util.h b/ipc/chromium/src/base/process_util.h
new file mode 100644
index 0000000000..45426d616e
--- /dev/null
+++ b/ipc/chromium/src/base/process_util.h
@@ -0,0 +1,342 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+// This file/namespace contains utility functions for enumerating, ending and
+// computing statistics of processes.
+
+#ifndef BASE_PROCESS_UTIL_H_
+#define BASE_PROCESS_UTIL_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+# include "mozilla/ipc/EnvironmentMap.h"
+# include <windows.h>
+# include <tlhelp32.h>
+#elif defined(XP_LINUX) || defined(__GLIBC__)
+# include <dirent.h>
+# include <limits.h>
+# include <sys/types.h>
+#elif defined(XP_DARWIN)
+# include <mach/mach.h>
+#endif
+
+#include <cstddef>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "base/process.h"
+
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Result.h"
+#include "mozilla/ResultVariant.h"
+
+#include "mozilla/ipc/LaunchError.h"
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+# include "nsStringFwd.h"
+# include "mozilla/ipc/FileDescriptorShuffle.h"
+
+namespace mozilla {
+namespace ipc {
+class FileDescriptor;
+}
+} // namespace mozilla
+#endif
+
+#if defined(XP_DARWIN)
+struct kinfo_proc;
+#endif
+
+class CommandLine;
+
+namespace base {
+
+using mozilla::Err;
+using mozilla::Ok;
+using mozilla::Result;
+using mozilla::ipc::LaunchError;
+
+enum ProcessArchitecture {
+ PROCESS_ARCH_INVALID = 0x0,
+ PROCESS_ARCH_I386 = 0x1,
+ PROCESS_ARCH_X86_64 = 0x2,
+ PROCESS_ARCH_PPC = 0x4,
+ PROCESS_ARCH_PPC_64 = 0x8,
+ PROCESS_ARCH_ARM = 0x10,
+ PROCESS_ARCH_ARM_64 = 0x20
+};
+
+// A minimalistic but hopefully cross-platform set of exit codes.
+// Do not change the enumeration values or you will break third-party
+// installers.
+enum {
+ PROCESS_END_NORMAL_TERMINATON = 0,
+ PROCESS_END_KILLED_BY_USER = 1,
+ PROCESS_END_PROCESS_WAS_HUNG = 2
+};
+
+// Returns the id of the current process.
+ProcessId GetCurrentProcId();
+
+// Returns the ProcessHandle of the current process.
+ProcessHandle GetCurrentProcessHandle();
+
+// Converts a PID to a process handle. This handle must be closed by
+// CloseProcessHandle when you are done with it. Returns true on success.
+bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
+
+// Converts a PID to a process handle. On Windows the handle is opened
+// with more access rights and must only be used by trusted code.
+// You have to close returned handle using CloseProcessHandle. Returns true
+// on success.
+bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle);
+
+// Closes the process handle opened by OpenProcessHandle.
+void CloseProcessHandle(ProcessHandle process);
+
+// Returns the unique ID for the specified process. This is functionally the
+// same as Windows' GetProcessId(), but works on versions of Windows before
+// Win XP SP1 as well.
+ProcessId GetProcId(ProcessHandle process);
+
+#if defined(XP_UNIX)
+// Close all file descriptors, except for std{in,out,err} and those
+// for which the given function returns true. Only call this function
+// in a child process where you know that there aren't any other
+// threads.
+void CloseSuperfluousFds(void* aCtx, bool (*aShouldPreserve)(void*, int));
+
+typedef std::vector<std::pair<int, int> > file_handle_mapping_vector;
+typedef std::map<std::string, std::string> environment_map;
+
+// Deleter for the array of strings allocated within BuildEnvironmentArray.
+struct FreeEnvVarsArray {
+ void operator()(char** array);
+};
+
+typedef mozilla::UniquePtr<char*[], FreeEnvVarsArray> EnvironmentArray;
+#endif
+
+struct LaunchOptions {
+ // If true, wait for the process to terminate. Otherwise, return
+ // immediately.
+ bool wait = false;
+
+#if defined(XP_WIN)
+ bool start_hidden = false;
+
+ // Start as an independent process rather than a process that is closed by the
+ // parent job. This will pass the flag CREATE_BREAKAWAY_FROM_JOB.
+ bool start_independent = false;
+
+ // Environment variables to be applied in addition to the current
+ // process's environment, replacing them where necessary.
+ EnvironmentMap env_map;
+
+ std::vector<HANDLE> handles_to_inherit;
+#endif
+#if defined(XP_UNIX)
+ environment_map env_map;
+
+ // If non-null, specifies the entire environment to use for the
+ // child process, instead of inheriting from the parent; env_map is
+ // ignored in that case. Note that the strings are allocated using
+ // malloc (e.g., with strdup), but the array of pointers is
+ // allocated with new[] and is terminated with a null pointer.
+ EnvironmentArray full_env;
+
+ // If non-empty, set the child process's current working directory.
+ std::string workdir;
+
+ // A mapping of (src fd -> dest fd) to propagate into the child
+ // process. All other fds will be closed, except std{in,out,err}.
+ file_handle_mapping_vector fds_to_remap;
+#endif
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+ bool use_forkserver = false;
+#endif
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ // These fields are used by the sandboxing code in SandboxLaunch.cpp.
+ // It's not ideal to have them here, but trying to abstract them makes
+ // it harder to serialize LaunchOptions for the fork server.
+ //
+ // (fork_flags holds extra flags for the clone() syscall, and
+ // sandbox_chroot indicates whether the child process will be given
+ // the ability to chroot() itself to an empty directory.)
+ int fork_flags = 0;
+ bool sandbox_chroot = false;
+#endif
+
+#ifdef XP_DARWIN
+ // On macOS 10.14+, disclaims responsibility for the child process
+ // with respect to privacy/security permission prompts and
+ // decisions. Ignored if not supported by the OS.
+ bool disclaim = false;
+# ifdef __aarch64__
+ // The architecture to launch when launching a "universal" binary.
+ // Note: the implementation only supports launching x64 child
+ // processes from arm64 parent processes.
+ uint32_t arch = PROCESS_ARCH_INVALID;
+# endif // __aarch64__
+#endif // XP_DARWIN
+};
+
+#if defined(XP_WIN)
+// Runs the given application name with the given command line. Normally, the
+// first command line argument should be the path to the process, and don't
+// forget to quote it.
+//
+// Example (including literal quotes)
+// cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
+//
+// If process_handle is non-NULL, the process handle of the launched app will be
+// stored there on a successful launch.
+// NOTE: In this case, the caller is responsible for closing the handle so
+// that it doesn't leak!
+Result<Ok, LaunchError> LaunchApp(const std::wstring& cmdline,
+ const LaunchOptions& options,
+ ProcessHandle* process_handle);
+
+Result<Ok, LaunchError> LaunchApp(const CommandLine& cl, const LaunchOptions&,
+ ProcessHandle* process_handle);
+#else
+// Runs the application specified in argv[0] with the command line argv.
+//
+// The pid will be stored in process_handle if that pointer is
+// non-null.
+//
+// Note that the first argument in argv must point to the filename,
+// and must be fully specified (i.e., this will not search $PATH).
+Result<Ok, LaunchError> LaunchApp(const std::vector<std::string>& argv,
+ LaunchOptions&& options,
+ ProcessHandle* process_handle);
+
+// Merge an environment map with the current environment.
+// Existing variables are overwritten by env_vars_to_set.
+EnvironmentArray BuildEnvironmentArray(const environment_map& env_vars_to_set);
+#endif
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+/**
+ * Create and initialize a new process as a content process.
+ *
+ * This class is used only by the fork server.
+ * To create a new content process, two steps are
+ * - calling |ForkProcess()| to create a new process, and
+ * - calling |InitAppProcess()| in the new process, the child
+ * process, to initialize it for running WEB content later.
+ *
+ * The fork server can clean up it's resources in-between the first
+ * and second step, that is why two steps.
+ */
+class AppProcessBuilder {
+ public:
+ AppProcessBuilder();
+ // This function will fork a new process for use as a
+ // content processes.
+ bool ForkProcess(const std::vector<std::string>& argv,
+ LaunchOptions&& options, ProcessHandle* process_handle);
+ // This function will be called in the child process to initializes
+ // the environment of the content process. It should be called
+ // after the message loop of the main thread, to make sure the fork
+ // server is destroyed properly in the child process.
+ //
+ // The message loop may allocate resources like file descriptors.
+ // If this function is called before the end of the loop, the
+ // reosurces may be destroyed while the loop is still alive.
+ void InitAppProcess(int* argcp, char*** argvp);
+
+ private:
+ void ReplaceArguments(int* argcp, char*** argvp);
+
+ mozilla::ipc::FileDescriptorShuffle shuffle_;
+ std::vector<std::string> argv_;
+};
+
+void InitForkServerProcess();
+
+/**
+ * Make a FD not being closed when create a new content process.
+ *
+ * AppProcessBuilder would close most unrelated FDs for new content
+ * processes. You may want to reserve some of FDs to keep using them
+ * in content processes.
+ */
+void RegisterForkServerNoCloseFD(int aFd);
+#endif
+
+// Attempts to kill the process identified by the given process
+// entry structure, giving it the specified exit code.
+// Returns true if this is successful, false otherwise.
+bool KillProcess(ProcessHandle process, int exit_code);
+
+#ifdef XP_UNIX
+// Returns whether the given process has exited. If it returns true,
+// the process status has been consumed and `IsProcessDead` should not
+// be called again on the same process (like `waitpid`).
+//
+// In various error cases (e.g., the process doesn't exist or isn't a
+// child of this process) it will also return true to indicate that
+// the caller should give up and not try again.
+//
+// If the `blocking` parameter is set to true, this function will try
+// to block the calling thread indefinitely until the process exits.
+// This may not be possible (if the child is also being debugged by
+// the parent process, e.g. due to the crash reporter), in which case
+// it will return false and the caller will need to wait and retry.
+bool IsProcessDead(ProcessHandle handle, bool blocking = false);
+#endif
+
+} // namespace base
+
+namespace mozilla {
+
+class EnvironmentLog {
+ public:
+ template <size_t N>
+ explicit EnvironmentLog(const char (&varname)[N])
+ : EnvironmentLog(varname, N) {}
+
+ ~EnvironmentLog() {}
+
+ void print(const char* format, ...);
+
+ private:
+ explicit EnvironmentLog(const char* varname, size_t len);
+
+#if defined(XP_WIN)
+ std::wstring fname_;
+#else
+ std::string fname_;
+#endif
+
+ DISALLOW_EVIL_CONSTRUCTORS(EnvironmentLog);
+};
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+typedef std::tuple<nsCString, nsCString> EnvVar;
+typedef std::tuple<mozilla::ipc::FileDescriptor, int> FdMapping;
+#endif
+
+} // namespace mozilla
+
+#if defined(XP_WIN)
+// Undo the windows.h damage
+# undef GetMessage
+# undef CreateEvent
+# undef GetClassName
+# undef GetBinaryType
+# undef RemoveDirectory
+# undef LoadImage
+# undef LoadIcon
+#endif
+
+#endif // BASE_PROCESS_UTIL_H_
diff --git a/ipc/chromium/src/base/process_util_linux.cc b/ipc/chromium/src/base/process_util_linux.cc
new file mode 100644
index 0000000000..4ea71906f2
--- /dev/null
+++ b/ipc/chromium/src/base/process_util_linux.cc
@@ -0,0 +1,368 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/process_util.h"
+
+#include <string>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#if defined(MOZ_CODE_COVERAGE)
+# include "nsString.h"
+#endif
+
+#include "mozilla/ipc/LaunchError.h"
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxLaunch.h"
+#endif
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+# include <stdlib.h>
+# include <fcntl.h>
+# if defined(DEBUG)
+# include "base/message_loop.h"
+# endif
+# include "mozilla/ipc/ForkServiceChild.h"
+
+# include "mozilla/Unused.h"
+# include "mozilla/ScopeExit.h"
+# include "mozilla/ipc/ProcessUtils.h"
+# include "mozilla/ipc/SetProcessTitle.h"
+
+using namespace mozilla::ipc;
+#endif
+
+#if defined(MOZ_CODE_COVERAGE)
+# include "prenv.h"
+# include "mozilla/ipc/EnvironmentMap.h"
+#endif
+
+#include "base/command_line.h"
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "mozilla/ipc/FileDescriptor.h"
+#include "mozilla/ipc/FileDescriptorShuffle.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/Result.h"
+
+// WARNING: despite the name, this file is also used on the BSDs and
+// Solaris (basically, Unixes that aren't Mac OS), not just Linux.
+
+namespace {
+
+static mozilla::EnvironmentLog gProcessLog("MOZ_PROCESS_LOG");
+
+} // namespace
+
+namespace base {
+
+#if defined(MOZ_ENABLE_FORKSERVER)
+static mozilla::StaticAutoPtr<std::vector<int> > sNoCloseFDs;
+
+void RegisterForkServerNoCloseFD(int fd) {
+ if (!sNoCloseFDs) {
+ sNoCloseFDs = new std::vector<int>();
+ }
+ sNoCloseFDs->push_back(fd);
+}
+
+static bool IsNoCloseFd(int fd) {
+ if (!sNoCloseFDs) {
+ return false;
+ }
+ return std::any_of(sNoCloseFDs->begin(), sNoCloseFDs->end(),
+ [fd](int regfd) -> bool { return regfd == fd; });
+}
+
+AppProcessBuilder::AppProcessBuilder() {}
+
+static void ReplaceEnviroment(const LaunchOptions& options) {
+ for (auto& elt : options.env_map) {
+ setenv(elt.first.c_str(), elt.second.c_str(), 1);
+ }
+}
+
+bool AppProcessBuilder::ForkProcess(const std::vector<std::string>& argv,
+ LaunchOptions&& options,
+ ProcessHandle* process_handle) {
+ auto cleanFDs = mozilla::MakeScopeExit([&] {
+ for (auto& elt : options.fds_to_remap) {
+ auto fd = std::get<0>(elt);
+ close(fd);
+ }
+ });
+
+# if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ mozilla::SandboxLaunch launcher;
+ if (!launcher.Prepare(&options)) {
+ return false;
+ }
+# else
+ struct {
+ pid_t Fork() { return fork(); }
+ } launcher;
+# endif
+
+ argv_ = argv;
+ if (!shuffle_.Init(options.fds_to_remap)) {
+ return false;
+ }
+
+ // Avoid the content of the buffer being sent out by child processes
+ // repeatly.
+ fflush(stdout);
+ fflush(stderr);
+
+ pid_t pid = launcher.Fork();
+ // WARNING: if pid == 0, only async signal safe operations are permitted from
+ // here until exec or _exit.
+ //
+ // Specifically, heap allocation is not safe: the sandbox's fork substitute
+ // won't run the pthread_atfork handlers that fix up the malloc locks.
+
+ if (pid < 0) {
+ return false;
+ }
+
+ if (pid == 0) {
+ cleanFDs.release();
+ ReplaceEnviroment(options);
+ } else {
+ gProcessLog.print("==> process %d launched child process %d\n",
+ GetCurrentProcId(), pid);
+ if (options.wait) HANDLE_EINTR(waitpid(pid, 0, 0));
+ }
+
+ if (process_handle) *process_handle = pid;
+
+ return true;
+}
+
+void AppProcessBuilder::ReplaceArguments(int* argcp, char*** argvp) {
+ // Change argc & argv of main() with the arguments passing
+ // through IPC.
+ char** argv = new char*[argv_.size() + 1];
+ char** p = argv;
+ for (auto& elt : argv_) {
+ *p++ = strdup(elt.c_str());
+ }
+ *p = nullptr;
+ *argvp = argv;
+ *argcp = argv_.size();
+ mozilla::SetProcessTitle(argv_);
+}
+
+void AppProcessBuilder::InitAppProcess(int* argcp, char*** argvp) {
+ MOZ_ASSERT(MessageLoop::current() == nullptr,
+ "The message loop of the main thread should have been destroyed");
+
+ // The fork server handle SIGCHLD to read status of content
+ // processes to handle Zombies. But, it is not necessary for
+ // content processes.
+ signal(SIGCHLD, SIG_DFL);
+
+ for (const auto& fds : shuffle_.Dup2Sequence()) {
+ int fd = HANDLE_EINTR(dup2(fds.first, fds.second));
+ MOZ_RELEASE_ASSERT(fd == fds.second, "dup2 failed");
+ }
+
+ CloseSuperfluousFds(&shuffle_, [](void* ctx, int fd) {
+ return static_cast<decltype(&shuffle_)>(ctx)->MapsTo(fd) || IsNoCloseFd(fd);
+ });
+ // Without this, the destructor of |shuffle_| would try to close FDs
+ // created by it, but they have been closed by
+ // |CloseSuperfluousFds()|.
+ shuffle_.Forget();
+
+ ReplaceArguments(argcp, argvp);
+}
+
+static void InstallChildSignalHandler() {
+ // Eventually (bug 1752638) we'll want a real SIGCHLD handler, but
+ // for now, cause child processes to be automatically collected.
+ signal(SIGCHLD, SIG_IGN);
+}
+
+static void ReserveFileDescriptors() {
+ // Reserve the lower positions of the file descriptors to make sure
+ // debug files and other files don't take these positions. So we
+ // can keep their file descriptors during CloseSuperfluousFds() with
+ // out any confliction with mapping passing from the parent process.
+ int fd = open("/dev/null", O_RDONLY);
+ for (int i = 1; i < 10; i++) {
+ mozilla::Unused << dup(fd);
+ }
+}
+
+void InitForkServerProcess() {
+ InstallChildSignalHandler();
+ ReserveFileDescriptors();
+ SetThisProcessName("forkserver");
+}
+
+static Result<Ok, LaunchError> LaunchAppWithForkServer(
+ const std::vector<std::string>& argv, const LaunchOptions& options,
+ ProcessHandle* process_handle) {
+ MOZ_ASSERT(ForkServiceChild::Get());
+
+ // Check for unsupported options
+ MOZ_ASSERT(options.workdir.empty());
+ MOZ_ASSERT(!options.full_env);
+ MOZ_ASSERT(!options.wait);
+
+ ForkServiceChild::Args forkArgs;
+
+# if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ forkArgs.mForkFlags = options.fork_flags;
+ forkArgs.mChroot = options.sandbox_chroot;
+# endif
+
+ for (auto& arg : argv) {
+ forkArgs.mArgv.AppendElement(arg.c_str());
+ }
+ for (auto& vv : options.env_map) {
+ forkArgs.mEnv.AppendElement(mozilla::EnvVar(nsCString(vv.first.c_str()),
+ nsCString(vv.second.c_str())));
+ }
+ for (auto& fdmapping : options.fds_to_remap) {
+ forkArgs.mFdsRemap.AppendElement(mozilla::FdMapping(
+ mozilla::ipc::FileDescriptor(fdmapping.first), fdmapping.second));
+ }
+
+ return ForkServiceChild::Get()->SendForkNewSubprocess(forkArgs,
+ process_handle);
+}
+#endif // MOZ_ENABLE_FORKSERVER
+
+Result<Ok, LaunchError> LaunchApp(const std::vector<std::string>& argv,
+ LaunchOptions&& options,
+ ProcessHandle* process_handle) {
+#if defined(MOZ_ENABLE_FORKSERVER)
+ if (options.use_forkserver && ForkServiceChild::Get()) {
+ return LaunchAppWithForkServer(argv, options, process_handle);
+ }
+#endif
+
+ mozilla::UniquePtr<char*[]> argv_cstr(new char*[argv.size() + 1]);
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ mozilla::SandboxLaunch launcher;
+ if (!launcher.Prepare(&options)) {
+ return Err(LaunchError("SL::Prepare", errno));
+ }
+#else
+ struct {
+ pid_t Fork() { return fork(); }
+ } launcher;
+#endif
+
+ EnvironmentArray env_storage;
+ const EnvironmentArray& envp =
+ options.full_env ? options.full_env
+ : (env_storage = BuildEnvironmentArray(options.env_map));
+
+ // Init() there will call fcntl(F_DUPFD/F_DUPFD_CLOEXEC) under the hood in
+ // https://searchfox.org/mozilla-central/rev/55d5c4b9dffe5e59eb6b019c1a930ec9ada47e10/ipc/glue/FileDescriptorShuffle.cpp#72
+ // so it will set errno.
+ mozilla::ipc::FileDescriptorShuffle shuffle;
+ if (!shuffle.Init(options.fds_to_remap)) {
+ CHROMIUM_LOG(WARNING) << "FileDescriptorShuffle::Init failed";
+ return Err(LaunchError("FileDescriptorShuffle", errno));
+ }
+
+#ifdef MOZ_CODE_COVERAGE
+ // Before gcc/clang 10 there is a gcda dump before the fork.
+ // This dump mustn't be interrupted by a SIGUSR1 else we may
+ // have a dead lock (see bug 1637377).
+ // So we just remove the handler and restore it after the fork
+ // It's up the child process to set it up.
+ // Once we switch to gcc/clang 10, we could just remove it in the child
+ // process
+ void (*ccovSigHandler)(int) = signal(SIGUSR1, SIG_IGN);
+ const char* gcov_child_prefix = PR_GetEnv("GCOV_CHILD_PREFIX");
+#endif
+
+ pid_t pid = launcher.Fork();
+ // WARNING: if pid == 0, only async signal safe operations are permitted from
+ // here until exec or _exit.
+ //
+ // Specifically, heap allocation is not safe: the sandbox's fork substitute
+ // won't run the pthread_atfork handlers that fix up the malloc locks.
+
+ if (pid < 0) {
+ CHROMIUM_LOG(WARNING) << "fork() failed: " << strerror(errno);
+ return Err(LaunchError("fork", errno));
+ }
+
+ if (pid == 0) {
+ // In the child:
+ if (!options.workdir.empty()) {
+ if (chdir(options.workdir.c_str()) != 0) {
+ // See under execve about logging unsafety.
+ DLOG(ERROR) << "chdir failed " << options.workdir;
+ _exit(127);
+ }
+ }
+
+ for (const auto& fds : shuffle.Dup2Sequence()) {
+ if (HANDLE_EINTR(dup2(fds.first, fds.second)) != fds.second) {
+ // This shouldn't happen, but check for it. And see below
+ // about logging being unsafe here, so this is debug only.
+ DLOG(ERROR) << "dup2 failed";
+ _exit(127);
+ }
+ }
+
+ CloseSuperfluousFds(&shuffle, [](void* aCtx, int aFd) {
+ return static_cast<decltype(&shuffle)>(aCtx)->MapsTo(aFd);
+ });
+
+ for (size_t i = 0; i < argv.size(); i++)
+ argv_cstr[i] = const_cast<char*>(argv[i].c_str());
+ argv_cstr[argv.size()] = NULL;
+
+#ifdef MOZ_CODE_COVERAGE
+ if (gcov_child_prefix && !options.full_env) {
+ const pid_t child_pid = getpid();
+ nsAutoCString new_gcov_prefix(gcov_child_prefix);
+ new_gcov_prefix.Append(std::to_string((size_t)child_pid));
+ EnvironmentMap new_map = options.env_map;
+ new_map[ENVIRONMENT_LITERAL("GCOV_PREFIX")] =
+ ENVIRONMENT_STRING(new_gcov_prefix.get());
+ // FIXME(bug 1783305): this won't work if full_env is set, and
+ // in general this block of code is doing things it shouldn't
+ // be (async signal unsafety).
+ env_storage = BuildEnvironmentArray(new_map);
+ }
+#endif
+
+ execve(argv_cstr[0], argv_cstr.get(), envp.get());
+ // if we get here, we're in serious trouble and should complain loudly
+ // NOTE: This is async signal unsafe; it could deadlock instead. (But
+ // only on debug builds; otherwise it's a signal-safe no-op.)
+ DLOG(ERROR) << "FAILED TO exec() CHILD PROCESS, path: " << argv_cstr[0];
+ _exit(127);
+ }
+
+ // In the parent:
+
+#ifdef MOZ_CODE_COVERAGE
+ // Restore the handler for SIGUSR1
+ signal(SIGUSR1, ccovSigHandler);
+#endif
+
+ gProcessLog.print("==> process %d launched child process %d\n",
+ GetCurrentProcId(), pid);
+ if (options.wait) HANDLE_EINTR(waitpid(pid, 0, 0));
+
+ if (process_handle) *process_handle = pid;
+
+ return Ok();
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/process_util_mac.mm b/ipc/chromium/src/base/process_util_mac.mm
new file mode 100644
index 0000000000..d3c91ee362
--- /dev/null
+++ b/ipc/chromium/src/base/process_util_mac.mm
@@ -0,0 +1,167 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/process_util.h"
+
+#include <fcntl.h>
+#include <os/availability.h>
+#include <spawn.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <string>
+
+#include "base/command_line.h"
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "mozilla/ipc/FileDescriptorShuffle.h"
+#include "mozilla/ScopeExit.h"
+#include "mozilla/Result.h"
+
+#include "mozilla/ipc/LaunchError.h"
+
+extern "C" {
+// N.B. the syscalls are available back to 10.5, but the C wrappers
+// only in 10.12. Fortunately, 10.15 is our current baseline.
+int pthread_fchdir_np(int fd) API_AVAILABLE(macosx(10.12));
+
+int responsibility_spawnattrs_setdisclaim(posix_spawnattr_t attrs, int disclaim)
+ API_AVAILABLE(macosx(10.14));
+}
+
+namespace {
+
+static mozilla::EnvironmentLog gProcessLog("MOZ_PROCESS_LOG");
+
+} // namespace
+
+namespace base {
+
+Result<Ok, LaunchError> LaunchApp(const std::vector<std::string>& argv,
+ LaunchOptions&& options,
+ ProcessHandle* process_handle) {
+ Result<Ok, LaunchError> retval = Ok();
+
+ char* argv_copy[argv.size() + 1];
+ for (size_t i = 0; i < argv.size(); i++) {
+ argv_copy[i] = const_cast<char*>(argv[i].c_str());
+ }
+ argv_copy[argv.size()] = NULL;
+
+ EnvironmentArray env_storage;
+ const EnvironmentArray& vars =
+ options.full_env ? options.full_env
+ : (env_storage = BuildEnvironmentArray(options.env_map));
+
+ posix_spawn_file_actions_t file_actions;
+ int err = posix_spawn_file_actions_init(&file_actions);
+ if (err != 0) {
+ DLOG(WARNING) << "posix_spawn_file_actions_init failed";
+ return Err(LaunchError("posix_spawn_file_actions_init", err));
+ }
+ auto file_actions_guard = mozilla::MakeScopeExit(
+ [&file_actions] { posix_spawn_file_actions_destroy(&file_actions); });
+
+ // Turn fds_to_remap array into a set of dup2 calls.
+ //
+ // Init() there will call fcntl(F_DUPFD/F_DUPFD_CLOEXEC) under the hood in
+ // https://searchfox.org/mozilla-central/rev/55d5c4b9dffe5e59eb6b019c1a930ec9ada47e10/ipc/glue/FileDescriptorShuffle.cpp#72
+ // so it will set errno.
+ mozilla::ipc::FileDescriptorShuffle shuffle;
+ if (!shuffle.Init(options.fds_to_remap)) {
+ DLOG(WARNING) << "FileDescriptorShuffle::Init failed";
+ return Err(LaunchError("FileDescriptorShuffle", errno));
+ }
+ for (const auto& fd_map : shuffle.Dup2Sequence()) {
+ int src_fd = fd_map.first;
+ int dest_fd = fd_map.second;
+
+ int rv = posix_spawn_file_actions_adddup2(&file_actions, src_fd, dest_fd);
+ if (rv != 0) {
+ DLOG(WARNING) << "posix_spawn_file_actions_adddup2 failed";
+ return Err(LaunchError("posix_spawn_file_actions_adddup2", rv));
+ }
+ }
+
+ if (!options.workdir.empty()) {
+ int rv = posix_spawn_file_actions_addchdir_np(&file_actions,
+ options.workdir.c_str());
+ if (rv != 0) {
+ DLOG(WARNING) << "posix_spawn_file_actions_addchdir_np failed";
+ return Err(LaunchError("posix_spawn_file_actions_addchdir", rv));
+ }
+ }
+
+ // Initialize spawn attributes.
+ posix_spawnattr_t spawnattr;
+ err = posix_spawnattr_init(&spawnattr);
+ if (err != 0) {
+ DLOG(WARNING) << "posix_spawnattr_init failed";
+ return Err(LaunchError("posix_spawnattr_init", err));
+ }
+ auto spawnattr_guard = mozilla::MakeScopeExit(
+ [&spawnattr] { posix_spawnattr_destroy(&spawnattr); });
+
+#if defined(XP_MACOSX) && defined(__aarch64__)
+ if (options.arch == PROCESS_ARCH_X86_64) {
+ cpu_type_t cpu_pref = CPU_TYPE_X86_64;
+ size_t count = 1;
+ size_t ocount = 0;
+ int rv =
+ posix_spawnattr_setbinpref_np(&spawnattr, count, &cpu_pref, &ocount);
+ if ((rv != 0) || (ocount != count)) {
+ DLOG(WARNING) << "posix_spawnattr_setbinpref_np failed";
+ return Err(LaunchError("posix_spawnattr_setbinpref_np", rv));
+ }
+ }
+#endif
+
+ if (options.disclaim) {
+ int err = responsibility_spawnattrs_setdisclaim(&spawnattr, 1);
+ if (err != 0) {
+ DLOG(WARNING) << "responsibility_spawnattrs_setdisclaim failed";
+ return Err(LaunchError("responsibility_spawnattrs_setdisclaim", err));
+ }
+ }
+
+ // Prevent the child process from inheriting any file descriptors
+ // that aren't named in `file_actions`. (This is an Apple-specific
+ // extension to posix_spawn.)
+ err = posix_spawnattr_setflags(&spawnattr, POSIX_SPAWN_CLOEXEC_DEFAULT);
+ if (err != 0) {
+ DLOG(WARNING) << "posix_spawnattr_setflags failed";
+ return Err(LaunchError("posix_spawnattr_setflags", err));
+ }
+
+ // Exempt std{in,out,err} from being closed by POSIX_SPAWN_CLOEXEC_DEFAULT.
+ for (int fd = 0; fd <= STDERR_FILENO; ++fd) {
+ err = posix_spawn_file_actions_addinherit_np(&file_actions, fd);
+ if (err != 0) {
+ DLOG(WARNING) << "posix_spawn_file_actions_addinherit_np failed";
+ return Err(LaunchError("posix_spawn_file_actions_addinherit_np", err));
+ }
+ }
+
+ int pid = 0;
+ int spawn_succeeded = (posix_spawnp(&pid, argv_copy[0], &file_actions,
+ &spawnattr, argv_copy, vars.get()) == 0);
+
+ bool process_handle_valid = pid > 0;
+ if (!spawn_succeeded || !process_handle_valid) {
+ DLOG(WARNING) << "posix_spawnp failed";
+ retval = Err(LaunchError("posix_spawnp", spawn_succeeded));
+ } else {
+ gProcessLog.print("==> process %d launched child process %d\n",
+ GetCurrentProcId(), pid);
+ if (options.wait) HANDLE_EINTR(waitpid(pid, 0, 0));
+
+ if (process_handle) *process_handle = pid;
+ }
+
+ return retval;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/process_util_posix.cc b/ipc/chromium/src/base/process_util_posix.cc
new file mode 100644
index 0000000000..3229570ad8
--- /dev/null
+++ b/ipc/chromium/src/base/process_util_posix.cc
@@ -0,0 +1,388 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include <limits>
+#include <set>
+
+#include "base/basictypes.h"
+#include "base/command_line.h"
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/platform_thread.h"
+#include "base/process_util.h"
+#include "base/time.h"
+#include "base/waitable_event.h"
+#include "base/dir_reader_posix.h"
+
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Unused.h"
+// For PR_DuplicateEnvironment:
+#include "prenv.h"
+#include "prmem.h"
+
+#ifdef MOZ_ENABLE_FORKSERVER
+# include "mozilla/ipc/ForkServiceChild.h"
+#endif
+
+// We could configure-test for `waitid`, but it's been in POSIX for a
+// long time and OpenBSD seems to be the only Unix we target that
+// doesn't have it. Note that `waitid` is used to resolve a conflict
+// with the crash reporter, which isn't available on OpenBSD.
+#ifndef __OpenBSD__
+# define HAVE_WAITID
+#endif
+
+namespace base {
+
+ProcessId GetCurrentProcId() { return getpid(); }
+
+ProcessHandle GetCurrentProcessHandle() { return GetCurrentProcId(); }
+
+bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
+ // On Posix platforms, process handles are the same as PIDs, so we
+ // don't need to do anything.
+ *handle = pid;
+ return true;
+}
+
+bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
+ // On POSIX permissions are checked for each operation on process,
+ // not when opening a "handle".
+ return OpenProcessHandle(pid, handle);
+}
+
+void CloseProcessHandle(ProcessHandle process) {
+ // See OpenProcessHandle, nothing to do.
+ return;
+}
+
+ProcessId GetProcId(ProcessHandle process) { return process; }
+
+// Attempts to kill the process identified by the given process
+// entry structure. Ignores specified exit_code; posix can't force that.
+// Returns true if this is successful, false otherwise.
+bool KillProcess(ProcessHandle process_id, int exit_code) {
+ // It's too easy to accidentally kill pid 0 (meaning the caller's
+ // process group) or pid -1 (all other processes killable by this
+ // user), and neither they nor other negative numbers (process
+ // groups) are legitimately used by this function's callers, so
+ // reject them all.
+ if (process_id <= 0) {
+ CHROMIUM_LOG(WARNING) << "base::KillProcess refusing to kill pid "
+ << process_id;
+ return false;
+ }
+
+ bool result = kill(process_id, SIGTERM) == 0;
+
+ if (!result && (errno == ESRCH)) {
+ result = true;
+ }
+
+ if (!result) DLOG(ERROR) << "Unable to terminate process.";
+
+ return result;
+}
+
+#ifdef ANDROID
+typedef unsigned long int rlim_t;
+#endif
+
+// A class to handle auto-closing of DIR*'s.
+class ScopedDIRClose {
+ public:
+ inline void operator()(DIR* x) const {
+ if (x) {
+ closedir(x);
+ }
+ }
+};
+typedef mozilla::UniquePtr<DIR, ScopedDIRClose> ScopedDIR;
+
+void CloseSuperfluousFds(void* aCtx, bool (*aShouldPreserve)(void*, int)) {
+ // DANGER: no calls to malloc (or locks, etc.) are allowed from now on:
+ // https://crbug.com/36678
+ // Also, beware of STL iterators: https://crbug.com/331459
+#if defined(ANDROID)
+ static const rlim_t kSystemDefaultMaxFds = 1024;
+ static const char kFDDir[] = "/proc/self/fd";
+#elif defined(XP_LINUX) || defined(XP_SOLARIS)
+ static const rlim_t kSystemDefaultMaxFds = 8192;
+ static const char kFDDir[] = "/proc/self/fd";
+#elif defined(XP_DARWIN)
+ static const rlim_t kSystemDefaultMaxFds = 256;
+ static const char kFDDir[] = "/dev/fd";
+#elif defined(__DragonFly__) || defined(XP_FREEBSD) || defined(XP_NETBSD) || \
+ defined(XP_OPENBSD)
+ // the getrlimit below should never fail, so whatever ..
+ static const rlim_t kSystemDefaultMaxFds = 1024;
+ // at least /dev/fd will exist
+ static const char kFDDir[] = "/dev/fd";
+#endif
+
+ // Get the maximum number of FDs possible.
+ struct rlimit nofile;
+ rlim_t max_fds;
+ if (getrlimit(RLIMIT_NOFILE, &nofile)) {
+ // getrlimit failed. Take a best guess.
+ max_fds = kSystemDefaultMaxFds;
+ DLOG(ERROR) << "getrlimit(RLIMIT_NOFILE) failed: " << errno;
+ } else {
+ max_fds = nofile.rlim_cur;
+ }
+
+ if (max_fds > INT_MAX) max_fds = INT_MAX;
+
+ DirReaderPosix fd_dir(kFDDir);
+
+ if (!fd_dir.IsValid()) {
+ // Fallback case: Try every possible fd.
+ for (rlim_t i = 0; i < max_fds; ++i) {
+ const int fd = static_cast<int>(i);
+ if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO ||
+ aShouldPreserve(aCtx, fd)) {
+ continue;
+ }
+
+ // Since we're just trying to close anything we can find,
+ // ignore any error return values of close().
+ close(fd);
+ }
+ return;
+ }
+
+ const int dir_fd = fd_dir.fd();
+
+ for (; fd_dir.Next();) {
+ // Skip . and .. entries.
+ if (fd_dir.name()[0] == '.') continue;
+
+ char* endptr;
+ errno = 0;
+ const long int fd = strtol(fd_dir.name(), &endptr, 10);
+ if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno) continue;
+ if (fd == dir_fd) continue;
+ if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO ||
+ aShouldPreserve(aCtx, fd)) {
+ continue;
+ }
+
+ // When running under Valgrind, Valgrind opens several FDs for its
+ // own use and will complain if we try to close them. All of
+ // these FDs are >= |max_fds|, so we can check against that here
+ // before closing. See https://bugs.kde.org/show_bug.cgi?id=191758
+ if (fd < static_cast<int>(max_fds)) {
+ int ret = IGNORE_EINTR(close(fd));
+ if (ret != 0) {
+ DLOG(ERROR) << "Problem closing fd";
+ }
+ }
+ }
+}
+
+bool IsProcessDead(ProcessHandle handle, bool blocking) {
+ auto handleForkServer = [handle]() -> mozilla::Maybe<bool> {
+#ifdef MOZ_ENABLE_FORKSERVER
+ if (errno == ECHILD && mozilla::ipc::ForkServiceChild::Get()) {
+ // We only know if a process exists, but not if it has crashed.
+ //
+ // Since content processes are not direct children of the chrome
+ // process any more, it is impossible to use |waitpid()| to wait for
+ // them.
+ const int r = kill(handle, 0);
+ // FIXME: for unexpected errors we should probably log a warning
+ // and return true, so that the caller doesn't loop / hang /
+ // try to kill the process. (Bug 1658072 will rewrite this code.)
+ return mozilla::Some(r < 0 && errno == ESRCH);
+ }
+#else
+ mozilla::Unused << handle;
+#endif
+ return mozilla::Nothing();
+ };
+
+#ifdef HAVE_WAITID
+
+ // We use `WNOWAIT` to read the process status without
+ // side-effecting it, in case it's something unexpected like a
+ // ptrace-stop for the crash reporter. If is an exit, the call is
+ // reissued (see the end of this function) without that flag in
+ // order to collect the process.
+ siginfo_t si{};
+ const int wflags = WEXITED | WNOWAIT | (blocking ? 0 : WNOHANG);
+ int result = HANDLE_EINTR(waitid(P_PID, handle, &si, wflags));
+ if (result == -1) {
+ if (auto forkServerReturn = handleForkServer()) {
+ return *forkServerReturn;
+ }
+
+ // This shouldn't happen, but sometimes it does. The error is
+ // probably ECHILD and the reason is probably that a pid was
+ // waited on again after a previous wait reclaimed its zombie.
+ // (It could also occur if the process isn't a direct child, but
+ // don't do that.) This is bad, because it risks interfering with
+ // an unrelated child process if the pid is reused.
+ //
+ // So, lacking reliable information, we indicate that the process
+ // is dead, in the hope that the caller will give up and stop
+ // calling us. See also bug 943174 and bug 933680.
+ CHROMIUM_LOG(ERROR) << "waitid failed pid:" << handle << " errno:" << errno;
+ return true;
+ }
+
+ if (si.si_pid == 0) {
+ // the child hasn't exited yet.
+ return false;
+ }
+
+ DCHECK(si.si_pid == handle);
+ switch (si.si_code) {
+ case CLD_STOPPED:
+ case CLD_CONTINUED:
+ DCHECK(false) << "waitid returned an event type that it shouldn't have";
+ [[fallthrough]];
+ case CLD_TRAPPED:
+ CHROMIUM_LOG(WARNING) << "ignoring non-exit event for process " << handle;
+ return false;
+
+ case CLD_KILLED:
+ case CLD_DUMPED:
+ CHROMIUM_LOG(WARNING)
+ << "process " << handle << " exited on signal " << si.si_status;
+ break;
+
+ case CLD_EXITED:
+ if (si.si_status != 0) {
+ CHROMIUM_LOG(WARNING)
+ << "process " << handle << " exited with status " << si.si_status;
+ }
+ break;
+
+ default:
+ CHROMIUM_LOG(ERROR) << "unexpected waitid si_code value: " << si.si_code;
+ DCHECK(false);
+ // This shouldn't happen, but assume that the process exited to
+ // avoid the caller possibly ending up in a loop.
+ }
+
+ // Now consume the status / collect the dead process
+ const int old_si_code = si.si_code;
+ si.si_pid = 0;
+ // In theory it shouldn't matter either way if we use `WNOHANG` at
+ // this point, but just in case, avoid unexpected blocking.
+ result = HANDLE_EINTR(waitid(P_PID, handle, &si, WEXITED | WNOHANG));
+ DCHECK(result == 0);
+ DCHECK(si.si_pid == handle);
+ DCHECK(si.si_code == old_si_code);
+ return true;
+
+#else // no waitid
+
+ int status;
+ const int result = waitpid(handle, &status, blocking ? 0 : WNOHANG);
+ if (result == -1) {
+ if (auto forkServerReturn = handleForkServer()) {
+ return *forkServerReturn;
+ }
+
+ CHROMIUM_LOG(ERROR) << "waitpid failed pid:" << handle
+ << " errno:" << errno;
+ return true;
+ }
+ if (result == 0) {
+ return false;
+ }
+
+ if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
+ CHROMIUM_LOG(WARNING) << "process " << handle << " exited with status "
+ << WEXITSTATUS(status);
+ } else if (WIFSIGNALED(status)) {
+ CHROMIUM_LOG(WARNING) << "process " << handle << " exited on signal "
+ << WTERMSIG(status);
+ }
+ return true;
+
+#endif // waitid
+}
+
+void FreeEnvVarsArray::operator()(char** array) {
+ for (char** varPtr = array; *varPtr != nullptr; ++varPtr) {
+ free(*varPtr);
+ }
+ delete[] array;
+}
+
+EnvironmentArray BuildEnvironmentArray(const environment_map& env_vars_to_set) {
+ base::environment_map combined_env_vars = env_vars_to_set;
+ char** environ = PR_DuplicateEnvironment();
+ for (char** varPtr = environ; *varPtr != nullptr; ++varPtr) {
+ std::string varString = *varPtr;
+ size_t equalPos = varString.find_first_of('=');
+ std::string varName = varString.substr(0, equalPos);
+ std::string varValue = varString.substr(equalPos + 1);
+ if (combined_env_vars.find(varName) == combined_env_vars.end()) {
+ combined_env_vars[varName] = varValue;
+ }
+ PR_Free(*varPtr); // PR_DuplicateEnvironment() uses PR_Malloc().
+ }
+ PR_Free(environ); // PR_DuplicateEnvironment() uses PR_Malloc().
+
+ EnvironmentArray array(new char*[combined_env_vars.size() + 1]);
+ size_t i = 0;
+ for (const auto& key_val : combined_env_vars) {
+ std::string entry(key_val.first);
+ entry += "=";
+ entry += key_val.second;
+ array[i] = strdup(entry.c_str());
+ i++;
+ }
+ array[i] = nullptr;
+ return array;
+}
+
+} // namespace base
+
+namespace mozilla {
+
+EnvironmentLog::EnvironmentLog(const char* varname, size_t len) {
+ const char* e = getenv(varname);
+ if (e && *e) {
+ fname_ = e;
+ }
+}
+
+void EnvironmentLog::print(const char* format, ...) {
+ if (!fname_.size()) return;
+
+ FILE* f;
+ if (fname_.compare("-") == 0) {
+ f = fdopen(dup(STDOUT_FILENO), "a");
+ } else {
+ f = fopen(fname_.c_str(), "a");
+ }
+
+ if (!f) return;
+
+ va_list a;
+ va_start(a, format);
+ vfprintf(f, format, a);
+ va_end(a);
+ fclose(f);
+}
+
+} // namespace mozilla
diff --git a/ipc/chromium/src/base/process_util_win.cc b/ipc/chromium/src/base/process_util_win.cc
new file mode 100644
index 0000000000..338917ef98
--- /dev/null
+++ b/ipc/chromium/src/base/process_util_win.cc
@@ -0,0 +1,392 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#include "base/process_util.h"
+
+#include <windows.h>
+#include <winternl.h>
+#include <psapi.h>
+#include <io.h>
+#ifndef STDOUT_FILENO
+# define STDOUT_FILENO 1
+#endif
+
+#include "base/command_line.h"
+#include "base/histogram.h"
+#include "base/logging.h"
+#include "base/win_util.h"
+
+#include "mozilla/ipc/LaunchError.h"
+#include "mozilla/Result.h"
+
+#include <algorithm>
+#include <stdio.h>
+#include <stdlib.h>
+
+namespace {
+
+typedef BOOL(WINAPI* InitializeProcThreadAttributeListFn)(
+ LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwAttributeCount,
+ DWORD dwFlags, PSIZE_T lpSize);
+
+typedef BOOL(WINAPI* DeleteProcThreadAttributeListFn)(
+ LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList);
+
+typedef BOOL(WINAPI* UpdateProcThreadAttributeFn)(
+ LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, DWORD dwFlags,
+ DWORD_PTR Attribute, PVOID lpValue, SIZE_T cbSize, PVOID lpPreviousValue,
+ PSIZE_T lpReturnSize);
+
+static InitializeProcThreadAttributeListFn InitializeProcThreadAttributeListPtr;
+static DeleteProcThreadAttributeListFn DeleteProcThreadAttributeListPtr;
+static UpdateProcThreadAttributeFn UpdateProcThreadAttributePtr;
+
+static mozilla::EnvironmentLog gProcessLog("MOZ_PROCESS_LOG");
+
+} // namespace
+
+namespace base {
+
+ProcessId GetCurrentProcId() { return ::GetCurrentProcessId(); }
+
+ProcessHandle GetCurrentProcessHandle() { return ::GetCurrentProcess(); }
+
+bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
+ // TODO(phajdan.jr): Take even more permissions out of this list.
+ ProcessHandle result =
+ OpenProcess(PROCESS_DUP_HANDLE | PROCESS_TERMINATE |
+ PROCESS_QUERY_INFORMATION | SYNCHRONIZE,
+ FALSE, pid);
+
+ if (result == NULL) {
+ return false;
+ }
+
+ *handle = result;
+ return true;
+}
+
+bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
+ ProcessHandle result =
+ OpenProcess(PROCESS_DUP_HANDLE | PROCESS_TERMINATE |
+ PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE,
+ FALSE, pid);
+
+ if (result == NULL) {
+ return false;
+ }
+
+ *handle = result;
+ return true;
+}
+
+void CloseProcessHandle(ProcessHandle process) {
+ // closing a handle twice on Windows can be catastrophic - after the first
+ // close the handle value may be reused, so the second close will kill that
+ // other new handle.
+ BOOL ok = CloseHandle(process);
+ DCHECK(ok);
+}
+
+ProcessId GetProcId(ProcessHandle process) {
+ if (process == base::kInvalidProcessHandle || process == nullptr) {
+ return 0;
+ }
+ // This returns 0 if we have insufficient rights to query the process handle.
+ // Invalid handles or non-process handles will cause a diagnostic assert.
+ ProcessId result = GetProcessId(process);
+#ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
+ CHECK(result != 0 || GetLastError() != ERROR_INVALID_HANDLE)
+ << "process handle = " << process;
+#endif
+ return result;
+}
+
+// from sandbox_policy_base.cc in a later version of the chromium ipc code...
+bool IsInheritableHandle(HANDLE handle) {
+ if (!handle) return false;
+ if (handle == INVALID_HANDLE_VALUE) return false;
+ // File handles (FILE_TYPE_DISK) and pipe handles are known to be
+ // inheritable. Console handles (FILE_TYPE_CHAR) are not
+ // inheritable via PROC_THREAD_ATTRIBUTE_HANDLE_LIST.
+ DWORD handle_type = GetFileType(handle);
+ return handle_type == FILE_TYPE_DISK || handle_type == FILE_TYPE_PIPE;
+}
+
+void LoadThreadAttributeFunctions() {
+ HMODULE kernel32 = GetModuleHandle(L"kernel32.dll");
+ InitializeProcThreadAttributeListPtr =
+ reinterpret_cast<InitializeProcThreadAttributeListFn>(
+ GetProcAddress(kernel32, "InitializeProcThreadAttributeList"));
+ DeleteProcThreadAttributeListPtr =
+ reinterpret_cast<DeleteProcThreadAttributeListFn>(
+ GetProcAddress(kernel32, "DeleteProcThreadAttributeList"));
+ UpdateProcThreadAttributePtr = reinterpret_cast<UpdateProcThreadAttributeFn>(
+ GetProcAddress(kernel32, "UpdateProcThreadAttribute"));
+}
+
+// Creates and returns a "thread attribute list" to pass to the child process.
+// On return, is a pointer to a THREAD_ATTRIBUTE_LIST or NULL if either the
+// functions we need aren't available (eg, XP or earlier) or the functions we
+// need failed.
+// The result of this function must be passed to FreeThreadAttributeList.
+// Note that the pointer to the HANDLE array ends up embedded in the result of
+// this function and must stay alive until FreeThreadAttributeList is called,
+// hence it is passed in so the owner is the caller of this function.
+LPPROC_THREAD_ATTRIBUTE_LIST CreateThreadAttributeList(HANDLE* handlesToInherit,
+ int handleCount) {
+ if (!InitializeProcThreadAttributeListPtr ||
+ !DeleteProcThreadAttributeListPtr || !UpdateProcThreadAttributePtr)
+ LoadThreadAttributeFunctions();
+ // shouldn't happen as we are only called for Vista+, but better safe than
+ // sorry...
+ if (!InitializeProcThreadAttributeListPtr ||
+ !DeleteProcThreadAttributeListPtr || !UpdateProcThreadAttributePtr)
+ return NULL;
+
+ SIZE_T threadAttrSize;
+ LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList = NULL;
+
+ if (!(*InitializeProcThreadAttributeListPtr)(NULL, 1, 0, &threadAttrSize) &&
+ GetLastError() != ERROR_INSUFFICIENT_BUFFER)
+ goto fail;
+ lpAttributeList =
+ reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(malloc(threadAttrSize));
+ if (!lpAttributeList || !(*InitializeProcThreadAttributeListPtr)(
+ lpAttributeList, 1, 0, &threadAttrSize))
+ goto fail;
+
+ if (!(*UpdateProcThreadAttributePtr)(
+ lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
+ handlesToInherit, sizeof(handlesToInherit[0]) * handleCount, NULL,
+ NULL)) {
+ (*DeleteProcThreadAttributeListPtr)(lpAttributeList);
+ goto fail;
+ }
+ return lpAttributeList;
+
+fail:
+ if (lpAttributeList) free(lpAttributeList);
+ return NULL;
+}
+
+// Frees the data returned by CreateThreadAttributeList.
+void FreeThreadAttributeList(LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList) {
+ // must be impossible to get a NULL DeleteProcThreadAttributeListPtr, as
+ // we already checked it existed when creating the data we are now freeing.
+ (*DeleteProcThreadAttributeListPtr)(lpAttributeList);
+ free(lpAttributeList);
+}
+
+// The next two functions are from chromium/base/environment.cc
+//
+// Parses a null-terminated input string of an environment block. The key is
+// placed into the given string, and the total length of the line, including
+// the terminating null, is returned.
+static size_t ParseEnvLine(const NativeEnvironmentString::value_type* input,
+ NativeEnvironmentString* key) {
+ // Skip to the equals or end of the string, this is the key.
+ size_t cur = 0;
+ while (input[cur] && input[cur] != '=') cur++;
+ *key = NativeEnvironmentString(&input[0], cur);
+
+ // Now just skip to the end of the string.
+ while (input[cur]) cur++;
+ return cur + 1;
+}
+
+std::wstring AlterEnvironment(const wchar_t* env,
+ const EnvironmentMap& changes) {
+ std::wstring result;
+
+ // First copy all unmodified values to the output.
+ size_t cur_env = 0;
+ std::wstring key;
+ while (env[cur_env]) {
+ const wchar_t* line = &env[cur_env];
+ size_t line_length = ParseEnvLine(line, &key);
+
+ // Keep only values not specified in the change vector.
+ EnvironmentMap::const_iterator found_change = changes.find(key);
+ if (found_change == changes.end()) result.append(line, line_length);
+
+ cur_env += line_length;
+ }
+
+ // Now append all modified and new values.
+ for (EnvironmentMap::const_iterator i = changes.begin(); i != changes.end();
+ ++i) {
+ if (!i->second.empty()) {
+ result.append(i->first);
+ result.push_back('=');
+ result.append(i->second);
+ result.push_back(0);
+ }
+ }
+
+ // An additional null marks the end of the list. We always need a double-null
+ // in case nothing was added above.
+ if (result.empty()) result.push_back(0);
+ result.push_back(0);
+ return result;
+}
+
+Result<Ok, LaunchError> LaunchApp(const std::wstring& cmdline,
+ const LaunchOptions& options,
+ ProcessHandle* process_handle) {
+ // We want to inherit the std handles so dump() statements and assertion
+ // messages in the child process can be seen - but we *do not* want to
+ // blindly have all handles inherited. Vista and later has a technique
+ // where only specified handles are inherited - so we use this technique.
+ // If that fails we just don't inherit anything.
+ DWORD dwCreationFlags = 0;
+ BOOL bInheritHandles = FALSE;
+
+ // We use a STARTUPINFOEX, but if we can't do the thread attribute thing, we
+ // just pass the size of a STARTUPINFO.
+ STARTUPINFOEX startup_info_ex;
+ ZeroMemory(&startup_info_ex, sizeof(startup_info_ex));
+ STARTUPINFO& startup_info = startup_info_ex.StartupInfo;
+ startup_info.cb = sizeof(startup_info);
+ startup_info.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEOFFFEEDBACK;
+ startup_info.wShowWindow = options.start_hidden ? SW_HIDE : SW_SHOW;
+
+ // Per the comment in CreateThreadAttributeList, lpAttributeList will contain
+ // a pointer to handlesToInherit, so make sure they have the same lifetime.
+ LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList = NULL;
+ std::vector<HANDLE> handlesToInherit;
+ for (HANDLE h : options.handles_to_inherit) {
+ if (SetHandleInformation(h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) ==
+ 0) {
+ MOZ_DIAGNOSTIC_ASSERT(false, "SetHandleInformation failed");
+ return Err(LaunchError("SetHandleInformation", GetLastError()));
+ }
+ handlesToInherit.push_back(h);
+ }
+
+ // setup our handle array first - if we end up with no handles that can
+ // be inherited we can avoid trying to do the ThreadAttributeList dance...
+ HANDLE stdOut = ::GetStdHandle(STD_OUTPUT_HANDLE);
+ HANDLE stdErr = ::GetStdHandle(STD_ERROR_HANDLE);
+
+ if (IsInheritableHandle(stdOut)) handlesToInherit.push_back(stdOut);
+ if (stdErr != stdOut && IsInheritableHandle(stdErr))
+ handlesToInherit.push_back(stdErr);
+
+ if (!handlesToInherit.empty()) {
+ lpAttributeList = CreateThreadAttributeList(handlesToInherit.data(),
+ handlesToInherit.size());
+ if (lpAttributeList) {
+ // it's safe to inherit handles, so arrange for that...
+ startup_info.cb = sizeof(startup_info_ex);
+ startup_info.dwFlags |= STARTF_USESTDHANDLES;
+ startup_info.hStdOutput = stdOut;
+ startup_info.hStdError = stdErr;
+ startup_info.hStdInput = INVALID_HANDLE_VALUE;
+ startup_info_ex.lpAttributeList = lpAttributeList;
+ dwCreationFlags |= EXTENDED_STARTUPINFO_PRESENT;
+ bInheritHandles = TRUE;
+ }
+ }
+
+ dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
+ if (options.start_independent) {
+ dwCreationFlags |= CREATE_BREAKAWAY_FROM_JOB;
+ }
+
+ LPTCH original_environment = GetEnvironmentStrings();
+ base::NativeEnvironmentString new_environment =
+ AlterEnvironment(original_environment, options.env_map);
+ // Ignore return value? What can we do?
+ FreeEnvironmentStrings(original_environment);
+ LPVOID new_env_ptr = (void*)new_environment.data();
+
+ PROCESS_INFORMATION process_info;
+
+ BOOL createdOK = CreateProcess(
+ NULL, const_cast<wchar_t*>(cmdline.c_str()), NULL, NULL, bInheritHandles,
+ dwCreationFlags, new_env_ptr, NULL, &startup_info, &process_info);
+ if (lpAttributeList) FreeThreadAttributeList(lpAttributeList);
+ if (!createdOK) {
+ DLOG(WARNING) << "CreateProcess Failed: " << GetLastError();
+ return Err(LaunchError("CreateProcess", GetLastError()));
+ }
+
+ gProcessLog.print("==> process %d launched child process %d (%S)\n",
+ GetCurrentProcId(), process_info.dwProcessId,
+ cmdline.c_str());
+
+ // Handles must be closed or they will leak
+ CloseHandle(process_info.hThread);
+
+ if (options.wait) WaitForSingleObject(process_info.hProcess, INFINITE);
+
+ // If the caller wants the process handle, we won't close it.
+ if (process_handle) {
+ *process_handle = process_info.hProcess;
+ } else {
+ CloseHandle(process_info.hProcess);
+ }
+ return Ok();
+}
+
+Result<Ok, LaunchError> LaunchApp(const CommandLine& cl,
+ const LaunchOptions& options,
+ ProcessHandle* process_handle) {
+ return LaunchApp(cl.command_line_string(), options, process_handle);
+}
+
+bool KillProcess(ProcessHandle process, int exit_code) {
+ // INVALID_HANDLE_VALUE is not actually an invalid handle value, but
+ // instead is the value returned by GetCurrentProcess(). nullptr,
+ // in contrast, *is* an invalid handle value. Both values are too
+ // easy to accidentally try to kill, and neither is legitimately
+ // used by this function's callers, so reject them.
+ if (!process || process == INVALID_HANDLE_VALUE) {
+ CHROMIUM_LOG(WARNING)
+ << "base::KillProcess refusing to terminate process handle " << process;
+ return false;
+ }
+ bool result = (TerminateProcess(process, exit_code) != FALSE);
+ if (!result) {
+ DLOG(ERROR) << "Unable to terminate process: " << GetLastError();
+ }
+ return result;
+}
+
+} // namespace base
+
+namespace mozilla {
+
+EnvironmentLog::EnvironmentLog(const char* varname, size_t len) {
+ wchar_t wvarname[len];
+ std::copy(varname, varname + len, wvarname);
+ const wchar_t* e = _wgetenv(wvarname);
+ if (e && *e) {
+ fname_ = e;
+ }
+}
+
+void EnvironmentLog::print(const char* format, ...) {
+ if (!fname_.size()) return;
+
+ FILE* f;
+ if (fname_.compare(L"-") == 0) {
+ f = fdopen(dup(STDOUT_FILENO), "a");
+ } else {
+ f = _wfopen(fname_.c_str(), L"a");
+ }
+
+ if (!f) return;
+
+ va_list a;
+ va_start(a, format);
+ vfprintf(f, format, a);
+ va_end(a);
+ fclose(f);
+}
+
+} // namespace mozilla
diff --git a/ipc/chromium/src/base/rand_util.cc b/ipc/chromium/src/base/rand_util.cc
new file mode 100644
index 0000000000..bf14baa5d4
--- /dev/null
+++ b/ipc/chromium/src/base/rand_util.cc
@@ -0,0 +1,30 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/rand_util.h"
+
+#include <math.h>
+
+#include <limits>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "mozilla/RandomNum.h"
+
+namespace base {
+
+int RandInt(int min, int max) {
+ DCHECK(min <= max);
+
+ uint64_t range = static_cast<int64_t>(max) - min + 1;
+ mozilla::Maybe<uint64_t> number = mozilla::RandomUint64();
+ MOZ_RELEASE_ASSERT(number.isSome());
+ int result = min + static_cast<int>(number.value() % range);
+ DCHECK(result >= min && result <= max);
+ return result;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/rand_util.h b/ipc/chromium/src/base/rand_util.h
new file mode 100644
index 0000000000..963fc69599
--- /dev/null
+++ b/ipc/chromium/src/base/rand_util.h
@@ -0,0 +1,19 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef BASE_RAND_UTIL_H_
+#define BASE_RAND_UTIL_H_
+
+#include "base/basictypes.h"
+
+namespace base {
+
+// Returns a random number between min and max (inclusive). Thread-safe.
+int RandInt(int min, int max);
+
+} // namespace base
+
+#endif // BASE_RAND_UTIL_H_
diff --git a/ipc/chromium/src/base/revocable_store.cc b/ipc/chromium/src/base/revocable_store.cc
new file mode 100644
index 0000000000..b3d7414ee2
--- /dev/null
+++ b/ipc/chromium/src/base/revocable_store.cc
@@ -0,0 +1,40 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/revocable_store.h"
+
+#include "base/logging.h"
+
+RevocableStore::Revocable::Revocable(RevocableStore* store)
+ : store_reference_(store->owning_reference_) {
+ // We AddRef() the owning reference.
+ DCHECK(store_reference_->store());
+ store_reference_->store()->Add(this);
+}
+
+RevocableStore::RevocableStore() {
+ // Create a new owning reference.
+ owning_reference_ = new StoreRef(this);
+}
+
+RevocableStore::~RevocableStore() {
+ // Revoke all the items in the store.
+ owning_reference_->set_store(NULL);
+}
+
+void RevocableStore::Add(Revocable* item) {
+ DCHECK(!item->revoked());
+}
+
+void RevocableStore::RevokeAll() {
+ // We revoke all the existing items in the store and reset our count.
+ owning_reference_->set_store(NULL);
+
+ // Then we create a new owning reference for new items that get added.
+ // This Release()s the old owning reference, allowing it to be freed after
+ // all the items that were in the store are eventually destroyed.
+ owning_reference_ = new StoreRef(this);
+}
diff --git a/ipc/chromium/src/base/revocable_store.h b/ipc/chromium/src/base/revocable_store.h
new file mode 100644
index 0000000000..789c011cde
--- /dev/null
+++ b/ipc/chromium/src/base/revocable_store.h
@@ -0,0 +1,75 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_REVOCABLE_STORE_H_
+#define BASE_REVOCABLE_STORE_H_
+
+#include "base/basictypes.h"
+#include "nsISupportsImpl.h"
+
+// |RevocableStore| is a container of items that can be removed from the store.
+class RevocableStore {
+ public:
+ // A |StoreRef| is used to link the |RevocableStore| to its items. There is
+ // one StoreRef per store, and each item holds a reference to it. If the
+ // store wishes to revoke its items, it sets |store_| to null. Items are
+ // permitted to release their reference to the |StoreRef| when they no longer
+ // require the store.
+ class StoreRef final {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(StoreRef)
+ explicit StoreRef(RevocableStore* aStore) : store_(aStore) {}
+
+ void set_store(RevocableStore* aStore) { store_ = aStore; }
+ RevocableStore* store() const { return store_; }
+
+ protected:
+ ~StoreRef() {}
+
+ private:
+ RevocableStore* store_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(StoreRef);
+ };
+
+ // An item in the store. On construction, the object adds itself to the
+ // store.
+ class Revocable {
+ public:
+ explicit Revocable(RevocableStore* store);
+ ~Revocable() = default;
+
+ // This item has been revoked if it no longer has a pointer to the store.
+ bool revoked() const { return !store_reference_->store(); }
+
+ private:
+ // We hold a reference to the store through this ref pointer. We release
+ // this reference on destruction.
+ RefPtr<StoreRef> store_reference_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(Revocable);
+ };
+
+ RevocableStore();
+ ~RevocableStore();
+
+ // Revokes all the items in the store.
+ void RevokeAll();
+
+ private:
+ friend class Revocable;
+
+ // Adds an item to the store. To add an item to the store, construct it
+ // with a pointer to the store.
+ void Add(Revocable* item);
+
+ // This is the reference the unrevoked items in the store hold.
+ RefPtr<StoreRef> owning_reference_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(RevocableStore);
+};
+
+#endif // BASE_REVOCABLE_STORE_H_
diff --git a/ipc/chromium/src/base/scoped_bstr_win.h b/ipc/chromium/src/base/scoped_bstr_win.h
new file mode 100644
index 0000000000..4e7e133421
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_bstr_win.h
@@ -0,0 +1,138 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SCOPED_BSTR_WIN_H_
+#define BASE_SCOPED_BSTR_WIN_H_
+
+#include "base/basictypes.h" // needed to pick up XP_WIN
+
+#include "base/logging.h"
+
+#include <windows.h>
+#include <oleauto.h>
+
+// Manages a BSTR string pointer.
+// The class interface is based on scoped_ptr.
+class ScopedBstr {
+ public:
+ ScopedBstr() : bstr_(NULL) {}
+
+ // Constructor to create a new BSTR.
+ // NOTE: Do not pass a BSTR to this constructor expecting ownership to
+ // be transferred - even though it compiles! ;-)
+ explicit ScopedBstr(const wchar_t* non_bstr);
+ ~ScopedBstr();
+
+ // Give ScopedBstr ownership over an already allocated BSTR or NULL.
+ // If you need to allocate a new BSTR instance, use |allocate| instead.
+ void Reset(BSTR bstr = NULL);
+
+ // Releases ownership of the BSTR to the caller.
+ BSTR Release();
+
+ // Creates a new BSTR from a wide string.
+ // If you already have a BSTR and want to transfer ownership to the
+ // ScopedBstr instance, call |reset| instead.
+ // Returns a pointer to the new BSTR, or NULL if allocation failed.
+ BSTR Allocate(const wchar_t* wide_str);
+
+ // Allocates a new BSTR with the specified number of bytes.
+ // Returns a pointer to the new BSTR, or NULL if allocation failed.
+ BSTR AllocateBytes(int bytes);
+
+ // Sets the allocated length field of the already-allocated BSTR to be
+ // |bytes|. This is useful when the BSTR was preallocated with e.g.
+ // SysAllocStringLen or SysAllocStringByteLen (call |AllocateBytes|) and
+ // then not all the bytes are being used.
+ // Note that if you want to set the length to a specific number of characters,
+ // you need to multiply by sizeof(wchar_t). Oddly, there's no public API to
+ // set the length, so we do this ourselves by hand.
+ //
+ // NOTE: The actual allocated size of the BSTR MUST be >= bytes.
+ // That responsibility is with the caller.
+ void SetByteLen(uint32_t bytes);
+
+ // Swap values of two ScopedBstr's.
+ void Swap(ScopedBstr& bstr2);
+
+ // Retrieves the pointer address.
+ // Used to receive BSTRs as out arguments (and take ownership).
+ // The function DCHECKs on the current value being NULL.
+ // Usage: GetBstr(bstr.Receive());
+ BSTR* Receive();
+
+ // Returns number of chars in the BSTR.
+ uint32_t Length() const;
+
+ // Returns the number of bytes allocated for the BSTR.
+ uint32_t ByteLength() const;
+
+ operator BSTR() const { return bstr_; }
+
+ protected:
+ BSTR bstr_;
+
+ private:
+ // Forbid comparison of ScopedBstr types. You should never have the same
+ // BSTR owned by two different scoped_ptrs.
+ bool operator==(const ScopedBstr& bstr2) const;
+ bool operator!=(const ScopedBstr& bstr2) const;
+ DISALLOW_COPY_AND_ASSIGN(ScopedBstr);
+};
+
+// Template class to generate a BSTR from a static wide string
+// without touching the heap. Use this class via the StackBstrVar and
+// StackBstr macros.
+template <uint32_t string_bytes>
+class StackBstrT {
+ public:
+ // Try to stay as const as we can in an attempt to avoid someone
+ // using the class incorrectly (e.g. by supplying a variable instead
+ // of a verbatim string. We also have an assert in the constructor
+ // as an extra runtime check since the const-ness only catches one case.
+ explicit StackBstrT(const wchar_t* const str) {
+ // The BSTR API uses UINT, but we prefer uint32_t.
+ // Make sure we'll know about it if these types don't match.
+ COMPILE_ASSERT(sizeof(uint32_t) == sizeof(UINT), UintToUint32);
+ COMPILE_ASSERT(sizeof(wchar_t) == sizeof(OLECHAR), WcharToOlechar);
+
+ // You shouldn't pass string pointers to this constructor since
+ // there's no way for the compiler to calculate the length of the
+ // string (string_bytes will be equal to pointer size in those cases).
+ DCHECK(lstrlenW(str) == (string_bytes / sizeof(bstr_.str_[0])) - 1)
+ << "not expecting a string pointer";
+ memcpy(bstr_.str_, str, string_bytes);
+ bstr_.len_ = string_bytes - sizeof(wchar_t);
+ }
+
+ operator BSTR() { return bstr_.str_; }
+
+ protected:
+ struct BstrInternal {
+ uint32_t len_;
+ wchar_t str_[string_bytes / sizeof(wchar_t)];
+ } bstr_;
+};
+
+// Use this macro to generate an inline BSTR from a wide string.
+// This is about 6 times faster than using the SysAllocXxx functions to
+// allocate a BSTR and helps with keeping heap fragmentation down.
+// Example:
+// DoBstrStuff(StackBstr(L"This is my BSTR"));
+// Where DoBstrStuff is:
+// HRESULT DoBstrStuff(BSTR bstr) { ... }
+#define StackBstr(str) static_cast<BSTR>(StackBstrT<sizeof(str)>(str))
+
+// If you need a named BSTR variable that's based on a fixed string
+// (e.g. if the BSTR is used inside a loop or more than one place),
+// use StackBstrVar to declare a variable.
+// Example:
+// StackBstrVar(L"my_property", myprop);
+// for (int i = 0; i < objects.length(); ++i)
+// ProcessValue(objects[i].GetProp(myprop)); // GetProp accepts BSTR
+#define StackBstrVar(str, var) StackBstrT<sizeof(str)> var(str)
+
+#endif // BASE_SCOPED_BSTR_WIN_H_
diff --git a/ipc/chromium/src/base/scoped_cftyperef.h b/ipc/chromium/src/base/scoped_cftyperef.h
new file mode 100644
index 0000000000..9cd3cfa967
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_cftyperef.h
@@ -0,0 +1,68 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SCOPED_CFTYPEREF_H_
+#define BASE_SCOPED_CFTYPEREF_H_
+
+#include <CoreFoundation/CoreFoundation.h>
+#include "base/basictypes.h"
+
+// scoped_cftyperef<> is patterned after scoped_ptr<>, but maintains ownership
+// of a CoreFoundation object: any object that can be represented as a
+// CFTypeRef. Style deviations here are solely for compatibility with
+// scoped_ptr<>'s interface, with which everyone is already familiar.
+//
+// When scoped_cftyperef<> takes ownership of an object (in the constructor or
+// in reset()), it takes over the caller's existing ownership claim. The
+// caller must own the object it gives to scoped_cftyperef<>, and relinquishes
+// an ownership claim to that object. scoped_cftyperef<> does not call
+// CFRetain().
+template <typename CFT>
+class scoped_cftyperef {
+ public:
+ typedef CFT element_type;
+
+ explicit scoped_cftyperef(CFT object = NULL) : object_(object) {}
+
+ ~scoped_cftyperef() {
+ if (object_) CFRelease(object_);
+ }
+
+ void reset(CFT object = NULL) {
+ if (object_) CFRelease(object_);
+ object_ = object;
+ }
+
+ bool operator==(CFT that) const { return object_ == that; }
+
+ bool operator!=(CFT that) const { return object_ != that; }
+
+ operator CFT() const { return object_; }
+
+ CFT get() const { return object_; }
+
+ void swap(scoped_cftyperef& that) {
+ CFT temp = that.object_;
+ that.object_ = object_;
+ object_ = temp;
+ }
+
+ // scoped_cftyperef<>::release() is like scoped_ptr<>::release. It is NOT
+ // a wrapper for CFRelease(). To force a scoped_cftyperef<> object to call
+ // CFRelease(), use scoped_cftyperef<>::reset().
+ CFT release() {
+ CFT temp = object_;
+ object_ = NULL;
+ return temp;
+ }
+
+ private:
+ CFT object_;
+
+ DISALLOW_COPY_AND_ASSIGN(scoped_cftyperef);
+};
+
+#endif // BASE_SCOPED_CFTYPEREF_H_
diff --git a/ipc/chromium/src/base/scoped_handle.h b/ipc/chromium/src/base/scoped_handle.h
new file mode 100644
index 0000000000..97bb7f1240
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_handle.h
@@ -0,0 +1,52 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SCOPED_HANDLE_H_
+#define BASE_SCOPED_HANDLE_H_
+
+#include <stdio.h>
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+# include "base/scoped_handle_win.h"
+#endif
+
+class ScopedStdioHandle {
+ public:
+ ScopedStdioHandle() : handle_(NULL) {}
+
+ explicit ScopedStdioHandle(FILE* handle) : handle_(handle) {}
+
+ ~ScopedStdioHandle() { Close(); }
+
+ void Close() {
+ if (handle_) {
+ fclose(handle_);
+ handle_ = NULL;
+ }
+ }
+
+ FILE* get() const { return handle_; }
+
+ FILE* Take() {
+ FILE* temp = handle_;
+ handle_ = NULL;
+ return temp;
+ }
+
+ void Set(FILE* newhandle) {
+ Close();
+ handle_ = newhandle;
+ }
+
+ private:
+ FILE* handle_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ScopedStdioHandle);
+};
+
+#endif // BASE_SCOPED_HANDLE_H_
diff --git a/ipc/chromium/src/base/scoped_handle_win.h b/ipc/chromium/src/base/scoped_handle_win.h
new file mode 100644
index 0000000000..e8e419b7c5
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_handle_win.h
@@ -0,0 +1,193 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SCOPED_HANDLE_WIN_H_
+#define BASE_SCOPED_HANDLE_WIN_H_
+
+#include <windows.h>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+// Used so we always remember to close the handle.
+// The class interface matches that of ScopedStdioHandle in addition to an
+// IsValid() method since invalid handles on windows can be either NULL or
+// INVALID_HANDLE_VALUE (-1).
+//
+// Example:
+// ScopedHandle hfile(CreateFile(...));
+// if (!hfile.Get())
+// ...process error
+// ReadFile(hfile.Get(), ...);
+//
+// To sqirrel the handle away somewhere else:
+// secret_handle_ = hfile.Take();
+//
+// To explicitly close the handle:
+// hfile.Close();
+class ScopedHandle {
+ public:
+ ScopedHandle() : handle_(NULL) {}
+
+ explicit ScopedHandle(HANDLE h) : handle_(NULL) { Set(h); }
+
+ ~ScopedHandle() { Close(); }
+
+ // Use this instead of comparing to INVALID_HANDLE_VALUE to pick up our NULL
+ // usage for errors.
+ bool IsValid() const { return handle_ != NULL; }
+
+ void Set(HANDLE new_handle) {
+ Close();
+
+ // Windows is inconsistent about invalid handles, so we always use NULL
+ if (new_handle != INVALID_HANDLE_VALUE) handle_ = new_handle;
+ }
+
+ HANDLE Get() { return handle_; }
+
+ operator HANDLE() { return handle_; }
+
+ HANDLE Take() {
+ // transfers ownership away from this object
+ HANDLE h = handle_;
+ handle_ = NULL;
+ return h;
+ }
+
+ void Close() {
+ if (handle_) {
+ if (!::CloseHandle(handle_)) {
+ NOTREACHED();
+ }
+ handle_ = NULL;
+ }
+ }
+
+ private:
+ HANDLE handle_;
+ DISALLOW_EVIL_CONSTRUCTORS(ScopedHandle);
+};
+
+// Like ScopedHandle, but for HANDLEs returned from FindFile().
+class ScopedFindFileHandle {
+ public:
+ explicit ScopedFindFileHandle(HANDLE handle) : handle_(handle) {
+ // Windows is inconsistent about invalid handles, so we always use NULL
+ if (handle_ == INVALID_HANDLE_VALUE) handle_ = NULL;
+ }
+
+ ~ScopedFindFileHandle() {
+ if (handle_) FindClose(handle_);
+ }
+
+ // Use this instead of comparing to INVALID_HANDLE_VALUE to pick up our NULL
+ // usage for errors.
+ bool IsValid() const { return handle_ != NULL; }
+
+ operator HANDLE() { return handle_; }
+
+ private:
+ HANDLE handle_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ScopedFindFileHandle);
+};
+
+// Like ScopedHandle but for HDC. Only use this on HDCs returned from
+// CreateCompatibleDC. For an HDC returned by GetDC, use ReleaseDC instead.
+class ScopedHDC {
+ public:
+ ScopedHDC() : hdc_(NULL) {}
+ explicit ScopedHDC(HDC h) : hdc_(h) {}
+
+ ~ScopedHDC() { Close(); }
+
+ HDC Get() { return hdc_; }
+
+ void Set(HDC h) {
+ Close();
+ hdc_ = h;
+ }
+
+ operator HDC() { return hdc_; }
+
+ private:
+ void Close() {
+#ifdef NOGDI
+ assert(false);
+#else
+ if (hdc_) DeleteDC(hdc_);
+#endif // NOGDI
+ }
+
+ HDC hdc_;
+ DISALLOW_EVIL_CONSTRUCTORS(ScopedHDC);
+};
+
+// Like ScopedHandle but for GDI objects.
+template <class T>
+class ScopedGDIObject {
+ public:
+ ScopedGDIObject() : object_(NULL) {}
+ explicit ScopedGDIObject(T object) : object_(object) {}
+
+ ~ScopedGDIObject() { Close(); }
+
+ T Get() { return object_; }
+
+ void Set(T object) {
+ if (object_ && object != object_) Close();
+ object_ = object;
+ }
+
+ ScopedGDIObject& operator=(T object) {
+ Set(object);
+ return *this;
+ }
+
+ operator T() { return object_; }
+
+ private:
+ void Close() {
+ if (object_) DeleteObject(object_);
+ }
+
+ T object_;
+ DISALLOW_COPY_AND_ASSIGN(ScopedGDIObject);
+};
+
+// Typedefs for some common use cases.
+typedef ScopedGDIObject<HBITMAP> ScopedBitmap;
+typedef ScopedGDIObject<HRGN> ScopedHRGN;
+typedef ScopedGDIObject<HFONT> ScopedHFONT;
+
+// Like ScopedHandle except for HGLOBAL.
+template <class T>
+class ScopedHGlobal {
+ public:
+ explicit ScopedHGlobal(HGLOBAL glob) : glob_(glob) {
+ data_ = static_cast<T*>(GlobalLock(glob_));
+ }
+ ~ScopedHGlobal() { GlobalUnlock(glob_); }
+
+ T* get() { return data_; }
+
+ size_t Size() const { return GlobalSize(glob_); }
+
+ T* operator->() const {
+ assert(data_ != 0);
+ return data_;
+ }
+
+ private:
+ HGLOBAL glob_;
+
+ T* data_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ScopedHGlobal);
+};
+
+#endif // BASE_SCOPED_HANDLE_WIN_H_
diff --git a/ipc/chromium/src/base/scoped_nsautorelease_pool.h b/ipc/chromium/src/base/scoped_nsautorelease_pool.h
new file mode 100644
index 0000000000..37d173b028
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_nsautorelease_pool.h
@@ -0,0 +1,55 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef BASE_SCOPED_NSAUTORELEASE_POOL_H_
+#define BASE_SCOPED_NSAUTORELEASE_POOL_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_DARWIN)
+# if defined(__OBJC__)
+@class NSAutoreleasePool;
+# else // __OBJC__
+class NSAutoreleasePool;
+# endif // __OBJC__
+#endif // XP_DARWIN
+
+namespace base {
+
+// On the Mac, ScopedNSAutoreleasePool allocates an NSAutoreleasePool when
+// instantiated and sends it a -drain message when destroyed. This allows an
+// autorelease pool to be maintained in ordinary C++ code without bringing in
+// any direct Objective-C dependency.
+//
+// On other platforms, ScopedNSAutoreleasePool is an empty object with no
+// effects. This allows it to be used directly in cross-platform code without
+// ugly #ifdefs.
+class ScopedNSAutoreleasePool {
+ public:
+#if !defined(XP_DARWIN)
+ ScopedNSAutoreleasePool() {}
+ void Recycle() {}
+#else // XP_DARWIN
+ ScopedNSAutoreleasePool();
+ ~ScopedNSAutoreleasePool();
+
+ // Clear out the pool in case its position on the stack causes it to be
+ // alive for long periods of time (such as the entire length of the app).
+ // Only use then when you're certain the items currently in the pool are
+ // no longer needed.
+ void Recycle();
+
+ private:
+ NSAutoreleasePool* autorelease_pool_;
+#endif // XP_DARWIN
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ScopedNSAutoreleasePool);
+};
+
+} // namespace base
+
+#endif // BASE_SCOPED_NSAUTORELEASE_POOL_H_
diff --git a/ipc/chromium/src/base/scoped_nsautorelease_pool.mm b/ipc/chromium/src/base/scoped_nsautorelease_pool.mm
new file mode 100644
index 0000000000..174fb821d6
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_nsautorelease_pool.mm
@@ -0,0 +1,30 @@
+// Copyright (c) 2008 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.
+
+#include "base/scoped_nsautorelease_pool.h"
+
+#import <Foundation/Foundation.h>
+
+#include "base/logging.h"
+
+namespace base {
+
+ScopedNSAutoreleasePool::ScopedNSAutoreleasePool()
+ : autorelease_pool_([[NSAutoreleasePool alloc] init]) {
+ DCHECK(autorelease_pool_);
+}
+
+ScopedNSAutoreleasePool::~ScopedNSAutoreleasePool() {
+ [autorelease_pool_ drain];
+}
+
+// Cycle the internal pool, allowing everything there to get cleaned up and
+// start anew.
+void ScopedNSAutoreleasePool::Recycle() {
+ [autorelease_pool_ drain];
+ autorelease_pool_ = [[NSAutoreleasePool alloc] init];
+ DCHECK(autorelease_pool_);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/scoped_nsobject.h b/ipc/chromium/src/base/scoped_nsobject.h
new file mode 100644
index 0000000000..d1ef77d749
--- /dev/null
+++ b/ipc/chromium/src/base/scoped_nsobject.h
@@ -0,0 +1,66 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#ifndef BASE_SCOPED_NSOBJECT_H_
+#define BASE_SCOPED_NSOBJECT_H_
+
+#import <Foundation/Foundation.h>
+#include "base/basictypes.h"
+
+// scoped_nsobject<> is patterned after scoped_ptr<>, but maintains ownership
+// of an NSObject subclass object. Style deviations here are solely for
+// compatibility with scoped_ptr<>'s interface, with which everyone is already
+// familiar.
+//
+// When scoped_nsobject<> takes ownership of an object (in the constructor or
+// in reset()), it takes over the caller's existing ownership claim. The
+// caller must own the object it gives to scoped_nsobject<>, and relinquishes
+// an ownership claim to that object. scoped_nsobject<> does not call
+// -retain.
+template <typename NST>
+class scoped_nsobject {
+ public:
+ typedef NST* element_type;
+
+ explicit scoped_nsobject(NST* object = nil) : object_(object) {}
+
+ ~scoped_nsobject() { [object_ release]; }
+
+ void reset(NST* object = nil) {
+ [object_ release];
+ object_ = object;
+ }
+
+ bool operator==(NST* that) const { return object_ == that; }
+
+ bool operator!=(NST* that) const { return object_ != that; }
+
+ operator NST*() const { return object_; }
+
+ NST* get() const { return object_; }
+
+ void swap(scoped_nsobject& that) {
+ NST* temp = that.object_;
+ that.object_ = object_;
+ object_ = temp;
+ }
+
+ // scoped_nsobject<>::release() is like scoped_ptr<>::release. It is NOT
+ // a wrapper for [object_ release]. To force a scoped_nsobject<> object to
+ // call [object_ release], use scoped_nsobject<>::reset().
+ NST* release() {
+ NST* temp = object_;
+ object_ = nil;
+ return temp;
+ }
+
+ private:
+ NST* object_;
+
+ DISALLOW_COPY_AND_ASSIGN(scoped_nsobject);
+};
+
+#endif // BASE_SCOPED_NSOBJECT_H_
diff --git a/ipc/chromium/src/base/set_process_title_linux.cc b/ipc/chromium/src/base/set_process_title_linux.cc
new file mode 100644
index 0000000000..fed166a524
--- /dev/null
+++ b/ipc/chromium/src/base/set_process_title_linux.cc
@@ -0,0 +1,206 @@
+// Copyright 2009 The Chromium Authors
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This file implements BSD-style setproctitle() for Linux.
+// It is written such that it can easily be compiled outside Chromium.
+//
+// (This copy has been modified for use in the Mozilla codebase.)
+//
+// The Linux kernel sets up two locations in memory to pass arguments and
+// environment variables to processes. First, there are two char* arrays stored
+// one after another: argv and environ. A pointer to argv is passed to main(),
+// while glibc sets the global variable |environ| to point at the latter. Both
+// of these arrays are terminated by a null pointer; the environment array is
+// also followed by some empty space to allow additional variables to be added.
+//
+// These arrays contain pointers to a second location in memory, where the
+// strings themselves are stored one after another: first all the arguments,
+// then the environment variables.
+//
+// When the kernel reads the command line arguments for a process, it looks at
+// the range of memory that it initially used for the argument list. If the
+// terminating '\0' character is still where it expects, nothing further is
+// done. If it has been overwritten, the kernel will scan up to the size of
+// a page looking for another.
+//
+// Thus to change the process title, we must move any arguments and environment
+// variables out of the way to make room for a potentially longer title, and
+// then overwrite the memory pointed to by argv[0] with a single replacement
+// string, making sure its size does not exceed the available space.
+//
+// See the following kernel commit for the details of the contract between
+// kernel and setproctitle:
+// https://github.com/torvalds/linux/commit/2954152298c37804dab49d630aa959625b50cf64
+//
+// It is perhaps worth noting that patches to add a system call to Linux for
+// this, like in BSD, have never made it in: this is the "official" way to do
+// this on Linux. Presumably it is not in glibc due to some disagreement over
+// this position within the glibc project, leaving applications caught in the
+// middle. (Also, only a very few applications need or want this anyway.)
+
+#include "base/set_process_title_linux.h"
+
+#include "mozilla/UniquePtrExtensions.h"
+
+#include <fcntl.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+#include <vector>
+
+extern char** environ;
+
+// g_orig_argv0 is the original process name found in argv[0].
+// It is set to a copy of argv[0] in setproctitle_init. It is nullptr if
+// setproctitle_init was unsuccessful or not called.
+static const char* g_orig_argv0 = nullptr;
+
+// Following pointers hold the initial argv/envp memory range.
+// They are initialized in setproctitle_init and are used to overwrite the
+// argv/envp memory range with a new process title to be read by the kernel.
+// They are nullptr if setproctitle_init was unsuccessful or not called.
+// Note that g_envp_start is not necessary because it is the same as g_argv_end.
+static char* g_argv_start = nullptr;
+static char* g_argv_end = nullptr;
+static char* g_envp_end = nullptr;
+
+void setproctitle(const char* fmt, ...) {
+ va_list ap;
+
+ // Sanity check before we try and set the process title.
+ // The BSD version allows a null fmt to restore the original title.
+ if (!g_orig_argv0 || !fmt) {
+ return;
+ }
+
+ // The title can be up to the end of envp.
+ const size_t avail_size = g_envp_end - g_argv_start - 1;
+
+ // Linux 4.18--5.2 have a bug where we can never set a process title
+ // shorter than the initial argv. Check if the bug exists in the current
+ // kernel on the first call of setproctitle.
+ static const bool buggy_kernel = [avail_size]() {
+ // Attempt to set an empty title. This will set cmdline to:
+ // "" (on Linux --4.17)
+ // "\0\0\0...\0\0\0.\0" (on Linux 4.18--5.2)
+ // "\0" (on Linux 5.3--)
+ memset(g_argv_start, 0, avail_size + 1);
+ g_argv_end[-1] = '.';
+
+ mozilla::UniqueFileHandle fd(
+ open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC));
+ if (!fd) {
+ return false;
+ }
+
+ // We just want to see if there are at least 2 bytes in the file;
+ // we don't need to read the whole contents. Short reads probably
+ // aren't possible given how this procfs node is implemented, but
+ // it's not much more code to handle it anyway.
+ char buf[2];
+ ssize_t total_read = 0;
+ while (total_read < 2) {
+ ssize_t rd = read(fd.get(), buf, 2);
+ if (rd <= 0) {
+ return false;
+ }
+ total_read += rd;
+ }
+ return true;
+ }();
+
+ memset(g_argv_start, 0, avail_size + 1);
+
+ size_t size;
+ va_start(ap, fmt);
+ if (fmt[0] == '-') {
+ size = vsnprintf(g_argv_start, avail_size, &fmt[1], ap);
+ } else {
+ size = snprintf(g_argv_start, avail_size, "%s ", g_orig_argv0);
+ if (size < avail_size) {
+ size += vsnprintf(&g_argv_start[size], avail_size - size, fmt, ap);
+ }
+ }
+ va_end(ap);
+
+ // Kernel looks for a null terminator instead of the initial argv space
+ // when the end of the space is not terminated with a null.
+ // https://github.com/torvalds/linux/commit/d26d0cd97c88eb1a5704b42e41ab443406807810
+ //
+ // If the length of the new title is shorter than the original argv space,
+ // set the last byte of the space to an arbitrary non-null character to tell
+ // the kernel that setproctitle was called.
+ //
+ // On buggy kernels we can never make the process title shorter than the
+ // initial argv. In that case, just leave the remaining bytes filled with
+ // null characters.
+ const size_t argv_size = g_argv_end - g_argv_start - 1;
+ if (!buggy_kernel && size < argv_size) {
+ g_argv_end[-1] = '.';
+ }
+}
+
+// A version of this built into glibc would not need this function, since
+// it could stash the argv pointer in __libc_start_main(). But we need it.
+void setproctitle_init(char** main_argv) {
+ static bool init_called = false;
+ if (init_called) {
+ return;
+ }
+ init_called = true;
+
+ if (!main_argv) {
+ return;
+ }
+
+ // Verify that the memory layout matches expectation.
+ char** const argv = main_argv;
+ char* argv_start = argv[0];
+ char* p = argv_start;
+ for (size_t i = 0; argv[i]; ++i) {
+ if (p != argv[i]) {
+ return;
+ }
+ p += strlen(p) + 1;
+ }
+ char* argv_end = p;
+ size_t environ_size = 0;
+ for (size_t i = 0; environ[i]; ++i, ++environ_size) {
+ if (p != environ[i]) {
+ return;
+ }
+ p += strlen(p) + 1;
+ }
+ char* envp_end = p;
+
+ // Copy the arg and env strings into the heap. Leak Sanitizer
+ // doesn't seem to object to these strdup()s; if it ever does, we
+ // can always ensure the pointers are reachable from globals or add
+ // a suppresion for this function.
+ //
+ // Note that Chromium's version of this code didn't copy the
+ // arguments; this is probably because they access args via the
+ // CommandLine class, which copies into a std::vector<std::string>,
+ // but in general that's not a safe assumption for Gecko.
+ for (size_t i = 0; argv[i]; ++i) {
+ argv[i] = strdup(argv[i]);
+ }
+ for (size_t i = 0; environ[i]; ++i) {
+ environ[i] = strdup(environ[i]);
+ }
+
+ if (!argv[0]) {
+ return;
+ }
+
+ g_orig_argv0 = argv[0];
+ g_argv_start = argv_start;
+ g_argv_end = argv_end;
+ g_envp_end = envp_end;
+}
diff --git a/ipc/chromium/src/base/set_process_title_linux.h b/ipc/chromium/src/base/set_process_title_linux.h
new file mode 100644
index 0000000000..e950ce0619
--- /dev/null
+++ b/ipc/chromium/src/base/set_process_title_linux.h
@@ -0,0 +1,12 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef BASE_PROCESS_TITLE_LINUX_H_
+#define BASE_PROCESS_TITLE_LINUX_H_
+
+void setproctitle(const char* fmt, ...);
+void setproctitle_init(char** main_argv);
+
+#endif // BASE_PROCESS_TITLE_LINUX_H_
diff --git a/ipc/chromium/src/base/shared_memory.h b/ipc/chromium/src/base/shared_memory.h
new file mode 100644
index 0000000000..7735577334
--- /dev/null
+++ b/ipc/chromium/src/base/shared_memory.h
@@ -0,0 +1,197 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SHARED_MEMORY_H_
+#define BASE_SHARED_MEMORY_H_
+
+#if defined(XP_UNIX)
+# include <sys/types.h>
+# include <semaphore.h>
+#endif
+#include <string>
+
+#include "base/basictypes.h"
+#include "base/process.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/UniquePtrExtensions.h"
+
+namespace base {
+
+// SharedMemoryHandle is a platform specific type which represents
+// the underlying OS handle to a shared memory segment.
+typedef mozilla::UniqueFileHandle SharedMemoryHandle;
+
+// Platform abstraction for shared memory. Provides a C++ wrapper
+// around the OS primitive for a memory mapped file.
+class SharedMemory {
+ public:
+ // Create a new SharedMemory object.
+ SharedMemory() = default;
+
+ // Create a new SharedMemory object from an existing, open
+ // shared memory file.
+ SharedMemory(SharedMemoryHandle init_handle, bool read_only)
+ : SharedMemory() {
+ SetHandle(std::move(init_handle), read_only);
+ }
+
+ // Move constructor; transfers ownership.
+ SharedMemory(SharedMemory&& other) = default;
+
+ // Destructor. Will close any open files.
+ ~SharedMemory();
+
+ // Initialize a new SharedMemory object from an existing, open
+ // shared memory file.
+ bool SetHandle(SharedMemoryHandle handle, bool read_only);
+
+ // Return true iff the given handle is valid (i.e. not the distingished
+ // invalid value; NULL for a HANDLE and -1 for a file descriptor)
+ static bool IsHandleValid(const SharedMemoryHandle& handle);
+
+ // IsHandleValid applied to this object's handle.
+ bool IsValid() const { return static_cast<bool>(mapped_file_); }
+
+ // Return invalid handle (see comment above for exact definition).
+ static SharedMemoryHandle NULLHandle();
+
+ // Creates a shared memory segment.
+ // Returns true on success, false on failure.
+ bool Create(size_t size) { return CreateInternal(size, false); }
+
+ // Creates a shared memory segment that supports the Freeze()
+ // method; see below. (Warning: creating freezeable shared memory
+ // within a sandboxed process isn't possible on some platforms.)
+ // Returns true on success, false on failure.
+ bool CreateFreezeable(size_t size) { return CreateInternal(size, true); }
+
+ // Maps the shared memory into the caller's address space.
+ // Returns true on success, false otherwise. The memory address
+ // is accessed via the memory() accessor.
+ //
+ // If the specified fixed address is not null, it is the address that the
+ // shared memory must be mapped at. Returns false if the shared memory
+ // could not be mapped at that address.
+ bool Map(size_t bytes, void* fixed_address = nullptr);
+
+ // Unmaps the shared memory from the caller's address space.
+ void Unmap() { memory_ = nullptr; }
+
+ // Get the size of the opened shared memory backing file.
+ // Note: This size is only available to the creator of the
+ // shared memory, and not to those that opened shared memory
+ // created externally.
+ // Returns 0 if not opened or unknown.
+ size_t max_size() const { return max_size_; }
+
+ // Gets a pointer to the opened memory space if it has been
+ // Mapped via Map(). Returns NULL if it is not mapped.
+ void* memory() const { return memory_.get(); }
+
+ // Extracts the underlying file handle, returning a RAII type.
+ // If `unmap_view` is true, this unmaps the memory as a side-effect (and
+ // cleans up any OS-specific resources).
+ mozilla::UniqueFileHandle TakeHandle(bool unmap_view = true) {
+ mozilla::UniqueFileHandle handle = std::move(mapped_file_);
+ Close(unmap_view);
+ return handle;
+ }
+
+ // Creates a copy of the underlying file handle, returning a RAII type.
+ // This operation may fail, in which case the returned file handle will be
+ // invalid.
+ mozilla::UniqueFileHandle CloneHandle();
+
+ // Make the shared memory object read-only, such that it cannot be
+ // written even if it's sent to an untrusted process. If it was
+ // mapped in this process, it will be unmapped. The object must
+ // have been created with CreateFreezeable(), and must not have
+ // already been shared to another process.
+ //
+ // (See bug 1479960 comment #0 for OS-specific implementation
+ // details.)
+ [[nodiscard]] bool Freeze() {
+ Unmap();
+ return ReadOnlyCopy(this);
+ }
+
+ // Similar to Freeze(), but assigns the read-only capability to
+ // another SharedMemory object and leaves this object's mapping in
+ // place and writeable. This can be used to broadcast data to
+ // several untrusted readers without copying.
+ //
+ // The other constraints of Freeze() still apply: this object closes
+ // its handle (as if by `Close(false)`), it cannot have been
+ // previously shared, and the read-only handle cannot be used to
+ // write the memory even by a malicious process.
+ //
+ // (The out parameter can currently be the same as `this` if and
+ // only if the memory was unmapped, but this is an implementation
+ // detail and shouldn't be relied on; for that use case Freeze()
+ // should be used instead.)
+ [[nodiscard]] bool ReadOnlyCopy(SharedMemory* ro_out);
+
+ // Closes the open shared memory segment.
+ // It is safe to call Close repeatedly.
+ void Close(bool unmap_view = true);
+
+ // Returns a page-aligned address at which the given number of bytes could
+ // probably be mapped. Returns NULL on error or if there is insufficient
+ // contiguous address space to map the required number of pages.
+ //
+ // Note that there is no guarantee that the given address space will actually
+ // be free by the time this function returns, since another thread might map
+ // something there in the meantime.
+ static void* FindFreeAddressSpace(size_t size);
+
+#ifdef XP_UNIX
+ // If named POSIX shm is being used, append the prefix (including
+ // the leading '/') that would be used by a process with the given
+ // pid to the given string and return true. If not, return false.
+ // (This is public so that the Linux sandboxing code can use it.)
+ static bool AppendPosixShmPrefix(std::string* str, pid_t pid);
+ // Similar, but simply returns whether POSIX shm is in use.
+ static bool UsingPosixShm();
+#endif
+
+ private:
+ bool CreateInternal(size_t size, bool freezeable);
+
+ // Unmapping shared memory requires the mapped size on Unix but not
+ // Windows; this encapsulates that difference.
+ struct MappingDeleter {
+#ifdef XP_UNIX
+ // A default-constructed deleter must be used only with nullptr
+ // (to allow default-constructing UniqueMapping). A deleter with
+ // a size must be used at most once.
+ size_t mapped_size_ = 0;
+ explicit MappingDeleter(size_t size) : mapped_size_(size) {}
+#endif
+ MappingDeleter() = default;
+ void operator()(void* ptr);
+ };
+ using UniqueMapping = mozilla::UniquePtr<void, MappingDeleter>;
+
+ UniqueMapping memory_;
+ size_t max_size_ = 0;
+ mozilla::UniqueFileHandle mapped_file_;
+#if defined(XP_WIN)
+ // If true indicates this came from an external source so needs extra checks
+ // before being mapped.
+ bool external_section_ = false;
+#elif !defined(ANDROID)
+ mozilla::UniqueFileHandle frozen_file_;
+ bool is_memfd_ = false;
+#endif
+ bool read_only_ = false;
+ bool freezeable_ = false;
+
+ DISALLOW_EVIL_CONSTRUCTORS(SharedMemory);
+};
+
+} // namespace base
+
+#endif // BASE_SHARED_MEMORY_H_
diff --git a/ipc/chromium/src/base/shared_memory_posix.cc b/ipc/chromium/src/base/shared_memory_posix.cc
new file mode 100644
index 0000000000..bfe20e343a
--- /dev/null
+++ b/ipc/chromium/src/base/shared_memory_posix.cc
@@ -0,0 +1,563 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/shared_memory.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#ifdef ANDROID
+# include "mozilla/Ashmem.h"
+#endif
+
+#ifdef XP_LINUX
+# include "linux_memfd_defs.h"
+#endif
+#ifdef MOZ_WIDGET_GTK
+# include "mozilla/WidgetUtilsGtk.h"
+#endif
+
+#ifdef __FreeBSD__
+# include <sys/capsicum.h>
+#endif
+
+#ifdef MOZ_VALGRIND
+# include <valgrind/valgrind.h>
+#endif
+
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/string_util.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/ProfilerThreadSleep.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "prenv.h"
+
+namespace base {
+
+void SharedMemory::MappingDeleter::operator()(void* ptr) {
+ // Check that this isn't a default-constructed deleter. (`munmap`
+ // is specified to fail with `EINVAL` if the length is 0, so this
+ // assertion isn't load-bearing.)
+ DCHECK(mapped_size_ != 0);
+ munmap(ptr, mapped_size_);
+ // Guard against multiple calls of the same deleter, which shouldn't
+ // happen (but could, if `UniquePtr::reset` were used). Calling
+ // `munmap` with an incorrect non-zero length would be bad.
+ mapped_size_ = 0;
+}
+
+SharedMemory::~SharedMemory() {
+ // This is almost equal to the default destructor, except for the
+ // warning message about unfrozen freezable memory.
+ Close();
+}
+
+bool SharedMemory::SetHandle(SharedMemoryHandle handle, bool read_only) {
+ DCHECK(!mapped_file_);
+#ifndef ANDROID
+ DCHECK(!frozen_file_);
+#endif
+
+ freezeable_ = false;
+ mapped_file_ = std::move(handle);
+ read_only_ = read_only;
+ // is_memfd_ only matters for freezing, which isn't possible
+ return true;
+}
+
+// static
+bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
+ return handle != nullptr;
+}
+
+// static
+SharedMemoryHandle SharedMemory::NULLHandle() { return nullptr; }
+
+// static
+bool SharedMemory::UsingPosixShm() {
+ // Undocumented feature of AppendPosixShmPrefix to reduce code
+ // duplication: if the string pointer is null, it's ignored.
+ return AppendPosixShmPrefix(nullptr, 0);
+}
+
+#ifdef ANDROID
+
+// Android has its own shared memory API, ashmem. It doesn't support
+// POSIX shm_open, and the memfd support (see below) also doesn't work
+// because its SELinux policy prevents the procfs operations we'd use
+// (see bug 1670277 for more details).
+
+// static
+bool SharedMemory::AppendPosixShmPrefix(std::string* str, pid_t pid) {
+ return false;
+}
+
+bool SharedMemory::CreateInternal(size_t size, bool freezeable) {
+ read_only_ = false;
+
+ DCHECK(size > 0);
+ DCHECK(!mapped_file_);
+
+ int fd = mozilla::android::ashmem_create(nullptr, size);
+ if (fd < 0) {
+ CHROMIUM_LOG(WARNING) << "failed to open shm: " << strerror(errno);
+ return false;
+ }
+
+ mapped_file_.reset(fd);
+ max_size_ = size;
+ freezeable_ = freezeable;
+ return true;
+}
+
+bool SharedMemory::ReadOnlyCopy(SharedMemory* ro_out) {
+ DCHECK(mapped_file_);
+ DCHECK(!read_only_);
+ CHECK(freezeable_);
+
+ if (ro_out == this) {
+ DCHECK(!memory_);
+ }
+
+ if (mozilla::android::ashmem_setProt(mapped_file_.get(), PROT_READ) != 0) {
+ CHROMIUM_LOG(WARNING) << "failed to set ashmem read-only: "
+ << strerror(errno);
+ return false;
+ }
+
+ mozilla::UniqueFileHandle ro_file = std::move(mapped_file_);
+
+ freezeable_ = false;
+ ro_out->Close();
+ ro_out->mapped_file_ = std::move(ro_file);
+ ro_out->max_size_ = max_size_;
+ ro_out->read_only_ = true;
+ ro_out->freezeable_ = false;
+
+ return true;
+}
+
+#else // not Android
+
+// memfd_create is a nonstandard interface for creating anonymous
+// shared memory accessible as a file descriptor but not tied to any
+// filesystem. It first appeared in Linux 3.17, and was adopted by
+// FreeBSD in version 13.
+
+# if !defined(HAVE_MEMFD_CREATE) && defined(XP_LINUX) && \
+ defined(SYS_memfd_create)
+
+// Older libc versions (e.g., glibc before 2.27) don't have the
+// wrapper, but we can supply our own; see `linux_memfd_defs.h`.
+
+static int memfd_create(const char* name, unsigned int flags) {
+ return syscall(SYS_memfd_create, name, flags);
+}
+
+# define HAVE_MEMFD_CREATE 1
+# endif
+
+// memfd supports having "seals" applied to the file, to prevent
+// various types of changes (which apply to all fds referencing the
+// file). Unfortunately, we can't rely on F_SEAL_WRITE to implement
+// Freeze(); see the comments in ReadOnlyCopy() below.
+//
+// Instead, to prevent a child process from regaining write access to
+// a read-only copy, the OS must also provide a way to remove write
+// permissions at the file descriptor level. This next section
+// attempts to accomplish that.
+
+# ifdef HAVE_MEMFD_CREATE
+# ifdef XP_LINUX
+# define USE_MEMFD_CREATE 1
+
+// To create a read-only duplicate of an fd, we can use procfs; the
+// same operation could restore write access, but sandboxing prevents
+// child processes from accessing /proc.
+//
+// (Note: if this ever changes to not use /proc, also reconsider how
+// and if HaveMemfd should check whether this works.)
+
+static int DupReadOnly(int fd) {
+ std::string path = StringPrintf("/proc/self/fd/%d", fd);
+ // procfs opens probably won't EINTR, but checking for it can't hurt
+ return HANDLE_EINTR(open(path.c_str(), O_RDONLY | O_CLOEXEC));
+}
+
+# elif defined(__FreeBSD__)
+# define USE_MEMFD_CREATE 1
+
+// FreeBSD's Capsicum framework allows irrevocably restricting the
+// operations permitted on a file descriptor.
+
+static int DupReadOnly(int fd) {
+ int rofd = dup(fd);
+ if (rofd < 0) {
+ return -1;
+ }
+
+ cap_rights_t rights;
+ cap_rights_init(&rights, CAP_FSTAT, CAP_MMAP_R);
+ if (cap_rights_limit(rofd, &rights) < 0) {
+ int err = errno;
+ close(rofd);
+ errno = err;
+ return -1;
+ }
+
+ return rofd;
+}
+
+# else // unhandled OS
+# warning "OS has memfd_create but no DupReadOnly implementation"
+# endif // OS selection
+# endif // HAVE_MEMFD_CREATE
+
+// Runtime detection for memfd support.
+static bool HaveMemfd() {
+# ifdef USE_MEMFD_CREATE
+ static const bool kHave = [] {
+ mozilla::UniqueFileHandle fd(
+ memfd_create("mozilla-ipc-test", MFD_CLOEXEC | MFD_ALLOW_SEALING));
+ if (!fd) {
+ DCHECK_EQ(errno, ENOSYS);
+ return false;
+ }
+
+ // Verify that DupReadOnly works; on Linux it's known to fail if:
+ //
+ // * SELinux assigns the memfd a type for which this process's
+ // domain doesn't have "open" permission; this is always the
+ // case on Android but could occur on desktop as well
+ //
+ // * /proc (used by the DupReadOnly implementation) isn't mounted,
+ // which is a configuration that the Tor Browser project is
+ // interested in as a way to reduce fingerprinting risk
+ //
+ // Sandboxed processes on Linux also can't use it if sandboxing
+ // has already been started, but that's expected. It should be
+ // safe for sandboxed child processes to use memfd even if an
+ // unsandboxed process couldn't freeze them, because freezing
+ // isn't allowed (or meaningful) for memory created by another
+ // process.
+
+ if (!PR_GetEnv("MOZ_SANDBOXED")) {
+ mozilla::UniqueFileHandle rofd(DupReadOnly(fd.get()));
+ if (!rofd) {
+ CHROMIUM_LOG(WARNING) << "read-only dup failed (" << strerror(errno)
+ << "); not using memfd";
+ return false;
+ }
+ }
+ return true;
+ }();
+ return kHave;
+# else
+ return false;
+# endif // USE_MEMFD_CREATE
+}
+
+// static
+bool SharedMemory::AppendPosixShmPrefix(std::string* str, pid_t pid) {
+ if (HaveMemfd()) {
+ return false;
+ }
+ // See also UsingPosixShm().
+ if (!str) {
+ return true;
+ }
+ *str += '/';
+# ifdef MOZ_WIDGET_GTK
+ // The Snap package environment doesn't provide a private /dev/shm
+ // (it's used for communication with services like PulseAudio);
+ // instead AppArmor is used to restrict access to it. Anything with
+ // this prefix is allowed:
+ if (const char* snap = mozilla::widget::GetSnapInstanceName()) {
+ StringAppendF(str, "snap.%s.", snap);
+ }
+# endif // XP_LINUX
+ // Hopefully the "implementation defined" name length limit is long
+ // enough for this.
+ StringAppendF(str, "org.mozilla.ipc.%d.", static_cast<int>(pid));
+ return true;
+}
+
+bool SharedMemory::CreateInternal(size_t size, bool freezeable) {
+ read_only_ = false;
+
+ DCHECK(size > 0);
+ DCHECK(!mapped_file_);
+ DCHECK(!frozen_file_);
+
+ mozilla::UniqueFileHandle fd;
+ mozilla::UniqueFileHandle frozen_fd;
+ bool is_memfd = false;
+
+# ifdef USE_MEMFD_CREATE
+ if (HaveMemfd()) {
+ const unsigned flags = MFD_CLOEXEC | (freezeable ? MFD_ALLOW_SEALING : 0);
+ fd.reset(memfd_create("mozilla-ipc", flags));
+ if (!fd) {
+ // In general it's too late to fall back here -- in a sandboxed
+ // child process, shm_open is already blocked. And it shouldn't
+ // be necessary.
+ CHROMIUM_LOG(WARNING) << "failed to create memfd: " << strerror(errno);
+ return false;
+ }
+ is_memfd = true;
+ if (freezeable) {
+ frozen_fd.reset(DupReadOnly(fd.get()));
+ if (!frozen_fd) {
+ CHROMIUM_LOG(WARNING)
+ << "failed to create read-only memfd: " << strerror(errno);
+ return false;
+ }
+ }
+ }
+# endif
+
+ if (!fd) {
+ // Generic Unix: shm_open + shm_unlink
+ do {
+ // The names don't need to be unique, but it saves time if they
+ // usually are.
+ static mozilla::Atomic<size_t> sNameCounter;
+ std::string name;
+ CHECK(AppendPosixShmPrefix(&name, getpid()));
+ StringAppendF(&name, "%zu", sNameCounter++);
+ // O_EXCL means the names being predictable shouldn't be a problem.
+ fd.reset(HANDLE_EINTR(
+ shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600)));
+ if (fd) {
+ if (freezeable) {
+ frozen_fd.reset(HANDLE_EINTR(shm_open(name.c_str(), O_RDONLY, 0400)));
+ if (!frozen_fd) {
+ int open_err = errno;
+ shm_unlink(name.c_str());
+ DLOG(FATAL) << "failed to re-open freezeable shm: "
+ << strerror(open_err);
+ return false;
+ }
+ }
+ if (shm_unlink(name.c_str()) != 0) {
+ // This shouldn't happen, but if it does: assume the file is
+ // in fact leaked, and bail out now while it's still 0-length.
+ DLOG(FATAL) << "failed to unlink shm: " << strerror(errno);
+ return false;
+ }
+ }
+ } while (!fd && errno == EEXIST);
+ }
+
+ if (!fd) {
+ CHROMIUM_LOG(WARNING) << "failed to open shm: " << strerror(errno);
+ return false;
+ }
+
+ mozilla::Maybe<int> fallocateError;
+# if defined(HAVE_POSIX_FALLOCATE)
+ // Using posix_fallocate will ensure that there's actually space for this
+ // file. Otherwise we end up with a sparse file that can give SIGBUS if we
+ // run out of space while writing to it. (This doesn't apply to memfd.)
+ if (!is_memfd) {
+ int rv;
+ // Avoid repeated interruptions of posix_fallocate by the profiler's
+ // SIGPROF sampling signal. Indicating "thread sleep" here means we'll
+ // get up to one interruption but not more. See bug 1658847 for more.
+ // This has to be scoped outside the HANDLE_RV_EINTR retry loop.
+ {
+ AUTO_PROFILER_THREAD_SLEEP;
+
+ rv = HANDLE_RV_EINTR(
+ posix_fallocate(fd.get(), 0, static_cast<off_t>(size)));
+ }
+
+ // Some filesystems have trouble with posix_fallocate. For now, we must
+ // fallback ftruncate and accept the allocation failures like we do
+ // without posix_fallocate.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=1618914
+ if (rv != 0 && rv != EOPNOTSUPP && rv != EINVAL && rv != ENODEV) {
+ CHROMIUM_LOG(WARNING)
+ << "fallocate failed to set shm size: " << strerror(rv);
+ return false;
+ }
+ fallocateError = mozilla::Some(rv);
+ }
+# endif
+
+ // If posix_fallocate isn't supported / relevant for this type of
+ // file (either failed with an expected error, or wasn't attempted),
+ // then set the size with ftruncate:
+ if (fallocateError != mozilla::Some(0)) {
+ int rv = HANDLE_EINTR(ftruncate(fd.get(), static_cast<off_t>(size)));
+ if (rv != 0) {
+ int ftruncate_errno = errno;
+ if (fallocateError) {
+ CHROMIUM_LOG(WARNING) << "fallocate failed to set shm size: "
+ << strerror(*fallocateError);
+ }
+ CHROMIUM_LOG(WARNING)
+ << "ftruncate failed to set shm size: " << strerror(ftruncate_errno);
+ return false;
+ }
+ }
+
+ mapped_file_ = std::move(fd);
+ frozen_file_ = std::move(frozen_fd);
+ max_size_ = size;
+ freezeable_ = freezeable;
+ is_memfd_ = is_memfd;
+ return true;
+}
+
+bool SharedMemory::ReadOnlyCopy(SharedMemory* ro_out) {
+ DCHECK(mapped_file_);
+ DCHECK(!read_only_);
+ CHECK(freezeable_);
+
+ if (ro_out == this) {
+ DCHECK(!memory_);
+ }
+
+# ifdef USE_MEMFD_CREATE
+# ifdef MOZ_VALGRIND
+ // Valgrind allows memfd_create but doesn't understand F_ADD_SEALS.
+ static const bool haveSeals = RUNNING_ON_VALGRIND == 0;
+# else
+ static const bool haveSeals = true;
+# endif
+ static const bool useSeals = !PR_GetEnv("MOZ_SHM_NO_SEALS");
+ if (is_memfd_ && haveSeals && useSeals) {
+ // Seals are added to the file as defense-in-depth. The primary
+ // method of access control is creating a read-only fd (using
+ // procfs in this case) and requiring that sandboxes processes not
+ // have access to /proc/self/fd to regain write permission; this
+ // is the same as with shm_open.
+ //
+ // Unfortunately, F_SEAL_WRITE is unreliable: if the process
+ // forked while there was a writeable mapping, it will inherit a
+ // copy of the mapping, which causes the seal to fail.
+ //
+ // (Also, in the future we may want to split this into separate
+ // classes for mappings and shared memory handles, which would
+ // complicate identifying the case where `F_SEAL_WRITE` would be
+ // possible even in the absence of races with fork.)
+ //
+ // However, Linux 5.1 added F_SEAL_FUTURE_WRITE, which prevents
+ // write operations afterwards, but existing writeable mappings
+ // are unaffected (similar to ashmem protection semantics).
+
+ const int seals = F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL;
+ int sealError = EINVAL;
+
+# ifdef F_SEAL_FUTURE_WRITE
+ sealError =
+ fcntl(mapped_file_.get(), F_ADD_SEALS, seals | F_SEAL_FUTURE_WRITE) == 0
+ ? 0
+ : errno;
+# endif // F_SEAL_FUTURE_WRITE
+ if (sealError == EINVAL) {
+ sealError =
+ fcntl(mapped_file_.get(), F_ADD_SEALS, seals) == 0 ? 0 : errno;
+ }
+ if (sealError != 0) {
+ CHROMIUM_LOG(WARNING) << "failed to seal memfd: " << strerror(errno);
+ return false;
+ }
+ }
+# else // !USE_MEMFD_CREATE
+ DCHECK(!is_memfd_);
+# endif
+
+ DCHECK(frozen_file_);
+ DCHECK(mapped_file_);
+ mapped_file_ = nullptr;
+ mozilla::UniqueFileHandle ro_file = std::move(frozen_file_);
+
+ DCHECK(ro_file);
+ freezeable_ = false;
+ ro_out->Close();
+ ro_out->mapped_file_ = std::move(ro_file);
+ ro_out->max_size_ = max_size_;
+ ro_out->read_only_ = true;
+ ro_out->freezeable_ = false;
+
+ return true;
+}
+
+#endif // not Android
+
+#ifndef MAP_NORESERVE
+# define MAP_NORESERVE 0
+#endif
+
+bool SharedMemory::Map(size_t bytes, void* fixed_address) {
+ if (!mapped_file_) {
+ return false;
+ }
+ DCHECK(!memory_);
+
+ // Don't use MAP_FIXED when a fixed_address was specified, since that can
+ // replace pages that are alread mapped at that address.
+ void* mem =
+ mmap(fixed_address, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
+ MAP_SHARED, mapped_file_.get(), 0);
+
+ if (mem == MAP_FAILED) {
+ CHROMIUM_LOG(WARNING) << "Call to mmap failed: " << strerror(errno);
+ return false;
+ }
+
+ if (fixed_address && mem != fixed_address) {
+ bool munmap_succeeded = munmap(mem, bytes) == 0;
+ DCHECK(munmap_succeeded) << "Call to munmap failed, errno=" << errno;
+ return false;
+ }
+
+ memory_ = UniqueMapping(mem, MappingDeleter(bytes));
+ return true;
+}
+
+void* SharedMemory::FindFreeAddressSpace(size_t size) {
+ void* memory = mmap(nullptr, size, PROT_NONE,
+ MAP_ANONYMOUS | MAP_NORESERVE | MAP_PRIVATE, -1, 0);
+ if (memory == MAP_FAILED) {
+ return nullptr;
+ }
+ munmap(memory, size);
+ return memory;
+}
+
+SharedMemoryHandle SharedMemory::CloneHandle() {
+ freezeable_ = false;
+ const int new_fd = dup(mapped_file_.get());
+ if (new_fd < 0) {
+ CHROMIUM_LOG(WARNING) << "failed to duplicate file descriptor: "
+ << strerror(errno);
+ return nullptr;
+ }
+ return mozilla::UniqueFileHandle(new_fd);
+}
+void SharedMemory::Close(bool unmap_view) {
+ if (unmap_view) {
+ Unmap();
+ }
+
+ mapped_file_ = nullptr;
+#ifndef ANDROID
+ if (frozen_file_) {
+ CHROMIUM_LOG(WARNING) << "freezeable shared memory was never frozen";
+ frozen_file_ = nullptr;
+ }
+#endif
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/shared_memory_win.cc b/ipc/chromium/src/base/shared_memory_win.cc
new file mode 100644
index 0000000000..8269912156
--- /dev/null
+++ b/ipc/chromium/src/base/shared_memory_win.cc
@@ -0,0 +1,266 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/shared_memory.h"
+
+#include "base/logging.h"
+#include "base/win_util.h"
+#include "base/string_util.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/RandomNum.h"
+#include "nsDebug.h"
+#include "nsString.h"
+#ifdef MOZ_MEMORY
+# include "mozmemory_utils.h"
+#endif
+
+namespace {
+// NtQuerySection is an internal (but believed to be stable) API and the
+// structures it uses are defined in nt_internals.h.
+// So we have to define them ourselves.
+typedef enum _SECTION_INFORMATION_CLASS {
+ SectionBasicInformation,
+} SECTION_INFORMATION_CLASS;
+
+typedef struct _SECTION_BASIC_INFORMATION {
+ PVOID BaseAddress;
+ ULONG Attributes;
+ LARGE_INTEGER Size;
+} SECTION_BASIC_INFORMATION, *PSECTION_BASIC_INFORMATION;
+
+typedef ULONG(__stdcall* NtQuerySectionType)(
+ HANDLE SectionHandle, SECTION_INFORMATION_CLASS SectionInformationClass,
+ PVOID SectionInformation, ULONG SectionInformationLength,
+ PULONG ResultLength);
+
+// Checks if the section object is safe to map. At the moment this just means
+// it's not an image section.
+bool IsSectionSafeToMap(HANDLE handle) {
+ static NtQuerySectionType nt_query_section_func =
+ reinterpret_cast<NtQuerySectionType>(
+ ::GetProcAddress(::GetModuleHandle(L"ntdll.dll"), "NtQuerySection"));
+ DCHECK(nt_query_section_func);
+
+ // The handle must have SECTION_QUERY access for this to succeed.
+ SECTION_BASIC_INFORMATION basic_information = {};
+ ULONG status =
+ nt_query_section_func(handle, SectionBasicInformation, &basic_information,
+ sizeof(basic_information), nullptr);
+ if (status) {
+ return false;
+ }
+
+ return (basic_information.Attributes & SEC_IMAGE) != SEC_IMAGE;
+}
+
+} // namespace
+
+namespace base {
+
+void SharedMemory::MappingDeleter::operator()(void* ptr) {
+ UnmapViewOfFile(ptr);
+}
+
+SharedMemory::~SharedMemory() = default;
+
+bool SharedMemory::SetHandle(SharedMemoryHandle handle, bool read_only) {
+ DCHECK(!mapped_file_);
+
+ external_section_ = true;
+ freezeable_ = false; // just in case
+ mapped_file_ = std::move(handle);
+ read_only_ = read_only;
+ return true;
+}
+
+// static
+bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
+ return handle != nullptr;
+}
+
+// static
+SharedMemoryHandle SharedMemory::NULLHandle() { return nullptr; }
+
+// Wrapper around CreateFileMappingW for pagefile-backed regions. When out of
+// memory, may attempt to stall and retry rather than returning immediately, in
+// hopes that the page file is about to be expanded by Windows. (bug 1822383,
+// bug 1716727)
+//
+// This method is largely a copy of the MozVirtualAlloc method from
+// mozjemalloc.cpp, which implements this strategy for VirtualAlloc calls,
+// except re-purposed to handle CreateFileMapping.
+static HANDLE MozCreateFileMappingW(
+ LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect,
+ DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCWSTR lpName) {
+#ifdef MOZ_MEMORY
+ constexpr auto IsOOMError = [] {
+ return ::GetLastError() == ERROR_COMMITMENT_LIMIT;
+ };
+
+ {
+ HANDLE handle = ::CreateFileMappingW(
+ INVALID_HANDLE_VALUE, lpFileMappingAttributes, flProtect,
+ dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
+ if (MOZ_LIKELY(handle)) {
+ MOZ_DIAGNOSTIC_ASSERT(handle != INVALID_HANDLE_VALUE,
+ "::CreateFileMapping should return NULL, not "
+ "INVALID_HANDLE_VALUE, on failure");
+ return handle;
+ }
+
+ // We can't do anything for errors other than OOM.
+ if (!IsOOMError()) {
+ return nullptr;
+ }
+ }
+
+ // Retry as many times as desired (possibly zero).
+ const mozilla::StallSpecs stallSpecs = mozilla::GetAllocatorStallSpecs();
+
+ const auto ret =
+ stallSpecs.StallAndRetry(&::Sleep, [&]() -> std::optional<HANDLE> {
+ HANDLE handle = ::CreateFileMappingW(
+ INVALID_HANDLE_VALUE, lpFileMappingAttributes, flProtect,
+ dwMaximumSizeHigh, dwMaximumSizeLow, lpName);
+
+ if (handle) {
+ MOZ_DIAGNOSTIC_ASSERT(handle != INVALID_HANDLE_VALUE,
+ "::CreateFileMapping should return NULL, not "
+ "INVALID_HANDLE_VALUE, on failure");
+ return handle;
+ }
+
+ // Failure for some reason other than OOM.
+ if (!IsOOMError()) {
+ return nullptr;
+ }
+
+ return std::nullopt;
+ });
+
+ return ret.value_or(nullptr);
+#else
+ return ::CreateFileMappingW(INVALID_HANDLE_VALUE, lpFileMappingAttributes,
+ flProtect, dwMaximumSizeHigh, dwMaximumSizeLow,
+ lpName);
+#endif
+}
+
+bool SharedMemory::CreateInternal(size_t size, bool freezeable) {
+ DCHECK(!mapped_file_);
+ read_only_ = false;
+
+ // If the shared memory object has no DACL, any process can
+ // duplicate its handles with any access rights; e.g., re-add write
+ // access to a read-only handle. To prevent that, we give it an
+ // empty DACL, so that no process can do that.
+ SECURITY_ATTRIBUTES sa, *psa = nullptr;
+ SECURITY_DESCRIPTOR sd;
+ ACL dacl;
+
+ if (freezeable) {
+ psa = &sa;
+ sa.nLength = sizeof(sa);
+ sa.lpSecurityDescriptor = &sd;
+ sa.bInheritHandle = FALSE;
+
+ if (NS_WARN_IF(!InitializeAcl(&dacl, sizeof(dacl), ACL_REVISION)) ||
+ NS_WARN_IF(
+ !InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) ||
+ NS_WARN_IF(!SetSecurityDescriptorDacl(&sd, TRUE, &dacl, FALSE))) {
+ return false;
+ }
+ }
+
+ mapped_file_.reset(MozCreateFileMappingW(psa, PAGE_READWRITE, 0,
+ static_cast<DWORD>(size), nullptr));
+ if (!mapped_file_) return false;
+
+ max_size_ = size;
+ freezeable_ = freezeable;
+ return true;
+}
+
+bool SharedMemory::ReadOnlyCopy(SharedMemory* ro_out) {
+ DCHECK(!read_only_);
+ CHECK(freezeable_);
+
+ if (ro_out == this) {
+ DCHECK(!memory_);
+ }
+
+ HANDLE ro_handle;
+ if (!::DuplicateHandle(GetCurrentProcess(), mapped_file_.release(),
+ GetCurrentProcess(), &ro_handle,
+ GENERIC_READ | FILE_MAP_READ, false,
+ DUPLICATE_CLOSE_SOURCE)) {
+ // DUPLICATE_CLOSE_SOURCE applies even if there is an error.
+ return false;
+ }
+
+ freezeable_ = false;
+
+ ro_out->Close();
+ ro_out->mapped_file_.reset(ro_handle);
+ ro_out->max_size_ = max_size_;
+ ro_out->read_only_ = true;
+ ro_out->freezeable_ = false;
+ ro_out->external_section_ = external_section_;
+
+ return true;
+}
+
+bool SharedMemory::Map(size_t bytes, void* fixed_address) {
+ if (!mapped_file_) {
+ return false;
+ }
+
+ if (external_section_ && !IsSectionSafeToMap(mapped_file_.get())) {
+ return false;
+ }
+
+ void* mem = MapViewOfFileEx(
+ mapped_file_.get(),
+ read_only_ ? FILE_MAP_READ : FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, bytes,
+ fixed_address);
+ if (mem) {
+ MOZ_ASSERT(!fixed_address || mem == fixed_address,
+ "MapViewOfFileEx returned an expected address");
+ memory_.reset(mem);
+ return true;
+ }
+ return false;
+}
+
+void* SharedMemory::FindFreeAddressSpace(size_t size) {
+ void* memory = VirtualAlloc(NULL, size, MEM_RESERVE, PAGE_NOACCESS);
+ if (memory) {
+ VirtualFree(memory, 0, MEM_RELEASE);
+ }
+ return memory;
+}
+
+SharedMemoryHandle SharedMemory::CloneHandle() {
+ freezeable_ = false;
+ HANDLE handle = INVALID_HANDLE_VALUE;
+ if (DuplicateHandle(GetCurrentProcess(), mapped_file_.get(),
+ GetCurrentProcess(), &handle, 0, false,
+ DUPLICATE_SAME_ACCESS)) {
+ return SharedMemoryHandle(handle);
+ }
+ NS_WARNING("DuplicateHandle Failed!");
+ return nullptr;
+}
+
+void SharedMemory::Close(bool unmap_view) {
+ if (unmap_view) {
+ Unmap();
+ }
+
+ mapped_file_ = nullptr;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/stack_container.h b/ipc/chromium/src/base/stack_container.h
new file mode 100644
index 0000000000..d9add9904c
--- /dev/null
+++ b/ipc/chromium/src/base/stack_container.h
@@ -0,0 +1,244 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_STACK_CONTAINER_H_
+#define BASE_STACK_CONTAINER_H_
+
+#include <string>
+#include <vector>
+
+#include "base/basictypes.h"
+
+// This allocator can be used with STL containers to provide a stack buffer
+// from which to allocate memory and overflows onto the heap. This stack buffer
+// would be allocated on the stack and allows us to avoid heap operations in
+// some situations.
+//
+// STL likes to make copies of allocators, so the allocator itself can't hold
+// the data. Instead, we make the creator responsible for creating a
+// StackAllocator::Source which contains the data. Copying the allocator
+// merely copies the pointer to this shared source, so all allocators created
+// based on our allocator will share the same stack buffer.
+//
+// This stack buffer implementation is very simple. The first allocation that
+// fits in the stack buffer will use the stack buffer. Any subsequent
+// allocations will not use the stack buffer, even if there is unused room.
+// This makes it appropriate for array-like containers, but the caller should
+// be sure to reserve() in the container up to the stack buffer size. Otherwise
+// the container will allocate a small array which will "use up" the stack
+// buffer.
+template <typename T, size_t stack_capacity>
+class StackAllocator : public std::allocator<T> {
+ public:
+ typedef typename std::allocator<T>::pointer pointer;
+ typedef typename std::allocator<T>::size_type size_type;
+
+ // Backing store for the allocator. The container owner is responsible for
+ // maintaining this for as long as any containers using this allocator are
+ // live.
+ struct Source {
+ Source() : used_stack_buffer_(false) {}
+
+ // Casts the buffer in its right type.
+ T* stack_buffer() { return reinterpret_cast<T*>(stack_buffer_); }
+ const T* stack_buffer() const {
+ return reinterpret_cast<const T*>(stack_buffer_);
+ }
+
+ //
+ // IMPORTANT: Take care to ensure that stack_buffer_ is aligned
+ // since it is used to mimic an array of T.
+ // Be careful while declaring any unaligned types (like bool)
+ // before stack_buffer_.
+ //
+
+ // The buffer itself. It is not of type T because we don't want the
+ // constructors and destructors to be automatically called. Define a POD
+ // buffer of the right size instead.
+ char stack_buffer_[sizeof(T[stack_capacity])];
+
+ // Set when the stack buffer is used for an allocation. We do not track
+ // how much of the buffer is used, only that somebody is using it.
+ bool used_stack_buffer_;
+ };
+
+ // Used by containers when they want to refer to an allocator of type U.
+ template <typename U>
+ struct rebind {
+ typedef StackAllocator<U, stack_capacity> other;
+ };
+
+ // For the straight up copy c-tor, we can share storage.
+ StackAllocator(const StackAllocator<T, stack_capacity>& rhs)
+ : source_(rhs.source_) {}
+
+ // ISO C++ requires the following constructor to be defined,
+ // and std::vector in VC++2008SP1 Release fails with an error
+ // in the class _Container_base_aux_alloc_real (from <xutility>)
+ // if the constructor does not exist.
+ // For this constructor, we cannot share storage; there's
+ // no guarantee that the Source buffer of Ts is large enough
+ // for Us.
+ // TODO: If we were fancy pants, perhaps we could share storage
+ // iff sizeof(T) == sizeof(U).
+ template <typename U, size_t other_capacity>
+ explicit StackAllocator(const StackAllocator<U, other_capacity>& other)
+ : source_(NULL) {}
+
+ explicit StackAllocator(Source* source) : source_(source) {}
+
+ // Actually do the allocation. Use the stack buffer if nobody has used it yet
+ // and the size requested fits. Otherwise, fall through to the standard
+ // allocator.
+ pointer allocate(size_type n, void* hint = 0) {
+ if (source_ != NULL && !source_->used_stack_buffer_ &&
+ n <= stack_capacity) {
+ source_->used_stack_buffer_ = true;
+ return source_->stack_buffer();
+ } else {
+ return std::allocator<T>::allocate(n, hint);
+ }
+ }
+
+ // Free: when trying to free the stack buffer, just mark it as free. For
+ // non-stack-buffer pointers, just fall though to the standard allocator.
+ void deallocate(pointer p, size_type n) {
+ if (source_ != NULL && p == source_->stack_buffer())
+ source_->used_stack_buffer_ = false;
+ else
+ std::allocator<T>::deallocate(p, n);
+ }
+
+ private:
+ Source* source_;
+};
+
+// A wrapper around STL containers that maintains a stack-sized buffer that the
+// initial capacity of the vector is based on. Growing the container beyond the
+// stack capacity will transparently overflow onto the heap. The container must
+// support reserve().
+//
+// WATCH OUT: the ContainerType MUST use the proper StackAllocator for this
+// type. This object is really intended to be used only internally. You'll want
+// to use the wrappers below for different types.
+template <typename TContainerType, int stack_capacity>
+class StackContainer {
+ public:
+ typedef TContainerType ContainerType;
+ typedef typename ContainerType::value_type ContainedType;
+ typedef StackAllocator<ContainedType, stack_capacity> Allocator;
+
+ // Allocator must be constructed before the container!
+ StackContainer() : allocator_(&stack_data_), container_(allocator_) {
+ // Make the container use the stack allocation by reserving our buffer size
+ // before doing anything else.
+ container_.reserve(stack_capacity);
+ }
+
+ // Getters for the actual container.
+ //
+ // Danger: any copies of this made using the copy constructor must have
+ // shorter lifetimes than the source. The copy will share the same allocator
+ // and therefore the same stack buffer as the original. Use std::copy to
+ // copy into a "real" container for longer-lived objects.
+ ContainerType& container() { return container_; }
+ const ContainerType& container() const { return container_; }
+
+ // Support operator-> to get to the container. This allows nicer syntax like:
+ // StackContainer<...> foo;
+ // std::sort(foo->begin(), foo->end());
+ ContainerType* operator->() { return &container_; }
+ const ContainerType* operator->() const { return &container_; }
+
+#ifdef UNIT_TEST
+ // Retrieves the stack source so that that unit tests can verify that the
+ // buffer is being used properly.
+ const typename Allocator::Source& stack_data() const { return stack_data_; }
+#endif
+
+ protected:
+ typename Allocator::Source stack_data_;
+ Allocator allocator_;
+ ContainerType container_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(StackContainer);
+};
+
+// StackString
+template <size_t stack_capacity>
+class StackString
+ : public StackContainer<
+ std::basic_string<char, std::char_traits<char>,
+ StackAllocator<char, stack_capacity> >,
+ stack_capacity> {
+ public:
+ StackString()
+ : StackContainer<std::basic_string<char, std::char_traits<char>,
+ StackAllocator<char, stack_capacity> >,
+ stack_capacity>() {}
+
+ private:
+ DISALLOW_EVIL_CONSTRUCTORS(StackString);
+};
+
+// StackWString
+template <size_t stack_capacity>
+class StackWString
+ : public StackContainer<
+ std::basic_string<wchar_t, std::char_traits<wchar_t>,
+ StackAllocator<wchar_t, stack_capacity> >,
+ stack_capacity> {
+ public:
+ StackWString()
+ : StackContainer<
+ std::basic_string<wchar_t, std::char_traits<wchar_t>,
+ StackAllocator<wchar_t, stack_capacity> >,
+ stack_capacity>() {}
+
+ private:
+ DISALLOW_EVIL_CONSTRUCTORS(StackWString);
+};
+
+// StackVector
+//
+// Example:
+// StackVector<int, 16> foo;
+// foo->push_back(22); // we have overloaded operator->
+// foo[0] = 10; // as well as operator[]
+template <typename T, size_t stack_capacity>
+class StackVector
+ : public StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
+ stack_capacity> {
+ public:
+ StackVector()
+ : StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
+ stack_capacity>() {}
+
+ // We need to put this in STL containers sometimes, which requires a copy
+ // constructor. We can't call the regular copy constructor because that will
+ // take the stack buffer from the original. Here, we create an empty object
+ // and make a stack buffer of its own.
+ StackVector(const StackVector<T, stack_capacity>& other)
+ : StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
+ stack_capacity>() {
+ this->container().assign(other->begin(), other->end());
+ }
+
+ StackVector<T, stack_capacity>& operator=(
+ const StackVector<T, stack_capacity>& other) {
+ this->container().assign(other->begin(), other->end());
+ return *this;
+ }
+
+ // Vectors are commonly indexed, which isn't very convenient even with
+ // operator-> (using "->at()" does exception stuff we don't want).
+ T& operator[](size_t i) { return this->container().operator[](i); }
+ const T& operator[](size_t i) const {
+ return this->container().operator[](i);
+ }
+};
+
+#endif // BASE_STACK_CONTAINER_H_
diff --git a/ipc/chromium/src/base/stl_util-inl.h b/ipc/chromium/src/base/stl_util-inl.h
new file mode 100644
index 0000000000..034c16049c
--- /dev/null
+++ b/ipc/chromium/src/base/stl_util-inl.h
@@ -0,0 +1,435 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// STL utility functions. Usually, these replace built-in, but slow(!),
+// STL functions with more efficient versions.
+
+#ifndef BASE_STL_UTIL_INL_H_
+#define BASE_STL_UTIL_INL_H_
+
+#include <string.h> // for memcpy
+#include <functional>
+#include <set>
+#include <string>
+#include <vector>
+#include <cassert>
+
+// Clear internal memory of an STL object.
+// STL clear()/reserve(0) does not always free internal memory allocated
+// This function uses swap/destructor to ensure the internal memory is freed.
+template <class T>
+void STLClearObject(T* obj) {
+ T tmp;
+ tmp.swap(*obj);
+ obj->reserve(0); // this is because sometimes "T tmp" allocates objects with
+ // memory (arena implementation?). use reserve()
+ // to clear() even if it doesn't always work
+}
+
+// Reduce memory usage on behalf of object if it is using more than
+// "bytes" bytes of space. By default, we clear objects over 1MB.
+template <class T>
+inline void STLClearIfBig(T* obj, size_t limit = 1 << 20) {
+ if (obj->capacity() >= limit) {
+ STLClearObject(obj);
+ } else {
+ obj->clear();
+ }
+}
+
+// Reserve space for STL object.
+// STL's reserve() will always copy.
+// This function avoid the copy if we already have capacity
+template <class T>
+void STLReserveIfNeeded(T* obj, int new_size) {
+ if (obj->capacity() < new_size) // increase capacity
+ obj->reserve(new_size);
+ else if (obj->size() > new_size) // reduce size
+ obj->resize(new_size);
+}
+
+// STLDeleteContainerPointers()
+// For a range within a container of pointers, calls delete
+// (non-array version) on these pointers.
+// NOTE: for these three functions, we could just implement a DeleteObject
+// functor and then call for_each() on the range and functor, but this
+// requires us to pull in all of algorithm.h, which seems expensive.
+// For hash_[multi]set, it is important that this deletes behind the iterator
+// because the hash_set may call the hash function on the iterator when it is
+// advanced, which could result in the hash function trying to deference a
+// stale pointer.
+template <class ForwardIterator>
+void STLDeleteContainerPointers(ForwardIterator begin, ForwardIterator end) {
+ while (begin != end) {
+ ForwardIterator temp = begin;
+ ++begin;
+ delete *temp;
+ }
+}
+
+// STLDeleteContainerPairPointers()
+// For a range within a container of pairs, calls delete
+// (non-array version) on BOTH items in the pairs.
+// NOTE: Like STLDeleteContainerPointers, it is important that this deletes
+// behind the iterator because if both the key and value are deleted, the
+// container may call the hash function on the iterator when it is advanced,
+// which could result in the hash function trying to dereference a stale
+// pointer.
+template <class ForwardIterator>
+void STLDeleteContainerPairPointers(ForwardIterator begin,
+ ForwardIterator end) {
+ while (begin != end) {
+ ForwardIterator temp = begin;
+ ++begin;
+ delete temp->first;
+ delete temp->second;
+ }
+}
+
+// STLDeleteContainerPairFirstPointers()
+// For a range within a container of pairs, calls delete (non-array version)
+// on the FIRST item in the pairs.
+// NOTE: Like STLDeleteContainerPointers, deleting behind the iterator.
+template <class ForwardIterator>
+void STLDeleteContainerPairFirstPointers(ForwardIterator begin,
+ ForwardIterator end) {
+ while (begin != end) {
+ ForwardIterator temp = begin;
+ ++begin;
+ delete temp->first;
+ }
+}
+
+// STLDeleteContainerPairSecondPointers()
+// For a range within a container of pairs, calls delete
+// (non-array version) on the SECOND item in the pairs.
+template <class ForwardIterator>
+void STLDeleteContainerPairSecondPointers(ForwardIterator begin,
+ ForwardIterator end) {
+ while (begin != end) {
+ delete begin->second;
+ ++begin;
+ }
+}
+
+template <typename T>
+inline void STLAssignToVector(std::vector<T>* vec, const T* ptr, size_t n) {
+ vec->resize(n);
+ memcpy(&vec->front(), ptr, n * sizeof(T));
+}
+
+/***** Hack to allow faster assignment to a vector *****/
+
+// This routine speeds up an assignment of 32 bytes to a vector from
+// about 250 cycles per assignment to about 140 cycles.
+//
+// Usage:
+// STLAssignToVectorChar(&vec, ptr, size);
+// STLAssignToString(&str, ptr, size);
+
+inline void STLAssignToVectorChar(std::vector<char>* vec, const char* ptr,
+ size_t n) {
+ STLAssignToVector(vec, ptr, n);
+}
+
+inline void STLAssignToString(std::string* str, const char* ptr, size_t n) {
+ str->resize(n);
+ memcpy(&*str->begin(), ptr, n);
+}
+
+// To treat a possibly-empty vector as an array, use these functions.
+// If you know the array will never be empty, you can use &*v.begin()
+// directly, but that is allowed to dump core if v is empty. This
+// function is the most efficient code that will work, taking into
+// account how our STL is actually implemented. THIS IS NON-PORTABLE
+// CODE, so call us instead of repeating the nonportable code
+// everywhere. If our STL implementation changes, we will need to
+// change this as well.
+
+template <typename T>
+inline T* vector_as_array(std::vector<T>* v) {
+#ifdef NDEBUG
+ return &*v->begin();
+#else
+ return v->empty() ? NULL : &*v->begin();
+#endif
+}
+
+template <typename T>
+inline const T* vector_as_array(const std::vector<T>* v) {
+#ifdef NDEBUG
+ return &*v->begin();
+#else
+ return v->empty() ? NULL : &*v->begin();
+#endif
+}
+
+// Return a mutable char* pointing to a string's internal buffer,
+// which may not be null-terminated. Writing through this pointer will
+// modify the string.
+//
+// string_as_array(&str)[i] is valid for 0 <= i < str.size() until the
+// next call to a string method that invalidates iterators.
+//
+// As of 2006-04, there is no standard-blessed way of getting a
+// mutable reference to a string's internal buffer. However, issue 530
+// (http://www.open-std.org/JTC1/SC22/WG21/docs/lwg-active.html#530)
+// proposes this as the method. According to Matt Austern, this should
+// already work on all current implementations.
+inline char* string_as_array(std::string* str) {
+ // DO NOT USE const_cast<char*>(str->data())! See the unittest for why.
+ return str->empty() ? NULL : &*str->begin();
+}
+
+// These are methods that test two hash maps/sets for equality. These exist
+// because the == operator in the STL can return false when the maps/sets
+// contain identical elements. This is because it compares the internal hash
+// tables which may be different if the order of insertions and deletions
+// differed.
+
+template <class HashSet>
+inline bool HashSetEquality(const HashSet& set_a, const HashSet& set_b) {
+ if (set_a.size() != set_b.size()) return false;
+ for (typename HashSet::const_iterator i = set_a.begin(); i != set_a.end();
+ ++i) {
+ if (set_b.find(*i) == set_b.end()) return false;
+ }
+ return true;
+}
+
+template <class HashMap>
+inline bool HashMapEquality(const HashMap& map_a, const HashMap& map_b) {
+ if (map_a.size() != map_b.size()) return false;
+ for (typename HashMap::const_iterator i = map_a.begin(); i != map_a.end();
+ ++i) {
+ typename HashMap::const_iterator j = map_b.find(i->first);
+ if (j == map_b.end()) return false;
+ if (i->second != j->second) return false;
+ }
+ return true;
+}
+
+// The following functions are useful for cleaning up STL containers
+// whose elements point to allocated memory.
+
+// STLDeleteElements() deletes all the elements in an STL container and clears
+// the container. This function is suitable for use with a vector, set,
+// hash_set, or any other STL container which defines sensible begin(), end(),
+// and clear() methods.
+//
+// If container is NULL, this function is a no-op.
+//
+// As an alternative to calling STLDeleteElements() directly, consider
+// STLElementDeleter (defined below), which ensures that your container's
+// elements are deleted when the STLElementDeleter goes out of scope.
+template <class T>
+void STLDeleteElements(T* container) {
+ if (!container) return;
+ STLDeleteContainerPointers(container->begin(), container->end());
+ container->clear();
+}
+
+// Given an STL container consisting of (key, value) pairs, STLDeleteValues
+// deletes all the "value" components and clears the container. Does nothing
+// in the case it's given a NULL pointer.
+
+template <class T>
+void STLDeleteValues(T* v) {
+ if (!v) return;
+ for (typename T::iterator i = v->begin(); i != v->end(); ++i) {
+ delete i->second;
+ }
+ v->clear();
+}
+
+// The following classes provide a convenient way to delete all elements or
+// values from STL containers when they goes out of scope. This greatly
+// simplifies code that creates temporary objects and has multiple return
+// statements. Example:
+//
+// vector<MyProto *> tmp_proto;
+// STLElementDeleter<vector<MyProto *> > d(&tmp_proto);
+// if (...) return false;
+// ...
+// return success;
+
+// Given a pointer to an STL container this class will delete all the element
+// pointers when it goes out of scope.
+
+template <class STLContainer>
+class STLElementDeleter {
+ public:
+ explicit STLElementDeleter(STLContainer* ptr) : container_ptr_(ptr) {}
+ ~STLElementDeleter() { STLDeleteElements(container_ptr_); }
+
+ private:
+ STLContainer* container_ptr_;
+};
+
+// Given a pointer to an STL container this class will delete all the value
+// pointers when it goes out of scope.
+
+template <class STLContainer>
+class STLValueDeleter {
+ public:
+ explicit STLValueDeleter(STLContainer* ptr) : container_ptr_(ptr) {}
+ ~STLValueDeleter() { STLDeleteValues(container_ptr_); }
+
+ private:
+ STLContainer* container_ptr_;
+};
+
+// Forward declare some callback classes in callback.h for STLBinaryFunction
+template <class R, class T1, class T2>
+class ResultCallback2;
+
+// STLBinaryFunction is a wrapper for the ResultCallback2 class in callback.h
+// It provides an operator () method instead of a Run method, so it may be
+// passed to STL functions in <algorithm>.
+//
+// The client should create callback with NewPermanentCallback, and should
+// delete callback after it is done using the STLBinaryFunction.
+
+template <class Result, class Arg1, class Arg2>
+class STLBinaryFunction : public std::binary_function<Arg1, Arg2, Result> {
+ public:
+ typedef ResultCallback2<Result, Arg1, Arg2> Callback;
+
+ explicit STLBinaryFunction(Callback* callback) : callback_(callback) {
+ assert(callback_);
+ }
+
+ Result operator()(Arg1 arg1, Arg2 arg2) { return callback_->Run(arg1, arg2); }
+
+ private:
+ Callback* callback_;
+};
+
+// STLBinaryPredicate is a specialized version of STLBinaryFunction, where the
+// return type is bool and both arguments have type Arg. It can be used
+// wherever STL requires a StrictWeakOrdering, such as in sort() or
+// lower_bound().
+//
+// templated typedefs are not supported, so instead we use inheritance.
+
+template <class Arg>
+class STLBinaryPredicate : public STLBinaryFunction<bool, Arg, Arg> {
+ public:
+ typedef typename STLBinaryPredicate<Arg>::Callback Callback;
+ explicit STLBinaryPredicate(Callback* callback)
+ : STLBinaryFunction<bool, Arg, Arg>(callback) {}
+};
+
+// Functors that compose arbitrary unary and binary functions with a
+// function that "projects" one of the members of a pair.
+// Specifically, if p1 and p2, respectively, are the functions that
+// map a pair to its first and second, respectively, members, the
+// table below summarizes the functions that can be constructed:
+//
+// * UnaryOperate1st<pair>(f) returns the function x -> f(p1(x))
+// * UnaryOperate2nd<pair>(f) returns the function x -> f(p2(x))
+// * BinaryOperate1st<pair>(f) returns the function (x,y) -> f(p1(x),p1(y))
+// * BinaryOperate2nd<pair>(f) returns the function (x,y) -> f(p2(x),p2(y))
+//
+// A typical usage for these functions would be when iterating over
+// the contents of an STL map. For other sample usage, see the unittest.
+
+template <typename Pair, typename UnaryOp>
+class UnaryOperateOnFirst
+ : public std::unary_function<Pair, typename UnaryOp::result_type> {
+ public:
+ UnaryOperateOnFirst() {}
+
+ explicit UnaryOperateOnFirst(const UnaryOp& f) : f_(f) {}
+
+ typename UnaryOp::result_type operator()(const Pair& p) const {
+ return f_(p.first);
+ }
+
+ private:
+ UnaryOp f_;
+};
+
+template <typename Pair, typename UnaryOp>
+UnaryOperateOnFirst<Pair, UnaryOp> UnaryOperate1st(const UnaryOp& f) {
+ return UnaryOperateOnFirst<Pair, UnaryOp>(f);
+}
+
+template <typename Pair, typename UnaryOp>
+class UnaryOperateOnSecond
+ : public std::unary_function<Pair, typename UnaryOp::result_type> {
+ public:
+ UnaryOperateOnSecond() {}
+
+ explicit UnaryOperateOnSecond(const UnaryOp& f) : f_(f) {}
+
+ typename UnaryOp::result_type operator()(const Pair& p) const {
+ return f_(p.second);
+ }
+
+ private:
+ UnaryOp f_;
+};
+
+template <typename Pair, typename UnaryOp>
+UnaryOperateOnSecond<Pair, UnaryOp> UnaryOperate2nd(const UnaryOp& f) {
+ return UnaryOperateOnSecond<Pair, UnaryOp>(f);
+}
+
+template <typename Pair, typename BinaryOp>
+class BinaryOperateOnFirst
+ : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> {
+ public:
+ BinaryOperateOnFirst() {}
+
+ explicit BinaryOperateOnFirst(const BinaryOp& f) : f_(f) {}
+
+ typename BinaryOp::result_type operator()(const Pair& p1,
+ const Pair& p2) const {
+ return f_(p1.first, p2.first);
+ }
+
+ private:
+ BinaryOp f_;
+};
+
+template <typename Pair, typename BinaryOp>
+BinaryOperateOnFirst<Pair, BinaryOp> BinaryOperate1st(const BinaryOp& f) {
+ return BinaryOperateOnFirst<Pair, BinaryOp>(f);
+}
+
+template <typename Pair, typename BinaryOp>
+class BinaryOperateOnSecond
+ : public std::binary_function<Pair, Pair, typename BinaryOp::result_type> {
+ public:
+ BinaryOperateOnSecond() {}
+
+ explicit BinaryOperateOnSecond(const BinaryOp& f) : f_(f) {}
+
+ typename BinaryOp::result_type operator()(const Pair& p1,
+ const Pair& p2) const {
+ return f_(p1.second, p2.second);
+ }
+
+ private:
+ BinaryOp f_;
+};
+
+template <typename Pair, typename BinaryOp>
+BinaryOperateOnSecond<Pair, BinaryOp> BinaryOperate2nd(const BinaryOp& f) {
+ return BinaryOperateOnSecond<Pair, BinaryOp>(f);
+}
+
+// Translates a set into a vector.
+template <typename T>
+std::vector<T> SetToVector(const std::set<T>& values) {
+ std::vector<T> result;
+ result.reserve(values.size());
+ result.insert(result.begin(), values.begin(), values.end());
+ return result;
+}
+
+#endif // BASE_STL_UTIL_INL_H_
diff --git a/ipc/chromium/src/base/string16.cc b/ipc/chromium/src/base/string16.cc
new file mode 100644
index 0000000000..8a0c406eff
--- /dev/null
+++ b/ipc/chromium/src/base/string16.cc
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/string16.h"
+
+#if defined(XP_WIN)
+
+# error This file should not be used on 2-byte wchar_t systems
+// If this winds up being needed on 2-byte wchar_t systems, either the
+// definitions below can be used, or the host system's wide character
+// functions like wmemcmp can be wrapped.
+
+#else
+
+# include "base/string_util.h"
+
+namespace base {
+
+int c16memcmp(const char16* s1, const char16* s2, size_t n) {
+ // We cannot call memcmp because that changes the semantics.
+ while (n-- > 0) {
+ if (*s1 != *s2) {
+ // We cannot use (*s1 - *s2) because char16 is unsigned.
+ return ((*s1 < *s2) ? -1 : 1);
+ }
+ ++s1;
+ ++s2;
+ }
+ return 0;
+}
+
+size_t c16len(const char16* s) {
+ const char16* s_orig = s;
+ while (*s) {
+ ++s;
+ }
+ return s - s_orig;
+}
+
+const char16* c16memchr(const char16* s, char16 c, size_t n) {
+ while (n-- > 0) {
+ if (*s == c) {
+ return s;
+ }
+ ++s;
+ }
+ return 0;
+}
+
+char16* c16memmove(char16* s1, const char16* s2, size_t n) {
+ return reinterpret_cast<char16*>(memmove(s1, s2, n * sizeof(char16)));
+}
+
+char16* c16memcpy(char16* s1, const char16* s2, size_t n) {
+ return reinterpret_cast<char16*>(memcpy(s1, s2, n * sizeof(char16)));
+}
+
+char16* c16memset(char16* s, char16 c, size_t n) {
+ char16* s_orig = s;
+ while (n-- > 0) {
+ *s = c;
+ ++s;
+ }
+ return s_orig;
+}
+
+} // namespace base
+
+template class std::basic_string<char16, base::string16_char_traits>;
+
+#endif
diff --git a/ipc/chromium/src/base/string16.h b/ipc/chromium/src/base/string16.h
new file mode 100644
index 0000000000..c7cc1868e2
--- /dev/null
+++ b/ipc/chromium/src/base/string16.h
@@ -0,0 +1,161 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_STRING16_H_
+#define BASE_STRING16_H_
+
+// WHAT:
+// A version of std::basic_string that provides 2-byte characters even when
+// wchar_t is not implemented as a 2-byte type. You can access this class as
+// string16. We also define char16, which string16 is based upon.
+//
+// WHY:
+// On Windows, wchar_t is 2 bytes, and it can conveniently handle UTF-16/UCS-2
+// data. Plenty of existing code operates on strings encoded as UTF-16.
+//
+// On many other platforms, sizeof(wchar_t) is 4 bytes by default. We can make
+// it 2 bytes by using the GCC flag -fshort-wchar. But then std::wstring fails
+// at run time, because it calls some functions (like wcslen) that come from
+// the system's native C library -- which was built with a 4-byte wchar_t!
+// It's wasteful to use 4-byte wchar_t strings to carry UTF-16 data, and it's
+// entirely improper on those systems where the encoding of wchar_t is defined
+// as UTF-32.
+//
+// Here, we define string16, which is similar to std::wstring but replaces all
+// libc functions with custom, 2-byte-char compatible routines. It is capable
+// of carrying UTF-16-encoded data.
+
+#include <stdio.h>
+#include <string>
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+
+typedef wchar_t char16;
+typedef std::wstring string16;
+
+#else
+
+typedef uint16_t char16;
+
+namespace base {
+
+// char16 versions of the functions required by string16_char_traits; these
+// are based on the wide character functions of similar names ("w" or "wcs"
+// instead of "c16").
+int c16memcmp(const char16* s1, const char16* s2, size_t n);
+size_t c16len(const char16* s);
+const char16* c16memchr(const char16* s, char16 c, size_t n);
+char16* c16memmove(char16* s1, const char16* s2, size_t n);
+char16* c16memcpy(char16* s1, const char16* s2, size_t n);
+char16* c16memset(char16* s, char16 c, size_t n);
+
+struct string16_char_traits {
+ typedef char16 char_type;
+ typedef int int_type;
+
+ // int_type needs to be able to hold each possible value of char_type, and in
+ // addition, the distinct value of eof().
+ COMPILE_ASSERT(sizeof(int_type) > sizeof(char_type), unexpected_type_width);
+
+ typedef std::streamoff off_type;
+ typedef mbstate_t state_type;
+ typedef std::fpos<state_type> pos_type;
+
+ static void assign(char_type& c1, const char_type& c2) { c1 = c2; }
+
+ static bool eq(const char_type& c1, const char_type& c2) { return c1 == c2; }
+ static bool lt(const char_type& c1, const char_type& c2) { return c1 < c2; }
+
+ static int compare(const char_type* s1, const char_type* s2, size_t n) {
+ return c16memcmp(s1, s2, n);
+ }
+
+ static size_t length(const char_type* s) { return c16len(s); }
+
+ static const char_type* find(const char_type* s, size_t n,
+ const char_type& a) {
+ return c16memchr(s, a, n);
+ }
+
+ static char_type* move(char_type* s1, const char_type* s2, int_type n) {
+ return c16memmove(s1, s2, n);
+ }
+
+ static char_type* copy(char_type* s1, const char_type* s2, size_t n) {
+ return c16memcpy(s1, s2, n);
+ }
+
+ static char_type* assign(char_type* s, size_t n, char_type a) {
+ return c16memset(s, a, n);
+ }
+
+ static int_type not_eof(const int_type& c) {
+ return eq_int_type(c, eof()) ? 0 : c;
+ }
+
+ static char_type to_char_type(const int_type& c) { return char_type(c); }
+
+ static int_type to_int_type(const char_type& c) { return int_type(c); }
+
+ static bool eq_int_type(const int_type& c1, const int_type& c2) {
+ return c1 == c2;
+ }
+
+ static int_type eof() { return static_cast<int_type>(EOF); }
+};
+
+} // namespace base
+
+// The string class will be explicitly instantiated only once, in string16.cc.
+//
+// std::basic_string<> in GNU libstdc++ contains a static data member,
+// _S_empty_rep_storage, to represent empty strings. When an operation such
+// as assignment or destruction is performed on a string, causing its existing
+// data member to be invalidated, it must not be freed if this static data
+// member is being used. Otherwise, it counts as an attempt to free static
+// (and not allocated) data, which is a memory error.
+//
+// Generally, due to C++ template magic, _S_empty_rep_storage will be marked
+// as a coalesced symbol, meaning that the linker will combine multiple
+// instances into a single one when generating output.
+//
+// If a string class is used by multiple shared libraries, a problem occurs.
+// Each library will get its own copy of _S_empty_rep_storage. When strings
+// are passed across a library boundary for alteration or destruction, memory
+// errors will result. GNU libstdc++ contains a configuration option,
+// --enable-fully-dynamic-string (_GLIBCXX_FULLY_DYNAMIC_STRING), which
+// disables the static data member optimization, but it's a good optimization
+// and non-STL code is generally at the mercy of the system's STL
+// configuration. Fully-dynamic strings are not the default for GNU libstdc++
+// libstdc++ itself or for the libstdc++ installations on the systems we care
+// about, such as Mac OS X and relevant flavors of Linux.
+//
+// See also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=24196 .
+//
+// To avoid problems, string classes need to be explicitly instantiated only
+// once, in exactly one library. All other string users see it via an "extern"
+// declaration. This is precisely how GNU libstdc++ handles
+// std::basic_string<char> (string) and std::basic_string<wchar_t> (wstring).
+//
+// This also works around a Mac OS X linker bug in ld64-85.2.1 (Xcode 3.1.2),
+// in which the linker does not fully coalesce symbols when dead code
+// stripping is enabled. This bug causes the memory errors described above
+// to occur even when a std::basic_string<> does not cross shared library
+// boundaries, such as in statically-linked executables.
+//
+// TODO(mark): File this bug with Apple and update this note with a bug number.
+
+extern template class std::basic_string<char16, base::string16_char_traits>;
+
+typedef std::basic_string<char16, base::string16_char_traits> string16;
+
+extern std::ostream& operator<<(std::ostream& out, const string16& str);
+
+#endif
+
+#endif // BASE_STRING16_H_
diff --git a/ipc/chromium/src/base/string_piece.cc b/ipc/chromium/src/base/string_piece.cc
new file mode 100644
index 0000000000..7b83df0758
--- /dev/null
+++ b/ipc/chromium/src/base/string_piece.cc
@@ -0,0 +1,190 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+// Copied from strings/stringpiece.cc with modifications
+
+#include <algorithm>
+#include <ostream>
+
+#include "base/string_piece.h"
+
+typedef StringPiece::size_type size_type;
+
+std::ostream& operator<<(std::ostream& o, const StringPiece& piece) {
+ o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
+ return o;
+}
+
+bool operator==(const StringPiece& x, const StringPiece& y) {
+ if (x.size() != y.size()) return false;
+
+ return StringPiece::wordmemcmp(x.data(), y.data(), x.size()) == 0;
+}
+
+void StringPiece::CopyToString(std::string* target) const {
+ target->assign(!empty() ? data() : "", size());
+}
+
+void StringPiece::AppendToString(std::string* target) const {
+ if (!empty()) target->append(data(), size());
+}
+
+size_type StringPiece::copy(char* buf, size_type n, size_type pos) const {
+ size_type ret = std::min(length_ - pos, n);
+ memcpy(buf, ptr_ + pos, ret);
+ return ret;
+}
+
+size_type StringPiece::find(const StringPiece& s, size_type pos) const {
+ if (pos > length_) return npos;
+
+ const char* result =
+ std::search(ptr_ + pos, ptr_ + length_, s.ptr_, s.ptr_ + s.length_);
+ const size_type xpos = result - ptr_;
+ return xpos + s.length_ <= length_ ? xpos : npos;
+}
+
+size_type StringPiece::find(char c, size_type pos) const {
+ if (pos >= length_) return npos;
+
+ const char* result = std::find(ptr_ + pos, ptr_ + length_, c);
+ return result != ptr_ + length_ ? result - ptr_ : npos;
+}
+
+size_type StringPiece::rfind(const StringPiece& s, size_type pos) const {
+ if (length_ < s.length_) return npos;
+
+ if (s.empty()) return std::min(length_, pos);
+
+ const char* last = ptr_ + std::min(length_ - s.length_, pos) + s.length_;
+ const char* result = std::find_end(ptr_, last, s.ptr_, s.ptr_ + s.length_);
+ return result != last ? result - ptr_ : npos;
+}
+
+size_type StringPiece::rfind(char c, size_type pos) const {
+ if (length_ == 0) return npos;
+
+ for (size_type i = std::min(pos, length_ - 1);; --i) {
+ if (ptr_[i] == c) return i;
+ if (i == 0) break;
+ }
+ return npos;
+}
+
+// For each character in characters_wanted, sets the index corresponding
+// to the ASCII code of that character to 1 in table. This is used by
+// the find_.*_of methods below to tell whether or not a character is in
+// the lookup table in constant time.
+// The argument `table' must be an array that is large enough to hold all
+// the possible values of an unsigned char. Thus it should be be declared
+// as follows:
+// bool table[UCHAR_MAX + 1]
+static inline void BuildLookupTable(const StringPiece& characters_wanted,
+ bool* table) {
+ const size_type length = characters_wanted.length();
+ const char* const data = characters_wanted.data();
+ for (size_type i = 0; i < length; ++i) {
+ table[static_cast<unsigned char>(data[i])] = true;
+ }
+}
+
+size_type StringPiece::find_first_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0 || s.length_ == 0) return npos;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1) return find_first_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = {false};
+ BuildLookupTable(s, lookup);
+ for (size_type i = pos; i < length_; ++i) {
+ if (lookup[static_cast<unsigned char>(ptr_[i])]) {
+ return i;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_first_not_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0) return npos;
+
+ if (s.length_ == 0) return 0;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1) return find_first_not_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = {false};
+ BuildLookupTable(s, lookup);
+ for (size_type i = pos; i < length_; ++i) {
+ if (!lookup[static_cast<unsigned char>(ptr_[i])]) {
+ return i;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_first_not_of(char c, size_type pos) const {
+ if (length_ == 0) return npos;
+
+ for (; pos < length_; ++pos) {
+ if (ptr_[pos] != c) {
+ return pos;
+ }
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_of(const StringPiece& s, size_type pos) const {
+ if (length_ == 0 || s.length_ == 0) return npos;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1) return find_last_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = {false};
+ BuildLookupTable(s, lookup);
+ for (size_type i = std::min(pos, length_ - 1);; --i) {
+ if (lookup[static_cast<unsigned char>(ptr_[i])]) return i;
+ if (i == 0) break;
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_not_of(const StringPiece& s,
+ size_type pos) const {
+ if (length_ == 0) return npos;
+
+ size_type i = std::min(pos, length_ - 1);
+ if (s.length_ == 0) return i;
+
+ // Avoid the cost of BuildLookupTable() for a single-character search.
+ if (s.length_ == 1) return find_last_not_of(s.ptr_[0], pos);
+
+ bool lookup[UCHAR_MAX + 1] = {false};
+ BuildLookupTable(s, lookup);
+ for (;; --i) {
+ if (!lookup[static_cast<unsigned char>(ptr_[i])]) return i;
+ if (i == 0) break;
+ }
+ return npos;
+}
+
+size_type StringPiece::find_last_not_of(char c, size_type pos) const {
+ if (length_ == 0) return npos;
+
+ for (size_type i = std::min(pos, length_ - 1);; --i) {
+ if (ptr_[i] != c) return i;
+ if (i == 0) break;
+ }
+ return npos;
+}
+
+StringPiece StringPiece::substr(size_type pos, size_type n) const {
+ if (pos > length_) pos = length_;
+ if (n > length_ - pos) n = length_ - pos;
+ return StringPiece(ptr_ + pos, n);
+}
+
+const StringPiece::size_type StringPiece::npos = size_type(-1);
diff --git a/ipc/chromium/src/base/string_piece.h b/ipc/chromium/src/base/string_piece.h
new file mode 100644
index 0000000000..8ebdb281d1
--- /dev/null
+++ b/ipc/chromium/src/base/string_piece.h
@@ -0,0 +1,189 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+// Copied from strings/stringpiece.h with modifications
+//
+// A string-like object that points to a sized piece of memory.
+//
+// Functions or methods may use const StringPiece& parameters to accept either
+// a "const char*" or a "string" value that will be implicitly converted to
+// a StringPiece. The implicit conversion means that it is often appropriate
+// to include this .h file in other files rather than forward-declaring
+// StringPiece as would be appropriate for most other Google classes.
+//
+// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
+// conversions from "const char*" to "string" and back again.
+//
+
+#ifndef BASE_STRING_PIECE_H_
+#define BASE_STRING_PIECE_H_
+
+#include <algorithm>
+#include <iosfwd>
+#include <string>
+
+#include "base/basictypes.h"
+
+class StringPiece {
+ public:
+ typedef size_t size_type;
+
+ private:
+ const char* ptr_;
+ size_type length_;
+
+ public:
+ // We provide non-explicit singleton constructors so users can pass
+ // in a "const char*" or a "string" wherever a "StringPiece" is
+ // expected.
+ StringPiece() : ptr_(NULL), length_(0) {}
+ MOZ_IMPLICIT StringPiece(const char* str)
+ : ptr_(str), length_((str == NULL) ? 0 : strlen(str)) {}
+ MOZ_IMPLICIT StringPiece(const std::string& str)
+ : ptr_(str.data()), length_(str.size()) {}
+ StringPiece(const char* offset, size_type len) : ptr_(offset), length_(len) {}
+
+ // data() may return a pointer to a buffer with embedded NULs, and the
+ // returned buffer may or may not be null terminated. Therefore it is
+ // typically a mistake to pass data() to a routine that expects a NUL
+ // terminated string.
+ const char* data() const { return ptr_; }
+ size_type size() const { return length_; }
+ size_type length() const { return length_; }
+ bool empty() const { return length_ == 0; }
+
+ void clear() {
+ ptr_ = NULL;
+ length_ = 0;
+ }
+ void set(const char* aData, size_type aLen) {
+ ptr_ = aData;
+ length_ = aLen;
+ }
+ void set(const char* str) {
+ ptr_ = str;
+ length_ = str ? strlen(str) : 0;
+ }
+ void set(const void* aData, size_type aLen) {
+ ptr_ = reinterpret_cast<const char*>(aData);
+ length_ = aLen;
+ }
+
+ char operator[](size_type i) const { return ptr_[i]; }
+
+ void remove_prefix(size_type n) {
+ ptr_ += n;
+ length_ -= n;
+ }
+
+ void remove_suffix(size_type n) { length_ -= n; }
+
+ int compare(const StringPiece& x) const {
+ int r = wordmemcmp(ptr_, x.ptr_, std::min(length_, x.length_));
+ if (r == 0) {
+ if (length_ < x.length_)
+ r = -1;
+ else if (length_ > x.length_)
+ r = +1;
+ }
+ return r;
+ }
+
+ std::string as_string() const {
+ // std::string doesn't like to take a NULL pointer even with a 0 size.
+ return std::string(!empty() ? data() : "", size());
+ }
+
+ void CopyToString(std::string* target) const;
+ void AppendToString(std::string* target) const;
+
+ // Does "this" start with "x"
+ bool starts_with(const StringPiece& x) const {
+ return ((length_ >= x.length_) &&
+ (wordmemcmp(ptr_, x.ptr_, x.length_) == 0));
+ }
+
+ // Does "this" end with "x"
+ bool ends_with(const StringPiece& x) const {
+ return ((length_ >= x.length_) &&
+ (wordmemcmp(ptr_ + (length_ - x.length_), x.ptr_, x.length_) == 0));
+ }
+
+ // standard STL container boilerplate
+ typedef char value_type;
+ typedef const char* pointer;
+ typedef const char& reference;
+ typedef const char& const_reference;
+ typedef ptrdiff_t difference_type;
+ static const size_type npos;
+ typedef const char* const_iterator;
+ typedef const char* iterator;
+ typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
+ typedef std::reverse_iterator<iterator> reverse_iterator;
+ iterator begin() const { return ptr_; }
+ iterator end() const { return ptr_ + length_; }
+ const_reverse_iterator rbegin() const {
+ return const_reverse_iterator(ptr_ + length_);
+ }
+ const_reverse_iterator rend() const { return const_reverse_iterator(ptr_); }
+
+ size_type max_size() const { return length_; }
+ size_type capacity() const { return length_; }
+
+ size_type copy(char* buf, size_type n, size_type pos = 0) const;
+
+ size_type find(const StringPiece& s, size_type pos = 0) const;
+ size_type find(char c, size_type pos = 0) const;
+ size_type rfind(const StringPiece& s, size_type pos = npos) const;
+ size_type rfind(char c, size_type pos = npos) const;
+
+ size_type find_first_of(const StringPiece& s, size_type pos = 0) const;
+ size_type find_first_of(char c, size_type pos = 0) const {
+ return find(c, pos);
+ }
+ size_type find_first_not_of(const StringPiece& s, size_type pos = 0) const;
+ size_type find_first_not_of(char c, size_type pos = 0) const;
+ size_type find_last_of(const StringPiece& s, size_type pos = npos) const;
+ size_type find_last_of(char c, size_type pos = npos) const {
+ return rfind(c, pos);
+ }
+ size_type find_last_not_of(const StringPiece& s, size_type pos = npos) const;
+ size_type find_last_not_of(char c, size_type pos = npos) const;
+
+ StringPiece substr(size_type pos, size_type n = npos) const;
+
+ static int wordmemcmp(const char* p, const char* p2, size_type N) {
+ return memcmp(p, p2, N);
+ }
+};
+
+bool operator==(const ::StringPiece& x, const ::StringPiece& y);
+
+inline bool operator!=(const ::StringPiece& x, const ::StringPiece& y) {
+ return !(x == y);
+}
+
+inline bool operator<(const ::StringPiece& x, const ::StringPiece& y) {
+ const int r = ::StringPiece::wordmemcmp(x.data(), y.data(),
+ std::min(x.size(), y.size()));
+ return ((r < 0) || ((r == 0) && (x.size() < y.size())));
+}
+
+inline bool operator>(const ::StringPiece& x, const ::StringPiece& y) {
+ return y < x;
+}
+
+inline bool operator<=(const ::StringPiece& x, const ::StringPiece& y) {
+ return !(x > y);
+}
+
+inline bool operator>=(const ::StringPiece& x, const ::StringPiece& y) {
+ return !(x < y);
+}
+
+// allow StringPiece to be logged (needed for unit testing).
+extern std::ostream& operator<<(std::ostream& o, const ::StringPiece& piece);
+
+#endif // BASE_STRING_PIECE_H_
diff --git a/ipc/chromium/src/base/string_util.cc b/ipc/chromium/src/base/string_util.cc
new file mode 100644
index 0000000000..39b8463cb1
--- /dev/null
+++ b/ipc/chromium/src/base/string_util.cc
@@ -0,0 +1,719 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/string_util.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <math.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <wchar.h>
+#include <wctype.h>
+
+#include <algorithm>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+
+namespace {
+
+// Hack to convert any char-like type to its unsigned counterpart.
+// For example, it will convert char, signed char and unsigned char to unsigned
+// char.
+template <typename T>
+struct ToUnsigned {
+ typedef T Unsigned;
+};
+
+template <>
+struct ToUnsigned<char> {
+ typedef unsigned char Unsigned;
+};
+template <>
+struct ToUnsigned<signed char> {
+ typedef unsigned char Unsigned;
+};
+template <>
+struct ToUnsigned<wchar_t> {
+#if defined(XP_WIN)
+ typedef unsigned short Unsigned;
+#else
+ typedef uint32_t Unsigned;
+#endif
+};
+template <>
+struct ToUnsigned<short> {
+ typedef unsigned short Unsigned;
+};
+
+// Generalized string-to-number conversion.
+//
+// StringToNumberTraits should provide:
+// - a typedef for string_type, the STL string type used as input.
+// - a typedef for value_type, the target numeric type.
+// - a static function, convert_func, which dispatches to an appropriate
+// strtol-like function and returns type value_type.
+// - a static function, valid_func, which validates |input| and returns a bool
+// indicating whether it is in proper form. This is used to check for
+// conditions that convert_func tolerates but should result in
+// StringToNumber returning false. For strtol-like funtions, valid_func
+// should check for leading whitespace.
+template <typename StringToNumberTraits>
+bool StringToNumber(const typename StringToNumberTraits::string_type& input,
+ typename StringToNumberTraits::value_type* output) {
+ typedef StringToNumberTraits traits;
+
+ errno = 0; // Thread-safe? It is on at least Mac, Linux, and Windows.
+ typename traits::string_type::value_type* endptr = NULL;
+ typename traits::value_type value =
+ traits::convert_func(input.c_str(), &endptr);
+ *output = value;
+
+ // Cases to return false:
+ // - If errno is ERANGE, there was an overflow or underflow.
+ // - If the input string is empty, there was nothing to parse.
+ // - If endptr does not point to the end of the string, there are either
+ // characters remaining in the string after a parsed number, or the string
+ // does not begin with a parseable number. endptr is compared to the
+ // expected end given the string's stated length to correctly catch cases
+ // where the string contains embedded NUL characters.
+ // - valid_func determines that the input is not in preferred form.
+ return errno == 0 && !input.empty() &&
+ input.c_str() + input.length() == endptr && traits::valid_func(input);
+}
+
+class StringToLongTraits {
+ public:
+ typedef std::string string_type;
+ typedef long value_type;
+ static const int kBase = 10;
+ static inline value_type convert_func(const string_type::value_type* str,
+ string_type::value_type** endptr) {
+ return strtol(str, endptr, kBase);
+ }
+ static inline bool valid_func(const string_type& str) {
+ return !str.empty() && !isspace(str[0]);
+ }
+};
+
+class String16ToLongTraits {
+ public:
+ typedef string16 string_type;
+ typedef long value_type;
+ static const int kBase = 10;
+ static inline value_type convert_func(const string_type::value_type* str,
+ string_type::value_type** endptr) {
+#if defined(XP_WIN)
+ return wcstol(str, endptr, kBase);
+#else
+ std::string ascii_string = UTF16ToASCII(string16(str));
+ char* ascii_end = NULL;
+ value_type ret = strtol(ascii_string.c_str(), &ascii_end, kBase);
+ if (ascii_string.c_str() + ascii_string.length() == ascii_end) {
+ *endptr =
+ const_cast<string_type::value_type*>(str) + ascii_string.length();
+ }
+ return ret;
+#endif
+ }
+ static inline bool valid_func(const string_type& str) {
+ return !str.empty() && !iswspace(str[0]);
+ }
+};
+
+class StringToInt64Traits {
+ public:
+ typedef std::string string_type;
+ typedef int64_t value_type;
+ static const int kBase = 10;
+ static inline value_type convert_func(const string_type::value_type* str,
+ string_type::value_type** endptr) {
+#ifdef XP_WIN
+ return _strtoi64(str, endptr, kBase);
+#else // assume XP_UNIX
+ return strtoll(str, endptr, kBase);
+#endif
+ }
+ static inline bool valid_func(const string_type& str) {
+ return !str.empty() && !isspace(str[0]);
+ }
+};
+
+class String16ToInt64Traits {
+ public:
+ typedef string16 string_type;
+ typedef int64_t value_type;
+ static const int kBase = 10;
+ static inline value_type convert_func(const string_type::value_type* str,
+ string_type::value_type** endptr) {
+#ifdef XP_WIN
+ return _wcstoi64(str, endptr, kBase);
+#else // assume XP_UNIX
+ std::string ascii_string = UTF16ToASCII(string16(str));
+ char* ascii_end = NULL;
+ value_type ret = strtoll(ascii_string.c_str(), &ascii_end, kBase);
+ if (ascii_string.c_str() + ascii_string.length() == ascii_end) {
+ *endptr =
+ const_cast<string_type::value_type*>(str) + ascii_string.length();
+ }
+ return ret;
+#endif
+ }
+ static inline bool valid_func(const string_type& str) {
+ return !str.empty() && !iswspace(str[0]);
+ }
+};
+
+} // namespace
+
+namespace base {
+
+bool IsWprintfFormatPortable(const wchar_t* format) {
+ for (const wchar_t* position = format; *position != '\0'; ++position) {
+ if (*position == '%') {
+ bool in_specification = true;
+ bool modifier_l = false;
+ while (in_specification) {
+ // Eat up characters until reaching a known specifier.
+ if (*++position == '\0') {
+ // The format string ended in the middle of a specification. Call
+ // it portable because no unportable specifications were found. The
+ // string is equally broken on all platforms.
+ return true;
+ }
+
+ if (*position == 'l') {
+ // 'l' is the only thing that can save the 's' and 'c' specifiers.
+ modifier_l = true;
+ } else if (((*position == 's' || *position == 'c') && !modifier_l) ||
+ *position == 'S' || *position == 'C' || *position == 'F' ||
+ *position == 'D' || *position == 'O' || *position == 'U') {
+ // Not portable.
+ return false;
+ }
+
+ if (wcschr(L"diouxXeEfgGaAcspn%", *position)) {
+ // Portable, keep scanning the rest of the format string.
+ in_specification = false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+} // namespace base
+
+static const wchar_t kWhitespaceWide[] = {
+ 0x0009, // <control-0009> to <control-000D>
+ 0x000A, 0x000B, 0x000C, 0x000D,
+ 0x0020, // Space
+ 0x0085, // <control-0085>
+ 0x00A0, // No-Break Space
+ 0x1680, // Ogham Space Mark
+ 0x180E, // Mongolian Vowel Separator
+ 0x2000, // En Quad to Hair Space
+ 0x2001, 0x2002, 0x2003, 0x2004, 0x2005,
+ 0x2006, 0x2007, 0x2008, 0x2009, 0x200A,
+ 0x200C, // Zero Width Non-Joiner
+ 0x2028, // Line Separator
+ 0x2029, // Paragraph Separator
+ 0x202F, // Narrow No-Break Space
+ 0x205F, // Medium Mathematical Space
+ 0x3000, // Ideographic Space
+ 0};
+static const char kWhitespaceASCII[] = {
+ 0x09, // <control-0009> to <control-000D>
+ 0x0A, 0x0B, 0x0C, 0x0D,
+ 0x20, // Space
+ 0};
+
+template <typename STR>
+TrimPositions TrimStringT(const STR& input,
+ const typename STR::value_type trim_chars[],
+ TrimPositions positions, STR* output) {
+ // Find the edges of leading/trailing whitespace as desired.
+ const typename STR::size_type last_char = input.length() - 1;
+ const typename STR::size_type first_good_char =
+ (positions & TRIM_LEADING) ? input.find_first_not_of(trim_chars) : 0;
+ const typename STR::size_type last_good_char =
+ (positions & TRIM_TRAILING) ? input.find_last_not_of(trim_chars)
+ : last_char;
+
+ // When the string was all whitespace, report that we stripped off whitespace
+ // from whichever position the caller was interested in. For empty input, we
+ // stripped no whitespace, but we still need to clear |output|.
+ if (input.empty() || (first_good_char == STR::npos) ||
+ (last_good_char == STR::npos)) {
+ bool input_was_empty = input.empty(); // in case output == &input
+ output->clear();
+ return input_was_empty ? TRIM_NONE : positions;
+ }
+
+ // Trim the whitespace.
+ *output = input.substr(first_good_char, last_good_char - first_good_char + 1);
+
+ // Return where we trimmed from.
+ return static_cast<TrimPositions>(
+ ((first_good_char == 0) ? TRIM_NONE : TRIM_LEADING) |
+ ((last_good_char == last_char) ? TRIM_NONE : TRIM_TRAILING));
+}
+
+TrimPositions TrimWhitespace(const std::wstring& input, TrimPositions positions,
+ std::wstring* output) {
+ return TrimStringT(input, kWhitespaceWide, positions, output);
+}
+
+TrimPositions TrimWhitespaceASCII(const std::string& input,
+ TrimPositions positions,
+ std::string* output) {
+ return TrimStringT(input, kWhitespaceASCII, positions, output);
+}
+
+// This function is only for backward-compatibility.
+// To be removed when all callers are updated.
+TrimPositions TrimWhitespace(const std::string& input, TrimPositions positions,
+ std::string* output) {
+ return TrimWhitespaceASCII(input, positions, output);
+}
+
+std::string WideToASCII(const std::wstring& wide) {
+ DCHECK(IsStringASCII(wide));
+ return std::string(wide.begin(), wide.end());
+}
+
+std::wstring ASCIIToWide(const std::string& ascii) {
+ DCHECK(IsStringASCII(ascii));
+ return std::wstring(ascii.begin(), ascii.end());
+}
+
+std::string UTF16ToASCII(const string16& utf16) {
+ DCHECK(IsStringASCII(utf16));
+ return std::string(utf16.begin(), utf16.end());
+}
+
+string16 ASCIIToUTF16(const std::string& ascii) {
+ DCHECK(IsStringASCII(ascii));
+ return string16(ascii.begin(), ascii.end());
+}
+
+template <class STR>
+static bool DoIsStringASCII(const STR& str) {
+ for (size_t i = 0; i < str.length(); i++) {
+ typename ToUnsigned<typename STR::value_type>::Unsigned c = str[i];
+ if (c > 0x7F) return false;
+ }
+ return true;
+}
+
+bool IsStringASCII(const std::wstring& str) { return DoIsStringASCII(str); }
+
+#if !defined(XP_WIN)
+bool IsStringASCII(const string16& str) { return DoIsStringASCII(str); }
+#endif
+
+bool IsStringASCII(const std::string& str) { return DoIsStringASCII(str); }
+
+// Overloaded wrappers around vsnprintf and vswprintf. The buf_size parameter
+// is the size of the buffer. These return the number of characters in the
+// formatted string excluding the NUL terminator. If the buffer is not
+// large enough to accommodate the formatted string without truncation, they
+// return the number of characters that would be in the fully-formatted string
+// (vsnprintf, and vswprintf on Windows), or -1 (vswprintf on POSIX platforms).
+inline int vsnprintfT(char* buffer, size_t buf_size, const char* format,
+ va_list argptr) {
+ return base::vsnprintf(buffer, buf_size, format, argptr);
+}
+
+inline int vsnprintfT(wchar_t* buffer, size_t buf_size, const wchar_t* format,
+ va_list argptr) {
+ return base::vswprintf(buffer, buf_size, format, argptr);
+}
+
+// Templatized backend for StringPrintF/StringAppendF. This does not finalize
+// the va_list, the caller is expected to do that.
+template <class StringType>
+static void StringAppendVT(StringType* dst,
+ const typename StringType::value_type* format,
+ va_list ap) {
+ // First try with a small fixed size buffer.
+ // This buffer size should be kept in sync with StringUtilTest.GrowBoundary
+ // and StringUtilTest.StringPrintfBounds.
+ typename StringType::value_type stack_buf[1024];
+
+ va_list backup_ap;
+ base_va_copy(backup_ap, ap);
+
+#if !defined(XP_WIN)
+ errno = 0;
+#endif
+ int result = vsnprintfT(stack_buf, arraysize(stack_buf), format, backup_ap);
+ va_end(backup_ap);
+
+ if (result >= 0 && result < static_cast<int>(arraysize(stack_buf))) {
+ // It fit.
+ dst->append(stack_buf, result);
+ return;
+ }
+
+ // Repeatedly increase buffer size until it fits.
+ int mem_length = arraysize(stack_buf);
+ while (true) {
+ if (result < 0) {
+#if !defined(XP_WIN)
+ // On Windows, vsnprintfT always returns the number of characters in a
+ // fully-formatted string, so if we reach this point, something else is
+ // wrong and no amount of buffer-doubling is going to fix it.
+ if (errno != 0 && errno != EOVERFLOW)
+#endif
+ {
+ // If an error other than overflow occurred, it's never going to work.
+ DLOG(WARNING) << "Unable to printf the requested string due to error.";
+ return;
+ }
+ // Try doubling the buffer size.
+ mem_length *= 2;
+ } else {
+ // We need exactly "result + 1" characters.
+ mem_length = result + 1;
+ }
+
+ if (mem_length > 32 * 1024 * 1024) {
+ // That should be plenty, don't try anything larger. This protects
+ // against huge allocations when using vsnprintfT implementations that
+ // return -1 for reasons other than overflow without setting errno.
+ DLOG(WARNING) << "Unable to printf the requested string due to size.";
+ return;
+ }
+
+ std::vector<typename StringType::value_type> mem_buf(mem_length);
+
+ // Restore the va_list before we use it again.
+ base_va_copy(backup_ap, ap);
+
+ result = vsnprintfT(&mem_buf[0], mem_length, format, ap);
+ va_end(backup_ap);
+
+ if ((result >= 0) && (result < mem_length)) {
+ // It fit.
+ dst->append(&mem_buf[0], result);
+ return;
+ }
+ }
+}
+
+namespace {
+
+template <typename STR, typename INT, typename UINT, bool NEG>
+struct IntToStringT {
+ // This is to avoid a compiler warning about unary minus on unsigned type.
+ // For example, say you had the following code:
+ // template <typename INT>
+ // INT abs(INT value) { return value < 0 ? -value : value; }
+ // Even though if INT is unsigned, it's impossible for value < 0, so the
+ // unary minus will never be taken, the compiler will still generate a
+ // warning. We do a little specialization dance...
+ template <typename INT2, typename UINT2, bool NEG2>
+ struct ToUnsignedT {};
+
+ template <typename INT2, typename UINT2>
+ struct ToUnsignedT<INT2, UINT2, false> {
+ static UINT2 ToUnsigned(INT2 value) { return static_cast<UINT2>(value); }
+ };
+
+ template <typename INT2, typename UINT2>
+ struct ToUnsignedT<INT2, UINT2, true> {
+ static UINT2 ToUnsigned(INT2 value) {
+ return static_cast<UINT2>(value < 0 ? -value : value);
+ }
+ };
+
+ // This set of templates is very similar to the above templates, but
+ // for testing whether an integer is negative.
+ template <typename INT2, bool NEG2>
+ struct TestNegT {};
+ template <typename INT2>
+ struct TestNegT<INT2, false> {
+ static bool TestNeg(INT2 value) {
+ // value is unsigned, and can never be negative.
+ return false;
+ }
+ };
+ template <typename INT2>
+ struct TestNegT<INT2, true> {
+ static bool TestNeg(INT2 value) { return value < 0; }
+ };
+
+ static STR IntToString(INT value) {
+ // log10(2) ~= 0.3 bytes needed per bit or per byte log10(2**8) ~= 2.4.
+ // So round up to allocate 3 output characters per byte, plus 1 for '-'.
+ const int kOutputBufSize = 3 * sizeof(INT) + 1;
+
+ // Allocate the whole string right away, we will right back to front, and
+ // then return the substr of what we ended up using.
+ STR outbuf(kOutputBufSize, 0);
+
+ bool is_neg = TestNegT<INT, NEG>::TestNeg(value);
+ // Even though is_neg will never be true when INT is parameterized as
+ // unsigned, even the presence of the unary operation causes a warning.
+ UINT res = ToUnsignedT<INT, UINT, NEG>::ToUnsigned(value);
+
+ for (typename STR::iterator it = outbuf.end();;) {
+ --it;
+ DCHECK(it != outbuf.begin());
+ *it = static_cast<typename STR::value_type>((res % 10) + '0');
+ res /= 10;
+
+ // We're done..
+ if (res == 0) {
+ if (is_neg) {
+ --it;
+ DCHECK(it != outbuf.begin());
+ *it = static_cast<typename STR::value_type>('-');
+ }
+ return STR(it, outbuf.end());
+ }
+ }
+ NOTREACHED();
+ return STR();
+ }
+};
+
+} // namespace
+
+std::string IntToString(int value) {
+ return IntToStringT<std::string, int, unsigned int, true>::IntToString(value);
+}
+std::wstring IntToWString(int value) {
+ return IntToStringT<std::wstring, int, unsigned int, true>::IntToString(
+ value);
+}
+std::string UintToString(unsigned int value) {
+ return IntToStringT<std::string, unsigned int, unsigned int,
+ false>::IntToString(value);
+}
+std::wstring UintToWString(unsigned int value) {
+ return IntToStringT<std::wstring, unsigned int, unsigned int,
+ false>::IntToString(value);
+}
+std::string Int64ToString(int64_t value) {
+ return IntToStringT<std::string, int64_t, uint64_t, true>::IntToString(value);
+}
+std::wstring Int64ToWString(int64_t value) {
+ return IntToStringT<std::wstring, int64_t, uint64_t, true>::IntToString(
+ value);
+}
+std::string Uint64ToString(uint64_t value) {
+ return IntToStringT<std::string, uint64_t, uint64_t, false>::IntToString(
+ value);
+}
+std::wstring Uint64ToWString(uint64_t value) {
+ return IntToStringT<std::wstring, uint64_t, uint64_t, false>::IntToString(
+ value);
+}
+
+// Lower-level routine that takes a va_list and appends to a specified
+// string. All other routines are just convenience wrappers around it.
+static void StringAppendV(std::string* dst, const char* format, va_list ap) {
+ StringAppendVT(dst, format, ap);
+}
+
+static void StringAppendV(std::wstring* dst, const wchar_t* format,
+ va_list ap) {
+ StringAppendVT(dst, format, ap);
+}
+
+std::string StringPrintf(const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ std::string result;
+ StringAppendV(&result, format, ap);
+ va_end(ap);
+ return result;
+}
+
+std::wstring StringPrintf(const wchar_t* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ std::wstring result;
+ StringAppendV(&result, format, ap);
+ va_end(ap);
+ return result;
+}
+
+const std::string& SStringPrintf(std::string* dst, const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ dst->clear();
+ StringAppendV(dst, format, ap);
+ va_end(ap);
+ return *dst;
+}
+
+const std::wstring& SStringPrintf(std::wstring* dst, const wchar_t* format,
+ ...) {
+ va_list ap;
+ va_start(ap, format);
+ dst->clear();
+ StringAppendV(dst, format, ap);
+ va_end(ap);
+ return *dst;
+}
+
+void StringAppendF(std::string* dst, const char* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ StringAppendV(dst, format, ap);
+ va_end(ap);
+}
+
+void StringAppendF(std::wstring* dst, const wchar_t* format, ...) {
+ va_list ap;
+ va_start(ap, format);
+ StringAppendV(dst, format, ap);
+ va_end(ap);
+}
+
+template <typename STR>
+static void SplitStringT(const STR& str, const typename STR::value_type s,
+ bool trim_whitespace, std::vector<STR>* r) {
+ size_t last = 0;
+ size_t i;
+ size_t c = str.size();
+ for (i = 0; i <= c; ++i) {
+ if (i == c || str[i] == s) {
+ size_t len = i - last;
+ STR tmp = str.substr(last, len);
+ if (trim_whitespace) {
+ STR t_tmp;
+ TrimWhitespace(tmp, TRIM_ALL, &t_tmp);
+ r->push_back(t_tmp);
+ } else {
+ r->push_back(tmp);
+ }
+ last = i + 1;
+ }
+ }
+}
+
+void SplitString(const std::wstring& str, wchar_t s,
+ std::vector<std::wstring>* r) {
+ SplitStringT(str, s, true, r);
+}
+
+void SplitString(const std::string& str, char s, std::vector<std::string>* r) {
+ SplitStringT(str, s, true, r);
+}
+
+// For the various *ToInt conversions, there are no *ToIntTraits classes to use
+// because there's no such thing as strtoi. Use *ToLongTraits through a cast
+// instead, requiring that long and int are compatible and equal-width. They
+// are on our target platforms.
+
+// XXX Sigh.
+
+#if !defined(HAVE_64BIT_BUILD)
+bool StringToInt(const std::string& input, int* output) {
+ COMPILE_ASSERT(sizeof(int) == sizeof(long), cannot_strtol_to_int);
+ return StringToNumber<StringToLongTraits>(input,
+ reinterpret_cast<long*>(output));
+}
+
+bool StringToInt(const string16& input, int* output) {
+ COMPILE_ASSERT(sizeof(int) == sizeof(long), cannot_wcstol_to_int);
+ return StringToNumber<String16ToLongTraits>(input,
+ reinterpret_cast<long*>(output));
+}
+
+#else
+bool StringToInt(const std::string& input, int* output) {
+ long tmp;
+ bool ok = StringToNumber<StringToLongTraits>(input, &tmp);
+ if (!ok || tmp > kint32max) {
+ return false;
+ }
+ *output = static_cast<int>(tmp);
+ return true;
+}
+
+bool StringToInt(const string16& input, int* output) {
+ long tmp;
+ bool ok = StringToNumber<String16ToLongTraits>(input, &tmp);
+ if (!ok || tmp > kint32max) {
+ return false;
+ }
+ *output = static_cast<int>(tmp);
+ return true;
+}
+#endif // !defined(HAVE_64BIT_BUILD)
+
+bool StringToInt64(const std::string& input, int64_t* output) {
+ return StringToNumber<StringToInt64Traits>(input, output);
+}
+
+bool StringToInt64(const string16& input, int64_t* output) {
+ return StringToNumber<String16ToInt64Traits>(input, output);
+}
+
+int StringToInt(const std::string& value) {
+ int result;
+ StringToInt(value, &result);
+ return result;
+}
+
+int StringToInt(const string16& value) {
+ int result;
+ StringToInt(value, &result);
+ return result;
+}
+
+int64_t StringToInt64(const std::string& value) {
+ int64_t result;
+ StringToInt64(value, &result);
+ return result;
+}
+
+int64_t StringToInt64(const string16& value) {
+ int64_t result;
+ StringToInt64(value, &result);
+ return result;
+}
+
+// The following code is compatible with the OpenBSD lcpy interface. See:
+// http://www.gratisoft.us/todd/papers/strlcpy.html
+// ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/{wcs,str}lcpy.c
+
+namespace {
+
+template <typename CHAR>
+size_t lcpyT(CHAR* dst, const CHAR* src, size_t dst_size) {
+ for (size_t i = 0; i < dst_size; ++i) {
+ if ((dst[i] = src[i]) == 0) // We hit and copied the terminating NULL.
+ return i;
+ }
+
+ // We were left off at dst_size. We over copied 1 byte. Null terminate.
+ if (dst_size != 0) dst[dst_size - 1] = 0;
+
+ // Count the rest of the |src|, and return it's length in characters.
+ while (src[dst_size]) ++dst_size;
+ return dst_size;
+}
+
+} // namespace
+
+size_t base::strlcpy(char* dst, const char* src, size_t dst_size) {
+ return lcpyT<char>(dst, src, dst_size);
+}
+size_t base::wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size) {
+ return lcpyT<wchar_t>(dst, src, dst_size);
+}
diff --git a/ipc/chromium/src/base/string_util.h b/ipc/chromium/src/base/string_util.h
new file mode 100644
index 0000000000..b6adcd96d7
--- /dev/null
+++ b/ipc/chromium/src/base/string_util.h
@@ -0,0 +1,229 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+//
+// This file defines utility functions for working with strings.
+
+#ifndef BASE_STRING_UTIL_H_
+#define BASE_STRING_UTIL_H_
+
+#include <stdarg.h> // va_list
+#include <ctype.h>
+
+#include <string>
+#include <vector>
+
+#include "base/basictypes.h"
+#include "base/string16.h"
+#include "base/string_piece.h" // For implicit conversions.
+
+// Safe standard library wrappers for all platforms.
+
+namespace base {
+
+// C standard-library functions like "strncasecmp" and "snprintf" that aren't
+// cross-platform are provided as "base::strncasecmp", and their prototypes
+// are listed below. These functions are then implemented as inline calls
+// to the platform-specific equivalents in the platform-specific headers.
+
+// Compare the two strings s1 and s2 without regard to case using
+// the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
+// s2 > s1 according to a lexicographic comparison.
+int strcasecmp(const char* s1, const char* s2);
+
+// Compare up to count characters of s1 and s2 without regard to case using
+// the current locale; returns 0 if they are equal, 1 if s1 > s2, and -1 if
+// s2 > s1 according to a lexicographic comparison.
+int strncasecmp(const char* s1, const char* s2, size_t count);
+
+// Wrapper for vsnprintf that always null-terminates and always returns the
+// number of characters that would be in an untruncated formatted
+// string, even when truncation occurs.
+int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments);
+
+// vswprintf always null-terminates, but when truncation occurs, it will either
+// return -1 or the number of characters that would be in an untruncated
+// formatted string. The actual return value depends on the underlying
+// C library's vswprintf implementation.
+int vswprintf(wchar_t* buffer, size_t size, const wchar_t* format,
+ va_list arguments);
+
+// Some of these implementations need to be inlined.
+
+inline int snprintf(char* buffer, size_t size, const char* format, ...) {
+ va_list arguments;
+ va_start(arguments, format);
+ int result = vsnprintf(buffer, size, format, arguments);
+ va_end(arguments);
+ return result;
+}
+
+inline int swprintf(wchar_t* buffer, size_t size, const wchar_t* format, ...) {
+ va_list arguments;
+ va_start(arguments, format);
+ int result = vswprintf(buffer, size, format, arguments);
+ va_end(arguments);
+ return result;
+}
+
+// BSD-style safe and consistent string copy functions.
+// Copies |src| to |dst|, where |dst_size| is the total allocated size of |dst|.
+// Copies at most |dst_size|-1 characters, and always NULL terminates |dst|, as
+// long as |dst_size| is not 0. Returns the length of |src| in characters.
+// If the return value is >= dst_size, then the output was truncated.
+// NOTE: All sizes are in number of characters, NOT in bytes.
+size_t strlcpy(char* dst, const char* src, size_t dst_size);
+size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size);
+
+// Scan a wprintf format string to determine whether it's portable across a
+// variety of systems. This function only checks that the conversion
+// specifiers used by the format string are supported and have the same meaning
+// on a variety of systems. It doesn't check for other errors that might occur
+// within a format string.
+//
+// Nonportable conversion specifiers for wprintf are:
+// - 's' and 'c' without an 'l' length modifier. %s and %c operate on char
+// data on all systems except Windows, which treat them as wchar_t data.
+// Use %ls and %lc for wchar_t data instead.
+// - 'S' and 'C', which operate on wchar_t data on all systems except Windows,
+// which treat them as char data. Use %ls and %lc for wchar_t data
+// instead.
+// - 'F', which is not identified by Windows wprintf documentation.
+// - 'D', 'O', and 'U', which are deprecated and not available on all systems.
+// Use %ld, %lo, and %lu instead.
+//
+// Note that there is no portable conversion specifier for char data when
+// working with wprintf.
+//
+// This function is intended to be called from base::vswprintf.
+bool IsWprintfFormatPortable(const wchar_t* format);
+
+} // namespace base
+
+#if defined(XP_WIN)
+# include "base/string_util_win.h"
+#else
+# include "base/string_util_posix.h"
+#endif
+
+// Trims any whitespace from either end of the input string. Returns where
+// whitespace was found.
+// The non-wide version has two functions:
+// * TrimWhitespaceASCII()
+// This function is for ASCII strings and only looks for ASCII whitespace;
+// * TrimWhitespaceUTF8()
+// This function is for UTF-8 strings and looks for Unicode whitespace.
+// Please choose the best one according to your usage.
+// NOTE: Safe to use the same variable for both input and output.
+enum TrimPositions {
+ TRIM_NONE = 0,
+ TRIM_LEADING = 1 << 0,
+ TRIM_TRAILING = 1 << 1,
+ TRIM_ALL = TRIM_LEADING | TRIM_TRAILING
+};
+TrimPositions TrimWhitespace(const std::wstring& input, TrimPositions positions,
+ std::wstring* output);
+TrimPositions TrimWhitespaceASCII(const std::string& input,
+ TrimPositions positions, std::string* output);
+
+// Deprecated. This function is only for backward compatibility and calls
+// TrimWhitespaceASCII().
+TrimPositions TrimWhitespace(const std::string& input, TrimPositions positions,
+ std::string* output);
+
+// Searches for CR or LF characters. Removes all contiguous whitespace
+// strings that contain them. This is useful when trying to deal with text
+// copied from terminals.
+// Returns |text, with the following three transformations:
+// (1) Leading and trailing whitespace is trimmed.
+// (2) If |trim_sequences_with_line_breaks| is true, any other whitespace
+// sequences containing a CR or LF are trimmed.
+// (3) All other whitespace sequences are converted to single spaces.
+std::wstring CollapseWhitespace(const std::wstring& text,
+ bool trim_sequences_with_line_breaks);
+
+// These convert between ASCII (7-bit) and Wide/UTF16 strings.
+std::string WideToASCII(const std::wstring& wide);
+std::wstring ASCIIToWide(const std::string& ascii);
+std::string UTF16ToASCII(const string16& utf16);
+string16 ASCIIToUTF16(const std::string& ascii);
+
+// These convert between UTF-8, -16, and -32 strings. They are potentially slow,
+// so avoid unnecessary conversions. The low-level versions return a boolean
+// indicating whether the conversion was 100% valid. In this case, it will still
+// do the best it can and put the result in the output buffer. The versions that
+// return strings ignore this error and just return the best conversion
+// possible.
+bool WideToUTF8(const wchar_t* src, size_t src_len, std::string* output);
+std::string WideToUTF8(const std::wstring& wide);
+bool UTF8ToWide(const char* src, size_t src_len, std::wstring* output);
+std::wstring UTF8ToWide(const ::StringPiece& utf8);
+
+bool IsStringASCII(const std::wstring& str);
+bool IsStringASCII(const std::string& str);
+bool IsStringASCII(const string16& str);
+
+// Specialized string-conversion functions.
+std::string IntToString(int value);
+std::wstring IntToWString(int value);
+std::string UintToString(unsigned int value);
+std::wstring UintToWString(unsigned int value);
+std::string Int64ToString(int64_t value);
+std::wstring Int64ToWString(int64_t value);
+std::string Uint64ToString(uint64_t value);
+std::wstring Uint64ToWString(uint64_t value);
+// The DoubleToString methods convert the double to a string format that
+// ignores the locale. If you want to use locale specific formatting, use ICU.
+std::string DoubleToString(double value);
+std::wstring DoubleToWString(double value);
+
+// Perform a best-effort conversion of the input string to a numeric type,
+// setting |*output| to the result of the conversion. Returns true for
+// "perfect" conversions; returns false in the following cases:
+// - Overflow/underflow. |*output| will be set to the maximum value supported
+// by the data type.
+// - Trailing characters in the string after parsing the number. |*output|
+// will be set to the value of the number that was parsed.
+// - No characters parseable as a number at the beginning of the string.
+// |*output| will be set to 0.
+// - Empty string. |*output| will be set to 0.
+bool StringToInt(const std::string& input, int* output);
+bool StringToInt(const string16& input, int* output);
+bool StringToInt64(const std::string& input, int64_t* output);
+bool StringToInt64(const string16& input, int64_t* output);
+
+// Convenience forms of the above, when the caller is uninterested in the
+// boolean return value. These return only the |*output| value from the
+// above conversions: a best-effort conversion when possible, otherwise, 0.
+int StringToInt(const std::string& value);
+int StringToInt(const string16& value);
+int64_t StringToInt64(const std::string& value);
+int64_t StringToInt64(const string16& value);
+
+// Return a C++ string given printf-like input.
+std::string StringPrintf(const char* format, ...);
+std::wstring StringPrintf(const wchar_t* format, ...);
+
+// Store result into a supplied string and return it
+const std::string& SStringPrintf(std::string* dst, const char* format, ...);
+const std::wstring& SStringPrintf(std::wstring* dst, const wchar_t* format,
+ ...);
+
+// Append result to a supplied string
+void StringAppendF(std::string* dst, const char* format, ...);
+void StringAppendF(std::wstring* dst, const wchar_t* format, ...);
+
+//-----------------------------------------------------------------------------
+
+// Splits |str| into a vector of strings delimited by |s|. Append the results
+// into |r| as they appear. If several instances of |s| are contiguous, or if
+// |str| begins with or ends with |s|, then an empty string is inserted.
+//
+// Every substring is trimmed of any leading or trailing white space.
+void SplitString(const std::wstring& str, wchar_t s,
+ std::vector<std::wstring>* r);
+void SplitString(const std::string& str, char s, std::vector<std::string>* r);
+
+#endif // BASE_STRING_UTIL_H_
diff --git a/ipc/chromium/src/base/string_util_posix.h b/ipc/chromium/src/base/string_util_posix.h
new file mode 100644
index 0000000000..02818a6441
--- /dev/null
+++ b/ipc/chromium/src/base/string_util_posix.h
@@ -0,0 +1,44 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_STRING_UTIL_POSIX_H_
+#define BASE_STRING_UTIL_POSIX_H_
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <wchar.h>
+
+#include "base/logging.h"
+
+namespace base {
+
+// Chromium code style is to not use malloc'd strings; this is only for use
+// for interaction with APIs that require it.
+inline char* strdup(const char* str) { return ::strdup(str); }
+
+inline int strcasecmp(const char* string1, const char* string2) {
+ return ::strcasecmp(string1, string2);
+}
+
+inline int strncasecmp(const char* string1, const char* string2, size_t count) {
+ return ::strncasecmp(string1, string2, count);
+}
+
+inline int vsnprintf(char* buffer, size_t size, const char* format,
+ va_list arguments) {
+ return ::vsnprintf(buffer, size, format, arguments);
+}
+
+inline int vswprintf(wchar_t* buffer, size_t size, const wchar_t* format,
+ va_list arguments) {
+ DCHECK(IsWprintfFormatPortable(format));
+ return ::vswprintf(buffer, size, format, arguments);
+}
+
+} // namespace base
+
+#endif // BASE_STRING_UTIL_POSIX_H_
diff --git a/ipc/chromium/src/base/string_util_win.h b/ipc/chromium/src/base/string_util_win.h
new file mode 100644
index 0000000000..7f8586889b
--- /dev/null
+++ b/ipc/chromium/src/base/string_util_win.h
@@ -0,0 +1,41 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_STRING_UTIL_WIN_H_
+#define BASE_STRING_UTIL_WIN_H_
+
+#include <stdarg.h>
+#include <stdio.h>
+#include <string.h>
+#include <wchar.h>
+
+#include "base/logging.h"
+
+namespace base {
+
+// Chromium code style is to not use malloc'd strings; this is only for use
+// for interaction with APIs that require it.
+inline char* strdup(const char* str) { return _strdup(str); }
+
+inline int vsnprintf(char* buffer, size_t size, const char* format,
+ va_list arguments) {
+ int length = vsnprintf_s(buffer, size, size - 1, format, arguments);
+ if (length < 0) return _vscprintf(format, arguments);
+ return length;
+}
+
+inline int vswprintf(wchar_t* buffer, size_t size, const wchar_t* format,
+ va_list arguments) {
+ DCHECK(IsWprintfFormatPortable(format));
+
+ int length = _vsnwprintf_s(buffer, size, size - 1, format, arguments);
+ if (length < 0) return _vscwprintf(format, arguments);
+ return length;
+}
+
+} // namespace base
+
+#endif // BASE_STRING_UTIL_WIN_H_
diff --git a/ipc/chromium/src/base/sys_string_conversions.h b/ipc/chromium/src/base/sys_string_conversions.h
new file mode 100644
index 0000000000..e3a51964a7
--- /dev/null
+++ b/ipc/chromium/src/base/sys_string_conversions.h
@@ -0,0 +1,35 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_SYS_STRING_CONVERSIONS_H_
+#define BASE_SYS_STRING_CONVERSIONS_H_
+
+// Provides system-dependent string type conversions for cases where it's
+// necessary to not use ICU. Generally, you should not need this in Chrome,
+// but it is used in some shared code. Dependencies should be minimal.
+
+#include <string>
+#include "base/basictypes.h"
+#include "base/string16.h"
+
+class StringPiece;
+
+namespace base {
+
+// Converts between wide and UTF-8 representations of a string. On error, the
+// result is system-dependent.
+std::string SysWideToUTF8(const std::wstring& wide);
+std::wstring SysUTF8ToWide(const StringPiece& utf8);
+
+// Converts between wide and the system multi-byte representations of a string.
+// DANGER: This will lose information and can change (on Windows, this can
+// change between reboots).
+std::string SysWideToNativeMB(const std::wstring& wide);
+std::wstring SysNativeMBToWide(const StringPiece& native_mb);
+
+} // namespace base
+
+#endif // BASE_SYS_STRING_CONVERSIONS_H_
diff --git a/ipc/chromium/src/base/sys_string_conversions_mac.mm b/ipc/chromium/src/base/sys_string_conversions_mac.mm
new file mode 100644
index 0000000000..c33ffef6bc
--- /dev/null
+++ b/ipc/chromium/src/base/sys_string_conversions_mac.mm
@@ -0,0 +1,126 @@
+// Copyright (c) 2006-2008 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.
+
+#include "base/sys_string_conversions.h"
+
+#import <Foundation/Foundation.h>
+
+#include <vector>
+
+#include "base/scoped_cftyperef.h"
+#include "base/string_piece.h"
+
+namespace base {
+
+namespace {
+
+// Convert the supplied CFString into the specified encoding, and return it as
+// an STL string of the template type. Returns an empty string on failure.
+//
+// Do not assert in this function since it is used by the asssertion code!
+template <typename StringType>
+static StringType CFStringToSTLStringWithEncodingT(CFStringRef cfstring,
+ CFStringEncoding encoding) {
+ CFIndex length = CFStringGetLength(cfstring);
+ if (length == 0) return StringType();
+
+ CFRange whole_string = CFRangeMake(0, length);
+ CFIndex out_size;
+ CFIndex converted = CFStringGetBytes(cfstring, whole_string, encoding,
+ 0, // lossByte
+ false, // isExternalRepresentation
+ NULL, // buffer
+ 0, // maxBufLen
+ &out_size);
+ if (converted == 0 || out_size == 0) return StringType();
+
+ // out_size is the number of UInt8-sized units needed in the destination.
+ // A buffer allocated as UInt8 units might not be properly aligned to
+ // contain elements of StringType::value_type. Use a container for the
+ // proper value_type, and convert out_size by figuring the number of
+ // value_type elements per UInt8. Leave room for a NUL terminator.
+ typename StringType::size_type elements =
+ out_size * sizeof(UInt8) / sizeof(typename StringType::value_type) + 1;
+
+ std::vector<typename StringType::value_type> out_buffer(elements);
+ converted =
+ CFStringGetBytes(cfstring, whole_string, encoding,
+ 0, // lossByte
+ false, // isExternalRepresentation
+ reinterpret_cast<UInt8*>(&out_buffer[0]), out_size,
+ NULL); // usedBufLen
+ if (converted == 0) return StringType();
+
+ out_buffer[elements - 1] = '\0';
+ return StringType(&out_buffer[0], elements - 1);
+}
+
+// Given an STL string |in| with an encoding specified by |in_encoding|,
+// convert it to |out_encoding| and return it as an STL string of the
+// |OutStringType| template type. Returns an empty string on failure.
+//
+// Do not assert in this function since it is used by the asssertion code!
+template <typename InStringType, typename OutStringType>
+static OutStringType STLStringToSTLStringWithEncodingsT(
+ const InStringType& in, CFStringEncoding in_encoding,
+ CFStringEncoding out_encoding) {
+ typename InStringType::size_type in_length = in.length();
+ if (in_length == 0) return OutStringType();
+
+ scoped_cftyperef<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy(
+ NULL, reinterpret_cast<const UInt8*>(in.data()),
+ in_length * sizeof(typename InStringType::value_type), in_encoding, false,
+ kCFAllocatorNull));
+ if (!cfstring) return OutStringType();
+
+ return CFStringToSTLStringWithEncodingT<OutStringType>(cfstring,
+ out_encoding);
+}
+
+// Given an STL string |in| with an encoding specified by |in_encoding|,
+// return it as a CFStringRef. Returns NULL on failure.
+template <typename StringType>
+static CFStringRef STLStringToCFStringWithEncodingsT(
+ const StringType& in, CFStringEncoding in_encoding) {
+ typename StringType::size_type in_length = in.length();
+ if (in_length == 0) return CFSTR("");
+
+ return CFStringCreateWithBytes(
+ kCFAllocatorDefault, reinterpret_cast<const UInt8*>(in.data()),
+ in_length * sizeof(typename StringType::value_type), in_encoding, false);
+}
+
+// Specify the byte ordering explicitly, otherwise CFString will be confused
+// when strings don't carry BOMs, as they typically won't.
+static const CFStringEncoding kNarrowStringEncoding = kCFStringEncodingUTF8;
+
+#ifdef __BIG_ENDIAN__
+static const CFStringEncoding kWideStringEncoding = kCFStringEncodingUTF32BE;
+#elif defined(__LITTLE_ENDIAN__)
+static const CFStringEncoding kWideStringEncoding = kCFStringEncodingUTF32LE;
+#endif // __LITTLE_ENDIAN__
+
+} // namespace
+
+// Do not assert in this function since it is used by the asssertion code!
+std::string SysWideToUTF8(const std::wstring& wide) {
+ return STLStringToSTLStringWithEncodingsT<std::wstring, std::string>(
+ wide, kWideStringEncoding, kNarrowStringEncoding);
+}
+
+// Do not assert in this function since it is used by the asssertion code!
+std::wstring SysUTF8ToWide(const StringPiece& utf8) {
+ return STLStringToSTLStringWithEncodingsT<StringPiece, std::wstring>(
+ utf8, kNarrowStringEncoding, kWideStringEncoding);
+}
+
+std::string SysWideToNativeMB(const std::wstring& wide) {
+ return SysWideToUTF8(wide);
+}
+
+std::wstring SysNativeMBToWide(const StringPiece& native_mb) {
+ return SysUTF8ToWide(native_mb);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/sys_string_conversions_win.cc b/ipc/chromium/src/base/sys_string_conversions_win.cc
new file mode 100644
index 0000000000..148685ca7e
--- /dev/null
+++ b/ipc/chromium/src/base/sys_string_conversions_win.cc
@@ -0,0 +1,68 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/sys_string_conversions.h"
+
+#include <windows.h>
+
+#include "base/string_piece.h"
+
+namespace base {
+
+// Do not assert in this function since it is used by the asssertion code!
+std::wstring SysMultiByteToWide(const StringPiece& mb, uint32_t code_page) {
+ if (mb.empty()) return std::wstring();
+
+ int mb_length = static_cast<int>(mb.length());
+ // Compute the length of the buffer.
+ int charcount =
+ MultiByteToWideChar(code_page, 0, mb.data(), mb_length, NULL, 0);
+ if (charcount == 0) return std::wstring();
+
+ std::wstring wide;
+ wide.resize(charcount);
+ MultiByteToWideChar(code_page, 0, mb.data(), mb_length, &wide[0], charcount);
+
+ return wide;
+}
+
+// Do not assert in this function since it is used by the asssertion code!
+std::string SysWideToMultiByte(const std::wstring& wide, uint32_t code_page) {
+ int wide_length = static_cast<int>(wide.length());
+ if (wide_length == 0) return std::string();
+
+ // Compute the length of the buffer we'll need.
+ int charcount = WideCharToMultiByte(code_page, 0, wide.data(), wide_length,
+ NULL, 0, NULL, NULL);
+ if (charcount == 0) return std::string();
+
+ std::string mb;
+ mb.resize(charcount);
+ WideCharToMultiByte(code_page, 0, wide.data(), wide_length, &mb[0], charcount,
+ NULL, NULL);
+
+ return mb;
+}
+
+// Do not assert in this function since it is used by the asssertion code!
+std::string SysWideToUTF8(const std::wstring& wide) {
+ return SysWideToMultiByte(wide, CP_UTF8);
+}
+
+// Do not assert in this function since it is used by the asssertion code!
+std::wstring SysUTF8ToWide(const StringPiece& utf8) {
+ return SysMultiByteToWide(utf8, CP_UTF8);
+}
+
+std::string SysWideToNativeMB(const std::wstring& wide) {
+ return SysWideToMultiByte(wide, CP_ACP);
+}
+
+std::wstring SysNativeMBToWide(const StringPiece& native_mb) {
+ return SysMultiByteToWide(native_mb, CP_ACP);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/task.h b/ipc/chromium/src/base/task.h
new file mode 100644
index 0000000000..9b1ae7feff
--- /dev/null
+++ b/ipc/chromium/src/base/task.h
@@ -0,0 +1,227 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_TASK_H_
+#define BASE_TASK_H_
+
+#include "base/revocable_store.h"
+#include "base/tuple.h"
+
+#include "nsISupportsImpl.h"
+#include "nsThreadUtils.h"
+
+#include <type_traits>
+#include <utility>
+
+// Helper functions so that we can call a function a pass it arguments that come
+// from a Tuple.
+
+namespace details {
+
+// Call the given method on the given object. Arguments are passed by move
+// semantics from the given tuple. If the tuple has length N, the sequence must
+// be IndexSequence<0, 1, ..., N-1>.
+template <size_t... Indices, class ObjT, class Method, typename... Args>
+void CallMethod(std::index_sequence<Indices...>, ObjT* obj, Method method,
+ std::tuple<Args...>& arg) {
+ (obj->*method)(std::move(std::get<Indices>(arg))...);
+}
+
+// Same as above, but call a function.
+template <size_t... Indices, typename Function, typename... Args>
+void CallFunction(std::index_sequence<Indices...>, Function function,
+ std::tuple<Args...>& arg) {
+ (*function)(std::move(std::get<Indices>(arg))...);
+}
+
+} // namespace details
+
+// Call a method on the given object. Arguments are passed by move semantics
+// from the given tuple.
+template <class ObjT, class Method, typename... Args>
+void DispatchTupleToMethod(ObjT* obj, Method method, std::tuple<Args...>& arg) {
+ details::CallMethod(std::index_sequence_for<Args...>{}, obj, method, arg);
+}
+
+// Same as above, but call a function.
+template <typename Function, typename... Args>
+void DispatchTupleToFunction(Function function, std::tuple<Args...>& arg) {
+ details::CallFunction(std::index_sequence_for<Args...>{}, function, arg);
+}
+
+// General task implementations ------------------------------------------------
+
+// Task to delete an object
+template <class T>
+class DeleteTask : public mozilla::CancelableRunnable {
+ public:
+ explicit DeleteTask(T* obj)
+ : mozilla::CancelableRunnable("DeleteTask"), obj_(obj) {}
+ NS_IMETHOD Run() override {
+ delete obj_;
+ return NS_OK;
+ }
+ virtual nsresult Cancel() override {
+ obj_ = NULL;
+ return NS_OK;
+ }
+
+ private:
+ T* MOZ_UNSAFE_REF(
+ "The validity of this pointer must be enforced by "
+ "external factors.") obj_;
+};
+
+// RunnableMethodTraits --------------------------------------------------------
+//
+// This traits-class is used by RunnableMethod to manage the lifetime of the
+// callee object. By default, it is assumed that the callee supports AddRef
+// and Release methods. A particular class can specialize this template to
+// define other lifetime management. For example, if the callee is known to
+// live longer than the RunnableMethod object, then a RunnableMethodTraits
+// struct could be defined with empty RetainCallee and ReleaseCallee methods.
+
+template <class T>
+struct RunnableMethodTraits {
+ static void RetainCallee(T* obj) { obj->AddRef(); }
+ static void ReleaseCallee(T* obj) { obj->Release(); }
+};
+
+// This allows using the NewRunnableMethod() functions with a const pointer
+// to the callee object. See the similar support in nsRefPtr for a rationale
+// of why this is reasonable.
+template <class T>
+struct RunnableMethodTraits<const T> {
+ static void RetainCallee(const T* obj) { const_cast<T*>(obj)->AddRef(); }
+ static void ReleaseCallee(const T* obj) { const_cast<T*>(obj)->Release(); }
+};
+
+// RunnableMethod and RunnableFunction -----------------------------------------
+//
+// Runnable methods are a type of task that call a function on an object when
+// they are run. We implement both an object and a set of NewRunnableMethod and
+// NewRunnableFunction functions for convenience. These functions are
+// overloaded and will infer the template types, simplifying calling code.
+//
+// The template definitions all use the following names:
+// T - the class type of the object you're supplying
+// this is not needed for the Static version of the call
+// Method/Function - the signature of a pointer to the method or function you
+// want to call
+// Param - the parameter(s) to the method, possibly packed as a Tuple
+// A - the first parameter (if any) to the method
+// B - the second parameter (if any) to the mathod
+//
+// Put these all together and you get an object that can call a method whose
+// signature is:
+// R T::MyFunction([A[, B]])
+//
+// Usage:
+// PostTask(NewRunnableMethod(object, &Object::method[, a[, b]])
+// PostTask(NewRunnableFunction(&function[, a[, b]])
+
+// RunnableMethod and NewRunnableMethod implementation -------------------------
+
+template <class T, class Method, class Params>
+class RunnableMethod : public mozilla::CancelableRunnable,
+ public RunnableMethodTraits<T> {
+ public:
+ RunnableMethod(T* obj, Method meth, Params&& params)
+ : mozilla::CancelableRunnable("RunnableMethod"),
+ obj_(obj),
+ meth_(meth),
+ params_(std::forward<Params>(params)) {
+ this->RetainCallee(obj_);
+ }
+ ~RunnableMethod() { ReleaseCallee(); }
+
+ NS_IMETHOD Run() override {
+ if (obj_) DispatchTupleToMethod(obj_, meth_, params_);
+ return NS_OK;
+ }
+
+ virtual nsresult Cancel() override {
+ ReleaseCallee();
+ return NS_OK;
+ }
+
+ private:
+ void ReleaseCallee() {
+ if (obj_) {
+ RunnableMethodTraits<T>::ReleaseCallee(obj_);
+ obj_ = nullptr;
+ }
+ }
+
+ // This is owning because of the RetainCallee and ReleaseCallee calls in the
+ // constructor and destructor.
+ T* MOZ_OWNING_REF obj_;
+ Method meth_;
+ Params params_;
+};
+
+namespace dont_add_new_uses_of_this {
+
+// Don't add new uses of this!!!!
+template <class T, class Method, typename... Args>
+inline already_AddRefed<mozilla::Runnable> NewRunnableMethod(T* object,
+ Method method,
+ Args&&... args) {
+ typedef std::tuple<std::decay_t<Args>...> ArgsTuple;
+ RefPtr<mozilla::Runnable> t = new RunnableMethod<T, Method, ArgsTuple>(
+ object, method, std::make_tuple(std::forward<Args>(args)...));
+ return t.forget();
+}
+
+} // namespace dont_add_new_uses_of_this
+
+// RunnableFunction and NewRunnableFunction implementation ---------------------
+
+template <class Function, class Params>
+class RunnableFunction : public mozilla::CancelableRunnable {
+ public:
+ RunnableFunction(const char* name, Function function, Params&& params)
+ : mozilla::CancelableRunnable(name),
+ function_(function),
+ params_(std::forward<Params>(params)) {}
+
+ ~RunnableFunction() {}
+
+ NS_IMETHOD Run() override {
+ if (function_) DispatchTupleToFunction(function_, params_);
+ return NS_OK;
+ }
+
+ virtual nsresult Cancel() override {
+ function_ = nullptr;
+ return NS_OK;
+ }
+
+ Function function_;
+ Params params_;
+};
+
+template <class Function, typename... Args>
+inline already_AddRefed<mozilla::CancelableRunnable>
+NewCancelableRunnableFunction(const char* name, Function function,
+ Args&&... args) {
+ typedef std::tuple<std::decay_t<Args>...> ArgsTuple;
+ RefPtr<mozilla::CancelableRunnable> t =
+ new RunnableFunction<Function, ArgsTuple>(
+ name, function, std::make_tuple(std::forward<Args>(args)...));
+ return t.forget();
+}
+
+template <class Function, typename... Args>
+inline already_AddRefed<mozilla::Runnable> NewRunnableFunction(
+ const char* name, Function function, Args&&... args) {
+ typedef std::tuple<std::decay_t<Args>...> ArgsTuple;
+ RefPtr<mozilla::Runnable> t = new RunnableFunction<Function, ArgsTuple>(
+ name, function, std::make_tuple(std::forward<Args>(args)...));
+ return t.forget();
+}
+
+#endif // BASE_TASK_H_
diff --git a/ipc/chromium/src/base/thread.cc b/ipc/chromium/src/base/thread.cc
new file mode 100644
index 0000000000..c856272162
--- /dev/null
+++ b/ipc/chromium/src/base/thread.cc
@@ -0,0 +1,201 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// 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.
+
+#include "base/thread.h"
+
+#include "base/string_util.h"
+#include "base/thread_local.h"
+#include "base/waitable_event.h"
+#include "GeckoProfiler.h"
+#include "mozilla/EventQueue.h"
+#include "mozilla/IOInterposer.h"
+#include "mozilla/ThreadEventQueue.h"
+#include "nsThreadUtils.h"
+#include "nsThreadManager.h"
+
+namespace base {
+
+// This task is used to trigger the message loop to exit.
+class ThreadQuitTask : public mozilla::Runnable {
+ public:
+ ThreadQuitTask() : mozilla::Runnable("ThreadQuitTask") {}
+ NS_IMETHOD Run() override {
+ MessageLoop::current()->Quit();
+ Thread::SetThreadWasQuitProperly(true);
+ return NS_OK;
+ }
+};
+
+// Used to pass data to ThreadMain. This structure is allocated on the stack
+// from within StartWithOptions.
+struct Thread::StartupData {
+ // We get away with a const reference here because of how we are allocated.
+ const Thread::Options& options;
+
+ // Used to synchronize thread startup.
+ WaitableEvent event;
+
+ explicit StartupData(const Options& opt)
+ : options(opt), event(false, false) {}
+};
+
+Thread::Thread(const char* name)
+ : startup_data_(NULL),
+ thread_(0),
+ message_loop_(NULL),
+ thread_id_(0),
+ name_(name) {
+ MOZ_COUNT_CTOR(base::Thread);
+}
+
+Thread::~Thread() {
+ MOZ_COUNT_DTOR(base::Thread);
+ Stop();
+}
+
+namespace {
+
+// We use this thread-local variable to record whether or not a thread exited
+// because its Stop method was called. This allows us to catch cases where
+// MessageLoop::Quit() is called directly, which is unexpected when using a
+// Thread to setup and run a MessageLoop.
+
+static base::ThreadLocalBoolean& get_tls_bool() {
+ static base::ThreadLocalBoolean tls_ptr;
+ return tls_ptr;
+}
+
+} // namespace
+
+void Thread::SetThreadWasQuitProperly(bool flag) { get_tls_bool().Set(flag); }
+
+bool Thread::GetThreadWasQuitProperly() {
+ bool quit_properly = true;
+#ifndef NDEBUG
+ quit_properly = get_tls_bool().Get();
+#endif
+ return quit_properly;
+}
+
+bool Thread::Start() { return StartWithOptions(Options()); }
+
+bool Thread::StartWithOptions(const Options& options) {
+ DCHECK(!message_loop_);
+
+ SetThreadWasQuitProperly(false);
+
+ StartupData startup_data(options);
+ startup_data_ = &startup_data;
+
+ if (!PlatformThread::Create(options.stack_size, this, &thread_)) {
+ DLOG(ERROR) << "failed to create thread";
+ startup_data_ = NULL; // Record that we failed to start.
+ return false;
+ }
+
+ // Wait for the thread to start and initialize message_loop_
+ startup_data.event.Wait();
+
+ DCHECK(message_loop_);
+ return true;
+}
+
+void Thread::Stop() {
+ if (!thread_was_started()) return;
+
+ // We should only be called on the same thread that started us.
+ DCHECK_NE(thread_id_, PlatformThread::CurrentId());
+
+ // StopSoon may have already been called.
+ if (message_loop_) {
+ RefPtr<ThreadQuitTask> task = new ThreadQuitTask();
+ message_loop_->PostTask(task.forget());
+ }
+
+ // Wait for the thread to exit. It should already have terminated but make
+ // sure this assumption is valid.
+ //
+ // TODO(darin): Unfortunately, we need to keep message_loop_ around until
+ // the thread exits. Some consumers are abusing the API. Make them stop.
+ //
+ PlatformThread::Join(thread_);
+
+ // The thread can't receive messages anymore.
+ message_loop_ = NULL;
+
+ // The thread no longer needs to be joined.
+ startup_data_ = NULL;
+}
+
+void Thread::StopSoon() {
+ if (!message_loop_) return;
+
+ // We should only be called on the same thread that started us.
+ DCHECK_NE(thread_id_, PlatformThread::CurrentId());
+
+ // We had better have a message loop at this point! If we do not, then it
+ // most likely means that the thread terminated unexpectedly, probably due
+ // to someone calling Quit() on our message loop directly.
+ DCHECK(message_loop_);
+
+ RefPtr<ThreadQuitTask> task = new ThreadQuitTask();
+ message_loop_->PostTask(task.forget());
+}
+
+void Thread::ThreadMain() {
+ nsCOMPtr<nsIThread> xpcomThread;
+ auto loopType = startup_data_->options.message_loop_type;
+ if (loopType == MessageLoop::TYPE_MOZILLA_NONMAINTHREAD ||
+ loopType == MessageLoop::TYPE_MOZILLA_NONMAINUITHREAD) {
+ auto queue = mozilla::MakeRefPtr<mozilla::ThreadEventQueue>(
+ mozilla::MakeUnique<mozilla::EventQueue>());
+ xpcomThread = nsThreadManager::get().CreateCurrentThread(queue);
+ } else {
+ xpcomThread = NS_GetCurrentThread();
+ }
+
+ AUTO_PROFILER_REGISTER_THREAD(name_.c_str());
+ mozilla::IOInterposer::RegisterCurrentThread();
+
+ // The message loop for this thread.
+ MessageLoop message_loop(startup_data_->options.message_loop_type,
+ xpcomThread);
+
+ xpcomThread = nullptr;
+
+ // Complete the initialization of our Thread object.
+ thread_id_ = PlatformThread::CurrentId();
+ PlatformThread::SetName(name_.c_str());
+ NS_SetCurrentThreadName(name_.c_str());
+ message_loop.set_thread_name(name_);
+ message_loop.set_hang_timeouts(startup_data_->options.transient_hang_timeout,
+ startup_data_->options.permanent_hang_timeout);
+ message_loop_ = &message_loop;
+
+ // Let the thread do extra initialization.
+ // Let's do this before signaling we are started.
+ Init();
+
+ startup_data_->event.Signal();
+ // startup_data_ can't be touched anymore since the starting thread is now
+ // unlocked.
+
+ message_loop.Run();
+
+ // Let the thread do extra cleanup.
+ CleanUp();
+
+ // Assert that MessageLoop::Quit was called by ThreadQuitTask.
+ DCHECK(GetThreadWasQuitProperly());
+
+ mozilla::IOInterposer::UnregisterCurrentThread();
+
+ // We can't receive messages anymore.
+ message_loop_ = NULL;
+ thread_id_ = 0;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/thread.h b/ipc/chromium/src/base/thread.h
new file mode 100644
index 0000000000..7b9a5975d3
--- /dev/null
+++ b/ipc/chromium/src/base/thread.h
@@ -0,0 +1,176 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// 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.
+
+#ifndef BASE_THREAD_H_
+#define BASE_THREAD_H_
+
+#include <stdint.h>
+#include <string>
+
+#include "base/message_loop.h"
+#include "base/platform_thread.h"
+
+namespace base {
+
+// A simple thread abstraction that establishes a MessageLoop on a new thread.
+// The consumer uses the MessageLoop of the thread to cause code to execute on
+// the thread. When this object is destroyed the thread is terminated. All
+// pending tasks queued on the thread's message loop will run to completion
+// before the thread is terminated.
+class Thread : PlatformThread::Delegate {
+ public:
+ struct Options {
+ // Specifies the type of message loop that will be allocated on the thread.
+ MessageLoop::Type message_loop_type;
+
+ // Specifies the maximum stack size that the thread is allowed to use.
+ // This does not necessarily correspond to the thread's initial stack size.
+ // A value of 0 indicates that the default maximum should be used.
+ size_t stack_size;
+
+ // Specifies the transient and permanent hang timeouts for background hang
+ // monitoring. A value of 0 indicates there is no timeout.
+ uint32_t transient_hang_timeout;
+ uint32_t permanent_hang_timeout;
+
+ Options()
+ : message_loop_type(MessageLoop::TYPE_DEFAULT),
+ stack_size(0),
+ transient_hang_timeout(0),
+ permanent_hang_timeout(0) {}
+ Options(MessageLoop::Type type, size_t size)
+ : message_loop_type(type),
+ stack_size(size),
+ transient_hang_timeout(0),
+ permanent_hang_timeout(0) {}
+ };
+
+ // Constructor.
+ // name is a display string to identify the thread.
+ explicit Thread(const char* name);
+
+ // Destroys the thread, stopping it if necessary.
+ //
+ // NOTE: If you are subclassing from Thread, and you wish for your CleanUp
+ // method to be called, then you need to call Stop() from your destructor.
+ //
+ virtual ~Thread();
+
+ // Starts the thread. Returns true if the thread was successfully started;
+ // otherwise, returns false. Upon successful return, the message_loop()
+ // getter will return non-null.
+ //
+ // Note: This function can't be called on Windows with the loader lock held;
+ // i.e. during a DllMain, global object construction or destruction, atexit()
+ // callback.
+ bool Start();
+
+ // Starts the thread. Behaves exactly like Start in addition to allow to
+ // override the default options.
+ //
+ // Note: This function can't be called on Windows with the loader lock held;
+ // i.e. during a DllMain, global object construction or destruction, atexit()
+ // callback.
+ bool StartWithOptions(const Options& options);
+
+ // Signals the thread to exit and returns once the thread has exited. After
+ // this method returns, the Thread object is completely reset and may be used
+ // as if it were newly constructed (i.e., Start may be called again).
+ //
+ // Stop may be called multiple times and is simply ignored if the thread is
+ // already stopped.
+ //
+ // NOTE: This method is optional. It is not strictly necessary to call this
+ // method as the Thread's destructor will take care of stopping the thread if
+ // necessary.
+ //
+ void Stop();
+
+ // Signals the thread to exit in the near future.
+ //
+ // WARNING: This function is not meant to be commonly used. Use at your own
+ // risk. Calling this function will cause message_loop() to become invalid in
+ // the near future. This function was created to workaround a specific
+ // deadlock on Windows with printer worker thread. In any other case, Stop()
+ // should be used.
+ //
+ // StopSoon should not be called multiple times as it is risky to do so. It
+ // could cause a timing issue in message_loop() access. Call Stop() to reset
+ // the thread object once it is known that the thread has quit.
+ void StopSoon();
+
+ // Returns the message loop for this thread. Use the MessageLoop's
+ // PostTask methods to execute code on the thread. This only returns
+ // non-null after a successful call to Start. After Stop has been called,
+ // this will return NULL.
+ //
+ // NOTE: You must not call this MessageLoop's Quit method directly. Use
+ // the Thread's Stop method instead.
+ //
+ MessageLoop* message_loop() const { return message_loop_; }
+
+ // Set the name of this thread (for display in debugger too).
+ const std::string& thread_name() { return name_; }
+
+ // The native thread handle.
+ PlatformThreadHandle thread_handle() { return thread_; }
+
+ // The thread ID.
+ PlatformThreadId thread_id() const { return thread_id_; }
+
+ // Reset thread ID as current thread.
+ PlatformThreadId reset_thread_id() {
+ thread_id_ = PlatformThread::CurrentId();
+ return thread_id_;
+ }
+
+ // Returns true if the thread has been started, and not yet stopped.
+ // When a thread is running, the thread_id_ is non-zero.
+ bool IsRunning() const { return thread_id_ != 0; }
+
+ protected:
+ // Called just prior to starting the message loop
+ virtual void Init() {}
+
+ // Called just after the message loop ends
+ virtual void CleanUp() {}
+
+ static void SetThreadWasQuitProperly(bool flag);
+ static bool GetThreadWasQuitProperly();
+
+ private:
+ // PlatformThread::Delegate methods:
+ virtual void ThreadMain() override;
+
+ // We piggy-back on the startup_data_ member to know if we successfully
+ // started the thread. This way we know that we need to call Join.
+ bool thread_was_started() const { return startup_data_ != NULL; }
+
+ // Used to pass data to ThreadMain.
+ struct StartupData;
+ StartupData* startup_data_;
+
+ // The thread's handle.
+ PlatformThreadHandle thread_;
+
+ // The thread's message loop. Valid only while the thread is alive. Set
+ // by the created thread.
+ MessageLoop* message_loop_;
+
+ // Our thread's ID.
+ PlatformThreadId thread_id_;
+
+ // The name of the thread. Used for debugging purposes.
+ std::string name_;
+
+ friend class ThreadQuitTask;
+
+ DISALLOW_COPY_AND_ASSIGN(Thread);
+};
+
+} // namespace base
+
+#endif // BASE_THREAD_H_
diff --git a/ipc/chromium/src/base/thread_local.h b/ipc/chromium/src/base/thread_local.h
new file mode 100644
index 0000000000..c031875d01
--- /dev/null
+++ b/ipc/chromium/src/base/thread_local.h
@@ -0,0 +1,121 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// WARNING: Thread local storage is a bit tricky to get right. Please make
+// sure that this is really the proper solution for what you're trying to
+// achieve. Don't prematurely optimize, most likely you can just use a Lock.
+//
+// These classes implement a warpper around the platform's TLS storage
+// mechanism. On construction, they will allocate a TLS slot, and free the
+// TLS slot on destruction. No memory management (creation or destruction) is
+// handled. This means for uses of ThreadLocalPointer, you must correctly
+// manage the memory yourself, these classes will not destroy the pointer for
+// you. There are no at-thread-exit actions taken by these classes.
+//
+// ThreadLocalPointer<Type> wraps a Type*. It performs no creation or
+// destruction, so memory management must be handled elsewhere. The first call
+// to Get() on a thread will return NULL. You can update the pointer with a
+// call to Set().
+//
+// ThreadLocalBoolean wraps a bool. It will default to false if it has never
+// been set otherwise with Set().
+//
+// Thread Safety: An instance of ThreadLocalStorage is completely thread safe
+// once it has been created. If you want to dynamically create an instance,
+// you must of course properly deal with safety and race conditions. This
+// means a function-level static initializer is generally inappropiate.
+//
+// Example usage:
+// // My class is logically attached to a single thread. We cache a pointer
+// // on the thread it was created on, so we can implement current().
+// MyClass::MyClass() {
+// DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() == NULL);
+// Singleton<ThreadLocalPointer<MyClass> >::get()->Set(this);
+// }
+//
+// MyClass::~MyClass() {
+// DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() != NULL);
+// Singleton<ThreadLocalPointer<MyClass> >::get()->Set(NULL);
+// }
+//
+// // Return the current MyClass associated with the calling thread, can be
+// // NULL if there isn't a MyClass associated.
+// MyClass* MyClass::current() {
+// return Singleton<ThreadLocalPointer<MyClass> >::get()->Get();
+// }
+
+#ifndef BASE_THREAD_LOCAL_H_
+#define BASE_THREAD_LOCAL_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+#else
+# include <pthread.h>
+#endif
+
+namespace base {
+
+// Helper functions that abstract the cross-platform APIs. Do not use directly.
+struct ThreadLocalPlatform {
+#if defined(XP_WIN)
+ typedef DWORD SlotType;
+#else
+ typedef pthread_key_t SlotType;
+#endif
+
+ static void AllocateSlot(SlotType& slot);
+ static void FreeSlot(SlotType& slot);
+ static void* GetValueFromSlot(SlotType& slot);
+ static void SetValueInSlot(SlotType& slot, void* value);
+};
+
+template <typename Type>
+class ThreadLocalPointer {
+ public:
+ ThreadLocalPointer() : slot_() { ThreadLocalPlatform::AllocateSlot(slot_); }
+
+ ThreadLocalPointer(const ThreadLocalPointer&) = delete;
+ ThreadLocalPointer& operator=(const ThreadLocalPointer&) = delete;
+
+ ~ThreadLocalPointer() { ThreadLocalPlatform::FreeSlot(slot_); }
+
+ Type* Get() {
+ return static_cast<Type*>(ThreadLocalPlatform::GetValueFromSlot(slot_));
+ }
+
+ void Set(Type* ptr) { ThreadLocalPlatform::SetValueInSlot(slot_, ptr); }
+
+ private:
+ typedef ThreadLocalPlatform::SlotType SlotType;
+
+ SlotType slot_;
+};
+
+class ThreadLocalBoolean {
+ public:
+ ThreadLocalBoolean() {}
+
+ ThreadLocalBoolean(const ThreadLocalBoolean&) = delete;
+ ThreadLocalBoolean& operator=(const ThreadLocalBoolean&) = delete;
+
+ ~ThreadLocalBoolean() {}
+
+ bool Get() { return tlp_.Get() != NULL; }
+
+ void Set(bool val) {
+ uintptr_t intVal = val ? 1 : 0;
+ tlp_.Set(reinterpret_cast<void*>(intVal));
+ }
+
+ private:
+ ThreadLocalPointer<void> tlp_;
+};
+
+} // namespace base
+
+#endif // BASE_THREAD_LOCAL_H_
diff --git a/ipc/chromium/src/base/thread_local_posix.cc b/ipc/chromium/src/base/thread_local_posix.cc
new file mode 100644
index 0000000000..050a6e4b92
--- /dev/null
+++ b/ipc/chromium/src/base/thread_local_posix.cc
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/thread_local.h"
+
+#include <pthread.h>
+
+#include "base/logging.h"
+
+namespace base {
+
+// static
+void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
+ int error = pthread_key_create(&slot, NULL);
+ CHECK(error == 0);
+}
+
+// static
+void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
+ int error = pthread_key_delete(slot);
+ DCHECK(error == 0);
+}
+
+// static
+void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
+ return pthread_getspecific(slot);
+}
+
+// static
+void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
+ int error = pthread_setspecific(slot, value);
+ CHECK(error == 0);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/thread_local_storage.h b/ipc/chromium/src/base/thread_local_storage.h
new file mode 100644
index 0000000000..1134aa6ad9
--- /dev/null
+++ b/ipc/chromium/src/base/thread_local_storage.h
@@ -0,0 +1,95 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_THREAD_LOCAL_STORAGE_H_
+#define BASE_THREAD_LOCAL_STORAGE_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_UNIX)
+# include <pthread.h>
+#endif
+
+// Wrapper for thread local storage. This class doesn't do much except provide
+// an API for portability.
+class ThreadLocalStorage {
+ public:
+ // Prototype for the TLS destructor function, which can be optionally used to
+ // cleanup thread local storage on thread exit. 'value' is the data that is
+ // stored in thread local storage.
+ typedef void (*TLSDestructorFunc)(void* value);
+
+ // A key representing one value stored in TLS.
+ class Slot {
+ public:
+ explicit Slot(TLSDestructorFunc destructor = NULL);
+
+ // This constructor should be used for statics.
+ // It returns an uninitialized Slot.
+ explicit Slot(base::LinkerInitialized x) {}
+
+ // Set up the TLS slot. Called by the constructor.
+ // 'destructor' is a pointer to a function to perform per-thread cleanup of
+ // this object. If set to NULL, no cleanup is done for this TLS slot.
+ // Returns false on error.
+ bool Initialize(TLSDestructorFunc destructor);
+
+ // Free a previously allocated TLS 'slot'.
+ // If a destructor was set for this slot, removes
+ // the destructor so that remaining threads exiting
+ // will not free data.
+ void Free();
+
+ // Get the thread-local value stored in slot 'slot'.
+ // Values are guaranteed to initially be zero.
+ void* Get() const;
+
+ // Set the thread-local value stored in slot 'slot' to
+ // value 'value'.
+ void Set(void* value);
+
+ bool initialized() const { return initialized_; }
+
+ private:
+ // The internals of this struct should be considered private.
+ bool initialized_;
+#if defined(XP_WIN)
+ int slot_;
+#else
+ pthread_key_t key_;
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(Slot);
+ };
+
+#if defined(XP_WIN)
+ // Function called when on thread exit to call TLS
+ // destructor functions. This function is used internally.
+ static void ThreadExit();
+
+ private:
+ // Function to lazily initialize our thread local storage.
+ static void** Initialize();
+
+ private:
+ // The maximum number of 'slots' in our thread local storage stack.
+ // For now, this is fixed. We could either increase statically, or
+ // we could make it dynamic in the future.
+ static const int kThreadLocalStorageSize = 64;
+
+ static long tls_key_;
+ static long tls_max_;
+ static TLSDestructorFunc tls_destructors_[kThreadLocalStorageSize];
+#endif // XP_WIN
+
+ DISALLOW_COPY_AND_ASSIGN(ThreadLocalStorage);
+};
+
+// Temporary backwards-compatible name.
+// TODO(evanm): replace all usage of TLSSlot.
+typedef ThreadLocalStorage::Slot TLSSlot;
+
+#endif // BASE_THREAD_LOCAL_STORAGE_H_
diff --git a/ipc/chromium/src/base/thread_local_win.cc b/ipc/chromium/src/base/thread_local_win.cc
new file mode 100644
index 0000000000..2eb68e63b3
--- /dev/null
+++ b/ipc/chromium/src/base/thread_local_win.cc
@@ -0,0 +1,41 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/thread_local.h"
+
+#include <windows.h>
+
+#include "base/logging.h"
+
+namespace base {
+
+// static
+void ThreadLocalPlatform::AllocateSlot(SlotType& slot) {
+ slot = TlsAlloc();
+ CHECK(slot != TLS_OUT_OF_INDEXES);
+}
+
+// static
+void ThreadLocalPlatform::FreeSlot(SlotType& slot) {
+ if (!TlsFree(slot)) {
+ NOTREACHED() << "Failed to deallocate tls slot with TlsFree().";
+ }
+}
+
+// static
+void* ThreadLocalPlatform::GetValueFromSlot(SlotType& slot) {
+ return TlsGetValue(slot);
+}
+
+// static
+void ThreadLocalPlatform::SetValueInSlot(SlotType& slot, void* value) {
+ if (!TlsSetValue(slot, value)) {
+ CHECK(false)
+ << "Failed to TlsSetValue().";
+ }
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/time.cc b/ipc/chromium/src/base/time.cc
new file mode 100644
index 0000000000..2d76878005
--- /dev/null
+++ b/ipc/chromium/src/base/time.cc
@@ -0,0 +1,97 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/time.h"
+#include "base/string_util.h"
+#include "base/sys_string_conversions.h"
+#include "prtime.h"
+
+#include "base/logging.h"
+
+namespace base {
+
+// TimeDelta ------------------------------------------------------------------
+
+int TimeDelta::InDays() const {
+ return static_cast<int>(delta_ / Time::kMicrosecondsPerDay);
+}
+
+int TimeDelta::InHours() const {
+ return static_cast<int>(delta_ / Time::kMicrosecondsPerHour);
+}
+
+int TimeDelta::InMinutes() const {
+ return static_cast<int>(delta_ / Time::kMicrosecondsPerMinute);
+}
+
+double TimeDelta::InSecondsF() const {
+ return static_cast<double>(delta_) / Time::kMicrosecondsPerSecond;
+}
+
+int64_t TimeDelta::InSeconds() const {
+ return delta_ / Time::kMicrosecondsPerSecond;
+}
+
+double TimeDelta::InMillisecondsF() const {
+ return static_cast<double>(delta_) / Time::kMicrosecondsPerMillisecond;
+}
+
+int64_t TimeDelta::InMilliseconds() const {
+ return delta_ / Time::kMicrosecondsPerMillisecond;
+}
+
+int64_t TimeDelta::InMicroseconds() const { return delta_; }
+
+// Time -----------------------------------------------------------------------
+
+// static
+Time Time::FromTimeT(time_t tt) {
+ if (tt == 0) return Time(); // Preserve 0 so we can tell it doesn't exist.
+ return Time((tt * kMicrosecondsPerSecond) + kTimeTToMicrosecondsOffset);
+}
+
+time_t Time::ToTimeT() const {
+ if (us_ == 0) return 0; // Preserve 0 so we can tell it doesn't exist.
+ return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond;
+}
+
+// static
+Time Time::FromDoubleT(double dt) {
+ return Time((dt * static_cast<double>(kMicrosecondsPerSecond)) +
+ kTimeTToMicrosecondsOffset);
+}
+
+double Time::ToDoubleT() const {
+ if (us_ == 0) return 0; // Preserve 0 so we can tell it doesn't exist.
+ return (static_cast<double>(us_ - kTimeTToMicrosecondsOffset) /
+ static_cast<double>(kMicrosecondsPerSecond));
+}
+
+Time Time::LocalMidnight() const {
+ Exploded exploded;
+ LocalExplode(&exploded);
+ exploded.hour = 0;
+ exploded.minute = 0;
+ exploded.second = 0;
+ exploded.millisecond = 0;
+ return FromLocalExploded(exploded);
+}
+
+// static
+bool Time::FromString(const wchar_t* time_string, Time* parsed_time) {
+ DCHECK((time_string != NULL) && (parsed_time != NULL));
+ std::string ascii_time_string = SysWideToUTF8(time_string);
+ if (ascii_time_string.length() == 0) return false;
+ PRTime result_time = 0;
+ PRStatus result =
+ PR_ParseTimeString(ascii_time_string.c_str(), PR_FALSE, &result_time);
+ if (PR_SUCCESS != result) return false;
+ result_time += kTimeTToMicrosecondsOffset;
+ *parsed_time = Time(result_time);
+ return true;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/time.h b/ipc/chromium/src/base/time.h
new file mode 100644
index 0000000000..cc9bc8e30e
--- /dev/null
+++ b/ipc/chromium/src/base/time.h
@@ -0,0 +1,392 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// Time represents an absolute point in time, internally represented as
+// microseconds (s/1,000,000) since a platform-dependent epoch. Each
+// platform's epoch, along with other system-dependent clock interface
+// routines, is defined in time_PLATFORM.cc.
+//
+// TimeDelta represents a duration of time, internally represented in
+// microseconds.
+//
+// TimeTicks represents an abstract time that is always incrementing for use
+// in measuring time durations. It is internally represented in microseconds.
+// It can not be converted to a human-readable time, but is guaranteed not to
+// decrease (if the user changes the computer clock, Time::Now() may actually
+// decrease or jump).
+//
+// These classes are represented as only a 64-bit value, so they can be
+// efficiently passed by value.
+
+#ifndef BASE_TIME_H_
+#define BASE_TIME_H_
+
+#include <time.h>
+
+#include "base/basictypes.h"
+
+namespace base {
+
+class Time;
+class TimeTicks;
+
+// This unit test does a lot of manual time manipulation.
+class PageLoadTrackerUnitTest;
+
+// TimeDelta ------------------------------------------------------------------
+
+class TimeDelta {
+ public:
+ TimeDelta() : delta_(0) {}
+
+ // Converts units of time to TimeDeltas.
+ static TimeDelta FromDays(int64_t days);
+ static TimeDelta FromHours(int64_t hours);
+ static TimeDelta FromMinutes(int64_t minutes);
+ static TimeDelta FromSeconds(int64_t secs);
+ static TimeDelta FromMilliseconds(int64_t ms);
+ static TimeDelta FromMicroseconds(int64_t us);
+
+ // Returns the internal numeric value of the TimeDelta object. Please don't
+ // use this and do arithmetic on it, as it is more error prone than using the
+ // provided operators.
+ int64_t ToInternalValue() const { return delta_; }
+
+ // Returns the time delta in some unit. The F versions return a floating
+ // point value, the "regular" versions return a rounded-down value.
+ int InDays() const;
+ int InHours() const;
+ int InMinutes() const;
+ double InSecondsF() const;
+ int64_t InSeconds() const;
+ double InMillisecondsF() const;
+ int64_t InMilliseconds() const;
+ int64_t InMicroseconds() const;
+
+ TimeDelta& operator=(TimeDelta other) {
+ delta_ = other.delta_;
+ return *this;
+ }
+
+ // Computations with other deltas.
+ TimeDelta operator+(TimeDelta other) const {
+ return TimeDelta(delta_ + other.delta_);
+ }
+ TimeDelta operator-(TimeDelta other) const {
+ return TimeDelta(delta_ - other.delta_);
+ }
+
+ TimeDelta& operator+=(TimeDelta other) {
+ delta_ += other.delta_;
+ return *this;
+ }
+ TimeDelta& operator-=(TimeDelta other) {
+ delta_ -= other.delta_;
+ return *this;
+ }
+ TimeDelta operator-() const { return TimeDelta(-delta_); }
+
+ // Computations with ints, note that we only allow multiplicative operations
+ // with ints, and additive operations with other deltas.
+ TimeDelta operator*(int64_t a) const { return TimeDelta(delta_ * a); }
+ TimeDelta operator/(int64_t a) const { return TimeDelta(delta_ / a); }
+ TimeDelta& operator*=(int64_t a) {
+ delta_ *= a;
+ return *this;
+ }
+ TimeDelta& operator/=(int64_t a) {
+ delta_ /= a;
+ return *this;
+ }
+ int64_t operator/(TimeDelta a) const { return delta_ / a.delta_; }
+
+ // Defined below because it depends on the definition of the other classes.
+ Time operator+(Time t) const;
+ TimeTicks operator+(TimeTicks t) const;
+
+ // Comparison operators.
+ bool operator==(TimeDelta other) const { return delta_ == other.delta_; }
+ bool operator!=(TimeDelta other) const { return delta_ != other.delta_; }
+ bool operator<(TimeDelta other) const { return delta_ < other.delta_; }
+ bool operator<=(TimeDelta other) const { return delta_ <= other.delta_; }
+ bool operator>(TimeDelta other) const { return delta_ > other.delta_; }
+ bool operator>=(TimeDelta other) const { return delta_ >= other.delta_; }
+
+ private:
+ friend class Time;
+ friend class TimeTicks;
+ friend TimeDelta operator*(int64_t a, TimeDelta td);
+
+ // Constructs a delta given the duration in microseconds. This is private
+ // to avoid confusion by callers with an integer constructor. Use
+ // FromSeconds, FromMilliseconds, etc. instead.
+ explicit TimeDelta(int64_t delta_us) : delta_(delta_us) {}
+
+ // Delta in microseconds.
+ int64_t delta_;
+};
+
+inline TimeDelta operator*(int64_t a, TimeDelta td) {
+ return TimeDelta(a * td.delta_);
+}
+
+// Time -----------------------------------------------------------------------
+
+// Represents a wall clock time.
+class Time {
+ public:
+ static const int64_t kMillisecondsPerSecond = 1000;
+ static const int64_t kMicrosecondsPerMillisecond = 1000;
+ static const int64_t kMicrosecondsPerSecond =
+ kMicrosecondsPerMillisecond * kMillisecondsPerSecond;
+ static const int64_t kMicrosecondsPerMinute = kMicrosecondsPerSecond * 60;
+ static const int64_t kMicrosecondsPerHour = kMicrosecondsPerMinute * 60;
+ static const int64_t kMicrosecondsPerDay = kMicrosecondsPerHour * 24;
+ static const int64_t kMicrosecondsPerWeek = kMicrosecondsPerDay * 7;
+ static const int64_t kNanosecondsPerMicrosecond = 1000;
+ static const int64_t kNanosecondsPerSecond =
+ kNanosecondsPerMicrosecond * kMicrosecondsPerSecond;
+
+ // Represents an exploded time that can be formatted nicely. This is kind of
+ // like the Win32 SYSTEMTIME structure or the Unix "struct tm" with a few
+ // additions and changes to prevent errors.
+ struct Exploded {
+ int year; // Four digit year "2007"
+ signed char month; // 1-based month (values 1 = January, etc.)
+ signed char day_of_week; // 0-based day of week (0 = Sunday, etc.)
+ signed char day_of_month; // 1-based day of month (1-31)
+ signed char hour; // Hour within the current day (0-23)
+ signed char minute; // Minute within the current hour (0-59)
+ signed char second; // Second within the current minute (0-59 plus
+ // leap seconds which may take it up to 60).
+ int millisecond; // Milliseconds within the current second (0-999)
+ };
+
+ // Contains the NULL time. Use Time::Now() to get the current time.
+ explicit Time() : us_(0) {}
+
+ // Returns true if the time object has not been initialized.
+ bool is_null() const { return us_ == 0; }
+
+ // Returns the current time. Watch out, the system might adjust its clock
+ // in which case time will actually go backwards. We don't guarantee that
+ // times are increasing, or that two calls to Now() won't be the same.
+ static Time Now();
+
+ // Returns the current time. Same as Now() except that this function always
+ // uses system time so that there are no discrepancies between the returned
+ // time and system time even on virtual environments including our test bot.
+ // For timing sensitive unittests, this function should be used.
+ static Time NowFromSystemTime();
+
+ // Converts to/from time_t in UTC and a Time class.
+ // TODO(brettw) this should be removed once everybody starts using the |Time|
+ // class.
+ static Time FromTimeT(time_t tt);
+ time_t ToTimeT() const;
+
+ // Converts time to/from a double which is the number of seconds since epoch
+ // (Jan 1, 1970). Webkit uses this format to represent time.
+ static Time FromDoubleT(double dt);
+ double ToDoubleT() const;
+
+ // Converts an exploded structure representing either the local time or UTC
+ // into a Time class.
+ static Time FromUTCExploded(const Exploded& exploded) {
+ return FromExploded(false, exploded);
+ }
+ static Time FromLocalExploded(const Exploded& exploded) {
+ return FromExploded(true, exploded);
+ }
+
+ // Converts an integer value representing Time to a class. This is used
+ // when deserializing a |Time| structure, using a value known to be
+ // compatible. It is not provided as a constructor because the integer type
+ // may be unclear from the perspective of a caller.
+ static Time FromInternalValue(int64_t us) { return Time(us); }
+
+ // Converts a string representation of time to a Time object.
+ // An example of a time string which is converted is as below:-
+ // "Tue, 15 Nov 1994 12:45:26 GMT". If the timezone is not specified
+ // in the input string, we assume local time.
+ // TODO(iyengar) Move the FromString/FromTimeT/ToTimeT/FromFileTime to
+ // a new time converter class.
+ static bool FromString(const wchar_t* time_string, Time* parsed_time);
+
+ // For serializing, use FromInternalValue to reconstitute. Please don't use
+ // this and do arithmetic on it, as it is more error prone than using the
+ // provided operators.
+ int64_t ToInternalValue() const { return us_; }
+
+ // Fills the given exploded structure with either the local time or UTC from
+ // this time structure (containing UTC).
+ void UTCExplode(Exploded* exploded) const { return Explode(false, exploded); }
+ void LocalExplode(Exploded* exploded) const {
+ return Explode(true, exploded);
+ }
+
+ // Rounds this time down to the nearest day in local time. It will represent
+ // midnight on that day.
+ Time LocalMidnight() const;
+
+ Time& operator=(Time other) {
+ us_ = other.us_;
+ return *this;
+ }
+
+ // Compute the difference between two times.
+ TimeDelta operator-(Time other) const { return TimeDelta(us_ - other.us_); }
+
+ // Modify by some time delta.
+ Time& operator+=(TimeDelta delta) {
+ us_ += delta.delta_;
+ return *this;
+ }
+ Time& operator-=(TimeDelta delta) {
+ us_ -= delta.delta_;
+ return *this;
+ }
+
+ // Return a new time modified by some delta.
+ Time operator+(TimeDelta delta) const { return Time(us_ + delta.delta_); }
+ Time operator-(TimeDelta delta) const { return Time(us_ - delta.delta_); }
+
+ // Comparison operators
+ bool operator==(Time other) const { return us_ == other.us_; }
+ bool operator!=(Time other) const { return us_ != other.us_; }
+ bool operator<(Time other) const { return us_ < other.us_; }
+ bool operator<=(Time other) const { return us_ <= other.us_; }
+ bool operator>(Time other) const { return us_ > other.us_; }
+ bool operator>=(Time other) const { return us_ >= other.us_; }
+
+ private:
+ friend class TimeDelta;
+
+ // Explodes the given time to either local time |is_local = true| or UTC
+ // |is_local = false|.
+ void Explode(bool is_local, Exploded* exploded) const;
+
+ // Unexplodes a given time assuming the source is either local time
+ // |is_local = true| or UTC |is_local = false|.
+ static Time FromExploded(bool is_local, const Exploded& exploded);
+
+ explicit Time(int64_t us) : us_(us) {}
+
+ // The representation of Jan 1, 1970 UTC in microseconds since the
+ // platform-dependent epoch.
+ static const int64_t kTimeTToMicrosecondsOffset;
+
+ // Time in microseconds in UTC.
+ int64_t us_;
+};
+
+inline Time TimeDelta::operator+(Time t) const { return Time(t.us_ + delta_); }
+
+// Inline the TimeDelta factory methods, for fast TimeDelta construction.
+
+// static
+inline TimeDelta TimeDelta::FromDays(int64_t days) {
+ return TimeDelta(days * Time::kMicrosecondsPerDay);
+}
+
+// static
+inline TimeDelta TimeDelta::FromHours(int64_t hours) {
+ return TimeDelta(hours * Time::kMicrosecondsPerHour);
+}
+
+// static
+inline TimeDelta TimeDelta::FromMinutes(int64_t minutes) {
+ return TimeDelta(minutes * Time::kMicrosecondsPerMinute);
+}
+
+// static
+inline TimeDelta TimeDelta::FromSeconds(int64_t secs) {
+ return TimeDelta(secs * Time::kMicrosecondsPerSecond);
+}
+
+// static
+inline TimeDelta TimeDelta::FromMilliseconds(int64_t ms) {
+ return TimeDelta(ms * Time::kMicrosecondsPerMillisecond);
+}
+
+// static
+inline TimeDelta TimeDelta::FromMicroseconds(int64_t us) {
+ return TimeDelta(us);
+}
+
+// TimeTicks ------------------------------------------------------------------
+
+class TimeTicks {
+ public:
+ TimeTicks() : ticks_(0) {}
+ TimeTicks(const TimeTicks&) = default;
+
+ // Platform-dependent tick count representing "right now."
+ // The resolution of this clock is ~1-15ms. Resolution varies depending
+ // on hardware/operating system configuration.
+ static TimeTicks Now();
+
+ // Returns true if this object has not been initialized.
+ bool is_null() const { return ticks_ == 0; }
+
+ // Returns the internal numeric value of the TimeTicks object.
+ int64_t ToInternalValue() const { return ticks_; }
+
+ TimeTicks& operator=(TimeTicks other) {
+ ticks_ = other.ticks_;
+ return *this;
+ }
+
+ // Compute the difference between two times.
+ TimeDelta operator-(TimeTicks other) const {
+ return TimeDelta(ticks_ - other.ticks_);
+ }
+
+ // Modify by some time delta.
+ TimeTicks& operator+=(TimeDelta delta) {
+ ticks_ += delta.delta_;
+ return *this;
+ }
+ TimeTicks& operator-=(TimeDelta delta) {
+ ticks_ -= delta.delta_;
+ return *this;
+ }
+
+ // Return a new TimeTicks modified by some delta.
+ TimeTicks operator+(TimeDelta delta) const {
+ return TimeTicks(ticks_ + delta.delta_);
+ }
+ TimeTicks operator-(TimeDelta delta) const {
+ return TimeTicks(ticks_ - delta.delta_);
+ }
+
+ // Comparison operators
+ bool operator==(TimeTicks other) const { return ticks_ == other.ticks_; }
+ bool operator!=(TimeTicks other) const { return ticks_ != other.ticks_; }
+ bool operator<(TimeTicks other) const { return ticks_ < other.ticks_; }
+ bool operator<=(TimeTicks other) const { return ticks_ <= other.ticks_; }
+ bool operator>(TimeTicks other) const { return ticks_ > other.ticks_; }
+ bool operator>=(TimeTicks other) const { return ticks_ >= other.ticks_; }
+
+ protected:
+ friend class TimeDelta;
+ friend class PageLoadTrackerUnitTest;
+
+ // Please use Now() to create a new object. This is for internal use
+ // and testing. Ticks is in microseconds.
+ explicit TimeTicks(int64_t ticks) : ticks_(ticks) {}
+
+ // Tick count in microseconds.
+ int64_t ticks_;
+};
+
+inline TimeTicks TimeDelta::operator+(TimeTicks t) const {
+ return TimeTicks(t.ticks_ + delta_);
+}
+
+} // namespace base
+
+#endif // BASE_TIME_H_
diff --git a/ipc/chromium/src/base/time_mac.cc b/ipc/chromium/src/base/time_mac.cc
new file mode 100644
index 0000000000..6ab1515601
--- /dev/null
+++ b/ipc/chromium/src/base/time_mac.cc
@@ -0,0 +1,122 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "base/time.h"
+
+#include <CoreFoundation/CFDate.h>
+#include <CoreFoundation/CFTimeZone.h>
+#include <mach/mach_time.h>
+#include <sys/time.h>
+#include <time.h>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/scoped_cftyperef.h"
+
+namespace base {
+
+// The Time routines in this file use Mach and CoreFoundation APIs, since the
+// POSIX definition of time_t in Mac OS X wraps around after 2038--and
+// there are already cookie expiration dates, etc., past that time out in
+// the field. Using CFDate prevents that problem, and using mach_absolute_time
+// for TimeTicks gives us nice high-resolution interval timing.
+
+// Time -----------------------------------------------------------------------
+
+// The internal representation of Time uses a 64-bit microsecond count
+// from 1970-01-01 00:00:00 UTC. Core Foundation uses a double second count
+// since 2001-01-01 00:00:00 UTC.
+
+// Some functions in time.cc use time_t directly, so we provide a zero offset
+// for them. The epoch is 1970-01-01 00:00:00 UTC.
+// static
+const int64_t Time::kTimeTToMicrosecondsOffset = GG_INT64_C(0);
+
+// static
+Time Time::Now() {
+ CFAbsoluteTime now =
+ CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970;
+ return Time(static_cast<int64_t>(now * kMicrosecondsPerSecond));
+}
+
+// static
+Time Time::NowFromSystemTime() {
+ // Just use Now() because Now() returns the system time.
+ return Now();
+}
+
+// static
+Time Time::FromExploded(bool is_local, const Exploded& exploded) {
+ CFGregorianDate date;
+ date.second =
+ exploded.second +
+ exploded.millisecond / static_cast<double>(kMillisecondsPerSecond);
+ date.minute = exploded.minute;
+ date.hour = exploded.hour;
+ date.day = exploded.day_of_month;
+ date.month = exploded.month;
+ date.year = exploded.year;
+
+ scoped_cftyperef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem()
+ : NULL);
+ CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) +
+ kCFAbsoluteTimeIntervalSince1970;
+ return Time(static_cast<int64_t>(seconds * kMicrosecondsPerSecond));
+}
+
+void Time::Explode(bool is_local, Exploded* exploded) const {
+ CFAbsoluteTime seconds = (static_cast<double>(us_) / kMicrosecondsPerSecond) -
+ kCFAbsoluteTimeIntervalSince1970;
+
+ scoped_cftyperef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem()
+ : NULL);
+ CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone);
+
+ exploded->year = date.year;
+ exploded->month = date.month;
+ exploded->day_of_month = date.day;
+ exploded->hour = date.hour;
+ exploded->minute = date.minute;
+ exploded->second = date.second;
+ exploded->millisecond =
+ static_cast<int>(date.second * kMillisecondsPerSecond) %
+ kMillisecondsPerSecond;
+}
+
+// TimeTicks ------------------------------------------------------------------
+
+// static
+TimeTicks TimeTicks::Now() {
+ uint64_t absolute_micro;
+
+ static mach_timebase_info_data_t timebase_info;
+ if (timebase_info.denom == 0) {
+ // Zero-initialization of statics guarantees that denom will be 0 before
+ // calling mach_timebase_info. mach_timebase_info will never set denom to
+ // 0 as that would be invalid, so the zero-check can be used to determine
+ // whether mach_timebase_info has already been called. This is
+ // recommended by Apple's QA1398.
+ kern_return_t kr = mach_timebase_info(&timebase_info);
+ DCHECK(kr == KERN_SUCCESS);
+ }
+
+ // mach_absolute_time is it when it comes to ticks on the Mac. Other calls
+ // with less precision (such as TickCount) just call through to
+ // mach_absolute_time.
+
+ // timebase_info converts absolute time tick units into nanoseconds. Convert
+ // to microseconds up front to stave off overflows.
+ absolute_micro = mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
+ timebase_info.numer / timebase_info.denom;
+
+ // Don't bother with the rollover handling that the Windows version does.
+ // With numer and denom = 1 (the expected case), the 64-bit absolute time
+ // reported in nanoseconds is enough to last nearly 585 years.
+
+ return TimeTicks(absolute_micro);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/time_posix.cc b/ipc/chromium/src/base/time_posix.cc
new file mode 100644
index 0000000000..1f122bb698
--- /dev/null
+++ b/ipc/chromium/src/base/time_posix.cc
@@ -0,0 +1,200 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/time.h"
+
+#ifdef XP_DARWIN
+# include <mach/mach_time.h>
+#endif
+#include <sys/time.h>
+#if defined(ANDROID) && !defined(__LP64__)
+# include <time64.h>
+#else
+# include <time.h>
+#endif
+#if defined(ANDROID) || defined(XP_UNIX)
+# include <unistd.h>
+#endif
+
+#include <limits>
+#include <cstdint>
+
+#include "base/logging.h"
+
+namespace base {
+
+// The Time routines in this file use standard POSIX routines, or almost-
+// standard routines in the case of timegm. We need to use a Mach-specific
+// function for TimeTicks::Now() on Mac OS X.
+
+// Time -----------------------------------------------------------------------
+
+// Some functions in time.cc use time_t directly, so we provide a zero offset
+// for them. The epoch is 1970-01-01 00:00:00 UTC.
+// static
+const int64_t Time::kTimeTToMicrosecondsOffset = GG_INT64_C(0);
+
+// static
+Time Time::Now() {
+ struct timeval tv;
+ struct timezone tz = {0, 0}; // UTC
+ if (gettimeofday(&tv, &tz) != 0) {
+ DCHECK(0) << "Could not determine time of day";
+ }
+ // Combine seconds and microseconds in a 64-bit field containing microseconds
+ // since the epoch. That's enough for nearly 600 centuries.
+ return Time(tv.tv_sec * kMicrosecondsPerSecond + tv.tv_usec);
+}
+
+// static
+Time Time::NowFromSystemTime() {
+ // Just use Now() because Now() returns the system time.
+ return Now();
+}
+
+// static
+Time Time::FromExploded(bool is_local, const Exploded& exploded) {
+ struct tm timestruct;
+ timestruct.tm_sec = exploded.second;
+ timestruct.tm_min = exploded.minute;
+ timestruct.tm_hour = exploded.hour;
+ timestruct.tm_mday = exploded.day_of_month;
+ timestruct.tm_mon = exploded.month - 1;
+ timestruct.tm_year = exploded.year - 1900;
+ timestruct.tm_wday = exploded.day_of_week; // mktime/timegm ignore this
+ timestruct.tm_yday = 0; // mktime/timegm ignore this
+ timestruct.tm_isdst = -1; // attempt to figure it out
+#ifndef XP_SOLARIS
+ timestruct.tm_gmtoff = 0; // not a POSIX field, so mktime/timegm ignore
+ timestruct.tm_zone = NULL; // not a POSIX field, so mktime/timegm ignore
+#endif
+
+ time_t seconds;
+#ifdef ANDROID
+ seconds = mktime(&timestruct);
+#else
+ if (is_local)
+ seconds = mktime(&timestruct);
+ else
+ seconds = timegm(&timestruct);
+#endif
+
+ int64_t milliseconds;
+ // Handle overflow. Clamping the range to what mktime and timegm might
+ // return is the best that can be done here. It's not ideal, but it's better
+ // than failing here or ignoring the overflow case and treating each time
+ // overflow as one second prior to the epoch.
+ if (seconds == -1 && (exploded.year < 1969 || exploded.year > 1970)) {
+ // If exploded.year is 1969 or 1970, take -1 as correct, with the
+ // time indicating 1 second prior to the epoch. (1970 is allowed to handle
+ // time zone and DST offsets.) Otherwise, return the most future or past
+ // time representable. Assumes the time_t epoch is 1970-01-01 00:00:00 UTC.
+ //
+ // The minimum and maximum representible times that mktime and timegm could
+ // return are used here instead of values outside that range to allow for
+ // proper round-tripping between exploded and counter-type time
+ // representations in the presence of possible truncation to time_t by
+ // division and use with other functions that accept time_t.
+ //
+ // When representing the most distant time in the future, add in an extra
+ // 999ms to avoid the time being less than any other possible value that
+ // this function can return.
+
+ // Take care to avoid overflows when time_t is int64_t.
+ if (exploded.year < 1969) {
+ int64_t min_seconds = (sizeof(time_t) < sizeof(int64_t))
+ ? std::numeric_limits<time_t>::min()
+ : std::numeric_limits<int32_t>::min();
+ milliseconds = min_seconds * kMillisecondsPerSecond;
+ } else {
+ int64_t max_seconds = (sizeof(time_t) < sizeof(int64_t))
+ ? std::numeric_limits<time_t>::max()
+ : std::numeric_limits<int32_t>::max();
+ milliseconds = max_seconds * kMillisecondsPerSecond;
+ milliseconds += kMillisecondsPerSecond - 1;
+ }
+ } else {
+ milliseconds = seconds * kMillisecondsPerSecond + exploded.millisecond;
+ }
+
+ return Time(milliseconds * kMicrosecondsPerMillisecond);
+}
+
+void Time::Explode(bool is_local, Exploded* exploded) const {
+ // Time stores times with microsecond resolution, but Exploded only carries
+ // millisecond resolution, so begin by being lossy.
+ int64_t milliseconds = us_ / kMicrosecondsPerMillisecond;
+ time_t seconds = milliseconds / kMillisecondsPerSecond;
+
+ struct tm timestruct;
+ if (is_local)
+ localtime_r(&seconds, &timestruct);
+ else
+ gmtime_r(&seconds, &timestruct);
+
+ exploded->year = timestruct.tm_year + 1900;
+ exploded->month = timestruct.tm_mon + 1;
+ exploded->day_of_week = timestruct.tm_wday;
+ exploded->day_of_month = timestruct.tm_mday;
+ exploded->hour = timestruct.tm_hour;
+ exploded->minute = timestruct.tm_min;
+ exploded->second = timestruct.tm_sec;
+ exploded->millisecond = milliseconds % kMillisecondsPerSecond;
+}
+
+// TimeTicks ------------------------------------------------------------------
+
+// static
+TimeTicks TimeTicks::Now() {
+ uint64_t absolute_micro;
+
+#if defined(XP_DARWIN)
+ static mach_timebase_info_data_t timebase_info;
+ if (timebase_info.denom == 0) {
+ // Zero-initialization of statics guarantees that denom will be 0 before
+ // calling mach_timebase_info. mach_timebase_info will never set denom to
+ // 0 as that would be invalid, so the zero-check can be used to determine
+ // whether mach_timebase_info has already been called. This is
+ // recommended by Apple's QA1398.
+ kern_return_t kr = mach_timebase_info(&timebase_info);
+ DCHECK(kr == KERN_SUCCESS);
+ }
+
+ // mach_absolute_time is it when it comes to ticks on the Mac. Other calls
+ // with less precision (such as TickCount) just call through to
+ // mach_absolute_time.
+
+ // timebase_info converts absolute time tick units into nanoseconds. Convert
+ // to microseconds up front to stave off overflows.
+ absolute_micro = mach_absolute_time() / Time::kNanosecondsPerMicrosecond *
+ timebase_info.numer / timebase_info.denom;
+
+ // Don't bother with the rollover handling that the Windows version does.
+ // With numer and denom = 1 (the expected case), the 64-bit absolute time
+ // reported in nanoseconds is enough to last nearly 585 years.
+
+#elif defined(XP_OPENBSD) || defined(XP_UNIX) && \
+ defined(_POSIX_MONOTONIC_CLOCK) && \
+ _POSIX_MONOTONIC_CLOCK >= 0
+
+ struct timespec ts;
+ if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
+ NOTREACHED() << "clock_gettime(CLOCK_MONOTONIC) failed.";
+ return TimeTicks();
+ }
+
+ absolute_micro =
+ (static_cast<int64_t>(ts.tv_sec) * Time::kMicrosecondsPerSecond) +
+ (static_cast<int64_t>(ts.tv_nsec) / Time::kNanosecondsPerMicrosecond);
+
+#else // _POSIX_MONOTONIC_CLOCK
+# error No usable tick clock function on this platform.
+#endif // _POSIX_MONOTONIC_CLOCK
+
+ return TimeTicks(absolute_micro);
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/time_win.cc b/ipc/chromium/src/base/time_win.cc
new file mode 100644
index 0000000000..d39416cd6d
--- /dev/null
+++ b/ipc/chromium/src/base/time_win.cc
@@ -0,0 +1,263 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// Windows Timer Primer
+//
+// A good article: http://www.ddj.com/windows/184416651
+// A good mozilla bug: http://bugzilla.mozilla.org/show_bug.cgi?id=363258
+//
+// The default windows timer, GetSystemTimeAsFileTime is not very precise.
+// It is only good to ~15.5ms.
+//
+// QueryPerformanceCounter is the logical choice for a high-precision timer.
+// However, it is known to be buggy on some hardware. Specifically, it can
+// sometimes "jump". On laptops, QPC can also be very expensive to call.
+// It's 3-4x slower than timeGetTime() on desktops, but can be 10x slower
+// on laptops. A unittest exists which will show the relative cost of various
+// timers on any system.
+//
+// The next logical choice is timeGetTime(). timeGetTime has a precision of
+// 1ms, but only if you call APIs (timeBeginPeriod()) which affect all other
+// applications on the system. By default, precision is only 15.5ms.
+// Unfortunately, we don't want to call timeBeginPeriod because we don't
+// want to affect other applications. Further, on mobile platforms, use of
+// faster multimedia timers can hurt battery life. See the intel
+// article about this here:
+// http://softwarecommunity.intel.com/articles/eng/1086.htm
+//
+// To work around all this, we're going to generally use timeGetTime(). We
+// will only increase the system-wide timer if we're not running on battery
+// power. Using timeBeginPeriod(1) is a requirement in order to make our
+// message loop waits have the same resolution that our time measurements
+// do. Otherwise, WaitForSingleObject(..., 1) will no less than 15ms when
+// there is nothing else to waken the Wait.
+
+#include "base/time.h"
+
+#ifndef __MINGW32__
+# pragma comment(lib, "winmm.lib")
+#endif
+#include <windows.h>
+#include <mmsystem.h>
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "mozilla/Casting.h"
+#include "mozilla/StaticMutex.h"
+
+using base::Time;
+using base::TimeDelta;
+using base::TimeTicks;
+using mozilla::BitwiseCast;
+
+namespace {
+
+// From MSDN, FILETIME "Contains a 64-bit value representing the number of
+// 100-nanosecond intervals since January 1, 1601 (UTC)."
+int64_t FileTimeToMicroseconds(const FILETIME& ft) {
+ // Need to BitwiseCast to fix alignment, then divide by 10 to convert
+ // 100-nanoseconds to milliseconds. This only works on little-endian
+ // machines.
+ return BitwiseCast<int64_t>(ft) / 10;
+}
+
+void MicrosecondsToFileTime(int64_t us, FILETIME* ft) {
+ DCHECK(us >= 0) << "Time is less than 0, negative values are not "
+ "representable in FILETIME";
+
+ // Multiply by 10 to convert milliseconds to 100-nanoseconds. BitwiseCast will
+ // handle alignment problems. This only works on little-endian machines.
+ *ft = BitwiseCast<FILETIME>(us * 10);
+}
+
+int64_t CurrentWallclockMicroseconds() {
+ FILETIME ft;
+ ::GetSystemTimeAsFileTime(&ft);
+ return FileTimeToMicroseconds(ft);
+}
+
+// Time between resampling the un-granular clock for this API. 60 seconds.
+const int kMaxMillisecondsToAvoidDrift = 60 * Time::kMillisecondsPerSecond;
+
+int64_t initial_time = 0;
+TimeTicks initial_ticks;
+
+void InitializeClock() {
+ initial_ticks = TimeTicks::Now();
+ initial_time = CurrentWallclockMicroseconds();
+}
+
+} // namespace
+
+// Time -----------------------------------------------------------------------
+
+// The internal representation of Time uses FILETIME, whose epoch is 1601-01-01
+// 00:00:00 UTC. ((1970-1601)*365+89)*24*60*60*1000*1000, where 89 is the
+// number of leap year days between 1601 and 1970: (1970-1601)/4 excluding
+// 1700, 1800, and 1900.
+// static
+const int64_t Time::kTimeTToMicrosecondsOffset = GG_INT64_C(11644473600000000);
+
+// static
+Time Time::Now() {
+ if (initial_time == 0) InitializeClock();
+
+ // We implement time using the high-resolution timers so that we can get
+ // timeouts which are smaller than 10-15ms. If we just used
+ // CurrentWallclockMicroseconds(), we'd have the less-granular timer.
+ //
+ // To make this work, we initialize the clock (initial_time) and the
+ // counter (initial_ctr). To compute the initial time, we can check
+ // the number of ticks that have elapsed, and compute the delta.
+ //
+ // To avoid any drift, we periodically resync the counters to the system
+ // clock.
+ while (true) {
+ TimeTicks ticks = TimeTicks::Now();
+
+ // Calculate the time elapsed since we started our timer
+ TimeDelta elapsed = ticks - initial_ticks;
+
+ // Check if enough time has elapsed that we need to resync the clock.
+ if (elapsed.InMilliseconds() > kMaxMillisecondsToAvoidDrift) {
+ InitializeClock();
+ continue;
+ }
+
+ return Time(elapsed + Time(initial_time));
+ }
+}
+
+// static
+Time Time::NowFromSystemTime() {
+ // Force resync.
+ InitializeClock();
+ return Time(initial_time);
+}
+
+// static
+Time Time::FromExploded(bool is_local, const Exploded& exploded) {
+ // Create the system struct representing our exploded time. It will either be
+ // in local time or UTC.
+ SYSTEMTIME st;
+ st.wYear = exploded.year;
+ st.wMonth = exploded.month;
+ st.wDayOfWeek = exploded.day_of_week;
+ st.wDay = exploded.day_of_month;
+ st.wHour = exploded.hour;
+ st.wMinute = exploded.minute;
+ st.wSecond = exploded.second;
+ st.wMilliseconds = exploded.millisecond;
+
+ // Convert to FILETIME.
+ FILETIME ft;
+ if (!SystemTimeToFileTime(&st, &ft)) {
+ NOTREACHED() << "Unable to convert time";
+ return Time(0);
+ }
+
+ // Ensure that it's in UTC.
+ if (is_local) {
+ FILETIME utc_ft;
+ LocalFileTimeToFileTime(&ft, &utc_ft);
+ return Time(FileTimeToMicroseconds(utc_ft));
+ }
+ return Time(FileTimeToMicroseconds(ft));
+}
+
+void Time::Explode(bool is_local, Exploded* exploded) const {
+ // FILETIME in UTC.
+ FILETIME utc_ft;
+ MicrosecondsToFileTime(us_, &utc_ft);
+
+ // FILETIME in local time if necessary.
+ BOOL success = TRUE;
+ FILETIME ft;
+ if (is_local)
+ success = FileTimeToLocalFileTime(&utc_ft, &ft);
+ else
+ ft = utc_ft;
+
+ // FILETIME in SYSTEMTIME (exploded).
+ SYSTEMTIME st;
+ if (!success || !FileTimeToSystemTime(&ft, &st)) {
+ NOTREACHED() << "Unable to convert time, don't know why";
+ ZeroMemory(exploded, sizeof(*exploded));
+ return;
+ }
+
+ exploded->year = st.wYear;
+ exploded->month = st.wMonth;
+ exploded->day_of_week = st.wDayOfWeek;
+ exploded->day_of_month = st.wDay;
+ exploded->hour = st.wHour;
+ exploded->minute = st.wMinute;
+ exploded->second = st.wSecond;
+ exploded->millisecond = st.wMilliseconds;
+}
+
+// TimeTicks ------------------------------------------------------------------
+namespace {
+
+// We define a wrapper to adapt between the __stdcall and __cdecl call of the
+// mock function, and to avoid a static constructor. Assigning an import to a
+// function pointer directly would require setup code to fetch from the IAT.
+DWORD timeGetTimeWrapper() { return timeGetTime(); }
+
+DWORD (*tick_function)(void) = &timeGetTimeWrapper;
+
+// This setup is a little gross: the `now` instance lives until libxul is
+// unloaded, but leak checking runs prior to that, and would see a Mutex
+// instance contained in NowSingleton as still live. Said instance would
+// be reported as a leak...but it's not, really. To avoid that, we need
+// to use StaticMutex (which is not leak-checked), but StaticMutex can't
+// be a member variable. So we have to have this separate static variable.
+static mozilla::StaticMutex sNowSingletonLock;
+
+// We use timeGetTime() to implement TimeTicks::Now(). This can be problematic
+// because it returns the number of milliseconds since Windows has started,
+// which will roll over the 32-bit value every ~49 days. We try to track
+// rollover ourselves, which works if TimeTicks::Now() is called at least every
+// 49 days.
+class NowSingleton {
+ public:
+ TimeDelta Now() {
+ mozilla::StaticMutexAutoLock locked(sNowSingletonLock);
+ // We should hold the lock while calling tick_function to make sure that
+ // we keep our last_seen_ stay correctly in sync.
+ DWORD now = tick_function();
+ if (now < last_seen_)
+ rollover_ +=
+ TimeDelta::FromMilliseconds(GG_LONGLONG(0x100000000)); // ~49.7 days.
+ last_seen_ = now;
+ return TimeDelta::FromMilliseconds(now) + rollover_;
+ }
+
+ static NowSingleton& instance() {
+ static NowSingleton now;
+ return now;
+ }
+
+ private:
+ explicit NowSingleton()
+ : rollover_(TimeDelta::FromMilliseconds(0)), last_seen_(0) {}
+ ~NowSingleton() = default;
+
+ TimeDelta rollover_ MOZ_GUARDED_BY(
+ sNowSingletonLock); // Accumulation of time lost due to rollover.
+ DWORD last_seen_
+ MOZ_GUARDED_BY(sNowSingletonLock); // The last timeGetTime value we saw,
+ // to detect rollover.
+
+ DISALLOW_COPY_AND_ASSIGN(NowSingleton);
+};
+
+} // namespace
+
+// static
+TimeTicks TimeTicks::Now() {
+ return TimeTicks() + NowSingleton::instance().Now();
+}
diff --git a/ipc/chromium/src/base/timer.cc b/ipc/chromium/src/base/timer.cc
new file mode 100644
index 0000000000..b2d880797a
--- /dev/null
+++ b/ipc/chromium/src/base/timer.cc
@@ -0,0 +1,31 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/timer.h"
+
+#include "base/message_loop.h"
+
+namespace base {
+
+void BaseTimer_Helper::OrphanDelayedTask() {
+ if (delayed_task_) {
+ delayed_task_->timer_ = nullptr;
+ delayed_task_ = nullptr;
+ }
+}
+
+void BaseTimer_Helper::InitiateDelayedTask(TimerTask* timer_task) {
+ OrphanDelayedTask();
+
+ delayed_task_ = timer_task;
+ delayed_task_->timer_ = this;
+ RefPtr<TimerTask> addrefedTask = timer_task;
+ MessageLoop::current()->PostDelayedTask(
+ addrefedTask.forget(),
+ static_cast<int>(timer_task->delay_.InMilliseconds()));
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/timer.h b/ipc/chromium/src/base/timer.h
new file mode 100644
index 0000000000..eceea8d23b
--- /dev/null
+++ b/ipc/chromium/src/base/timer.h
@@ -0,0 +1,261 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// OneShotTimer and RepeatingTimer provide a simple timer API. As the names
+// suggest, OneShotTimer calls you back once after a time delay expires.
+// RepeatingTimer on the other hand calls you back periodically with the
+// prescribed time interval.
+//
+// OneShotTimer and RepeatingTimer both cancel the timer when they go out of
+// scope, which makes it easy to ensure that you do not get called when your
+// object has gone out of scope. Just instantiate a OneShotTimer or
+// RepeatingTimer as a member variable of the class for which you wish to
+// receive timer events.
+//
+// Sample RepeatingTimer usage:
+//
+// class MyClass {
+// public:
+// void StartDoingStuff() {
+// timer_.Start(TimeDelta::FromSeconds(1), this, &MyClass::DoStuff);
+// }
+// void StopDoingStuff() {
+// timer_.Stop();
+// }
+// private:
+// void DoStuff() {
+// // This method is called every second to do stuff.
+// ...
+// }
+// base::RepeatingTimer<MyClass> timer_;
+// };
+//
+// Both OneShotTimer and RepeatingTimer also support a Reset method, which
+// allows you to easily defer the timer event until the timer delay passes once
+// again. So, in the above example, if 0.5 seconds have already passed,
+// calling Reset on timer_ would postpone DoStuff by another 1 second. In
+// other words, Reset is shorthand for calling Stop and then Start again with
+// the same arguments.
+
+#ifndef BASE_TIMER_H_
+#define BASE_TIMER_H_
+
+// IMPORTANT: If you change timer code, make sure that all tests (including
+// disabled ones) from timer_unittests.cc pass locally. Some are disabled
+// because they're flaky on the buildbot, but when you run them locally you
+// should be able to tell the difference.
+
+#include "base/logging.h"
+#include "base/task.h"
+#include "base/time.h"
+
+class MessageLoop;
+
+namespace base {
+
+//-----------------------------------------------------------------------------
+// This class is an implementation detail of OneShotTimer and RepeatingTimer.
+// Please do not use this class directly.
+//
+// This class exists to share code between BaseTimer<T> template instantiations.
+//
+class BaseTimer_Helper {
+ public:
+ // Stops the timer.
+ ~BaseTimer_Helper() { OrphanDelayedTask(); }
+
+ // Returns true if the timer is running (i.e., not stopped).
+ bool IsRunning() const { return !!delayed_task_; }
+
+ // Returns the current delay for this timer. May only call this method when
+ // the timer is running!
+ TimeDelta GetCurrentDelay() const {
+ DCHECK(IsRunning());
+ return delayed_task_->delay_;
+ }
+
+ protected:
+ BaseTimer_Helper() {}
+
+ // We have access to the timer_ member so we can orphan this task.
+ class TimerTask : public mozilla::Runnable {
+ public:
+ explicit TimerTask(TimeDelta delay)
+ : mozilla::Runnable("base::BaseTimer_Helper::TimerTask"),
+ delay_(delay) {
+ // timer_ is set in InitiateDelayedTask.
+ }
+ virtual ~TimerTask() {}
+ BaseTimer_Helper* timer_;
+ TimeDelta delay_;
+ };
+
+ // Used to orphan delayed_task_ so that when it runs it does nothing.
+ void OrphanDelayedTask();
+
+ // Used to initiated a new delayed task. This has the side-effect of
+ // orphaning delayed_task_ if it is non-null.
+ void InitiateDelayedTask(TimerTask* timer_task);
+
+ RefPtr<TimerTask> delayed_task_;
+
+ DISALLOW_COPY_AND_ASSIGN(BaseTimer_Helper);
+};
+
+//-----------------------------------------------------------------------------
+// This class is an implementation detail of OneShotTimer and RepeatingTimer.
+// Please do not use this class directly.
+template <class Receiver, bool kIsRepeating>
+class BaseTimer : public BaseTimer_Helper {
+ public:
+ typedef void (Receiver::*ReceiverMethod)();
+
+ // Call this method to start the timer. It is an error to call this method
+ // while the timer is already running.
+ void Start(TimeDelta delay, Receiver* receiver, ReceiverMethod method) {
+ DCHECK(!IsRunning());
+ InitiateDelayedTask(new TimerTask(delay, receiver, method));
+ }
+
+ // Call this method to stop the timer. It is a no-op if the timer is not
+ // running.
+ void Stop() { OrphanDelayedTask(); }
+
+ // Call this method to reset the timer delay of an already running timer.
+ void Reset() {
+ DCHECK(IsRunning());
+ InitiateDelayedTask(static_cast<TimerTask*>(delayed_task_.get())->Clone());
+ }
+
+ private:
+ typedef BaseTimer<Receiver, kIsRepeating> SelfType;
+
+ class TimerTask : public BaseTimer_Helper::TimerTask {
+ public:
+ TimerTask(TimeDelta delay, Receiver* receiver, ReceiverMethod method)
+ : BaseTimer_Helper::TimerTask(delay),
+ receiver_(receiver),
+ method_(method) {}
+
+ virtual ~TimerTask() {
+ // This task may be getting cleared because the MessageLoop has been
+ // destructed. If so, don't leave the Timer with a dangling pointer
+ // to this now-defunct task.
+ ClearBaseTimer();
+ }
+
+ NS_IMETHOD Run() override {
+ if (!timer_) // timer_ is null if we were orphaned.
+ return NS_OK;
+ if (kIsRepeating)
+ ResetBaseTimer();
+ else
+ ClearBaseTimer();
+ DispatchToMethod(receiver_, method_, Tuple0());
+ return NS_OK;
+ }
+
+ TimerTask* Clone() const {
+ return new TimerTask(delay_, receiver_, method_);
+ }
+
+ private:
+ // Inform the Base that the timer is no longer active.
+ void ClearBaseTimer() {
+ if (timer_) {
+ SelfType* self = static_cast<SelfType*>(timer_);
+ // It is possible that the Timer has already been reset, and that this
+ // Task is old. So, if the Timer points to a different task, assume
+ // that the Timer has already taken care of properly setting the task.
+ if (self->delayed_task_ == this) self->delayed_task_ = nullptr;
+ // By now the delayed_task_ in the Timer does not point to us anymore.
+ // We should reset our own timer_ because the Timer can not do this
+ // for us in its destructor.
+ timer_ = NULL;
+ }
+ }
+
+ // Inform the Base that we're resetting the timer.
+ void ResetBaseTimer() {
+ DCHECK(timer_);
+ DCHECK(kIsRepeating);
+ SelfType* self = static_cast<SelfType*>(timer_);
+ self->Reset();
+ }
+
+ Receiver* receiver_;
+ ReceiverMethod method_;
+ };
+};
+
+//-----------------------------------------------------------------------------
+// A simple, one-shot timer. See usage notes at the top of the file.
+template <class Receiver>
+class OneShotTimer : public BaseTimer<Receiver, false> {};
+
+//-----------------------------------------------------------------------------
+// A simple, repeating timer. See usage notes at the top of the file.
+template <class Receiver>
+class RepeatingTimer : public BaseTimer<Receiver, true> {};
+
+//-----------------------------------------------------------------------------
+// A Delay timer is like The Button from Lost. Once started, you have to keep
+// calling Reset otherwise it will call the given method in the MessageLoop
+// thread.
+//
+// Once created, it is inactive until Reset is called. Once |delay| seconds have
+// passed since the last call to Reset, the callback is made. Once the callback
+// has been made, it's inactive until Reset is called again.
+//
+// If destroyed, the timeout is canceled and will not occur even if already
+// inflight.
+template <class Receiver>
+class DelayTimer {
+ public:
+ typedef void (Receiver::*ReceiverMethod)();
+
+ DelayTimer(TimeDelta delay, Receiver* receiver, ReceiverMethod method)
+ : receiver_(receiver), method_(method), delay_(delay) {}
+
+ void Reset() { DelayFor(delay_); }
+
+ private:
+ void DelayFor(TimeDelta delay) {
+ trigger_time_ = Time::Now() + delay;
+
+ // If we already have a timer that will expire at or before the given delay,
+ // then we have nothing more to do now.
+ if (timer_.IsRunning() && timer_.GetCurrentDelay() <= delay) return;
+
+ // The timer isn't running, or will expire too late, so restart it.
+ timer_.Stop();
+ timer_.Start(delay, this, &DelayTimer<Receiver>::Check);
+ }
+
+ void Check() {
+ if (trigger_time_.is_null()) return;
+
+ // If we have not waited long enough, then wait some more.
+ const Time now = Time::Now();
+ if (now < trigger_time_) {
+ DelayFor(trigger_time_ - now);
+ return;
+ }
+
+ (receiver_->*method_)();
+ }
+
+ Receiver* const receiver_;
+ const ReceiverMethod method_;
+ const TimeDelta delay_;
+
+ OneShotTimer<DelayTimer<Receiver> > timer_;
+ Time trigger_time_;
+};
+
+} // namespace base
+
+#endif // BASE_TIMER_H_
diff --git a/ipc/chromium/src/base/tuple.h b/ipc/chromium/src/base/tuple.h
new file mode 100644
index 0000000000..62655784d4
--- /dev/null
+++ b/ipc/chromium/src/base/tuple.h
@@ -0,0 +1,838 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+// A Tuple is a generic templatized container, similar in concept to std::pair.
+// There are classes Tuple0 to Tuple6, cooresponding to the number of elements
+// it contains. The convenient MakeTuple() function takes 0 to 6 arguments,
+// and will construct and return the appropriate Tuple object. The functions
+// DispatchToMethod and DispatchToFunction take a function pointer or instance
+// and method pointer, and unpack a tuple into arguments to the call.
+//
+// Tuple elements are copied by value, and stored in the tuple. See the unit
+// tests for more details of how/when the values are copied.
+//
+// Example usage:
+// // These two methods of creating a Tuple are identical.
+// Tuple2<int, const char*> tuple_a(1, "wee");
+// Tuple2<int, const char*> tuple_b = MakeTuple(1, "wee");
+//
+// void SomeFunc(int a, const char* b) { }
+// DispatchToFunction(&SomeFunc, tuple_a); // SomeFunc(1, "wee")
+// DispatchToFunction(
+// &SomeFunc, MakeTuple(10, "foo")); // SomeFunc(10, "foo")
+//
+// struct { void SomeMeth(int a, int b, int c) { } } foo;
+// DispatchToMethod(&foo, &Foo::SomeMeth, MakeTuple(1, 2, 3));
+// // foo->SomeMeth(1, 2, 3);
+
+#ifndef BASE_TUPLE_H__
+#define BASE_TUPLE_H__
+
+// Traits ----------------------------------------------------------------------
+//
+// A simple traits class for tuple arguments.
+//
+// ValueType: the bare, nonref version of a type (same as the type for nonrefs).
+// RefType: the ref version of a type (same as the type for refs).
+// ParamType: what type to pass to functions (refs should not be constified).
+
+template <class P>
+struct TupleTraits {
+ typedef P ValueType;
+ typedef P& RefType;
+ typedef const P& ParamType;
+};
+
+template <class P>
+struct TupleTraits<P&> {
+ typedef P ValueType;
+ typedef P& RefType;
+ typedef P& ParamType;
+};
+
+// Tuple -----------------------------------------------------------------------
+//
+// This set of classes is useful for bundling 0 or more heterogeneous data types
+// into a single variable. The advantage of this is that it greatly simplifies
+// function objects that need to take an arbitrary number of parameters; see
+// RunnableMethod and IPC::MessageWithTuple.
+//
+// Tuple0 is supplied to act as a 'void' type. It can be used, for example,
+// when dispatching to a function that accepts no arguments (see the
+// Dispatchers below).
+// Tuple1<A> is rarely useful. One such use is when A is non-const ref that you
+// want filled by the dispatchee, and the tuple is merely a container for that
+// output (a "tier"). See MakeRefTuple and its usages.
+
+struct Tuple0 {
+ typedef Tuple0 ValueTuple;
+ typedef Tuple0 RefTuple;
+};
+
+template <class A>
+struct Tuple1 {
+ public:
+ typedef A TypeA;
+ typedef Tuple1<typename TupleTraits<A>::ValueType> ValueTuple;
+ typedef Tuple1<typename TupleTraits<A>::RefType> RefTuple;
+
+ Tuple1() {}
+ explicit Tuple1(typename TupleTraits<A>::ParamType aA) : a(aA) {}
+
+ A a;
+};
+
+template <class A, class B>
+struct Tuple2 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef Tuple2<typename TupleTraits<A>::ValueType,
+ typename TupleTraits<B>::ValueType>
+ ValueTuple;
+ typedef Tuple2<typename TupleTraits<A>::RefType,
+ typename TupleTraits<B>::RefType>
+ RefTuple;
+
+ Tuple2() {}
+ Tuple2(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB)
+ : a(aA), b(aB) {}
+
+ A a;
+ B b;
+};
+
+template <class A, class B, class C>
+struct Tuple3 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef C TypeC;
+ typedef Tuple3<typename TupleTraits<A>::ValueType,
+ typename TupleTraits<B>::ValueType,
+ typename TupleTraits<C>::ValueType>
+ ValueTuple;
+ typedef Tuple3<typename TupleTraits<A>::RefType,
+ typename TupleTraits<B>::RefType,
+ typename TupleTraits<C>::RefType>
+ RefTuple;
+
+ Tuple3() {}
+ Tuple3(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB,
+ typename TupleTraits<C>::ParamType aC)
+ : a(aA), b(aB), c(aC) {}
+
+ A a;
+ B b;
+ C c;
+};
+
+template <class A, class B, class C, class D>
+struct Tuple4 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef C TypeC;
+ typedef D TypeD;
+ typedef Tuple4<
+ typename TupleTraits<A>::ValueType, typename TupleTraits<B>::ValueType,
+ typename TupleTraits<C>::ValueType, typename TupleTraits<D>::ValueType>
+ ValueTuple;
+ typedef Tuple4<
+ typename TupleTraits<A>::RefType, typename TupleTraits<B>::RefType,
+ typename TupleTraits<C>::RefType, typename TupleTraits<D>::RefType>
+ RefTuple;
+
+ Tuple4() {}
+ Tuple4(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB,
+ typename TupleTraits<C>::ParamType aC,
+ typename TupleTraits<D>::ParamType aD)
+ : a(aA), b(aB), c(aC), d(aD) {}
+
+ A a;
+ B b;
+ C c;
+ D d;
+};
+
+template <class A, class B, class C, class D, class E>
+struct Tuple5 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef C TypeC;
+ typedef D TypeD;
+ typedef E TypeE;
+ typedef Tuple5<
+ typename TupleTraits<A>::ValueType, typename TupleTraits<B>::ValueType,
+ typename TupleTraits<C>::ValueType, typename TupleTraits<D>::ValueType,
+ typename TupleTraits<E>::ValueType>
+ ValueTuple;
+ typedef Tuple5<
+ typename TupleTraits<A>::RefType, typename TupleTraits<B>::RefType,
+ typename TupleTraits<C>::RefType, typename TupleTraits<D>::RefType,
+ typename TupleTraits<E>::RefType>
+ RefTuple;
+
+ Tuple5() {}
+ Tuple5(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB,
+ typename TupleTraits<C>::ParamType aC,
+ typename TupleTraits<D>::ParamType aD,
+ typename TupleTraits<E>::ParamType aE)
+ : a(aA), b(aB), c(aC), d(aD), e(aE) {}
+
+ A a;
+ B b;
+ C c;
+ D d;
+ E e;
+};
+
+template <class A, class B, class C, class D, class E, class F>
+struct Tuple6 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef C TypeC;
+ typedef D TypeD;
+ typedef E TypeE;
+ typedef F TypeF;
+ typedef Tuple6<
+ typename TupleTraits<A>::ValueType, typename TupleTraits<B>::ValueType,
+ typename TupleTraits<C>::ValueType, typename TupleTraits<D>::ValueType,
+ typename TupleTraits<E>::ValueType, typename TupleTraits<F>::ValueType>
+ ValueTuple;
+ typedef Tuple6<
+ typename TupleTraits<A>::RefType, typename TupleTraits<B>::RefType,
+ typename TupleTraits<C>::RefType, typename TupleTraits<D>::RefType,
+ typename TupleTraits<E>::RefType, typename TupleTraits<F>::RefType>
+ RefTuple;
+
+ Tuple6() {}
+ Tuple6(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB,
+ typename TupleTraits<C>::ParamType aC,
+ typename TupleTraits<D>::ParamType aD,
+ typename TupleTraits<E>::ParamType aE,
+ typename TupleTraits<F>::ParamType aF)
+ : a(aA), b(aB), c(aC), d(aD), e(aE), f(aF) {}
+
+ A a;
+ B b;
+ C c;
+ D d;
+ E e;
+ F f;
+};
+
+template <class A, class B, class C, class D, class E, class F, class G>
+struct Tuple7 {
+ public:
+ typedef A TypeA;
+ typedef B TypeB;
+ typedef C TypeC;
+ typedef D TypeD;
+ typedef E TypeE;
+ typedef F TypeF;
+ typedef G TypeG;
+ typedef Tuple7<
+ typename TupleTraits<A>::ValueType, typename TupleTraits<B>::ValueType,
+ typename TupleTraits<C>::ValueType, typename TupleTraits<D>::ValueType,
+ typename TupleTraits<E>::ValueType, typename TupleTraits<F>::ValueType,
+ typename TupleTraits<G>::ValueType>
+ ValueTuple;
+ typedef Tuple7<
+ typename TupleTraits<A>::RefType, typename TupleTraits<B>::RefType,
+ typename TupleTraits<C>::RefType, typename TupleTraits<D>::RefType,
+ typename TupleTraits<E>::RefType, typename TupleTraits<F>::RefType,
+ typename TupleTraits<G>::RefType>
+ RefTuple;
+
+ Tuple7() {}
+ Tuple7(typename TupleTraits<A>::ParamType aA,
+ typename TupleTraits<B>::ParamType aB,
+ typename TupleTraits<C>::ParamType aC,
+ typename TupleTraits<D>::ParamType aD,
+ typename TupleTraits<E>::ParamType aE,
+ typename TupleTraits<F>::ParamType aF,
+ typename TupleTraits<G>::ParamType aG)
+ : a(aA), b(aB), c(aC), d(aD), e(aE), f(aF), g(aG) {}
+
+ A a;
+ B b;
+ C c;
+ D d;
+ E e;
+ F f;
+ G g;
+};
+
+// Tuple creators -------------------------------------------------------------
+//
+// Helper functions for constructing tuples while inferring the template
+// argument types.
+
+namespace base {
+
+inline Tuple0 MakeTuple() { return Tuple0(); }
+
+template <class A>
+inline Tuple1<A> MakeTuple(const A& a) {
+ return Tuple1<A>(a);
+}
+
+template <class A, class B>
+inline Tuple2<A, B> MakeTuple(const A& a, const B& b) {
+ return Tuple2<A, B>(a, b);
+}
+
+template <class A, class B, class C>
+inline Tuple3<A, B, C> MakeTuple(const A& a, const B& b, const C& c) {
+ return Tuple3<A, B, C>(a, b, c);
+}
+
+template <class A, class B, class C, class D>
+inline Tuple4<A, B, C, D> MakeTuple(const A& a, const B& b, const C& c,
+ const D& d) {
+ return Tuple4<A, B, C, D>(a, b, c, d);
+}
+
+template <class A, class B, class C, class D, class E>
+inline Tuple5<A, B, C, D, E> MakeTuple(const A& a, const B& b, const C& c,
+ const D& d, const E& e) {
+ return Tuple5<A, B, C, D, E>(a, b, c, d, e);
+}
+
+template <class A, class B, class C, class D, class E, class F>
+inline Tuple6<A, B, C, D, E, F> MakeTuple(const A& a, const B& b, const C& c,
+ const D& d, const E& e, const F& f) {
+ return Tuple6<A, B, C, D, E, F>(a, b, c, d, e, f);
+}
+
+template <class A, class B, class C, class D, class E, class F, class G>
+inline Tuple7<A, B, C, D, E, F, G> MakeTuple(const A& a, const B& b, const C& c,
+ const D& d, const E& e, const F& f,
+ const G& g) {
+ return Tuple7<A, B, C, D, E, F, G>(a, b, c, d, e, f, g);
+}
+
+} // end namespace base
+
+// The following set of helpers make what Boost refers to as "Tiers" - a tuple
+// of references.
+
+template <class A>
+inline Tuple1<A&> MakeRefTuple(A& a) {
+ return Tuple1<A&>(a);
+}
+
+template <class A, class B>
+inline Tuple2<A&, B&> MakeRefTuple(A& a, B& b) {
+ return Tuple2<A&, B&>(a, b);
+}
+
+template <class A, class B, class C>
+inline Tuple3<A&, B&, C&> MakeRefTuple(A& a, B& b, C& c) {
+ return Tuple3<A&, B&, C&>(a, b, c);
+}
+
+template <class A, class B, class C, class D>
+inline Tuple4<A&, B&, C&, D&> MakeRefTuple(A& a, B& b, C& c, D& d) {
+ return Tuple4<A&, B&, C&, D&>(a, b, c, d);
+}
+
+template <class A, class B, class C, class D, class E>
+inline Tuple5<A&, B&, C&, D&, E&> MakeRefTuple(A& a, B& b, C& c, D& d, E& e) {
+ return Tuple5<A&, B&, C&, D&, E&>(a, b, c, d, e);
+}
+
+template <class A, class B, class C, class D, class E, class F>
+inline Tuple6<A&, B&, C&, D&, E&, F&> MakeRefTuple(A& a, B& b, C& c, D& d, E& e,
+ F& f) {
+ return Tuple6<A&, B&, C&, D&, E&, F&>(a, b, c, d, e, f);
+}
+
+template <class A, class B, class C, class D, class E, class F, class G>
+inline Tuple7<A&, B&, C&, D&, E&, F&, G&> MakeRefTuple(A& a, B& b, C& c, D& d,
+ E& e, F& f, G& g) {
+ return Tuple7<A&, B&, C&, D&, E&, F&, G&>(a, b, c, d, e, f, g);
+}
+
+// Dispatchers ----------------------------------------------------------------
+//
+// Helper functions that call the given method on an object, with the unpacked
+// tuple arguments. Notice that they all have the same number of arguments,
+// so you need only write:
+// DispatchToMethod(object, &Object::method, args);
+// This is very useful for templated dispatchers, since they don't need to know
+// what type |args| is.
+
+// Non-Static Dispatchers with no out params.
+
+template <class ObjT, class Method>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& arg) {
+ (obj->*method)();
+}
+
+template <class ObjT, class Method, class A>
+inline void DispatchToMethod(ObjT* obj, Method method, const A& arg) {
+ (obj->*method)(arg);
+}
+
+template <class ObjT, class Method, class A>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<A>& arg) {
+ (obj->*method)(arg.a);
+}
+
+template <class ObjT, class Method, class A, class B>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<A, B>& arg) {
+ (obj->*method)(arg.a, arg.b);
+}
+
+template <class ObjT, class Method, class A, class B, class C>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<A, B, C>& arg) {
+ (obj->*method)(arg.a, arg.b, arg.c);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<A, B, C, D>& arg) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D, class E>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<A, B, C, D, E>& arg) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D, class E,
+ class F>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<A, B, C, D, E, F>& arg) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D, class E,
+ class F, class G>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple7<A, B, C, D, E, F, G>& arg) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f, arg.g);
+}
+
+// Static Dispatchers with no out params.
+
+template <class Function>
+inline void DispatchToFunction(Function function, const Tuple0& arg) {
+ (*function)();
+}
+
+template <class Function, class A>
+inline void DispatchToFunction(Function function, const A& arg) {
+ (*function)(arg);
+}
+
+template <class Function, class A>
+inline void DispatchToFunction(Function function, const Tuple1<A>& arg) {
+ (*function)(arg.a);
+}
+
+template <class Function, class A, class B>
+inline void DispatchToFunction(Function function, const Tuple2<A, B>& arg) {
+ (*function)(arg.a, arg.b);
+}
+
+template <class Function, class A, class B, class C>
+inline void DispatchToFunction(Function function, const Tuple3<A, B, C>& arg) {
+ (*function)(arg.a, arg.b, arg.c);
+}
+
+template <class Function, class A, class B, class C, class D>
+inline void DispatchToFunction(Function function,
+ const Tuple4<A, B, C, D>& arg) {
+ (*function)(arg.a, arg.b, arg.c, arg.d);
+}
+
+template <class Function, class A, class B, class C, class D, class E>
+inline void DispatchToFunction(Function function,
+ const Tuple5<A, B, C, D, E>& arg) {
+ (*function)(arg.a, arg.b, arg.c, arg.d, arg.e);
+}
+
+template <class Function, class A, class B, class C, class D, class E, class F>
+inline void DispatchToFunction(Function function,
+ const Tuple6<A, B, C, D, E, F>& arg) {
+ (*function)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f);
+}
+
+// Dispatchers with 0 out param (as a Tuple0).
+
+template <class ObjT, class Method>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& arg,
+ Tuple0*) {
+ (obj->*method)();
+}
+
+template <class ObjT, class Method, class A>
+inline void DispatchToMethod(ObjT* obj, Method method, const A& arg, Tuple0*) {
+ (obj->*method)(arg);
+}
+
+template <class ObjT, class Method, class A>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<A>& arg,
+ Tuple0*) {
+ (obj->*method)(arg.a);
+}
+
+template <class ObjT, class Method, class A, class B>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple2<A, B>& arg,
+ Tuple0*) {
+ (obj->*method)(arg.a, arg.b);
+}
+
+template <class ObjT, class Method, class A, class B, class C>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<A, B, C>& arg, Tuple0*) {
+ (obj->*method)(arg.a, arg.b, arg.c);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<A, B, C, D>& arg, Tuple0*) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D, class E>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<A, B, C, D, E>& arg, Tuple0*) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e);
+}
+
+template <class ObjT, class Method, class A, class B, class C, class D, class E,
+ class F>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<A, B, C, D, E, F>& arg, Tuple0*) {
+ (obj->*method)(arg.a, arg.b, arg.c, arg.d, arg.e, arg.f);
+}
+
+// Dispatchers with 1 out param.
+
+template <class ObjT, class Method, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(&out->a);
+}
+
+template <class ObjT, class Method, class InA, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method, const InA& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<InA>& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in.a, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class InB, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<InA, InB>& in, Tuple1<OutA>* out) {
+ (obj->*method)(in.a, in.b, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<InA, InB, InC>& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in.a, in.b, in.c, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<InA, InB, InC, InD>& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<InA, InB, InC, InD, InE>& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class InF, class OutA>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<InA, InB, InC, InD, InE, InF>& in,
+ Tuple1<OutA>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, in.f, &out->a);
+}
+
+// Dispatchers with 2 out params.
+
+template <class ObjT, class Method, class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(&out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method, const InA& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<InA>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class InB, class OutA,
+ class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<InA, InB>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, in.b, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class OutA,
+ class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<InA, InB, InC>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, in.b, in.c, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<InA, InB, InC, InD>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<InA, InB, InC, InD, InE>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class InF, class OutA, class OutB>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<InA, InB, InC, InD, InE, InF>& in,
+ Tuple2<OutA, OutB>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, in.f, &out->a, &out->b);
+}
+
+// Dispatchers with 3 out params.
+
+template <class ObjT, class Method, class OutA, class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(&out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method, const InA& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<InA>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class InB, class OutA,
+ class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<InA, InB>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, in.b, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class OutA,
+ class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<InA, InB, InC>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, in.b, in.c, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class OutA, class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<InA, InB, InC, InD>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class OutA, class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<InA, InB, InC, InD, InE>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b, &out->c);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class InF, class OutA, class OutB, class OutC>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<InA, InB, InC, InD, InE, InF>& in,
+ Tuple3<OutA, OutB, OutC>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, in.f, &out->a, &out->b, &out->c);
+}
+
+// Dispatchers with 4 out params.
+
+template <class ObjT, class Method, class OutA, class OutB, class OutC,
+ class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(&out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method, const InA& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in, &out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<InA>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, &out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class InB, class OutA,
+ class OutB, class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<InA, InB>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, in.b, &out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class OutA,
+ class OutB, class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<InA, InB, InC>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, in.b, in.c, &out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class OutA, class OutB, class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<InA, InB, InC, InD>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b, &out->c, &out->d);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class OutA, class OutB, class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<InA, InB, InC, InD, InE>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b, &out->c,
+ &out->d);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class InF, class OutA, class OutB, class OutC, class OutD>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<InA, InB, InC, InD, InE, InF>& in,
+ Tuple4<OutA, OutB, OutC, OutD>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, in.f, &out->a, &out->b, &out->c,
+ &out->d);
+}
+
+// Dispatchers with 5 out params.
+
+template <class ObjT, class Method, class OutA, class OutB, class OutC,
+ class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple0& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(&out->a, &out->b, &out->c, &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method, const InA& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in, &out->a, &out->b, &out->c, &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class OutA, class OutB,
+ class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method, const Tuple1<InA>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, &out->a, &out->b, &out->c, &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class InB, class OutA,
+ class OutB, class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple2<InA, InB>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, in.b, &out->a, &out->b, &out->c, &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class OutA,
+ class OutB, class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple3<InA, InB, InC>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, in.b, in.c, &out->a, &out->b, &out->c, &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class OutA, class OutB, class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple4<InA, InB, InC, InD>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, &out->a, &out->b, &out->c, &out->d,
+ &out->e);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class OutA, class OutB, class OutC, class OutD, class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple5<InA, InB, InC, InD, InE>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, &out->a, &out->b, &out->c,
+ &out->d, &out->e);
+}
+
+template <class ObjT, class Method, class InA, class InB, class InC, class InD,
+ class InE, class InF, class OutA, class OutB, class OutC, class OutD,
+ class OutE>
+inline void DispatchToMethod(ObjT* obj, Method method,
+ const Tuple6<InA, InB, InC, InD, InE, InF>& in,
+ Tuple5<OutA, OutB, OutC, OutD, OutE>* out) {
+ (obj->*method)(in.a, in.b, in.c, in.d, in.e, in.f, &out->a, &out->b, &out->c,
+ &out->d, &out->e);
+}
+
+#endif // BASE_TUPLE_H__
diff --git a/ipc/chromium/src/base/waitable_event.h b/ipc/chromium/src/base/waitable_event.h
new file mode 100644
index 0000000000..7c85435804
--- /dev/null
+++ b/ipc/chromium/src/base/waitable_event.h
@@ -0,0 +1,173 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_WAITABLE_EVENT_H_
+#define BASE_WAITABLE_EVENT_H_
+
+#include "base/basictypes.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+#endif
+
+#if defined(XP_UNIX)
+# include <list>
+# include <utility>
+# include "base/condition_variable.h"
+# include "base/lock.h"
+# include "nsISupportsImpl.h"
+#endif
+
+#include "base/message_loop.h"
+
+namespace base {
+
+// This replaces INFINITE from Win32
+static const int kNoTimeout = -1;
+
+class TimeDelta;
+
+// A WaitableEvent can be a useful thread synchronization tool when you want to
+// allow one thread to wait for another thread to finish some work. For
+// non-Windows systems, this can only be used from within a single address
+// space.
+//
+// Use a WaitableEvent when you would otherwise use a Lock+ConditionVariable to
+// protect a simple boolean value. However, if you find yourself using a
+// WaitableEvent in conjunction with a Lock to wait for a more complex state
+// change (e.g., for an item to be added to a queue), then you should probably
+// be using a ConditionVariable instead of a WaitableEvent.
+//
+// NOTE: On Windows, this class provides a subset of the functionality afforded
+// by a Windows event object. This is intentional. If you are writing Windows
+// specific code and you need other features of a Windows event, then you might
+// be better off just using an Windows event directly.
+class WaitableEvent {
+ public:
+ // If manual_reset is true, then to set the event state to non-signaled, a
+ // consumer must call the Reset method. If this parameter is false, then the
+ // system automatically resets the event state to non-signaled after a single
+ // waiting thread has been released.
+ WaitableEvent(bool manual_reset, bool initially_signaled);
+
+ ~WaitableEvent();
+
+ // Put the event in the un-signaled state.
+ void Reset();
+
+ // Put the event in the signaled state. Causing any thread blocked on Wait
+ // to be woken up.
+ void Signal();
+
+ // Returns true if the event is in the signaled state, else false. If this
+ // is not a manual reset event, then this test will cause a reset.
+ bool IsSignaled();
+
+ // Wait indefinitely for the event to be signaled. Returns true if the event
+ // was signaled, else false is returned to indicate that waiting failed.
+ bool Wait();
+
+ // Wait up until max_time has passed for the event to be signaled. Returns
+ // true if the event was signaled. If this method returns false, then it
+ // does not necessarily mean that max_time was exceeded.
+ bool TimedWait(const TimeDelta& max_time);
+
+#if defined(XP_WIN)
+ HANDLE handle() const { return handle_; }
+#endif
+
+ // Wait, synchronously, on multiple events.
+ // waitables: an array of WaitableEvent pointers
+ // count: the number of elements in @waitables
+ //
+ // returns: the index of a WaitableEvent which has been signaled.
+ //
+ // You MUST NOT delete any of the WaitableEvent objects while this wait is
+ // happening.
+ static size_t WaitMany(WaitableEvent** waitables, size_t count);
+
+ // For asynchronous waiting, see WaitableEventWatcher
+
+ // This is a private helper class. It's here because it's used by friends of
+ // this class (such as WaitableEventWatcher) to be able to enqueue elements
+ // of the wait-list
+ class Waiter {
+ public:
+ // Signal the waiter to wake up.
+ //
+ // Consider the case of a Waiter which is in multiple WaitableEvent's
+ // wait-lists. Each WaitableEvent is automatic-reset and two of them are
+ // signaled at the same time. Now, each will wake only the first waiter in
+ // the wake-list before resetting. However, if those two waiters happen to
+ // be the same object (as can happen if another thread didn't have a chance
+ // to dequeue the waiter from the other wait-list in time), two auto-resets
+ // will have happened, but only one waiter has been signaled!
+ //
+ // Because of this, a Waiter may "reject" a wake by returning false. In
+ // this case, the auto-reset WaitableEvent shouldn't act as if anything has
+ // been notified.
+ virtual bool Fire(WaitableEvent* signaling_event) = 0;
+
+ // Waiters may implement this in order to provide an extra condition for
+ // two Waiters to be considered equal. In WaitableEvent::Dequeue, if the
+ // pointers match then this function is called as a final check. See the
+ // comments in ~Handle for why.
+ virtual bool Compare(void* tag) = 0;
+ };
+
+ private:
+ friend class WaitableEventWatcher;
+
+#if defined(XP_WIN)
+ HANDLE handle_;
+#else
+ // On Windows, one can close a HANDLE which is currently being waited on. The
+ // MSDN documentation says that the resulting behaviour is 'undefined', but
+ // it doesn't crash. However, if we were to include the following members
+ // directly then, on POSIX, one couldn't use WaitableEventWatcher to watch an
+ // event which gets deleted. This mismatch has bitten us several times now,
+ // so we have a kernel of the WaitableEvent, which is reference counted.
+ // WaitableEventWatchers may then take a reference and thus match the Windows
+ // behaviour.
+ struct WaitableEventKernel final {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WaitableEventKernel)
+ WaitableEventKernel(bool manual_reset, bool initially_signaled)
+ : manual_reset_(manual_reset), signaled_(initially_signaled) {}
+
+ bool Dequeue(Waiter* waiter, void* tag);
+
+ Lock lock_;
+ const bool manual_reset_;
+ bool signaled_;
+ std::list<Waiter*> waiters_;
+
+ protected:
+ ~WaitableEventKernel() {}
+ };
+
+ RefPtr<WaitableEventKernel> kernel_;
+
+ bool SignalAll();
+ bool SignalOne();
+ void Enqueue(Waiter* waiter);
+
+ // When dealing with arrays of WaitableEvent*, we want to sort by the address
+ // of the WaitableEvent in order to have a globally consistent locking order.
+ // In that case we keep them, in sorted order, in an array of pairs where the
+ // second element is the index of the WaitableEvent in the original,
+ // unsorted, array.
+ typedef std::pair<WaitableEvent*, size_t> WaiterAndIndex;
+ static size_t EnqueueMany(WaiterAndIndex* waitables, size_t count,
+ Waiter* waiter);
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(WaitableEvent);
+};
+
+} // namespace base
+
+#endif // BASE_WAITABLE_EVENT_H_
diff --git a/ipc/chromium/src/base/waitable_event_posix.cc b/ipc/chromium/src/base/waitable_event_posix.cc
new file mode 100644
index 0000000000..ad63876016
--- /dev/null
+++ b/ipc/chromium/src/base/waitable_event_posix.cc
@@ -0,0 +1,362 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/waitable_event.h"
+
+#include "base/condition_variable.h"
+#include "base/lock.h"
+#include "base/message_loop.h"
+
+// -----------------------------------------------------------------------------
+// A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
+// support cross-process events (where one process can signal an event which
+// others are waiting on). Because of this, we can avoid having one thread per
+// listener in several cases.
+//
+// The WaitableEvent maintains a list of waiters, protected by a lock. Each
+// waiter is either an async wait, in which case we have a Task and the
+// MessageLoop to run it on, or a blocking wait, in which case we have the
+// condition variable to signal.
+//
+// Waiting involves grabbing the lock and adding oneself to the wait list. Async
+// waits can be canceled, which means grabbing the lock and removing oneself
+// from the list.
+//
+// Waiting on multiple events is handled by adding a single, synchronous wait to
+// the wait-list of many events. An event passes a pointer to itself when
+// firing a waiter and so we can store that pointer to find out which event
+// triggered.
+// -----------------------------------------------------------------------------
+
+namespace base {
+
+// -----------------------------------------------------------------------------
+// This is just an abstract base class for waking the two types of waiters
+// -----------------------------------------------------------------------------
+WaitableEvent::WaitableEvent(bool manual_reset, bool initially_signaled)
+ : kernel_(new WaitableEventKernel(manual_reset, initially_signaled)) {}
+
+WaitableEvent::~WaitableEvent() {}
+
+void WaitableEvent::Reset() {
+ AutoLock locked(kernel_->lock_);
+ kernel_->signaled_ = false;
+}
+
+void WaitableEvent::Signal() {
+ AutoLock locked(kernel_->lock_);
+
+ if (kernel_->signaled_) return;
+
+ if (kernel_->manual_reset_) {
+ SignalAll();
+ kernel_->signaled_ = true;
+ } else {
+ // In the case of auto reset, if no waiters were woken, we remain
+ // signaled.
+ if (!SignalOne()) kernel_->signaled_ = true;
+ }
+}
+
+bool WaitableEvent::IsSignaled() {
+ AutoLock locked(kernel_->lock_);
+
+ const bool result = kernel_->signaled_;
+ if (result && !kernel_->manual_reset_) kernel_->signaled_ = false;
+ return result;
+}
+
+// -----------------------------------------------------------------------------
+// Synchronous waits
+
+// -----------------------------------------------------------------------------
+// This is an synchronous waiter. The thread is waiting on the given condition
+// variable and the fired flag in this object.
+// -----------------------------------------------------------------------------
+class SyncWaiter : public WaitableEvent::Waiter {
+ public:
+ SyncWaiter(ConditionVariable* cv, Lock* lock)
+ : fired_(false), cv_(cv), lock_(lock), signaling_event_(NULL) {}
+
+ bool Fire(WaitableEvent* signaling_event) override {
+ lock_->Acquire();
+ const bool previous_value = fired_;
+ fired_ = true;
+ if (!previous_value) signaling_event_ = signaling_event;
+ lock_->Release();
+
+ if (previous_value) return false;
+
+ cv_->Broadcast();
+
+ // SyncWaiters are stack allocated on the stack of the blocking thread.
+ return true;
+ }
+
+ WaitableEvent* signaled_event() const { return signaling_event_; }
+
+ // ---------------------------------------------------------------------------
+ // These waiters are always stack allocated and don't delete themselves. Thus
+ // there's no problem and the ABA tag is the same as the object pointer.
+ // ---------------------------------------------------------------------------
+ bool Compare(void* tag) override { return this == tag; }
+
+ // ---------------------------------------------------------------------------
+ // Called with lock held.
+ // ---------------------------------------------------------------------------
+ bool fired() const { return fired_; }
+
+ // ---------------------------------------------------------------------------
+ // During a TimedWait, we need a way to make sure that an auto-reset
+ // WaitableEvent doesn't think that this event has been signaled between
+ // unlocking it and removing it from the wait-list. Called with lock held.
+ // ---------------------------------------------------------------------------
+ void Disable() { fired_ = true; }
+
+ private:
+ bool fired_;
+ ConditionVariable* const cv_;
+ Lock* const lock_;
+ WaitableEvent* signaling_event_; // The WaitableEvent which woke us
+};
+
+bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
+ const TimeTicks end_time(TimeTicks::Now() + max_time);
+ const bool finite_time = max_time.ToInternalValue() >= 0;
+
+ kernel_->lock_.Acquire();
+ if (kernel_->signaled_) {
+ if (!kernel_->manual_reset_) {
+ // In this case we were signaled when we had no waiters. Now that
+ // someone has waited upon us, we can automatically reset.
+ kernel_->signaled_ = false;
+ }
+
+ kernel_->lock_.Release();
+ return true;
+ }
+
+ Lock lock;
+ lock.Acquire();
+ ConditionVariable cv(&lock);
+ SyncWaiter sw(&cv, &lock);
+
+ Enqueue(&sw);
+ kernel_->lock_.Release();
+ // We are violating locking order here by holding the SyncWaiter lock but not
+ // the WaitableEvent lock. However, this is safe because we don't lock @lock_
+ // again before unlocking it.
+
+ for (;;) {
+ const TimeTicks current_time(TimeTicks::Now());
+
+ if (sw.fired() || (finite_time && current_time >= end_time)) {
+ const bool return_value = sw.fired();
+
+ // We can't acquire @lock_ before releasing @lock (because of locking
+ // order), however, inbetween the two a signal could be fired and @sw
+ // would accept it, however we will still return false, so the signal
+ // would be lost on an auto-reset WaitableEvent. Thus we call Disable
+ // which makes sw::Fire return false.
+ sw.Disable();
+ lock.Release();
+
+ kernel_->lock_.Acquire();
+ kernel_->Dequeue(&sw, &sw);
+ kernel_->lock_.Release();
+
+ return return_value;
+ }
+
+ if (finite_time) {
+ const TimeDelta max_wait(end_time - current_time);
+ cv.TimedWait(max_wait);
+ } else {
+ cv.Wait();
+ }
+ }
+}
+
+bool WaitableEvent::Wait() { return TimedWait(TimeDelta::FromSeconds(-1)); }
+
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// Synchronous waiting on multiple objects.
+
+static bool // StrictWeakOrdering
+cmp_fst_addr(const std::pair<WaitableEvent*, unsigned>& a,
+ const std::pair<WaitableEvent*, unsigned>& b) {
+ return a.first < b.first;
+}
+
+// static
+size_t WaitableEvent::WaitMany(WaitableEvent** raw_waitables, size_t count) {
+ DCHECK(count) << "Cannot wait on no events";
+
+ // We need to acquire the locks in a globally consistent order. Thus we sort
+ // the array of waitables by address. We actually sort a pairs so that we can
+ // map back to the original index values later.
+ std::vector<std::pair<WaitableEvent*, size_t> > waitables;
+ waitables.reserve(count);
+ for (size_t i = 0; i < count; ++i)
+ waitables.push_back(std::make_pair(raw_waitables[i], i));
+
+ DCHECK_EQ(count, waitables.size());
+
+ sort(waitables.begin(), waitables.end(), cmp_fst_addr);
+
+ // The set of waitables must be distinct. Since we have just sorted by
+ // address, we can check this cheaply by comparing pairs of consecutive
+ // elements.
+ for (size_t i = 0; i < waitables.size() - 1; ++i) {
+ DCHECK(waitables[i].first != waitables[i + 1].first);
+ }
+
+ Lock lock;
+ ConditionVariable cv(&lock);
+ SyncWaiter sw(&cv, &lock);
+
+ const size_t r = EnqueueMany(&waitables[0], count, &sw);
+ if (r) {
+ // One of the events is already signaled. The SyncWaiter has not been
+ // enqueued anywhere. EnqueueMany returns the count of remaining waitables
+ // when the signaled one was seen, so the index of the signaled event is
+ // @count - @r.
+ return waitables[count - r].second;
+ }
+
+ // At this point, we hold the locks on all the WaitableEvents and we have
+ // enqueued our waiter in them all.
+ lock.Acquire();
+ // Release the WaitableEvent locks in the reverse order
+ for (size_t i = 0; i < count; ++i) {
+ waitables[count - (1 + i)].first->kernel_->lock_.Release();
+ }
+
+ for (;;) {
+ if (sw.fired()) break;
+
+ cv.Wait();
+ }
+ lock.Release();
+
+ // The address of the WaitableEvent which fired is stored in the SyncWaiter.
+ WaitableEvent* const signaled_event = sw.signaled_event();
+ // This will store the index of the raw_waitables which fired.
+ size_t signaled_index = 0;
+
+ // Take the locks of each WaitableEvent in turn (except the signaled one) and
+ // remove our SyncWaiter from the wait-list
+ for (size_t i = 0; i < count; ++i) {
+ if (raw_waitables[i] != signaled_event) {
+ raw_waitables[i]->kernel_->lock_.Acquire();
+ // There's no possible ABA issue with the address of the SyncWaiter here
+ // because it lives on the stack. Thus the tag value is just the pointer
+ // value again.
+ raw_waitables[i]->kernel_->Dequeue(&sw, &sw);
+ raw_waitables[i]->kernel_->lock_.Release();
+ } else {
+ signaled_index = i;
+ }
+ }
+
+ return signaled_index;
+}
+
+// -----------------------------------------------------------------------------
+// If return value == 0:
+// The locks of the WaitableEvents have been taken in order and the Waiter has
+// been enqueued in the wait-list of each. None of the WaitableEvents are
+// currently signaled
+// else:
+// None of the WaitableEvent locks are held. The Waiter has not been enqueued
+// in any of them and the return value is the index of the first WaitableEvent
+// which was signaled, from the end of the array.
+// -----------------------------------------------------------------------------
+// static
+size_t WaitableEvent::EnqueueMany(std::pair<WaitableEvent*, size_t>* waitables,
+ size_t count, Waiter* waiter) {
+ if (!count) return 0;
+
+ waitables[0].first->kernel_->lock_.Acquire();
+ if (waitables[0].first->kernel_->signaled_) {
+ if (!waitables[0].first->kernel_->manual_reset_)
+ waitables[0].first->kernel_->signaled_ = false;
+ waitables[0].first->kernel_->lock_.Release();
+ return count;
+ }
+
+ const size_t r = EnqueueMany(waitables + 1, count - 1, waiter);
+ if (r) {
+ waitables[0].first->kernel_->lock_.Release();
+ } else {
+ waitables[0].first->Enqueue(waiter);
+ }
+
+ return r;
+}
+
+// -----------------------------------------------------------------------------
+
+// -----------------------------------------------------------------------------
+// Private functions...
+
+// -----------------------------------------------------------------------------
+// Wake all waiting waiters. Called with lock held.
+// -----------------------------------------------------------------------------
+bool WaitableEvent::SignalAll() {
+ bool signaled_at_least_one = false;
+
+ for (std::list<Waiter*>::iterator i = kernel_->waiters_.begin();
+ i != kernel_->waiters_.end(); ++i) {
+ if ((*i)->Fire(this)) signaled_at_least_one = true;
+ }
+
+ kernel_->waiters_.clear();
+ return signaled_at_least_one;
+}
+
+// ---------------------------------------------------------------------------
+// Try to wake a single waiter. Return true if one was woken. Called with lock
+// held.
+// ---------------------------------------------------------------------------
+bool WaitableEvent::SignalOne() {
+ for (;;) {
+ if (kernel_->waiters_.empty()) return false;
+
+ const bool r = (*kernel_->waiters_.begin())->Fire(this);
+ kernel_->waiters_.pop_front();
+ if (r) return true;
+ }
+}
+
+// -----------------------------------------------------------------------------
+// Add a waiter to the list of those waiting. Called with lock held.
+// -----------------------------------------------------------------------------
+void WaitableEvent::Enqueue(Waiter* waiter) {
+ kernel_->waiters_.push_back(waiter);
+}
+
+// -----------------------------------------------------------------------------
+// Remove a waiter from the list of those waiting. Return true if the waiter was
+// actually removed. Called with lock held.
+// -----------------------------------------------------------------------------
+bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter* waiter, void* tag) {
+ for (std::list<Waiter*>::iterator i = waiters_.begin(); i != waiters_.end();
+ ++i) {
+ if (*i == waiter && (*i)->Compare(tag)) {
+ waiters_.erase(i);
+ return true;
+ }
+ }
+
+ return false;
+}
+
+// -----------------------------------------------------------------------------
+
+} // namespace base
diff --git a/ipc/chromium/src/base/waitable_event_win.cc b/ipc/chromium/src/base/waitable_event_win.cc
new file mode 100644
index 0000000000..ca94c5cdd9
--- /dev/null
+++ b/ipc/chromium/src/base/waitable_event_win.cc
@@ -0,0 +1,81 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/waitable_event.h"
+
+#include <math.h>
+#include <windows.h>
+
+#include "base/logging.h"
+#include "base/time.h"
+
+namespace base {
+
+WaitableEvent::WaitableEvent(bool manual_reset, bool signaled)
+ : handle_(CreateEvent(NULL, manual_reset, signaled, NULL)) {
+ // We're probably going to crash anyways if this is ever NULL, so we might as
+ // well make our stack reports more informative by crashing here.
+ CHECK(handle_);
+}
+
+WaitableEvent::~WaitableEvent() { CloseHandle(handle_); }
+
+void WaitableEvent::Reset() { ResetEvent(handle_); }
+
+void WaitableEvent::Signal() { SetEvent(handle_); }
+
+bool WaitableEvent::IsSignaled() {
+ return TimedWait(TimeDelta::FromMilliseconds(0));
+}
+
+bool WaitableEvent::Wait() {
+ DWORD result = WaitForSingleObject(handle_, INFINITE);
+ // It is most unexpected that this should ever fail. Help consumers learn
+ // about it if it should ever fail.
+ DCHECK(result == WAIT_OBJECT_0) << "WaitForSingleObject failed";
+ return result == WAIT_OBJECT_0;
+}
+
+bool WaitableEvent::TimedWait(const TimeDelta& max_time) {
+ DCHECK(max_time >= TimeDelta::FromMicroseconds(0));
+ // Be careful here. TimeDelta has a precision of microseconds, but this API
+ // is in milliseconds. If there are 5.5ms left, should the delay be 5 or 6?
+ // It should be 6 to avoid returning too early.
+ double timeout = ceil(max_time.InMillisecondsF());
+ DWORD result = WaitForSingleObject(handle_, static_cast<DWORD>(timeout));
+ switch (result) {
+ case WAIT_OBJECT_0:
+ return true;
+ case WAIT_TIMEOUT:
+ return false;
+ }
+ // It is most unexpected that this should ever fail. Help consumers learn
+ // about it if it should ever fail.
+ NOTREACHED() << "WaitForSingleObject failed";
+ return false;
+}
+
+// static
+size_t WaitableEvent::WaitMany(WaitableEvent** events, size_t count) {
+ HANDLE handles[MAXIMUM_WAIT_OBJECTS];
+ CHECK(count <= MAXIMUM_WAIT_OBJECTS)
+ << "Can only wait on " << MAXIMUM_WAIT_OBJECTS << " with WaitMany";
+
+ for (size_t i = 0; i < count; ++i) handles[i] = events[i]->handle();
+
+ DWORD result =
+ WaitForMultipleObjects(count, handles,
+ FALSE, // don't wait for all the objects
+ INFINITE); // no timeout
+ if (result >= WAIT_OBJECT_0 + count) {
+ NOTREACHED() << "WaitForMultipleObjects failed: " << GetLastError();
+ return 0;
+ }
+
+ return result - WAIT_OBJECT_0;
+}
+
+} // namespace base
diff --git a/ipc/chromium/src/base/win_util.cc b/ipc/chromium/src/base/win_util.cc
new file mode 100644
index 0000000000..611603f56e
--- /dev/null
+++ b/ipc/chromium/src/base/win_util.cc
@@ -0,0 +1,37 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "base/win_util.h"
+
+#include <map>
+#include <sddl.h>
+
+#include "base/logging.h"
+#include "base/string_util.h"
+
+namespace win_util {
+
+std::wstring FormatMessage(unsigned messageid) {
+ wchar_t* string_buffer = NULL;
+ ::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, messageid, 0,
+ reinterpret_cast<wchar_t*>(&string_buffer), 0, NULL);
+
+ std::wstring formatted_string;
+ if (string_buffer) {
+ formatted_string = string_buffer;
+ LocalFree(reinterpret_cast<HLOCAL>(string_buffer));
+ } else {
+ // The formating failed. simply convert the message value into a string.
+ SStringPrintf(&formatted_string, L"message number %d", messageid);
+ }
+ return formatted_string;
+}
+
+std::wstring FormatLastWin32Error() { return FormatMessage(GetLastError()); }
+
+} // namespace win_util
diff --git a/ipc/chromium/src/base/win_util.h b/ipc/chromium/src/base/win_util.h
new file mode 100644
index 0000000000..b37411f60d
--- /dev/null
+++ b/ipc/chromium/src/base/win_util.h
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_WIN_UTIL_H__
+#define BASE_WIN_UTIL_H__
+
+#include <windows.h>
+#include <aclapi.h>
+
+#include <string>
+
+namespace win_util {
+
+// Uses the last Win32 error to generate a human readable message string.
+std::wstring FormatLastWin32Error();
+
+} // namespace win_util
+
+#endif // BASE_WIN_UTIL_H__
diff --git a/ipc/chromium/src/chrome/common/child_process.cc b/ipc/chromium/src/chrome/common/child_process.cc
new file mode 100644
index 0000000000..637564c30c
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/child_process.cc
@@ -0,0 +1,29 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "chrome/common/child_process.h"
+
+#include "base/basictypes.h"
+#include "base/string_util.h"
+#include "chrome/common/child_thread.h"
+
+ChildProcess* ChildProcess::child_process_;
+
+ChildProcess::ChildProcess(ChildThread* child_thread)
+ : child_thread_(child_thread) {
+ DCHECK(!child_process_);
+ child_process_ = this;
+ if (child_thread_.get()) // null in unittests.
+ child_thread_->Run();
+}
+
+ChildProcess::~ChildProcess() {
+ DCHECK(child_process_ == this);
+
+ if (child_thread_.get()) child_thread_->Stop();
+
+ child_process_ = NULL;
+}
diff --git a/ipc/chromium/src/chrome/common/child_process.h b/ipc/chromium/src/chrome/common/child_process.h
new file mode 100644
index 0000000000..7ce4cffa81
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/child_process.h
@@ -0,0 +1,45 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef CHROME_COMMON_CHILD_PROCESS_H__
+#define CHROME_COMMON_CHILD_PROCESS_H__
+
+#include <string>
+#include <vector>
+#include "base/basictypes.h"
+#include "base/message_loop.h"
+#include "base/waitable_event.h"
+#include "mozilla/UniquePtr.h"
+
+class ChildThread;
+
+// Base class for child processes of the browser process (i.e. renderer and
+// plugin host). This is a singleton object for each child process.
+class ChildProcess {
+ public:
+ // Child processes should have an object that derives from this class. The
+ // constructor will return once ChildThread has started.
+ explicit ChildProcess(ChildThread* child_thread);
+ virtual ~ChildProcess();
+
+ // Getter for this process' main thread.
+ ChildThread* child_thread() { return child_thread_.get(); }
+
+ // Getter for the one ChildProcess object for this process.
+ static ChildProcess* current() { return child_process_; }
+
+ private:
+ // NOTE: make sure that child_thread_ is listed before shutdown_event_, since
+ // it depends on it (indirectly through IPC::SyncChannel).
+ mozilla::UniquePtr<ChildThread> child_thread_;
+
+ // The singleton instance for this process.
+ static ChildProcess* child_process_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ChildProcess);
+};
+
+#endif // CHROME_COMMON_CHILD_PROCESS_H__
diff --git a/ipc/chromium/src/chrome/common/child_thread.cc b/ipc/chromium/src/chrome/common/child_thread.cc
new file mode 100644
index 0000000000..3363d5729b
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/child_thread.cc
@@ -0,0 +1,48 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#include "chrome/common/child_thread.h"
+
+#include "chrome/common/child_process.h"
+#include "mozilla/ipc/NodeController.h"
+
+ChildThread::ChildThread(Thread::Options options, base::ProcessId parent_pid)
+ : Thread("IPC I/O Child"),
+ owner_loop_(MessageLoop::current()),
+ options_(options),
+ parent_pid_(parent_pid) {
+ DCHECK(owner_loop_);
+}
+
+ChildThread::~ChildThread() = default;
+
+bool ChildThread::Run() {
+ bool r = StartWithOptions(options_);
+ return r;
+}
+
+ChildThread* ChildThread::current() {
+ return ChildProcess::current()->child_thread();
+}
+
+void ChildThread::Init() {
+ // Take ownership of the client channel handle which we inherited, and use it
+ // to start the initial IPC connection to the parent process.
+ IPC::Channel::ChannelHandle client_handle(
+ IPC::Channel::GetClientChannelHandle());
+ auto channel = mozilla::MakeUnique<IPC::Channel>(
+ std::move(client_handle), IPC::Channel::MODE_CLIENT, parent_pid_);
+#if defined(XP_WIN)
+ channel->StartAcceptingHandles(IPC::Channel::MODE_CLIENT);
+#elif defined(XP_DARWIN)
+ channel->StartAcceptingMachPorts(IPC::Channel::MODE_CLIENT);
+#endif
+
+ initial_port_ = mozilla::ipc::NodeController::InitChildProcess(
+ std::move(channel), parent_pid_);
+}
+
+void ChildThread::CleanUp() { mozilla::ipc::NodeController::CleanUp(); }
diff --git a/ipc/chromium/src/chrome/common/child_thread.h b/ipc/chromium/src/chrome/common/child_thread.h
new file mode 100644
index 0000000000..847a995cae
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/child_thread.h
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 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.
+
+#ifndef CHROME_COMMON_CHILD_THREAD_H_
+#define CHROME_COMMON_CHILD_THREAD_H_
+
+#include "base/thread.h"
+#include "chrome/common/ipc_channel.h"
+#include "mojo/core/ports/port_ref.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/ScopedPort.h"
+
+class ResourceDispatcher;
+
+// Child processes's background thread should derive from this class.
+class ChildThread : public base::Thread {
+ public:
+ // Creates the thread.
+ ChildThread(Thread::Options options, base::ProcessId parent_pid);
+ virtual ~ChildThread();
+
+ mozilla::ipc::ScopedPort TakeInitialPort() {
+ return std::move(initial_port_);
+ }
+
+ protected:
+ friend class ChildProcess;
+
+ // Starts the thread.
+ bool Run();
+
+ protected:
+ // Returns the one child thread.
+ static ChildThread* current();
+
+ // Thread implementation.
+ virtual void Init() override;
+ virtual void CleanUp() override;
+
+ private:
+ // The message loop used to run tasks on the thread that started this thread.
+ MessageLoop* owner_loop_;
+
+ mozilla::ipc::ScopedPort initial_port_;
+
+ Thread::Options options_;
+
+ base::ProcessId parent_pid_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ChildThread);
+};
+
+#endif // CHROME_COMMON_CHILD_THREAD_H_
diff --git a/ipc/chromium/src/chrome/common/chrome_switches.cc b/ipc/chromium/src/chrome/common/chrome_switches.cc
new file mode 100644
index 0000000000..185934c87d
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/chrome_switches.cc
@@ -0,0 +1,18 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// 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.
+
+#include "chrome/common/chrome_switches.h"
+
+namespace switches {
+
+// Can't find the switch you are looking for? try looking in
+// base/base_switches.cc instead.
+
+// The value of this switch tells the child process which
+// IPC channel the browser expects to use to communicate with it.
+const wchar_t kProcessChannelID[] = L"channel";
+
+} // namespace switches
diff --git a/ipc/chromium/src/chrome/common/chrome_switches.h b/ipc/chromium/src/chrome/common/chrome_switches.h
new file mode 100644
index 0000000000..b13a726980
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/chrome_switches.h
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// 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.
+
+// Defines all the command-line switches used by Chrome.
+
+#ifndef CHROME_COMMON_CHROME_SWITCHES_H__
+#define CHROME_COMMON_CHROME_SWITCHES_H__
+
+#if defined(_MSC_VER)
+# include <string.h>
+#endif
+
+namespace switches {
+
+extern const wchar_t kProcessChannelID[];
+
+} // namespace switches
+
+#endif // CHROME_COMMON_CHROME_SWITCHES_H__
diff --git a/ipc/chromium/src/chrome/common/ipc_channel.h b/ipc/chromium/src/chrome/common/ipc_channel.h
new file mode 100644
index 0000000000..5d342d7252
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel.h
@@ -0,0 +1,189 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef CHROME_COMMON_IPC_CHANNEL_H_
+#define CHROME_COMMON_IPC_CHANNEL_H_
+
+#include <cstdint>
+#include <queue>
+#include "base/basictypes.h"
+#include "base/process.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/WeakPtr.h"
+#include "chrome/common/ipc_message.h"
+
+#ifdef XP_WIN
+# include <string>
+#endif
+
+namespace IPC {
+
+class Message;
+class MessageReader;
+class MessageWriter;
+
+//------------------------------------------------------------------------------
+
+class Channel {
+ // Security tests need access to the pipe handle.
+ friend class ChannelTest;
+
+ public:
+ // For channels which are created after initialization, handles to the pipe
+ // endpoints may be passed around directly using IPC messages.
+ using ChannelHandle = mozilla::UniqueFileHandle;
+
+ // Implemented by consumers of a Channel to receive messages.
+ //
+ // All listeners will only be called on the IO thread, and must be destroyed
+ // on the IO thread.
+ class Listener {
+ public:
+ virtual ~Listener() = default;
+
+ // Called when a message is received.
+ virtual void OnMessageReceived(mozilla::UniquePtr<Message> message) = 0;
+
+ // Called when the channel is connected and we have received the internal
+ // Hello message from the peer.
+ virtual void OnChannelConnected(base::ProcessId peer_pid) {}
+
+ // Called when an error is detected that causes the channel to close.
+ // This method is not called when a channel is closed normally.
+ virtual void OnChannelError() {}
+ };
+
+ enum Mode { MODE_SERVER, MODE_CLIENT };
+
+ enum {
+
+ // The maximum message size in bytes. Attempting to receive a
+ // message of this size or bigger results in a channel error.
+ // This is larger in fuzzing builds to allow the fuzzing of passing
+ // large data structures into DOM methods without crashing.
+#ifndef FUZZING
+ kMaximumMessageSize = 256 * 1024 * 1024,
+#else
+ kMaximumMessageSize = 1792 * 1024 * 1024, // 1.75GB
+#endif
+
+ // Amount of data to read at once from the pipe.
+ kReadBufferSize = 4 * 1024,
+ };
+
+ // Initialize a Channel.
+ //
+ // |pipe| identifies the pipe which will be used. It should have been created
+ // using CreateRawPipe().
+ // |mode| specifies whether this channel is operating in server mode or client
+ // mode. One side of the connection should be the client, and the other should
+ // be the server.
+ // |other_pid| specifies the pid of the other side of this channel. This will
+ // be used for logging, and for transferring HANDLEs from a privileged process
+ // on Windows (if enabled).
+ //
+ // The Channel must be created and destroyed on the IO thread, and all
+ // methods, unless otherwise noted, are only safe to call on the I/O thread.
+ //
+ Channel(ChannelHandle pipe, Mode mode, base::ProcessId other_pid);
+
+ ~Channel();
+
+ // Connect the pipe. On the server side, this will initiate
+ // waiting for connections. On the client, it attempts to
+ // connect to a pre-existing pipe. Note, calling Connect()
+ // will not block the calling thread and may complete
+ // asynchronously.
+ //
+ // |listener| will receive a callback on the current thread for each newly
+ // received message.
+ bool Connect(Listener* listener);
+
+ // Close this Channel explicitly. May be called multiple times.
+ void Close();
+
+ // Send a message over the Channel to the listener on the other end.
+ //
+ // This method may be called from any thread, so long as the `Channel` is not
+ // destroyed before it returns.
+ //
+ // If you Send() a message on a Close()'d channel, we delete the message
+ // immediately.
+ bool Send(mozilla::UniquePtr<Message> message);
+
+ // Explicitly set the pid expected for the other side of this channel. This
+ // will be used for logging, and on Windows may be used for transferring
+ // handles between processes.
+ //
+ // If it is set this way, the "hello" message will be checked to ensure that
+ // the same pid is reported.
+ void SetOtherPid(base::ProcessId other_pid);
+
+ // IsClosed() is safe to call from any thread, but the value returned may
+ // be out of date.
+ bool IsClosed() const;
+
+#if defined(XP_DARWIN)
+ // Configure the mach task_t for the peer task.
+ void SetOtherMachTask(task_t task);
+
+ // Tell this pipe to accept mach ports. Exactly one side of the IPC connection
+ // must be set as `MODE_SERVER` and that side will be responsible for
+ // transferring the rights between processes.
+ void StartAcceptingMachPorts(Mode mode);
+#elif defined(XP_WIN)
+ // Tell this pipe to accept handles. Exactly one side of the IPC connection
+ // must be set as `MODE_SERVER`, and that side will be responsible for calling
+ // `DuplicateHandle` to transfer the handle between processes.
+ void StartAcceptingHandles(Mode mode);
+#endif
+
+#if defined(MOZ_WIDGET_ANDROID)
+ // Used to set the first IPC file descriptor in the child process on Android.
+ // See ipc_channel_posix.cc for further details on how this is used.
+ static void SetClientChannelFd(int fd);
+#endif // defined(MOZ_WIDGET_ANDROID)
+
+ // Get the first IPC channel handle in the child process. This will have been
+ // set by SetClientChannelFd on Android, will be a constant on other unix
+ // platforms, or will have been passed on the command line on Windows.
+ static ChannelHandle::ElementType GetClientChannelHandle();
+
+ // Create a new pair of pipe endpoints which can be used to establish a
+ // native IPC::Channel connection.
+ static bool CreateRawPipe(ChannelHandle* server, ChannelHandle* client);
+
+ private:
+ // PIMPL to which all channel calls are delegated.
+ class ChannelImpl;
+ RefPtr<ChannelImpl> channel_impl_;
+
+ enum {
+#if defined(XP_DARWIN)
+ // If the channel receives a message that contains file descriptors, then
+ // it will reply back with this message, indicating that the message has
+ // been received. The sending channel can then close any descriptors that
+ // had been marked as auto_close. This works around a sendmsg() bug on BSD
+ // where the kernel can eagerly close file descriptors that are in message
+ // queues but not yet delivered.
+ RECEIVED_FDS_MESSAGE_TYPE = kuint16max - 1,
+#endif
+
+ // The Hello message is internal to the Channel class. It is sent
+ // by the peer when the channel is connected. The message contains
+ // just the process id (pid). The message has a special routing_id
+ // (MSG_ROUTING_NONE) and type (HELLO_MESSAGE_TYPE).
+ HELLO_MESSAGE_TYPE = kuint16max // Maximum value of message type
+ // (uint16_t), to avoid conflicting with
+ // normal message types, which are
+ // enumeration constants starting from 0.
+ };
+};
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_CHANNEL_H_
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_capability.h b/ipc/chromium/src/chrome/common/ipc_channel_capability.h
new file mode 100644
index 0000000000..c23f16e577
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_capability.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef CHROME_COMMON_IPC_CHANNEL_CAPABILITY_H_
+#define CHROME_COMMON_IPC_CHANNEL_CAPABILITY_H_
+
+#include "mozilla/ThreadSafety.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/EventTargetCapability.h"
+#include "nsISerialEventTarget.h"
+
+namespace IPC {
+
+// A thread-safety capability used in IPC channel implementations. Combines an
+// EventTargetCapability and a Mutex to allow using each independently, as well
+// as combined together.
+//
+// The ChannelCapability grants shared access if on the IOThread or if the send
+// mutex is held, and only allows exclusive access if both on the IO thread and
+// holding the send mutex. This is similar to a `MutexSingleWriter`, but more
+// flexible due to providing access to each sub-capability.
+class MOZ_CAPABILITY("channel cap") ChannelCapability {
+ public:
+ using Mutex = mozilla::Mutex;
+ using Thread = mozilla::EventTargetCapability<nsISerialEventTarget>;
+
+ ChannelCapability(const char* mutex_name, nsISerialEventTarget* io_thread)
+ : send_mutex_(mutex_name), io_thread_(io_thread) {}
+
+ const Thread& IOThread() const MOZ_RETURN_CAPABILITY(io_thread_) {
+ return io_thread_;
+ }
+ Mutex& SendMutex() MOZ_RETURN_CAPABILITY(send_mutex_) { return send_mutex_; }
+
+ // Note that we're on the IO thread, and thus have shared access to values
+ // guarded by the channel capability for the thread-safety analysis.
+ void NoteOnIOThread() const MOZ_REQUIRES(io_thread_)
+ MOZ_ASSERT_SHARED_CAPABILITY(this) {}
+
+ // Note that we're holding the send mutex, and thus have shared access to
+ // values guarded by the channel capability for the thread-safety analysis.
+ void NoteSendMutex() const MOZ_REQUIRES(send_mutex_)
+ MOZ_ASSERT_SHARED_CAPABILITY(this) {}
+
+ // Note that we're holding the send mutex while on the IO thread, and thus
+ // have exclusive access to values guarded by the channel capability for the
+ // thread-safety analysis.
+ void NoteExclusiveAccess() const MOZ_REQUIRES(io_thread_, send_mutex_)
+ MOZ_ASSERT_CAPABILITY(this) {}
+
+ private:
+ mozilla::Mutex send_mutex_;
+ mozilla::EventTargetCapability<nsISerialEventTarget> io_thread_;
+};
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_CHANNEL_CAPABILITY_H_
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_posix.cc b/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
new file mode 100644
index 0000000000..0b34af40b1
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_posix.cc
@@ -0,0 +1,1256 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "chrome/common/ipc_channel_posix.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include "mozilla/Mutex.h"
+#if defined(XP_DARWIN)
+# include <mach/message.h>
+# include <mach/port.h>
+# include "mozilla/UniquePtrExtensions.h"
+# include "chrome/common/mach_ipc_mac.h"
+#endif
+#if defined(XP_DARWIN) || defined(XP_NETBSD)
+# include <sched.h>
+#endif
+#include <stddef.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/uio.h>
+
+#include <string>
+#include <map>
+
+#include "base/command_line.h"
+#include "base/eintr_wrapper.h"
+#include "base/logging.h"
+#include "base/process.h"
+#include "base/process_util.h"
+#include "base/string_util.h"
+#include "chrome/common/chrome_switches.h"
+#include "chrome/common/ipc_channel_utils.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Unused.h"
+
+// Use OS specific iovec array limit where it's possible.
+#if defined(IOV_MAX)
+static const size_t kMaxIOVecSize = IOV_MAX;
+#elif defined(ANDROID)
+static const size_t kMaxIOVecSize = 256;
+#else
+static const size_t kMaxIOVecSize = 16;
+#endif
+
+using namespace mozilla::ipc;
+
+namespace IPC {
+
+// IPC channels on Windows use named pipes (CreateNamedPipe()) with
+// channel ids as the pipe names. Channels on POSIX use anonymous
+// Unix domain sockets created via socketpair() as pipes. These don't
+// quite line up.
+//
+// When creating a child subprocess, the parent side of the fork
+// arranges it such that the initial control channel ends up on the
+// magic file descriptor gClientChannelFd in the child. Future
+// connections (file descriptors) can then be passed via that
+// connection via sendmsg().
+//
+// On Android, child processes are created as a service instead of
+// forking the parent process. The Android Binder service is used to
+// transport the IPC channel file descriptor to the child process.
+// So rather than re-mapping the file descriptor to a known value,
+// the received channel file descriptor is set by calling
+// SetClientChannelFd before gecko has been initialized and started
+// in the child process.
+
+//------------------------------------------------------------------------------
+namespace {
+
+// This is the file descriptor number that a client process expects to find its
+// IPC socket.
+static int gClientChannelFd =
+#if defined(MOZ_WIDGET_ANDROID)
+ // On android the fd is set at the time of child creation.
+ -1
+#else
+ 3
+#endif // defined(MOZ_WIDGET_ANDROID)
+ ;
+
+//------------------------------------------------------------------------------
+
+bool ErrorIsBrokenPipe(int err) { return err == EPIPE || err == ECONNRESET; }
+
+// Some Android ARM64 devices appear to have a bug where sendmsg
+// sometimes returns 0xFFFFFFFF, which we're assuming is a -1 that was
+// incorrectly truncated to 32-bit and then zero-extended.
+// See bug 1660826 for details.
+//
+// This is a workaround to detect that value and replace it with -1
+// (and check that there really was an error), because the largest
+// amount we'll ever write is Channel::kMaximumMessageSize (256MiB).
+//
+// The workaround is also enabled on x86_64 Android on debug builds,
+// although the bug isn't known to manifest there, so that there will
+// be some CI coverage of this code.
+
+static inline ssize_t corrected_sendmsg(int socket,
+ const struct msghdr* message,
+ int flags) {
+#if defined(ANDROID) && \
+ (defined(__aarch64__) || (defined(DEBUG) && defined(__x86_64__)))
+ static constexpr auto kBadValue = static_cast<ssize_t>(0xFFFFFFFF);
+ static_assert(kBadValue > 0);
+
+# ifdef MOZ_DIAGNOSTIC_ASSERT_ENABLED
+ errno = 0;
+# endif
+ ssize_t bytes_written = sendmsg(socket, message, flags);
+ if (bytes_written == kBadValue) {
+ MOZ_DIAGNOSTIC_ASSERT(errno != 0);
+ bytes_written = -1;
+ }
+ MOZ_DIAGNOSTIC_ASSERT(bytes_written < kBadValue);
+ return bytes_written;
+#else
+ return sendmsg(socket, message, flags);
+#endif
+}
+
+} // namespace
+//------------------------------------------------------------------------------
+
+#if defined(MOZ_WIDGET_ANDROID)
+void Channel::SetClientChannelFd(int fd) { gClientChannelFd = fd; }
+#endif // defined(MOZ_WIDGET_ANDROID)
+
+int Channel::GetClientChannelHandle() { return gClientChannelFd; }
+
+Channel::ChannelImpl::ChannelImpl(ChannelHandle pipe, Mode mode,
+ base::ProcessId other_pid)
+ : chan_cap_("ChannelImpl::SendMutex",
+ MessageLoopForIO::current()->SerialEventTarget()),
+ other_pid_(other_pid) {
+ Init(mode);
+ SetPipe(pipe.release());
+
+ EnqueueHelloMessage();
+}
+
+void Channel::ChannelImpl::SetPipe(int fd) {
+ chan_cap_.NoteExclusiveAccess();
+
+ pipe_ = fd;
+ pipe_buf_len_ = 0;
+ if (fd >= 0) {
+ int buf_len;
+ socklen_t optlen = sizeof(buf_len);
+ if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buf_len, &optlen) != 0) {
+ CHROMIUM_LOG(WARNING)
+ << "Unable to determine pipe buffer size: " << strerror(errno);
+ return;
+ }
+ CHECK(optlen == sizeof(buf_len));
+ CHECK(buf_len > 0);
+ pipe_buf_len_ = static_cast<unsigned>(buf_len);
+ }
+}
+
+bool Channel::ChannelImpl::PipeBufHasSpaceAfter(size_t already_written) {
+ // If the OS didn't tell us the buffer size for some reason, then
+ // don't apply this limitation on the amount we try to write.
+ return pipe_buf_len_ == 0 ||
+ static_cast<size_t>(pipe_buf_len_) > already_written;
+}
+
+void Channel::ChannelImpl::Init(Mode mode) {
+ // Verify that we fit in a "quantum-spaced" jemalloc bucket.
+ static_assert(sizeof(*this) <= 512, "Exceeded expected size class");
+
+ MOZ_RELEASE_ASSERT(kControlBufferHeaderSize >= CMSG_SPACE(0));
+ MOZ_RELEASE_ASSERT(kControlBufferSize >=
+ CMSG_SPACE(sizeof(int) * kControlBufferMaxFds));
+
+ chan_cap_.NoteExclusiveAccess();
+
+ mode_ = mode;
+ is_blocked_on_write_ = false;
+ partial_write_.reset();
+ input_buf_offset_ = 0;
+ input_buf_ = mozilla::MakeUnique<char[]>(Channel::kReadBufferSize);
+ input_cmsg_buf_ = mozilla::MakeUnique<char[]>(kControlBufferSize);
+ SetPipe(-1);
+ waiting_connect_ = true;
+#if defined(XP_DARWIN)
+ last_pending_fd_id_ = 0;
+ other_task_ = nullptr;
+#endif
+}
+
+bool Channel::ChannelImpl::EnqueueHelloMessage() {
+ mozilla::UniquePtr<Message> msg(
+ new Message(MSG_ROUTING_NONE, HELLO_MESSAGE_TYPE));
+ if (!msg->WriteInt(base::GetCurrentProcId())) {
+ CloseLocked();
+ return false;
+ }
+
+ OutputQueuePush(std::move(msg));
+ return true;
+}
+
+bool Channel::ChannelImpl::Connect(Listener* listener) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ if (pipe_ == -1) {
+ return false;
+ }
+
+ listener_ = listener;
+
+ return ContinueConnect();
+}
+
+bool Channel::ChannelImpl::ContinueConnect() {
+ chan_cap_.NoteExclusiveAccess();
+ MOZ_ASSERT(pipe_ != -1);
+
+#if defined(XP_DARWIN)
+ // If we're still waiting for our peer task to be provided, don't start
+ // listening yet. We'll start receiving messages once the task_t is set.
+ if (accept_mach_ports_ && privileged_ && !other_task_) {
+ MOZ_ASSERT(waiting_connect_);
+ return true;
+ }
+#endif
+
+ MessageLoopForIO::current()->WatchFileDescriptor(
+ pipe_, true, MessageLoopForIO::WATCH_READ, &read_watcher_, this);
+ waiting_connect_ = false;
+
+ return ProcessOutgoingMessages();
+}
+
+void Channel::ChannelImpl::SetOtherPid(base::ProcessId other_pid) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+ MOZ_RELEASE_ASSERT(
+ other_pid_ == base::kInvalidProcessId || other_pid_ == other_pid,
+ "Multiple sources of SetOtherPid disagree!");
+ other_pid_ = other_pid;
+}
+
+bool Channel::ChannelImpl::ProcessIncomingMessages() {
+ chan_cap_.NoteOnIOThread();
+
+ struct msghdr msg = {0};
+ struct iovec iov;
+
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = input_cmsg_buf_.get();
+
+ for (;;) {
+ msg.msg_controllen = kControlBufferSize;
+
+ if (pipe_ == -1) return false;
+
+ // In some cases the beginning of a message will be stored in input_buf_. We
+ // don't want to overwrite that, so we store the new data after it.
+ iov.iov_base = input_buf_.get() + input_buf_offset_;
+ iov.iov_len = Channel::kReadBufferSize - input_buf_offset_;
+
+ // Read from pipe.
+ // recvmsg() returns 0 if the connection has closed or EAGAIN if no data
+ // is waiting on the pipe.
+ ssize_t bytes_read = HANDLE_EINTR(recvmsg(pipe_, &msg, MSG_DONTWAIT));
+
+ if (bytes_read < 0) {
+ if (errno == EAGAIN) {
+ return true;
+ } else {
+ if (!ErrorIsBrokenPipe(errno)) {
+ CHROMIUM_LOG(ERROR)
+ << "pipe error (fd " << pipe_ << "): " << strerror(errno);
+ }
+ return false;
+ }
+ } else if (bytes_read == 0) {
+ // The pipe has closed...
+ Close();
+ return false;
+ }
+ DCHECK(bytes_read);
+
+ // a pointer to an array of |num_wire_fds| file descriptors from the read
+ const int* wire_fds = NULL;
+ unsigned num_wire_fds = 0;
+
+ // walk the list of control messages and, if we find an array of file
+ // descriptors, save a pointer to the array
+
+ // This next if statement is to work around an OSX issue where
+ // CMSG_FIRSTHDR will return non-NULL in the case that controllen == 0.
+ // Here's a test case:
+ //
+ // int main() {
+ // struct msghdr msg;
+ // msg.msg_control = &msg;
+ // msg.msg_controllen = 0;
+ // if (CMSG_FIRSTHDR(&msg))
+ // printf("Bug found!\n");
+ // }
+ if (msg.msg_controllen > 0) {
+ // On OSX, CMSG_FIRSTHDR doesn't handle the case where controllen is 0
+ // and will return a pointer into nowhere.
+ for (struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg;
+ cmsg = CMSG_NXTHDR(&msg, cmsg)) {
+ if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {
+ const unsigned payload_len = cmsg->cmsg_len - CMSG_LEN(0);
+ DCHECK(payload_len % sizeof(int) == 0);
+ wire_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
+ num_wire_fds = payload_len / 4;
+
+ if (msg.msg_flags & MSG_CTRUNC) {
+ CHROMIUM_LOG(ERROR)
+ << "SCM_RIGHTS message was truncated"
+ << " cmsg_len:" << cmsg->cmsg_len << " fd:" << pipe_;
+ for (unsigned i = 0; i < num_wire_fds; ++i)
+ IGNORE_EINTR(close(wire_fds[i]));
+ return false;
+ }
+ break;
+ }
+ }
+ }
+
+ // Process messages from input buffer.
+ const char* p = input_buf_.get();
+ const char* end = input_buf_.get() + input_buf_offset_ + bytes_read;
+
+ // A pointer to an array of |num_fds| file descriptors which includes any
+ // fds that have spilled over from a previous read.
+ const int* fds;
+ unsigned num_fds;
+ unsigned fds_i = 0; // the index of the first unused descriptor
+
+ if (input_overflow_fds_.empty()) {
+ fds = wire_fds;
+ num_fds = num_wire_fds;
+ } else {
+ // This code may look like a no-op in the case where
+ // num_wire_fds == 0, but in fact:
+ //
+ // 1. wire_fds will be nullptr, so passing it to memcpy is
+ // undefined behavior according to the C standard, even though
+ // the memcpy length is 0.
+ //
+ // 2. prev_size will be an out-of-bounds index for
+ // input_overflow_fds_; this is undefined behavior according to
+ // the C++ standard, even though the element only has its
+ // pointer taken and isn't accessed (and the corresponding
+ // operation on a C array would be defined).
+ //
+ // UBSan makes #1 a fatal error, and assertions in libstdc++ do
+ // the same for #2 if enabled.
+ if (num_wire_fds > 0) {
+ const size_t prev_size = input_overflow_fds_.size();
+ input_overflow_fds_.resize(prev_size + num_wire_fds);
+ memcpy(&input_overflow_fds_[prev_size], wire_fds,
+ num_wire_fds * sizeof(int));
+ }
+ fds = &input_overflow_fds_[0];
+ num_fds = input_overflow_fds_.size();
+ }
+
+ // The data for the message we're currently reading consists of any data
+ // stored in incoming_message_ followed by data in input_buf_ (followed by
+ // other messages).
+
+ // NOTE: We re-check `pipe_` after each message to make sure we weren't
+ // closed while calling `OnMessageReceived` or `OnChannelConnected`.
+ while (p < end && pipe_ != -1) {
+ // Try to figure out how big the message is. Size is 0 if we haven't read
+ // enough of the header to know the size.
+ uint32_t message_length = 0;
+ if (incoming_message_) {
+ message_length = incoming_message_->size();
+ } else {
+ message_length = Message::MessageSize(p, end);
+ }
+
+ if (!message_length) {
+ // We haven't seen the full message header.
+ MOZ_ASSERT(!incoming_message_);
+
+ // Move everything we have to the start of the buffer. We'll finish
+ // reading this message when we get more data. For now we leave it in
+ // input_buf_.
+ memmove(input_buf_.get(), p, end - p);
+ input_buf_offset_ = end - p;
+
+ break;
+ }
+
+ input_buf_offset_ = 0;
+
+ bool partial;
+ if (incoming_message_) {
+ // We already have some data for this message stored in
+ // incoming_message_. We want to append the new data there.
+ Message& m = *incoming_message_;
+
+ // How much data from this message remains to be added to
+ // incoming_message_?
+ MOZ_DIAGNOSTIC_ASSERT(message_length > m.CurrentSize());
+ uint32_t remaining = message_length - m.CurrentSize();
+
+ // How much data from this message is stored in input_buf_?
+ uint32_t in_buf = std::min(remaining, uint32_t(end - p));
+
+ m.InputBytes(p, in_buf);
+ p += in_buf;
+
+ // Are we done reading this message?
+ partial = in_buf != remaining;
+ } else {
+ // How much data from this message is stored in input_buf_?
+ uint32_t in_buf = std::min(message_length, uint32_t(end - p));
+
+ incoming_message_ = mozilla::MakeUnique<Message>(p, in_buf);
+ p += in_buf;
+
+ // Are we done reading this message?
+ partial = in_buf != message_length;
+ }
+
+ if (partial) {
+ break;
+ }
+
+ Message& m = *incoming_message_;
+
+ if (m.header()->num_handles) {
+ // the message has file descriptors
+ const char* error = NULL;
+ if (m.header()->num_handles > num_fds - fds_i) {
+ // the message has been completely received, but we didn't get
+ // enough file descriptors.
+ error = "Message needs unreceived descriptors";
+ }
+
+ if (m.header()->num_handles >
+ IPC::Message::MAX_DESCRIPTORS_PER_MESSAGE) {
+ // There are too many descriptors in this message
+ error = "Message requires an excessive number of descriptors";
+ }
+
+ if (error) {
+ CHROMIUM_LOG(WARNING)
+ << error << " channel:" << this << " message-type:" << m.type()
+ << " header()->num_handles:" << m.header()->num_handles
+ << " num_fds:" << num_fds << " fds_i:" << fds_i;
+ // close the existing file descriptors so that we don't leak them
+ for (unsigned i = fds_i; i < num_fds; ++i)
+ IGNORE_EINTR(close(fds[i]));
+ input_overflow_fds_.clear();
+ // abort the connection
+ return false;
+ }
+
+#if defined(XP_DARWIN)
+ // Send a message to the other side, indicating that we are now
+ // responsible for closing the descriptor.
+ auto fdAck = mozilla::MakeUnique<Message>(MSG_ROUTING_NONE,
+ RECEIVED_FDS_MESSAGE_TYPE);
+ DCHECK(m.fd_cookie() != 0);
+ fdAck->set_fd_cookie(m.fd_cookie());
+ {
+ mozilla::MutexAutoLock lock(SendMutex());
+ OutputQueuePush(std::move(fdAck));
+ }
+#endif
+
+ nsTArray<mozilla::UniqueFileHandle> handles(m.header()->num_handles);
+ for (unsigned end_i = fds_i + m.header()->num_handles; fds_i < end_i;
+ ++fds_i) {
+ handles.AppendElement(mozilla::UniqueFileHandle(fds[fds_i]));
+ }
+ m.SetAttachedFileHandles(std::move(handles));
+ }
+
+ // Note: We set other_pid_ below when we receive a Hello message (which
+ // has no routing ID), but we only emit a profiler marker for messages
+ // with a routing ID, so there's no conflict here.
+ AddIPCProfilerMarker(m, other_pid_, MessageDirection::eReceiving,
+ MessagePhase::TransferEnd);
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "received message on channel @" << this << " with type "
+ << m.type();
+#endif
+
+ if (m.routing_id() == MSG_ROUTING_NONE &&
+ m.type() == HELLO_MESSAGE_TYPE) {
+ // The Hello message contains only the process id.
+ int32_t other_pid = MessageIterator(m).NextInt();
+ SetOtherPid(other_pid);
+ listener_->OnChannelConnected(other_pid);
+#if defined(XP_DARWIN)
+ } else if (m.routing_id() == MSG_ROUTING_NONE &&
+ m.type() == RECEIVED_FDS_MESSAGE_TYPE) {
+ DCHECK(m.fd_cookie() != 0);
+ CloseDescriptors(m.fd_cookie());
+#endif
+ } else {
+ mozilla::LogIPCMessage::Run run(&m);
+#if defined(XP_DARWIN)
+ if (!AcceptMachPorts(m)) {
+ return false;
+ }
+#endif
+ listener_->OnMessageReceived(std::move(incoming_message_));
+ }
+
+ incoming_message_ = nullptr;
+ }
+
+ input_overflow_fds_ = std::vector<int>(&fds[fds_i], &fds[num_fds]);
+
+ // When the input data buffer is empty, the overflow fds should be too. If
+ // this is not the case, we probably have a rogue renderer which is trying
+ // to fill our descriptor table.
+ if (!incoming_message_ && input_buf_offset_ == 0 &&
+ !input_overflow_fds_.empty()) {
+ // We close these descriptors in Close()
+ return false;
+ }
+ }
+}
+
+bool Channel::ChannelImpl::ProcessOutgoingMessages() {
+ // NOTE: This method may be called on threads other than `IOThread()`.
+ chan_cap_.NoteSendMutex();
+
+ DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
+ // no connection?
+ is_blocked_on_write_ = false;
+
+ if (output_queue_.IsEmpty()) return true;
+
+ if (pipe_ == -1) return false;
+
+ // Write out all the messages we can till the write blocks or there are no
+ // more outgoing messages.
+ while (!output_queue_.IsEmpty()) {
+ Message* msg = output_queue_.FirstElement().get();
+
+ struct msghdr msgh = {0};
+
+ char cmsgBuf[kControlBufferSize];
+
+ if (partial_write_.isNothing()) {
+#if defined(XP_DARWIN)
+ if (!TransferMachPorts(*msg)) {
+ return false;
+ }
+#endif
+
+ if (msg->attached_handles_.Length() >
+ IPC::Message::MAX_DESCRIPTORS_PER_MESSAGE) {
+ MOZ_DIAGNOSTIC_ASSERT(false, "Too many file descriptors!");
+ CHROMIUM_LOG(FATAL) << "Too many file descriptors!";
+ // This should not be reached.
+ return false;
+ }
+
+ msg->header()->num_handles = msg->attached_handles_.Length();
+#if defined(XP_DARWIN)
+ if (!msg->attached_handles_.IsEmpty()) {
+ msg->set_fd_cookie(++last_pending_fd_id_);
+ }
+#endif
+
+ Pickle::BufferList::IterImpl iter(msg->Buffers());
+ MOZ_DIAGNOSTIC_ASSERT(!iter.Done(), "empty message");
+ partial_write_.emplace(PartialWrite{iter, msg->attached_handles_});
+
+ AddIPCProfilerMarker(*msg, other_pid_, MessageDirection::eSending,
+ MessagePhase::TransferStart);
+ }
+
+ if (partial_write_->iter_.Done()) {
+ MOZ_DIAGNOSTIC_ASSERT(false, "partial_write_->iter_ should not be done");
+ // report a send error to our caller, which will close the channel.
+ return false;
+ }
+
+ // How much of this message have we written so far?
+ Pickle::BufferList::IterImpl iter = partial_write_->iter_;
+ auto handles = partial_write_->handles_;
+
+ // Serialize attached file descriptors into the cmsg header. Only up to
+ // kControlBufferMaxFds can be serialized at once, so messages with more
+ // attachments must be sent over multiple `sendmsg` calls.
+ const size_t num_fds = std::min(handles.Length(), kControlBufferMaxFds);
+ size_t max_amt_to_write = iter.TotalBytesAvailable(msg->Buffers());
+ if (num_fds > 0) {
+ msgh.msg_control = cmsgBuf;
+ msgh.msg_controllen = CMSG_LEN(sizeof(int) * num_fds);
+ struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msgh);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = msgh.msg_controllen;
+ for (size_t i = 0; i < num_fds; ++i) {
+ reinterpret_cast<int*>(CMSG_DATA(cmsg))[i] = handles[i].get();
+ }
+
+ // Avoid writing one byte per remaining handle in excess of
+ // kControlBufferMaxFds. Each handle written will consume a minimum of 4
+ // bytes in the message (to store it's index), so we can depend on there
+ // being enough data to send every handle.
+ size_t remaining = handles.Length() - num_fds;
+ MOZ_ASSERT(max_amt_to_write > remaining,
+ "must be at least one byte in the message for each handle");
+ max_amt_to_write -= remaining;
+ }
+
+ // Store remaining segments to write into iovec.
+ //
+ // Don't add more than kMaxIOVecSize iovecs so that we avoid
+ // OS-dependent limits. Also, stop adding iovecs if we've already
+ // prepared to write at least the full buffer size.
+ struct iovec iov[kMaxIOVecSize];
+ size_t iov_count = 0;
+ size_t amt_to_write = 0;
+ while (!iter.Done() && iov_count < kMaxIOVecSize &&
+ PipeBufHasSpaceAfter(amt_to_write) &&
+ amt_to_write < max_amt_to_write) {
+ char* data = iter.Data();
+ size_t size =
+ std::min(iter.RemainingInSegment(), max_amt_to_write - amt_to_write);
+
+ iov[iov_count].iov_base = data;
+ iov[iov_count].iov_len = size;
+ iov_count++;
+ amt_to_write += size;
+ iter.Advance(msg->Buffers(), size);
+ }
+ MOZ_ASSERT(amt_to_write <= max_amt_to_write);
+ MOZ_ASSERT(amt_to_write > 0);
+
+ const bool intentional_short_write = !iter.Done();
+ msgh.msg_iov = iov;
+ msgh.msg_iovlen = iov_count;
+
+ ssize_t bytes_written =
+ HANDLE_EINTR(corrected_sendmsg(pipe_, &msgh, MSG_DONTWAIT));
+
+ if (bytes_written < 0) {
+ switch (errno) {
+ case EAGAIN:
+ // Not an error; the sendmsg would have blocked, so return to the
+ // event loop and try again later.
+ break;
+#if defined(XP_DARWIN) || defined(XP_NETBSD)
+ // (Note: this comment is copied from https://crrev.com/86c3d9ef4fdf6;
+ // see also bug 1142693 comment #73.)
+ //
+ // On OS X if sendmsg() is trying to send fds between processes and
+ // there isn't enough room in the output buffer to send the fd
+ // structure over atomically then EMSGSIZE is returned. The same
+ // applies to NetBSD as well.
+ //
+ // EMSGSIZE presents a problem since the system APIs can only call us
+ // when there's room in the socket buffer and not when there is
+ // "enough" room.
+ //
+ // The current behavior is to return to the event loop when EMSGSIZE
+ // is received and hopefull service another FD. This is however still
+ // technically a busy wait since the event loop will call us right
+ // back until the receiver has read enough data to allow passing the
+ // FD over atomically.
+ case EMSGSIZE:
+ // Because this is likely to result in a busy-wait, we'll try to make
+ // it easier for the receiver to make progress, but only if we're on
+ // the I/O thread already.
+ if (IOThread().IsOnCurrentThread()) {
+ sched_yield();
+ }
+ break;
+#endif
+ default:
+ if (!ErrorIsBrokenPipe(errno)) {
+ CHROMIUM_LOG(ERROR) << "pipe error: " << strerror(errno);
+ }
+ return false;
+ }
+ }
+
+ if (intentional_short_write ||
+ static_cast<size_t>(bytes_written) != amt_to_write) {
+ // If write() fails with EAGAIN or EMSGSIZE then bytes_written will be -1.
+ if (bytes_written > 0) {
+ MOZ_DIAGNOSTIC_ASSERT(intentional_short_write ||
+ static_cast<size_t>(bytes_written) <
+ amt_to_write);
+ partial_write_->iter_.AdvanceAcrossSegments(msg->Buffers(),
+ bytes_written);
+ partial_write_->handles_ = handles.From(num_fds);
+ // We should not hit the end of the buffer.
+ MOZ_DIAGNOSTIC_ASSERT(!partial_write_->iter_.Done());
+ }
+
+ is_blocked_on_write_ = true;
+ if (IOThread().IsOnCurrentThread()) {
+ // If we're on the I/O thread already, tell libevent to call us back
+ // when things are unblocked.
+ MessageLoopForIO::current()->WatchFileDescriptor(
+ pipe_,
+ false, // One shot
+ MessageLoopForIO::WATCH_WRITE, &write_watcher_, this);
+ } else {
+ // Otherwise, emulate being called back from libevent on the I/O thread,
+ // which will re-try the write, and then potentially start watching if
+ // still necessary.
+ IOThread().Dispatch(mozilla::NewRunnableMethod<int>(
+ "ChannelImpl::ContinueProcessOutgoing", this,
+ &ChannelImpl::OnFileCanWriteWithoutBlocking, -1));
+ }
+ return true;
+ } else {
+ MOZ_ASSERT(partial_write_->handles_.Length() == num_fds,
+ "not all handles were sent");
+ partial_write_.reset();
+
+#if defined(XP_DARWIN)
+ if (!msg->attached_handles_.IsEmpty()) {
+ pending_fds_.push_back(PendingDescriptors{
+ msg->fd_cookie(), std::move(msg->attached_handles_)});
+ }
+#else
+ if (bytes_written > 0) {
+ msg->attached_handles_.Clear();
+ }
+#endif
+
+ // Message sent OK!
+
+ AddIPCProfilerMarker(*msg, other_pid_, MessageDirection::eSending,
+ MessagePhase::TransferEnd);
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "sent message @" << msg << " on channel @" << this
+ << " with type " << msg->type();
+#endif
+ OutputQueuePop();
+ // msg has been destroyed, so clear the dangling reference.
+ msg = nullptr;
+ }
+ }
+ return true;
+}
+
+bool Channel::ChannelImpl::Send(mozilla::UniquePtr<Message> message) {
+ // NOTE: This method may be called on threads other than `IOThread()`.
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteSendMutex();
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "sending message @" << message.get() << " on channel @" << this
+ << " with type " << message->type() << " ("
+ << output_queue_.Count() << " in queue)";
+#endif
+
+ // If the channel has been closed, ProcessOutgoingMessages() is never going
+ // to pop anything off output_queue; output_queue will only get emptied when
+ // the channel is destructed. We might as well delete message now, instead
+ // of waiting for the channel to be destructed.
+ if (pipe_ == -1) {
+ if (mozilla::ipc::LoggingEnabled()) {
+ fprintf(stderr,
+ "Can't send message %s, because this channel is closed.\n",
+ message->name());
+ }
+ return false;
+ }
+
+ OutputQueuePush(std::move(message));
+ if (!waiting_connect_) {
+ if (!is_blocked_on_write_) {
+ if (!ProcessOutgoingMessages()) return false;
+ }
+ }
+
+ return true;
+}
+
+// Called by libevent when we can read from th pipe without blocking.
+void Channel::ChannelImpl::OnFileCanReadWithoutBlocking(int fd) {
+ IOThread().AssertOnCurrentThread();
+ chan_cap_.NoteOnIOThread();
+
+ if (!waiting_connect_ && fd == pipe_ && pipe_ != -1) {
+ if (!ProcessIncomingMessages()) {
+ Close();
+ listener_->OnChannelError();
+ // The OnChannelError() call may delete this, so we need to exit now.
+ return;
+ }
+ }
+}
+
+#if defined(XP_DARWIN)
+void Channel::ChannelImpl::CloseDescriptors(uint32_t pending_fd_id) {
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ DCHECK(pending_fd_id != 0);
+ for (std::list<PendingDescriptors>::iterator i = pending_fds_.begin();
+ i != pending_fds_.end(); i++) {
+ if ((*i).id == pending_fd_id) {
+ pending_fds_.erase(i);
+ return;
+ }
+ }
+ DCHECK(false) << "pending_fd_id not in our list!";
+}
+#endif
+
+void Channel::ChannelImpl::OutputQueuePush(mozilla::UniquePtr<Message> msg) {
+ chan_cap_.NoteSendMutex();
+
+ mozilla::LogIPCMessage::LogDispatchWithPid(msg.get(), other_pid_);
+
+ MOZ_DIAGNOSTIC_ASSERT(pipe_ != -1);
+ msg->AssertAsLargeAsHeader();
+ output_queue_.Push(std::move(msg));
+}
+
+void Channel::ChannelImpl::OutputQueuePop() {
+ // Clear any reference to the front of output_queue_ before we destroy it.
+ partial_write_.reset();
+
+ mozilla::UniquePtr<Message> message = output_queue_.Pop();
+}
+
+// Called by libevent when we can write to the pipe without blocking.
+void Channel::ChannelImpl::OnFileCanWriteWithoutBlocking(int fd) {
+ RefPtr<ChannelImpl> grip(this);
+ IOThread().AssertOnCurrentThread();
+ mozilla::ReleasableMutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+ if (pipe_ != -1 && !ProcessOutgoingMessages()) {
+ CloseLocked();
+ lock.Unlock();
+ listener_->OnChannelError();
+ }
+}
+
+void Channel::ChannelImpl::Close() {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ CloseLocked();
+}
+
+void Channel::ChannelImpl::CloseLocked() {
+ chan_cap_.NoteExclusiveAccess();
+
+ // Close can be called multiple times, so we need to make sure we're
+ // idempotent.
+
+ // Unregister libevent for the FIFO and close it.
+ read_watcher_.StopWatchingFileDescriptor();
+ write_watcher_.StopWatchingFileDescriptor();
+ if (pipe_ != -1) {
+ IGNORE_EINTR(close(pipe_));
+ SetPipe(-1);
+ }
+
+ while (!output_queue_.IsEmpty()) {
+ OutputQueuePop();
+ }
+
+ // Close any outstanding, received file descriptors
+ for (std::vector<int>::iterator i = input_overflow_fds_.begin();
+ i != input_overflow_fds_.end(); ++i) {
+ IGNORE_EINTR(close(*i));
+ }
+ input_overflow_fds_.clear();
+
+#if defined(XP_DARWIN)
+ pending_fds_.clear();
+
+ other_task_ = nullptr;
+#endif
+}
+
+#if defined(XP_DARWIN)
+void Channel::ChannelImpl::SetOtherMachTask(task_t task) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ if (NS_WARN_IF(pipe_ == -1)) {
+ return;
+ }
+
+ MOZ_ASSERT(accept_mach_ports_ && privileged_ && waiting_connect_);
+ other_task_ = mozilla::RetainMachSendRight(task);
+ // Now that `other_task_` is provided, we can continue connecting.
+ ContinueConnect();
+}
+
+void Channel::ChannelImpl::StartAcceptingMachPorts(Mode mode) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ if (accept_mach_ports_) {
+ MOZ_ASSERT(privileged_ == (MODE_SERVER == mode));
+ return;
+ }
+ accept_mach_ports_ = true;
+ privileged_ = MODE_SERVER == mode;
+}
+
+//------------------------------------------------------------------------------
+// Mach port transferring logic
+//
+// It is currently not possible to directly transfer a mach send right between
+// two content processes using SCM_RIGHTS, unlike how we can handle file
+// descriptors. This means that mach ports need to be transferred through a
+// separate mechanism. This file only implements support for transferring mach
+// ports between a (potentially sandboxed) child process and the parent process.
+// Support for transferring mach ports between other process pairs is handled by
+// `NodeController`, which is responsible for relaying messages which carry
+// handles via the parent process.
+//
+// The logic which we use for doing this is based on the following from
+// Chromium, which pioneered this technique. As of this writing, chromium no
+// longer uses this strategy, as all IPC messages are sent using mach ports on
+// macOS.
+// https://source.chromium.org/chromium/chromium/src/+/9f707e5e04598d8303fa99ca29eb507c839767d8:mojo/core/mach_port_relay.cc
+// https://source.chromium.org/chromium/chromium/src/+/9f707e5e04598d8303fa99ca29eb507c839767d8:base/mac/mach_port_util.cc.
+//
+// As we only need to consider messages between the privileged (parent) and
+// unprivileged (child) processes in this code, there are 2 relevant cases which
+// we need to handle:
+//
+// # Unprivileged (child) to Privileged (parent)
+//
+// As the privileged process has access to the unprivileged process' `task_t`,
+// it is possible to directly extract the mach port from the target process'
+// address space, given its name, using `mach_port_extract_right`.
+//
+// To transfer the port, the unprivileged process will leak a reference to the
+// send right, and include the port's name in the message footer. The privileged
+// process will extract that port right (and drop the reference in the old
+// process) using `mach_port_extract_right` with `MACH_MSG_TYPE_MOVE_SEND`. The
+// call to `mach_port_extract_right` is handled by `BrokerExtractSendRight`
+//
+// # Privileged (parent) to Unprivileged (child)
+//
+// Unfortunately, the process of transferring a right into a target process is
+// more complex. The only well-supported way to transfer a right into a process
+// is by sending it with `mach_msg`, and receiving it on the other side [1].
+//
+// To work around this, the privileged process uses `mach_port_allocate` to
+// create a new receive right in the target process using its `task_t`, and
+// `mach_port_extract_right` to extract a send-once right to that port. It then
+// sends a message to the port with port we're intending to send as an
+// attachment. This is handled by `BrokerTransferSendRight`, which returns the
+// name of the newly created receive right in the target process to be sent in
+// the message footer.
+//
+// In the unprivileged process, `mach_msg` is used to receive a single message
+// from the receive right, which will have the actual port we were trying to
+// transfer as an attachment. This is handled by the `MachReceivePortSendRight`
+// function.
+//
+// [1] We cannot use `mach_port_insert_right` to transfer the right into the
+// target process, as that method requires explicitly specifying the remote
+// port's name, and we do not control the port name allocator.
+
+// Extract a send right from the given peer task. A reference to the remote
+// right will be dropped. See comment above for details.
+static mozilla::UniqueMachSendRight BrokerExtractSendRight(
+ task_t task, mach_port_name_t name) {
+ mach_port_t extractedRight = MACH_PORT_NULL;
+ mach_msg_type_name_t extractedRightType;
+ kern_return_t kr =
+ mach_port_extract_right(task, name, MACH_MSG_TYPE_MOVE_SEND,
+ &extractedRight, &extractedRightType);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR) << "failed to extract port right from other process. "
+ << mach_error_string(kr);
+ return nullptr;
+ }
+ MOZ_ASSERT(extractedRightType == MACH_MSG_TYPE_PORT_SEND,
+ "We asked the OS for a send port");
+ return mozilla::UniqueMachSendRight(extractedRight);
+}
+
+// Transfer a send right to the given peer task. The name of a receive right in
+// the remote process will be returned if successful. The sent port can be
+// obtained from that port in the peer task using `MachReceivePortSendRight`.
+// See comment above for details.
+static mozilla::Maybe<mach_port_name_t> BrokerTransferSendRight(
+ task_t task, mozilla::UniqueMachSendRight port_to_send) {
+ mach_port_name_t endpoint;
+ kern_return_t kr =
+ mach_port_allocate(task, MACH_PORT_RIGHT_RECEIVE, &endpoint);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR)
+ << "Unable to create receive right in TransferMachPorts. "
+ << mach_error_string(kr);
+ return mozilla::Nothing();
+ }
+
+ // Clean up the endpoint on error.
+ auto destroyEndpoint =
+ mozilla::MakeScopeExit([&] { mach_port_deallocate(task, endpoint); });
+
+ // Change its message queue limit so that it accepts one message.
+ mach_port_limits limits = {};
+ limits.mpl_qlimit = 1;
+ kr = mach_port_set_attributes(task, endpoint, MACH_PORT_LIMITS_INFO,
+ reinterpret_cast<mach_port_info_t>(&limits),
+ MACH_PORT_LIMITS_INFO_COUNT);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR)
+ << "Unable configure receive right in TransferMachPorts. "
+ << mach_error_string(kr);
+ return mozilla::Nothing();
+ }
+
+ // Get a send right.
+ mach_port_t send_once_right;
+ mach_msg_type_name_t send_right_type;
+ kr = mach_port_extract_right(task, endpoint, MACH_MSG_TYPE_MAKE_SEND_ONCE,
+ &send_once_right, &send_right_type);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR) << "Unable extract send right in TransferMachPorts. "
+ << mach_error_string(kr);
+ return mozilla::Nothing();
+ }
+ MOZ_ASSERT(MACH_MSG_TYPE_PORT_SEND_ONCE == send_right_type);
+
+ kr = MachSendPortSendRight(send_once_right, port_to_send.get(),
+ mozilla::Some(0), MACH_MSG_TYPE_MOVE_SEND_ONCE);
+ if (kr != KERN_SUCCESS) {
+ // This right will be destroyed due to being a SEND_ONCE right if we
+ // succeed.
+ mach_port_deallocate(mach_task_self(), send_once_right);
+ CHROMIUM_LOG(ERROR) << "Unable to transfer right in TransferMachPorts. "
+ << mach_error_string(kr);
+ return mozilla::Nothing();
+ }
+
+ destroyEndpoint.release();
+ return mozilla::Some(endpoint);
+}
+
+// Process footer information attached to the message, and acquire owning
+// references to any transferred mach ports. See comment above for details.
+bool Channel::ChannelImpl::AcceptMachPorts(Message& msg) {
+ chan_cap_.NoteOnIOThread();
+
+ uint32_t num_send_rights = msg.header()->num_send_rights;
+ if (num_send_rights == 0) {
+ return true;
+ }
+
+ if (!accept_mach_ports_) {
+ CHROMIUM_LOG(ERROR) << "invalid message: " << msg.name()
+ << ". channel is not configured to accept mach ports";
+ return false;
+ }
+
+ // Read in the payload from the footer, truncating the message.
+ nsTArray<uint32_t> payload;
+ payload.AppendElements(num_send_rights);
+ if (!msg.ReadFooter(payload.Elements(), num_send_rights * sizeof(uint32_t),
+ /* truncate */ true)) {
+ CHROMIUM_LOG(ERROR) << "failed to read mach port payload from message";
+ return false;
+ }
+ msg.header()->num_send_rights = 0;
+
+ // Read in the handles themselves, transferring ownership as required.
+ nsTArray<mozilla::UniqueMachSendRight> rights(num_send_rights);
+ for (uint32_t name : payload) {
+ mozilla::UniqueMachSendRight right;
+ if (privileged_) {
+ if (!other_task_) {
+ CHROMIUM_LOG(ERROR) << "other_task_ is invalid in AcceptMachPorts";
+ return false;
+ }
+ right = BrokerExtractSendRight(other_task_.get(), name);
+ } else {
+ kern_return_t kr = MachReceivePortSendRight(
+ mozilla::UniqueMachReceiveRight(name), mozilla::Some(0), &right);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR)
+ << "failed to receive mach send right. " << mach_error_string(kr);
+ return false;
+ }
+ }
+ if (!right) {
+ return false;
+ }
+ rights.AppendElement(std::move(right));
+ }
+
+ // We're done with the handle footer, truncate the message at that point.
+ msg.attached_send_rights_ = std::move(rights);
+ MOZ_ASSERT(msg.num_send_rights() == num_send_rights);
+ return true;
+}
+
+// Transfer ownership of any attached mach ports to the peer task, and add the
+// required information for AcceptMachPorts to the message footer. See comment
+// above for details.
+bool Channel::ChannelImpl::TransferMachPorts(Message& msg) {
+ uint32_t num_send_rights = msg.num_send_rights();
+ if (num_send_rights == 0) {
+ return true;
+ }
+
+ if (!accept_mach_ports_) {
+ CHROMIUM_LOG(ERROR) << "cannot send message: " << msg.name()
+ << ". channel is not configured to accept mach ports";
+ return false;
+ }
+
+# ifdef DEBUG
+ uint32_t rights_offset = msg.header()->payload_size;
+# endif
+
+ nsTArray<uint32_t> payload(num_send_rights);
+ for (auto& port_to_send : msg.attached_send_rights_) {
+ if (privileged_) {
+ if (!other_task_) {
+ CHROMIUM_LOG(ERROR) << "other_task_ is invalid in TransferMachPorts";
+ return false;
+ }
+ mozilla::Maybe<mach_port_name_t> endpoint =
+ BrokerTransferSendRight(other_task_.get(), std::move(port_to_send));
+ if (!endpoint) {
+ return false;
+ }
+ payload.AppendElement(*endpoint);
+ } else {
+ payload.AppendElement(port_to_send.release());
+ }
+ }
+ msg.attached_send_rights_.Clear();
+
+ msg.WriteFooter(payload.Elements(), payload.Length() * sizeof(uint32_t));
+ msg.header()->num_send_rights = num_send_rights;
+
+ MOZ_ASSERT(msg.header()->payload_size ==
+ rights_offset + (sizeof(uint32_t) * num_send_rights),
+ "Unexpected number of bytes written for send rights footer?");
+ return true;
+}
+#endif
+
+//------------------------------------------------------------------------------
+// Channel's methods simply call through to ChannelImpl.
+Channel::Channel(ChannelHandle pipe, Mode mode, base::ProcessId other_pid)
+ : channel_impl_(new ChannelImpl(std::move(pipe), mode, other_pid)) {
+ MOZ_COUNT_CTOR(IPC::Channel);
+}
+
+Channel::~Channel() { MOZ_COUNT_DTOR(IPC::Channel); }
+
+bool Channel::Connect(Listener* listener) {
+ return channel_impl_->Connect(listener);
+}
+
+void Channel::Close() { channel_impl_->Close(); }
+
+bool Channel::Send(mozilla::UniquePtr<Message> message) {
+ return channel_impl_->Send(std::move(message));
+}
+
+void Channel::SetOtherPid(base::ProcessId other_pid) {
+ channel_impl_->SetOtherPid(other_pid);
+}
+
+bool Channel::IsClosed() const { return channel_impl_->IsClosed(); }
+
+#if defined(XP_DARWIN)
+void Channel::SetOtherMachTask(task_t task) {
+ channel_impl_->SetOtherMachTask(task);
+}
+
+void Channel::StartAcceptingMachPorts(Mode mode) {
+ channel_impl_->StartAcceptingMachPorts(mode);
+}
+#endif
+
+// static
+bool Channel::CreateRawPipe(ChannelHandle* server, ChannelHandle* client) {
+ int fds[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
+ mozilla::ipc::AnnotateCrashReportWithErrno(
+ CrashReporter::Annotation::IpcCreatePipeSocketPairErrno, errno);
+ return false;
+ }
+
+ auto configureFd = [](int fd) -> bool {
+ // Mark the endpoints as non-blocking
+ if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
+ mozilla::ipc::AnnotateCrashReportWithErrno(
+ CrashReporter::Annotation::IpcCreatePipeFcntlErrno, errno);
+ return false;
+ }
+
+ // Mark the pipes as FD_CLOEXEC
+ int flags = fcntl(fd, F_GETFD);
+ if (flags == -1) {
+ mozilla::ipc::AnnotateCrashReportWithErrno(
+ CrashReporter::Annotation::IpcCreatePipeCloExecErrno, errno);
+ return false;
+ }
+ flags |= FD_CLOEXEC;
+ if (fcntl(fd, F_SETFD, flags) == -1) {
+ mozilla::ipc::AnnotateCrashReportWithErrno(
+ CrashReporter::Annotation::IpcCreatePipeCloExecErrno, errno);
+ return false;
+ }
+ return true;
+ };
+
+ if (!configureFd(fds[0]) || !configureFd(fds[1])) {
+ IGNORE_EINTR(close(fds[0]));
+ IGNORE_EINTR(close(fds[1]));
+ return false;
+ }
+
+ server->reset(fds[0]);
+ client->reset(fds[1]);
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_posix.h b/ipc/chromium/src/chrome/common/ipc_channel_posix.h
new file mode 100644
index 0000000000..b70640d04e
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_posix.h
@@ -0,0 +1,203 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef CHROME_COMMON_IPC_CHANNEL_POSIX_H_
+#define CHROME_COMMON_IPC_CHANNEL_POSIX_H_
+
+#include "chrome/common/ipc_channel.h"
+#include "chrome/common/ipc_channel_capability.h"
+
+#include <sys/socket.h> // for CMSG macros
+
+#include <atomic>
+#include <string>
+#include <vector>
+#include <list>
+
+#include "base/message_loop.h"
+#include "base/process.h"
+#include "base/task.h"
+
+#include "mozilla/Maybe.h"
+#include "mozilla/Queue.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "nsISupports.h"
+
+namespace IPC {
+
+// An implementation of ChannelImpl for POSIX systems that works via
+// socketpairs. See the .cc file for an overview of the implementation.
+class Channel::ChannelImpl : public MessageLoopForIO::Watcher {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DELETE_ON_EVENT_TARGET(
+ ChannelImpl, IOThread().GetEventTarget());
+
+ // Mirror methods of Channel, see ipc_channel.h for description.
+ ChannelImpl(ChannelHandle pipe, Mode mode, base::ProcessId other_pid);
+ bool Connect(Listener* listener) MOZ_EXCLUDES(SendMutex());
+ void Close() MOZ_EXCLUDES(SendMutex());
+
+ // NOTE: `Send` may be called on threads other than the I/O thread.
+ bool Send(mozilla::UniquePtr<Message> message) MOZ_EXCLUDES(SendMutex());
+
+ void SetOtherPid(base::ProcessId other_pid);
+
+ // See the comment in ipc_channel.h for info on IsClosed()
+ // NOTE: `IsClosed` may be called on threads other than the I/O thread.
+ bool IsClosed() MOZ_EXCLUDES(SendMutex()) {
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteSendMutex();
+ return pipe_ == -1;
+ }
+
+#if defined(XP_DARWIN)
+ void SetOtherMachTask(task_t task) MOZ_EXCLUDES(SendMutex());
+
+ void StartAcceptingMachPorts(Mode mode) MOZ_EXCLUDES(SendMutex());
+#endif
+
+ private:
+ ~ChannelImpl() { Close(); }
+
+ void Init(Mode mode) MOZ_REQUIRES(SendMutex(), IOThread());
+ void SetPipe(int fd) MOZ_REQUIRES(SendMutex(), IOThread());
+ bool PipeBufHasSpaceAfter(size_t already_written)
+ MOZ_REQUIRES_SHARED(chan_cap_);
+ bool EnqueueHelloMessage() MOZ_REQUIRES(SendMutex(), IOThread());
+ bool ContinueConnect() MOZ_REQUIRES(SendMutex(), IOThread());
+ void CloseLocked() MOZ_REQUIRES(SendMutex(), IOThread());
+
+ bool ProcessIncomingMessages() MOZ_REQUIRES(IOThread());
+ bool ProcessOutgoingMessages() MOZ_REQUIRES(SendMutex());
+
+ // MessageLoopForIO::Watcher implementation.
+ virtual void OnFileCanReadWithoutBlocking(int fd) override;
+ virtual void OnFileCanWriteWithoutBlocking(int fd) override;
+
+#if defined(XP_DARWIN)
+ void CloseDescriptors(uint32_t pending_fd_id) MOZ_REQUIRES(IOThread())
+ MOZ_EXCLUDES(SendMutex());
+
+ // Called on a Message immediately before it is sent/recieved to transfer
+ // handles to the remote process, or accept handles from the remote process.
+ bool AcceptMachPorts(Message& msg) MOZ_REQUIRES(IOThread());
+ bool TransferMachPorts(Message& msg) MOZ_REQUIRES_SHARED(chan_cap_);
+#endif
+
+ void OutputQueuePush(mozilla::UniquePtr<Message> msg)
+ MOZ_REQUIRES(SendMutex());
+ void OutputQueuePop() MOZ_REQUIRES(SendMutex());
+
+ const ChannelCapability::Thread& IOThread() const
+ MOZ_RETURN_CAPABILITY(chan_cap_.IOThread()) {
+ return chan_cap_.IOThread();
+ }
+
+ ChannelCapability::Mutex& SendMutex()
+ MOZ_RETURN_CAPABILITY(chan_cap_.SendMutex()) {
+ return chan_cap_.SendMutex();
+ }
+
+ // Compound capability of a Mutex and the IO thread.
+ ChannelCapability chan_cap_;
+
+ Mode mode_ MOZ_GUARDED_BY(IOThread());
+
+ // After accepting one client connection on our server socket we want to
+ // stop listening.
+ MessageLoopForIO::FileDescriptorWatcher read_watcher_
+ MOZ_GUARDED_BY(IOThread());
+ MessageLoopForIO::FileDescriptorWatcher write_watcher_
+ MOZ_GUARDED_BY(IOThread());
+
+ // Indicates whether we're currently blocked waiting for a write to complete.
+ bool is_blocked_on_write_ MOZ_GUARDED_BY(SendMutex()) = false;
+
+ // If sending a message blocks then we use this iterator to keep track of
+ // where in the message we are. It gets reset when the message is finished
+ // sending.
+ struct PartialWrite {
+ Pickle::BufferList::IterImpl iter_;
+ mozilla::Span<const mozilla::UniqueFileHandle> handles_;
+ };
+ mozilla::Maybe<PartialWrite> partial_write_ MOZ_GUARDED_BY(SendMutex());
+
+ int pipe_ MOZ_GUARDED_BY(chan_cap_);
+ // The SO_SNDBUF value of pipe_, or 0 if unknown.
+ unsigned pipe_buf_len_ MOZ_GUARDED_BY(chan_cap_);
+
+ Listener* listener_ MOZ_GUARDED_BY(IOThread());
+
+ // Messages to be sent are queued here.
+ mozilla::Queue<mozilla::UniquePtr<Message>, 64> output_queue_
+ MOZ_GUARDED_BY(SendMutex());
+
+ // We read from the pipe into these buffers.
+ size_t input_buf_offset_ MOZ_GUARDED_BY(IOThread());
+ mozilla::UniquePtr<char[]> input_buf_ MOZ_GUARDED_BY(IOThread());
+ mozilla::UniquePtr<char[]> input_cmsg_buf_ MOZ_GUARDED_BY(IOThread());
+
+ // The control message buffer will hold all of the file descriptors that will
+ // be read in during a single recvmsg call. Message::WriteFileDescriptor
+ // always writes one word of data for every file descriptor added to the
+ // message, and the number of file descriptors per recvmsg will not exceed
+ // kControlBufferMaxFds. This is based on the true maximum SCM_RIGHTS
+ // descriptor count, which is just over 250 on both Linux and macOS.
+ //
+ // This buffer also holds a control message header of size CMSG_SPACE(0)
+ // bytes. However, CMSG_SPACE is not a constant on Macs, so we can't use it
+ // here. Consequently, we pick a number here that is at least CMSG_SPACE(0) on
+ // all platforms. We assert at runtime, in Channel::ChannelImpl::Init, that
+ // it's big enough.
+ static constexpr size_t kControlBufferMaxFds = 200;
+ static constexpr size_t kControlBufferHeaderSize = 32;
+ static constexpr size_t kControlBufferSize =
+ kControlBufferMaxFds * sizeof(int) + kControlBufferHeaderSize;
+
+ // Large incoming messages that span multiple pipe buffers get built-up in the
+ // buffers of this message.
+ mozilla::UniquePtr<Message> incoming_message_ MOZ_GUARDED_BY(IOThread());
+ std::vector<int> input_overflow_fds_ MOZ_GUARDED_BY(IOThread());
+
+ // Will be set to `true` until `Connect()` has been called and communication
+ // is ready. For privileged connections on macOS, this will not be cleared
+ // until the peer mach port has been provided to allow transferring mach
+ // ports.
+ bool waiting_connect_ MOZ_GUARDED_BY(chan_cap_) = true;
+
+ // We keep track of the PID of the other side of this channel so that we can
+ // record this when generating logs of IPC messages.
+ base::ProcessId other_pid_ MOZ_GUARDED_BY(chan_cap_) =
+ base::kInvalidProcessId;
+
+#if defined(XP_DARWIN)
+ struct PendingDescriptors {
+ uint32_t id;
+ nsTArray<mozilla::UniqueFileHandle> handles;
+ };
+
+ std::list<PendingDescriptors> pending_fds_ MOZ_GUARDED_BY(SendMutex());
+
+ // A generation ID for RECEIVED_FD messages.
+ uint32_t last_pending_fd_id_ MOZ_GUARDED_BY(SendMutex()) = 0;
+
+ // Whether or not to accept mach ports from a remote process, and whether this
+ // process is the privileged side of a IPC::Channel which can transfer mach
+ // ports.
+ bool accept_mach_ports_ MOZ_GUARDED_BY(chan_cap_) = false;
+ bool privileged_ MOZ_GUARDED_BY(chan_cap_) = false;
+
+ // If available, the task port for the remote process.
+ mozilla::UniqueMachSendRight other_task_ MOZ_GUARDED_BY(chan_cap_);
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(ChannelImpl);
+};
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_CHANNEL_POSIX_H_
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_utils.cc b/ipc/chromium/src/chrome/common/ipc_channel_utils.cc
new file mode 100644
index 0000000000..7e737762f3
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_utils.cc
@@ -0,0 +1,58 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_channel_utils.h"
+
+#include "mozilla/ProfilerMarkers.h"
+#include "chrome/common/ipc_message.h"
+#include "base/process.h"
+
+namespace IPC {
+
+void AddIPCProfilerMarker(const Message& aMessage, int32_t aOtherPid,
+ mozilla::ipc::MessageDirection aDirection,
+ mozilla::ipc::MessagePhase aPhase) {
+ if (aMessage.routing_id() != MSG_ROUTING_NONE &&
+ profiler_feature_active(ProfilerFeature::IPCMessages)) {
+ if (static_cast<base::ProcessId>(aOtherPid) == base::kInvalidProcessId) {
+ DLOG(WARNING) << "Unable to record IPC profile marker, other PID not set";
+ return;
+ }
+
+ if (profiler_is_locked_on_current_thread()) {
+ // One of the profiler mutexes is locked on this thread, don't record
+ // markers, because we don't want to expose profiler IPCs due to the
+ // profiler itself, and also to avoid possible re-entrancy issues.
+ return;
+ }
+
+ // The current timestamp must be given to the `IPCMarker` payload.
+ [[maybe_unused]] const mozilla::TimeStamp now = mozilla::TimeStamp::Now();
+ bool isThreadBeingProfiled =
+ profiler_thread_is_being_profiled_for_markers();
+ PROFILER_MARKER(
+ "IPC", IPC,
+ mozilla::MarkerOptions(
+ mozilla::MarkerTiming::InstantAt(now),
+ // If the thread is being profiled, add the marker to
+ // the current thread. If the thread is not being
+ // profiled, add the marker to the main thread. It will
+ // appear in the main thread's IPC track. Profiler
+ // analysis UI correlates all the IPC markers from
+ // different threads and generates processed markers.
+ isThreadBeingProfiled ? mozilla::MarkerThreadId::CurrentThread()
+ : mozilla::MarkerThreadId::MainThread()),
+ IPCMarker, now, now, aOtherPid, aMessage.seqno(), aMessage.type(),
+ mozilla::ipc::UnknownSide, aDirection, aPhase, aMessage.is_sync(),
+ // aOriginThreadId: If the thread is being profiled, do not include a
+ // thread ID, as it's the same as the markers. Only include this field
+ // when the marker is being sent from another thread.
+ isThreadBeingProfiled ? mozilla::MarkerThreadId{}
+ : mozilla::MarkerThreadId::CurrentThread());
+ }
+}
+
+} // namespace IPC
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_utils.h b/ipc/chromium/src/chrome/common/ipc_channel_utils.h
new file mode 100644
index 0000000000..1bcfcf7032
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_utils.h
@@ -0,0 +1,21 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef CHROME_COMMON_IPC_CHANNEL_UTILS_H_
+#define CHROME_COMMON_IPC_CHANNEL_UTILS_H_
+
+#include "chrome/common/ipc_message.h"
+#include "mozilla/ipc/MessageChannel.h"
+
+namespace IPC {
+
+void AddIPCProfilerMarker(const Message& aMessage, int32_t aOtherPid,
+ mozilla::ipc::MessageDirection aDirection,
+ mozilla::ipc::MessagePhase aPhase);
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_CHANNEL_UTILS_H_
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_win.cc b/ipc/chromium/src/chrome/common/ipc_channel_win.cc
new file mode 100644
index 0000000000..3be582b3e2
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_win.cc
@@ -0,0 +1,814 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "chrome/common/ipc_channel_win.h"
+
+#include <windows.h>
+#include <winternl.h>
+#include <ntstatus.h>
+#include <sstream>
+
+#include "base/command_line.h"
+#include "base/compiler_specific.h"
+#include "base/logging.h"
+#include "base/process.h"
+#include "base/process_util.h"
+#include "base/rand_util.h"
+#include "base/string_util.h"
+#include "base/win_util.h"
+#include "chrome/common/chrome_switches.h"
+#include "chrome/common/ipc_channel_utils.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/LateWriteChecks.h"
+#include "mozilla/RandomNum.h"
+#include "nsThreadUtils.h"
+
+using namespace mozilla::ipc;
+
+namespace IPC {
+//------------------------------------------------------------------------------
+
+Channel::ChannelImpl::State::State(ChannelImpl* channel) {
+ memset(&context.overlapped, 0, sizeof(context.overlapped));
+ context.handler = channel;
+}
+
+Channel::ChannelImpl::State::~State() {
+ COMPILE_ASSERT(!offsetof(Channel::ChannelImpl::State, context),
+ starts_with_io_context);
+}
+
+//------------------------------------------------------------------------------
+
+Channel::ChannelImpl::ChannelImpl(ChannelHandle pipe, Mode mode,
+ base::ProcessId other_pid)
+ : chan_cap_("ChannelImpl::SendMutex",
+ MessageLoopForIO::current()->SerialEventTarget()),
+ ALLOW_THIS_IN_INITIALIZER_LIST(input_state_(this)),
+ ALLOW_THIS_IN_INITIALIZER_LIST(output_state_(this)),
+ other_pid_(other_pid) {
+ Init(mode);
+
+ if (!pipe) {
+ return;
+ }
+
+ pipe_ = pipe.release();
+ EnqueueHelloMessage();
+}
+
+void Channel::ChannelImpl::Init(Mode mode) {
+ // Verify that we fit in a "quantum-spaced" jemalloc bucket.
+ static_assert(sizeof(*this) <= 512, "Exceeded expected size class");
+
+ chan_cap_.NoteExclusiveAccess();
+
+ mode_ = mode;
+ pipe_ = INVALID_HANDLE_VALUE;
+ waiting_connect_ = true;
+ processing_incoming_ = false;
+ input_buf_offset_ = 0;
+ input_buf_ = mozilla::MakeUnique<char[]>(Channel::kReadBufferSize);
+ accept_handles_ = false;
+ privileged_ = false;
+ other_process_ = INVALID_HANDLE_VALUE;
+}
+
+void Channel::ChannelImpl::OutputQueuePush(mozilla::UniquePtr<Message> msg) {
+ chan_cap_.NoteSendMutex();
+
+ mozilla::LogIPCMessage::LogDispatchWithPid(msg.get(), other_pid_);
+
+ output_queue_.Push(std::move(msg));
+}
+
+void Channel::ChannelImpl::OutputQueuePop() {
+ mozilla::UniquePtr<Message> message = output_queue_.Pop();
+}
+
+void Channel::ChannelImpl::Close() {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ CloseLocked();
+}
+
+void Channel::ChannelImpl::CloseLocked() {
+ chan_cap_.NoteExclusiveAccess();
+
+ // If we still have pending I/O, cancel it. The references inside
+ // `input_state_` and `output_state_` will keep the buffers alive until they
+ // complete.
+ if (input_state_.is_pending || output_state_.is_pending) {
+ CancelIo(pipe_);
+ }
+
+ // Closing the handle at this point prevents us from issuing more requests
+ // form OnIOCompleted().
+ if (pipe_ != INVALID_HANDLE_VALUE) {
+ CloseHandle(pipe_);
+ pipe_ = INVALID_HANDLE_VALUE;
+ }
+
+ // If we have a connection to the other process, close the handle.
+ if (other_process_ != INVALID_HANDLE_VALUE) {
+ CloseHandle(other_process_);
+ other_process_ = INVALID_HANDLE_VALUE;
+ }
+
+ // Don't return from `CloseLocked()` until the IO has been completed,
+ // otherwise the IO thread may exit with outstanding IO, leaking the
+ // ChannelImpl.
+ //
+ // It's OK to unlock here, as calls to `Send` from other threads will be
+ // rejected, due to `pipe_` having been cleared.
+ while (input_state_.is_pending || output_state_.is_pending) {
+ mozilla::MutexAutoUnlock unlock(SendMutex());
+ MessageLoopForIO::current()->WaitForIOCompletion(INFINITE, this);
+ }
+
+ while (!output_queue_.IsEmpty()) {
+ OutputQueuePop();
+ }
+}
+
+bool Channel::ChannelImpl::Send(mozilla::UniquePtr<Message> message) {
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteSendMutex();
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "sending message @" << message.get() << " on channel @" << this
+ << " with type " << message->type() << " ("
+ << output_queue_.Count() << " in queue)";
+#endif
+
+ if (pipe_ == INVALID_HANDLE_VALUE) {
+ if (mozilla::ipc::LoggingEnabled()) {
+ fprintf(stderr,
+ "Can't send message %s, because this channel is closed.\n",
+ message->name());
+ }
+ return false;
+ }
+
+ OutputQueuePush(std::move(message));
+ // ensure waiting to write
+ if (!waiting_connect_) {
+ if (!output_state_.is_pending) {
+ if (!ProcessOutgoingMessages(NULL, 0, false)) {
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool Channel::ChannelImpl::EnqueueHelloMessage() {
+ chan_cap_.NoteExclusiveAccess();
+
+ auto m = mozilla::MakeUnique<Message>(MSG_ROUTING_NONE, HELLO_MESSAGE_TYPE);
+
+ // Also, don't send if the value is zero (for IPC backwards compatability).
+ if (!m->WriteInt(GetCurrentProcessId())) {
+ CloseHandle(pipe_);
+ pipe_ = INVALID_HANDLE_VALUE;
+ return false;
+ }
+
+ OutputQueuePush(std::move(m));
+ return true;
+}
+
+bool Channel::ChannelImpl::Connect(Listener* listener) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ if (pipe_ == INVALID_HANDLE_VALUE) return false;
+
+ listener_ = listener;
+
+ MessageLoopForIO::current()->RegisterIOHandler(pipe_, this);
+ waiting_connect_ = false;
+
+ DCHECK(!input_state_.is_pending);
+
+ // Complete setup asynchronously. By not setting input_state_.is_pending
+ // to `this`, we indicate to OnIOCompleted that this is the special
+ // initialization signal, while keeping a reference through the
+ // `RunnableMethod`.
+ IOThread().Dispatch(
+ mozilla::NewRunnableMethod<MessageLoopForIO::IOContext*, DWORD, DWORD>(
+ "ContinueConnect", this, &ChannelImpl::OnIOCompleted,
+ &input_state_.context, 0, 0));
+
+ DCHECK(!output_state_.is_pending);
+ ProcessOutgoingMessages(NULL, 0, false);
+ return true;
+}
+
+void Channel::ChannelImpl::SetOtherPid(base::ProcessId other_pid) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+ MOZ_RELEASE_ASSERT(
+ other_pid_ == base::kInvalidProcessId || other_pid_ == other_pid,
+ "Multiple sources of SetOtherPid disagree!");
+ other_pid_ = other_pid;
+
+ // Now that we know the remote pid, open a privileged handle to the
+ // child process if needed to transfer handles to/from it.
+ if (privileged_ && other_process_ == INVALID_HANDLE_VALUE) {
+ other_process_ = OpenProcess(PROCESS_DUP_HANDLE, false, other_pid_);
+ if (!other_process_) {
+ other_process_ = INVALID_HANDLE_VALUE;
+ CHROMIUM_LOG(ERROR) << "Failed to acquire privileged handle to "
+ << other_pid_ << ", cannot accept handles";
+ }
+ }
+}
+
+bool Channel::ChannelImpl::ProcessIncomingMessages(
+ MessageLoopForIO::IOContext* context, DWORD bytes_read, bool was_pending) {
+ chan_cap_.NoteOnIOThread();
+
+ DCHECK(!input_state_.is_pending);
+
+ if (was_pending) {
+ DCHECK(context);
+
+ if (!context || !bytes_read) return false;
+ } else {
+ // This happens at channel initialization.
+ DCHECK(!bytes_read && context == &input_state_.context);
+ }
+
+ for (;;) {
+ if (bytes_read == 0) {
+ if (INVALID_HANDLE_VALUE == pipe_) return false;
+
+ // Read from pipe...
+ BOOL ok = ReadFile(pipe_, input_buf_.get() + input_buf_offset_,
+ Channel::kReadBufferSize - input_buf_offset_,
+ &bytes_read, &input_state_.context.overlapped);
+ if (!ok) {
+ DWORD err = GetLastError();
+ if (err == ERROR_IO_PENDING) {
+ input_state_.is_pending = this;
+ return true;
+ }
+ if (err != ERROR_BROKEN_PIPE && err != ERROR_NO_DATA) {
+ CHROMIUM_LOG(ERROR)
+ << "pipe error in connection to " << other_pid_ << ": " << err;
+ }
+ return false;
+ }
+ input_state_.is_pending = this;
+ return true;
+ }
+ DCHECK(bytes_read);
+
+ // Process messages from input buffer.
+
+ const char* p = input_buf_.get();
+ const char* end = input_buf_.get() + input_buf_offset_ + bytes_read;
+
+ // NOTE: We re-check `pipe_` after each message to make sure we weren't
+ // closed while calling `OnMessageReceived` or `OnChannelConnected`.
+ while (p < end && INVALID_HANDLE_VALUE != pipe_) {
+ // Try to figure out how big the message is. Size is 0 if we haven't read
+ // enough of the header to know the size.
+ uint32_t message_length = 0;
+ if (incoming_message_) {
+ message_length = incoming_message_->size();
+ } else {
+ message_length = Message::MessageSize(p, end);
+ }
+
+ if (!message_length) {
+ // We haven't seen the full message header.
+ MOZ_ASSERT(!incoming_message_);
+
+ // Move everything we have to the start of the buffer. We'll finish
+ // reading this message when we get more data. For now we leave it in
+ // input_buf_.
+ memmove(input_buf_.get(), p, end - p);
+ input_buf_offset_ = end - p;
+
+ break;
+ }
+
+ input_buf_offset_ = 0;
+
+ bool partial;
+ if (incoming_message_) {
+ // We already have some data for this message stored in
+ // incoming_message_. We want to append the new data there.
+ Message& m = *incoming_message_;
+
+ // How much data from this message remains to be added to
+ // incoming_message_?
+ MOZ_ASSERT(message_length > m.CurrentSize());
+ uint32_t remaining = message_length - m.CurrentSize();
+
+ // How much data from this message is stored in input_buf_?
+ uint32_t in_buf = std::min(remaining, uint32_t(end - p));
+
+ m.InputBytes(p, in_buf);
+ p += in_buf;
+
+ // Are we done reading this message?
+ partial = in_buf != remaining;
+ } else {
+ // How much data from this message is stored in input_buf_?
+ uint32_t in_buf = std::min(message_length, uint32_t(end - p));
+
+ incoming_message_ = mozilla::MakeUnique<Message>(p, in_buf);
+ p += in_buf;
+
+ // Are we done reading this message?
+ partial = in_buf != message_length;
+ }
+
+ if (partial) {
+ break;
+ }
+
+ Message& m = *incoming_message_;
+
+ // Note: We set other_pid_ below when we receive a Hello message (which
+ // has no routing ID), but we only emit a profiler marker for messages
+ // with a routing ID, so there's no conflict here.
+ AddIPCProfilerMarker(m, other_pid_, MessageDirection::eReceiving,
+ MessagePhase::TransferEnd);
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "received message on channel @" << this << " with type "
+ << m.type();
+#endif
+ if (m.routing_id() == MSG_ROUTING_NONE &&
+ m.type() == HELLO_MESSAGE_TYPE) {
+ // The Hello message contains the process id and must include the
+ // shared secret, if we are waiting for it.
+ MessageIterator it = MessageIterator(m);
+ int32_t other_pid = it.NextInt();
+ SetOtherPid(other_pid);
+
+ listener_->OnChannelConnected(other_pid);
+ } else {
+ mozilla::LogIPCMessage::Run run(&m);
+ if (!AcceptHandles(m)) {
+ return false;
+ }
+ listener_->OnMessageReceived(std::move(incoming_message_));
+ }
+
+ incoming_message_ = nullptr;
+ }
+
+ bytes_read = 0; // Get more data.
+ }
+}
+
+bool Channel::ChannelImpl::ProcessOutgoingMessages(
+ MessageLoopForIO::IOContext* context, DWORD bytes_written,
+ bool was_pending) {
+ chan_cap_.NoteSendMutex();
+
+ DCHECK(!output_state_.is_pending);
+ DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
+ // no connection?
+ if (was_pending) {
+ DCHECK(context);
+ if (!context || bytes_written == 0) {
+ DWORD err = GetLastError();
+ if (err != ERROR_BROKEN_PIPE && err != ERROR_NO_DATA) {
+ CHROMIUM_LOG(ERROR)
+ << "pipe error in connection to " << other_pid_ << ": " << err;
+ }
+ return false;
+ }
+ // Message was sent.
+ DCHECK(!output_queue_.IsEmpty());
+ Message* m = output_queue_.FirstElement().get();
+
+ MOZ_RELEASE_ASSERT(partial_write_iter_.isSome());
+ Pickle::BufferList::IterImpl& iter = partial_write_iter_.ref();
+ iter.Advance(m->Buffers(), bytes_written);
+ if (iter.Done()) {
+ AddIPCProfilerMarker(*m, other_pid_, MessageDirection::eSending,
+ MessagePhase::TransferEnd);
+
+ partial_write_iter_.reset();
+ OutputQueuePop();
+ // m has been destroyed, so clear the dangling reference.
+ m = nullptr;
+ }
+ }
+
+ if (output_queue_.IsEmpty()) return true;
+
+ if (INVALID_HANDLE_VALUE == pipe_) return false;
+
+ // Write to pipe...
+ Message* m = output_queue_.FirstElement().get();
+
+ if (partial_write_iter_.isNothing()) {
+ AddIPCProfilerMarker(*m, other_pid_, MessageDirection::eSending,
+ MessagePhase::TransferStart);
+ if (!TransferHandles(*m)) {
+ return false;
+ }
+ Pickle::BufferList::IterImpl iter(m->Buffers());
+ partial_write_iter_.emplace(iter);
+ }
+
+ Pickle::BufferList::IterImpl& iter = partial_write_iter_.ref();
+
+ // Don't count this write for the purposes of late write checking. If this
+ // message results in a legitimate file write, that will show up when it
+ // happens.
+ mozilla::PushSuspendLateWriteChecks();
+ BOOL ok = WriteFile(pipe_, iter.Data(), iter.RemainingInSegment(),
+ &bytes_written, &output_state_.context.overlapped);
+ mozilla::PopSuspendLateWriteChecks();
+
+ if (!ok) {
+ DWORD err = GetLastError();
+ if (err == ERROR_IO_PENDING) {
+ output_state_.is_pending = this;
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "sent pending message @" << m << " on channel @" << this
+ << " with type " << m->type();
+#endif
+
+ return true;
+ }
+ if (err != ERROR_BROKEN_PIPE && err != ERROR_NO_DATA) {
+ CHROMIUM_LOG(ERROR) << "pipe error in connection to " << other_pid_
+ << ": " << err;
+ }
+ return false;
+ }
+
+#ifdef IPC_MESSAGE_DEBUG_EXTRA
+ DLOG(INFO) << "sent message @" << m << " on channel @" << this
+ << " with type " << m->type();
+#endif
+
+ output_state_.is_pending = this;
+ return true;
+}
+
+void Channel::ChannelImpl::OnIOCompleted(MessageLoopForIO::IOContext* context,
+ DWORD bytes_transfered, DWORD error) {
+ // NOTE: In case the pending reference was the last reference, release it
+ // outside of the lock.
+ RefPtr<ChannelImpl> was_pending;
+
+ IOThread().AssertOnCurrentThread();
+ chan_cap_.NoteOnIOThread();
+
+ bool ok;
+ if (context == &input_state_.context) {
+ was_pending = input_state_.is_pending.forget();
+ // we don't support recursion through OnMessageReceived yet!
+ DCHECK(!processing_incoming_);
+ processing_incoming_ = true;
+ ok = ProcessIncomingMessages(context, bytes_transfered, was_pending);
+ processing_incoming_ = false;
+ } else {
+ mozilla::MutexAutoLock lock(SendMutex());
+ DCHECK(context == &output_state_.context);
+ was_pending = output_state_.is_pending.forget();
+ ok = ProcessOutgoingMessages(context, bytes_transfered, was_pending);
+ }
+ if (!ok && INVALID_HANDLE_VALUE != pipe_) {
+ // We don't want to re-enter Close().
+ Close();
+ listener_->OnChannelError();
+ }
+}
+
+void Channel::ChannelImpl::StartAcceptingHandles(Mode mode) {
+ IOThread().AssertOnCurrentThread();
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteExclusiveAccess();
+
+ if (accept_handles_) {
+ MOZ_ASSERT(privileged_ == (mode == MODE_SERVER));
+ return;
+ }
+ accept_handles_ = true;
+ privileged_ = mode == MODE_SERVER;
+
+ if (privileged_ && other_pid_ != base::kInvalidProcessId &&
+ other_process_ == INVALID_HANDLE_VALUE) {
+ other_process_ = OpenProcess(PROCESS_DUP_HANDLE, false, other_pid_);
+ if (!other_process_) {
+ other_process_ = INVALID_HANDLE_VALUE;
+ CHROMIUM_LOG(ERROR) << "Failed to acquire privileged handle to "
+ << other_pid_ << ", cannot accept handles";
+ }
+ }
+}
+
+// This logic is borrowed from Chromium's `base/win/nt_status.cc`, and is used
+// to detect and silence DuplicateHandle errors caused due to the other process
+// exiting.
+//
+// https://source.chromium.org/chromium/chromium/src/+/main:base/win/nt_status.cc;drc=e4622aaeccea84652488d1822c28c78b7115684f
+static NTSTATUS GetLastNtStatus() {
+ using GetLastNtStatusFn = NTSTATUS NTAPI (*)();
+
+ static constexpr const wchar_t kNtDllName[] = L"ntdll.dll";
+ static constexpr const char kLastStatusFnName[] = "RtlGetLastNtStatus";
+
+ // This is equivalent to calling NtCurrentTeb() and extracting
+ // LastStatusValue from the returned _TEB structure, except that the public
+ // _TEB struct definition does not actually specify the location of the
+ // LastStatusValue field. We avoid depending on such a definition by
+ // internally using RtlGetLastNtStatus() from ntdll.dll instead.
+ static auto* get_last_nt_status = reinterpret_cast<GetLastNtStatusFn>(
+ ::GetProcAddress(::GetModuleHandle(kNtDllName), kLastStatusFnName));
+ return get_last_nt_status();
+}
+
+// ERROR_ACCESS_DENIED may indicate that the remote process (which could be
+// either the source or destination process here) is already terminated or has
+// begun termination and therefore no longer has a handle table. We don't want
+// these cases to crash because we know they happen in practice and are
+// largely unavoidable.
+//
+// https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:mojo/core/platform_handle_in_transit.cc;l=47-53;drc=fdfd85f836e0e59c79ed9bf6d527a2b8f7fdeb6e
+static bool WasOtherProcessExitingError(DWORD error) {
+ return error == ERROR_ACCESS_DENIED &&
+ GetLastNtStatus() == STATUS_PROCESS_IS_TERMINATING;
+}
+
+static uint32_t HandleToUint32(HANDLE h) {
+ // Cast through uintptr_t and then unsigned int to make the truncation to
+ // 32 bits explicit. Handles are size of-pointer but are always 32-bit values.
+ // https://docs.microsoft.com/en-ca/windows/win32/winprog64/interprocess-communication
+ // says: 64-bit versions of Windows use 32-bit handles for interoperability.
+ return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h));
+}
+
+static HANDLE Uint32ToHandle(uint32_t h) {
+ return reinterpret_cast<HANDLE>(
+ static_cast<uintptr_t>(static_cast<int32_t>(h)));
+}
+
+bool Channel::ChannelImpl::AcceptHandles(Message& msg) {
+ chan_cap_.NoteOnIOThread();
+
+ MOZ_ASSERT(msg.num_handles() == 0);
+
+ uint32_t num_handles = msg.header()->num_handles;
+ if (num_handles == 0) {
+ return true;
+ }
+
+ if (!accept_handles_) {
+ CHROMIUM_LOG(ERROR) << "invalid message: " << msg.name()
+ << ". channel is not configured to accept handles";
+ return false;
+ }
+
+ // Read in the payload from the footer, truncating the message.
+ nsTArray<uint32_t> payload;
+ payload.AppendElements(num_handles);
+ if (!msg.ReadFooter(payload.Elements(), num_handles * sizeof(uint32_t),
+ /* truncate */ true)) {
+ CHROMIUM_LOG(ERROR) << "failed to read handle payload from message";
+ return false;
+ }
+ msg.header()->num_handles = 0;
+
+ // Read in the handles themselves, transferring ownership as required.
+ nsTArray<mozilla::UniqueFileHandle> handles(num_handles);
+ for (uint32_t handleValue : payload) {
+ HANDLE ipc_handle = Uint32ToHandle(handleValue);
+ if (!ipc_handle || ipc_handle == INVALID_HANDLE_VALUE) {
+ CHROMIUM_LOG(ERROR)
+ << "Attempt to accept invalid or null handle from process "
+ << other_pid_ << " for message " << msg.name() << " in AcceptHandles";
+ return false;
+ }
+
+ // If we're the privileged process, the remote process will have leaked
+ // the sent handles in its local address space, and be relying on us to
+ // duplicate them, otherwise the remote privileged side will have
+ // transferred the handles to us already.
+ mozilla::UniqueFileHandle local_handle;
+ if (privileged_) {
+ MOZ_ASSERT(other_process_, "other_process_ cannot be null");
+ if (other_process_ == INVALID_HANDLE_VALUE) {
+ CHROMIUM_LOG(ERROR) << "other_process_ is invalid in AcceptHandles";
+ return false;
+ }
+ if (!::DuplicateHandle(other_process_, ipc_handle, GetCurrentProcess(),
+ getter_Transfers(local_handle), 0, FALSE,
+ DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE)) {
+ DWORD err = GetLastError();
+ // Don't log out a scary looking error if this failed due to the target
+ // process terminating.
+ if (!WasOtherProcessExitingError(err)) {
+ CHROMIUM_LOG(ERROR)
+ << "DuplicateHandle failed for handle " << ipc_handle
+ << " from process " << other_pid_ << " for message " << msg.name()
+ << " in AcceptHandles with error: " << err;
+ }
+ return false;
+ }
+ } else {
+ local_handle.reset(ipc_handle);
+ }
+
+ MOZ_DIAGNOSTIC_ASSERT(
+ local_handle, "Accepting invalid or null handle from another process");
+
+ // The handle is directly owned by this process now, and can be added to
+ // our `handles` array.
+ handles.AppendElement(std::move(local_handle));
+ }
+
+ // We're done with the handle footer, truncate the message at that point.
+ msg.SetAttachedFileHandles(std::move(handles));
+ MOZ_ASSERT(msg.num_handles() == num_handles);
+ return true;
+}
+
+bool Channel::ChannelImpl::TransferHandles(Message& msg) {
+ chan_cap_.NoteSendMutex();
+
+ MOZ_ASSERT(msg.header()->num_handles == 0);
+
+ uint32_t num_handles = msg.num_handles();
+ if (num_handles == 0) {
+ return true;
+ }
+
+ if (!accept_handles_) {
+ CHROMIUM_LOG(ERROR) << "cannot send message: " << msg.name()
+ << ". channel is not configured to accept handles";
+ return false;
+ }
+
+#ifdef DEBUG
+ uint32_t handles_offset = msg.header()->payload_size;
+#endif
+
+ nsTArray<uint32_t> payload(num_handles);
+ for (uint32_t i = 0; i < num_handles; ++i) {
+ // Take ownership of the handle.
+ mozilla::UniqueFileHandle local_handle =
+ std::move(msg.attached_handles_[i]);
+ if (!local_handle) {
+ CHROMIUM_LOG(ERROR)
+ << "Attempt to transfer invalid or null handle to process "
+ << other_pid_ << " for message " << msg.name()
+ << " in TransferHandles";
+ return false;
+ }
+
+ // If we're the privileged process, transfer the HANDLE to our remote before
+ // sending the message. Otherwise, the remote privileged process will
+ // transfer the handle for us, so leak it.
+ HANDLE ipc_handle = NULL;
+ if (privileged_) {
+ MOZ_ASSERT(other_process_, "other_process_ cannot be null");
+ if (other_process_ == INVALID_HANDLE_VALUE) {
+ CHROMIUM_LOG(ERROR) << "other_process_ is invalid in TransferHandles";
+ return false;
+ }
+ if (!::DuplicateHandle(GetCurrentProcess(), local_handle.get(),
+ other_process_, &ipc_handle, 0, FALSE,
+ DUPLICATE_SAME_ACCESS)) {
+ DWORD err = GetLastError();
+ // Don't log out a scary looking error if this failed due to the target
+ // process terminating.
+ if (!WasOtherProcessExitingError(err)) {
+ CHROMIUM_LOG(ERROR) << "DuplicateHandle failed for handle "
+ << (HANDLE)local_handle.get() << " to process "
+ << other_pid_ << " for message " << msg.name()
+ << " in TransferHandles with error: " << err;
+ }
+ return false;
+ }
+ } else {
+ // Release ownership of the handle. It'll be closed when the parent
+ // process transfers it with DuplicateHandle in the remote privileged
+ // process.
+ ipc_handle = local_handle.release();
+ }
+
+ MOZ_DIAGNOSTIC_ASSERT(
+ ipc_handle && ipc_handle != INVALID_HANDLE_VALUE,
+ "Transferring invalid or null handle to another process");
+
+ payload.AppendElement(HandleToUint32(ipc_handle));
+ }
+ msg.attached_handles_.Clear();
+
+ msg.WriteFooter(payload.Elements(), payload.Length() * sizeof(uint32_t));
+ msg.header()->num_handles = num_handles;
+
+ MOZ_ASSERT(msg.header()->payload_size ==
+ handles_offset + (sizeof(uint32_t) * num_handles),
+ "Unexpected number of bytes written for handles footer?");
+ return true;
+}
+
+//------------------------------------------------------------------------------
+// Channel's methods simply call through to ChannelImpl.
+Channel::Channel(ChannelHandle pipe, Mode mode, base::ProcessId other_pid)
+ : channel_impl_(new ChannelImpl(std::move(pipe), mode, other_pid)) {
+ MOZ_COUNT_CTOR(IPC::Channel);
+}
+
+Channel::~Channel() { MOZ_COUNT_DTOR(IPC::Channel); }
+
+bool Channel::Connect(Listener* listener) {
+ return channel_impl_->Connect(listener);
+}
+
+void Channel::Close() { channel_impl_->Close(); }
+
+void Channel::StartAcceptingHandles(Mode mode) {
+ channel_impl_->StartAcceptingHandles(mode);
+}
+
+bool Channel::Send(mozilla::UniquePtr<Message> message) {
+ return channel_impl_->Send(std::move(message));
+}
+
+void Channel::SetOtherPid(base::ProcessId other_pid) {
+ channel_impl_->SetOtherPid(other_pid);
+}
+
+bool Channel::IsClosed() const { return channel_impl_->IsClosed(); }
+
+HANDLE Channel::GetClientChannelHandle() {
+ // Read the switch from the command line which passed the initial handle for
+ // this process, and convert it back into a HANDLE.
+ std::wstring switchValue = CommandLine::ForCurrentProcess()->GetSwitchValue(
+ switches::kProcessChannelID);
+
+ uint32_t handleInt = std::stoul(switchValue);
+ return Uint32ToHandle(handleInt);
+}
+
+// static
+bool Channel::CreateRawPipe(ChannelHandle* server, ChannelHandle* client) {
+ std::wstring pipe_name =
+ StringPrintf(L"\\\\.\\pipe\\gecko.%lu.%lu.%I64u", ::GetCurrentProcessId(),
+ ::GetCurrentThreadId(), mozilla::RandomUint64OrDie());
+ const DWORD kOpenMode =
+ PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE;
+ const DWORD kPipeMode = PIPE_TYPE_BYTE | PIPE_READMODE_BYTE;
+ *server = mozilla::UniqueFileHandle(
+ ::CreateNamedPipeW(pipe_name.c_str(), kOpenMode, kPipeMode,
+ 1, // Max instances.
+ Channel::kReadBufferSize, // Output buffer size.
+ Channel::kReadBufferSize, // Input buffer size.
+ 5000, // Timeout in ms.
+ nullptr)); // Default security descriptor.
+ if (!server) {
+ NS_WARNING(
+ nsPrintfCString("CreateNamedPipeW Failed %lu", ::GetLastError()).get());
+ return false;
+ }
+
+ const DWORD kDesiredAccess = GENERIC_READ | GENERIC_WRITE;
+ // The SECURITY_ANONYMOUS flag means that the server side cannot impersonate
+ // the client, which is useful as both server & client may be unprivileged.
+ const DWORD kFlags =
+ SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS | FILE_FLAG_OVERLAPPED;
+ *client = mozilla::UniqueFileHandle(
+ ::CreateFileW(pipe_name.c_str(), kDesiredAccess, 0, nullptr,
+ OPEN_EXISTING, kFlags, nullptr));
+ if (!client) {
+ NS_WARNING(
+ nsPrintfCString("CreateFileW Failed %lu", ::GetLastError()).get());
+ return false;
+ }
+
+ // Since a client has connected, ConnectNamedPipe() should return zero and
+ // GetLastError() should return ERROR_PIPE_CONNECTED.
+ if (::ConnectNamedPipe(server->get(), nullptr) ||
+ ::GetLastError() != ERROR_PIPE_CONNECTED) {
+ NS_WARNING(
+ nsPrintfCString("ConnectNamedPipe Failed %lu", ::GetLastError()).get());
+ return false;
+ }
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/chromium/src/chrome/common/ipc_channel_win.h b/ipc/chromium/src/chrome/common/ipc_channel_win.h
new file mode 100644
index 0000000000..f091a81b76
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_channel_win.h
@@ -0,0 +1,167 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef CHROME_COMMON_IPC_CHANNEL_WIN_H_
+#define CHROME_COMMON_IPC_CHANNEL_WIN_H_
+
+#include "chrome/common/ipc_channel.h"
+#include "chrome/common/ipc_channel_capability.h"
+#include "chrome/common/ipc_message.h"
+
+#include <atomic>
+#include <string>
+
+#include "base/message_loop.h"
+#include "base/process.h"
+#include "base/task.h"
+#include "nsISupportsImpl.h"
+
+#include "mozilla/EventTargetCapability.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/Queue.h"
+#include "mozilla/UniquePtr.h"
+
+namespace IPC {
+
+class Channel::ChannelImpl : public MessageLoopForIO::IOHandler {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DELETE_ON_EVENT_TARGET(
+ ChannelImpl, IOThread().GetEventTarget());
+
+ using ChannelHandle = Channel::ChannelHandle;
+
+ // Mirror methods of Channel, see ipc_channel.h for description.
+ ChannelImpl(ChannelHandle pipe, Mode mode, base::ProcessId other_pid);
+ bool Connect(Listener* listener) MOZ_EXCLUDES(SendMutex());
+ void Close() MOZ_EXCLUDES(SendMutex());
+ void StartAcceptingHandles(Mode mode) MOZ_EXCLUDES(SendMutex());
+ // NOTE: `Send` may be called on threads other than the I/O thread.
+ bool Send(mozilla::UniquePtr<Message> message) MOZ_EXCLUDES(SendMutex());
+
+ void SetOtherPid(base::ProcessId other_pid);
+
+ // See the comment in ipc_channel.h for info on IsClosed()
+ // NOTE: `IsClosed` may be called on threads other than the I/O thread.
+ bool IsClosed() MOZ_EXCLUDES(SendMutex()) {
+ mozilla::MutexAutoLock lock(SendMutex());
+ chan_cap_.NoteSendMutex();
+ return pipe_ == INVALID_HANDLE_VALUE;
+ }
+
+ private:
+ ~ChannelImpl() {
+ IOThread().AssertOnCurrentThread();
+ if (pipe_ != INVALID_HANDLE_VALUE ||
+ other_process_ != INVALID_HANDLE_VALUE) {
+ Close();
+ }
+ }
+
+ void Init(Mode mode) MOZ_REQUIRES(SendMutex(), IOThread());
+
+ void OutputQueuePush(mozilla::UniquePtr<Message> msg)
+ MOZ_REQUIRES(SendMutex());
+ void OutputQueuePop() MOZ_REQUIRES(SendMutex());
+
+ bool EnqueueHelloMessage() MOZ_REQUIRES(SendMutex(), IOThread());
+ void CloseLocked() MOZ_REQUIRES(SendMutex(), IOThread());
+
+ bool ProcessIncomingMessages(MessageLoopForIO::IOContext* context,
+ DWORD bytes_read, bool was_pending)
+ MOZ_REQUIRES(IOThread());
+ bool ProcessOutgoingMessages(MessageLoopForIO::IOContext* context,
+ DWORD bytes_written, bool was_pending)
+ MOZ_REQUIRES(SendMutex());
+
+ // Called on a Message immediately before it is sent/recieved to transfer
+ // handles to the remote process, or accept handles from the remote process.
+ bool AcceptHandles(Message& msg) MOZ_REQUIRES(IOThread());
+ bool TransferHandles(Message& msg) MOZ_REQUIRES(SendMutex());
+
+ // MessageLoop::IOHandler implementation.
+ virtual void OnIOCompleted(MessageLoopForIO::IOContext* context,
+ DWORD bytes_transfered, DWORD error);
+
+ const ChannelCapability::Thread& IOThread() const
+ MOZ_RETURN_CAPABILITY(chan_cap_.IOThread()) {
+ return chan_cap_.IOThread();
+ }
+
+ ChannelCapability::Mutex& SendMutex()
+ MOZ_RETURN_CAPABILITY(chan_cap_.SendMutex()) {
+ return chan_cap_.SendMutex();
+ }
+
+ private:
+ // Compound capability of a Mutex and the IO thread.
+ ChannelCapability chan_cap_;
+
+ Mode mode_ MOZ_GUARDED_BY(IOThread());
+
+ struct State {
+ explicit State(ChannelImpl* channel);
+ ~State();
+ MessageLoopForIO::IOContext context;
+ // When there is pending I/O, this holds a strong reference to the
+ // ChannelImpl to prevent it from going away.
+ RefPtr<ChannelImpl> is_pending;
+ };
+
+ State input_state_ MOZ_GUARDED_BY(IOThread());
+ State output_state_ MOZ_GUARDED_BY(SendMutex());
+
+ HANDLE pipe_ MOZ_GUARDED_BY(chan_cap_) = INVALID_HANDLE_VALUE;
+
+ Listener* listener_ MOZ_GUARDED_BY(IOThread()) = nullptr;
+
+ // Messages to be sent are queued here.
+ mozilla::Queue<mozilla::UniquePtr<Message>, 64> output_queue_
+ MOZ_GUARDED_BY(SendMutex());
+
+ // If sending a message blocks then we use this iterator to keep track of
+ // where in the message we are. It gets reset when the message is finished
+ // sending.
+ mozilla::Maybe<Pickle::BufferList::IterImpl> partial_write_iter_
+ MOZ_GUARDED_BY(SendMutex());
+
+ // We read from the pipe into this buffer
+ mozilla::UniquePtr<char[]> input_buf_ MOZ_GUARDED_BY(IOThread());
+ size_t input_buf_offset_ MOZ_GUARDED_BY(IOThread()) = 0;
+
+ // Large incoming messages that span multiple pipe buffers get built-up in the
+ // buffers of this message.
+ mozilla::UniquePtr<Message> incoming_message_ MOZ_GUARDED_BY(IOThread());
+
+ // Will be set to `true` until `Connect()` has been called.
+ bool waiting_connect_ MOZ_GUARDED_BY(chan_cap_) = true;
+
+ // This flag is set when processing incoming messages. It is used to
+ // avoid recursing through ProcessIncomingMessages, which could cause
+ // problems. TODO(darin): make this unnecessary
+ bool processing_incoming_ MOZ_GUARDED_BY(IOThread()) = false;
+
+ // We keep track of the PID of the other side of this channel so that we can
+ // record this when generating logs of IPC messages.
+ base::ProcessId other_pid_ MOZ_GUARDED_BY(chan_cap_) =
+ base::kInvalidProcessId;
+
+ // Whether or not to accept handles from a remote process, and whether this
+ // process is the privileged side of a IPC::Channel which can transfer
+ // handles.
+ bool accept_handles_ MOZ_GUARDED_BY(chan_cap_) = false;
+ bool privileged_ MOZ_GUARDED_BY(chan_cap_) = false;
+
+ // A privileged process handle used to transfer HANDLEs to and from the remote
+ // process. This will only be used if `privileged_` is set.
+ HANDLE other_process_ MOZ_GUARDED_BY(chan_cap_) = INVALID_HANDLE_VALUE;
+
+ DISALLOW_COPY_AND_ASSIGN(ChannelImpl);
+};
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_CHANNEL_WIN_H_
diff --git a/ipc/chromium/src/chrome/common/ipc_message.cc b/ipc/chromium/src/chrome/common/ipc_message.cc
new file mode 100644
index 0000000000..472c0fb4e1
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_message.cc
@@ -0,0 +1,217 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "chrome/common/ipc_message.h"
+
+#include "base/logging.h"
+#include "mojo/core/ports/event.h"
+
+#include <utility>
+
+#include "nsISupportsImpl.h"
+
+namespace IPC {
+
+//------------------------------------------------------------------------------
+
+const mojo::core::ports::UserMessage::TypeInfo Message::kUserMessageTypeInfo{};
+
+Message::~Message() { MOZ_COUNT_DTOR(IPC::Message); }
+
+Message::Message(int32_t routing_id, msgid_t type, uint32_t segment_capacity,
+ HeaderFlags flags)
+ : UserMessage(&kUserMessageTypeInfo),
+ Pickle(sizeof(Header), segment_capacity) {
+ MOZ_COUNT_CTOR(IPC::Message);
+ header()->routing = routing_id;
+ header()->type = type;
+ header()->flags = flags;
+ header()->num_handles = 0;
+ header()->txid = -1;
+ header()->seqno = 0;
+#if defined(XP_DARWIN)
+ header()->cookie = 0;
+ header()->num_send_rights = 0;
+#endif
+ header()->event_footer_size = 0;
+}
+
+Message::Message(const char* data, int data_len)
+ : UserMessage(&kUserMessageTypeInfo),
+ Pickle(sizeof(Header), data, data_len) {
+ MOZ_COUNT_CTOR(IPC::Message);
+}
+
+/*static*/ mozilla::UniquePtr<Message> Message::IPDLMessage(
+ int32_t routing_id, msgid_t type, uint32_t segment_capacity,
+ HeaderFlags flags) {
+ return mozilla::MakeUnique<Message>(routing_id, type, segment_capacity,
+ flags);
+}
+
+/*static*/ mozilla::UniquePtr<Message> Message::ForSyncDispatchError(
+ NestedLevel level) {
+ auto m = mozilla::MakeUnique<Message>(0, 0, 0, HeaderFlags(level));
+ auto& flags = m->header()->flags;
+ flags.SetSync();
+ flags.SetReply();
+ flags.SetReplyError();
+ return m;
+}
+
+void Message::WriteFooter(const void* data, uint32_t data_len) {
+ if (data_len == 0) {
+ return;
+ }
+
+ WriteBytes(data, data_len);
+}
+
+bool Message::ReadFooter(void* buffer, uint32_t buffer_len, bool truncate) {
+ if (buffer_len == 0) {
+ return true;
+ }
+
+ if (NS_WARN_IF(AlignInt(header()->payload_size) != header()->payload_size) ||
+ NS_WARN_IF(AlignInt(buffer_len) > header()->payload_size)) {
+ return false;
+ }
+
+ // Seek to the start of the footer, and read it in. We read in with a
+ // duplicate of the iterator so we can use it to truncate later.
+ uint32_t offset = header()->payload_size - AlignInt(buffer_len);
+ PickleIterator footer_iter(*this);
+ if (NS_WARN_IF(!IgnoreBytes(&footer_iter, offset))) {
+ return false;
+ }
+
+ PickleIterator read_iter(footer_iter);
+ bool ok = ReadBytesInto(&read_iter, buffer, buffer_len);
+
+ // If requested, truncate the buffer to the start of the footer.
+ if (truncate) {
+ Truncate(&footer_iter);
+ }
+ return ok;
+}
+
+bool Message::WriteFileHandle(mozilla::UniqueFileHandle handle) {
+ uint32_t handle_index = attached_handles_.Length();
+ WriteUInt32(handle_index);
+ if (handle_index == MAX_DESCRIPTORS_PER_MESSAGE) {
+ return false;
+ }
+ attached_handles_.AppendElement(std::move(handle));
+ return true;
+}
+
+bool Message::ConsumeFileHandle(PickleIterator* iter,
+ mozilla::UniqueFileHandle* handle) const {
+ uint32_t handle_index;
+ if (!ReadUInt32(iter, &handle_index)) {
+ return false;
+ }
+ if (handle_index >= attached_handles_.Length()) {
+ return false;
+ }
+ // NOTE: This mutates the underlying array, replacing the handle with an
+ // invalid handle.
+ *handle = std::exchange(attached_handles_[handle_index], nullptr);
+ return true;
+}
+
+void Message::SetAttachedFileHandles(
+ nsTArray<mozilla::UniqueFileHandle> handles) {
+ MOZ_DIAGNOSTIC_ASSERT(attached_handles_.IsEmpty());
+ attached_handles_ = std::move(handles);
+}
+
+uint32_t Message::num_handles() const { return attached_handles_.Length(); }
+
+void Message::WritePort(mozilla::ipc::ScopedPort port) {
+ uint32_t port_index = attached_ports_.Length();
+ WriteUInt32(port_index);
+ attached_ports_.AppendElement(std::move(port));
+}
+
+bool Message::ConsumePort(PickleIterator* iter,
+ mozilla::ipc::ScopedPort* port) const {
+ uint32_t port_index;
+ if (!ReadUInt32(iter, &port_index)) {
+ return false;
+ }
+ if (port_index >= attached_ports_.Length()) {
+ return false;
+ }
+ // NOTE: This mutates the underlying array, replacing the port with a consumed
+ // port.
+ *port = std::exchange(attached_ports_[port_index], {});
+ return true;
+}
+
+void Message::SetAttachedPorts(nsTArray<mozilla::ipc::ScopedPort> ports) {
+ MOZ_DIAGNOSTIC_ASSERT(attached_ports_.IsEmpty());
+ attached_ports_ = std::move(ports);
+}
+
+#if defined(XP_DARWIN)
+bool Message::WriteMachSendRight(mozilla::UniqueMachSendRight port) {
+ uint32_t index = attached_send_rights_.Length();
+ WriteUInt32(index);
+ if (index == MAX_DESCRIPTORS_PER_MESSAGE) {
+ return false;
+ }
+ attached_send_rights_.AppendElement(std::move(port));
+ return true;
+}
+
+bool Message::ConsumeMachSendRight(PickleIterator* iter,
+ mozilla::UniqueMachSendRight* port) const {
+ uint32_t index;
+ if (!ReadUInt32(iter, &index)) {
+ return false;
+ }
+ if (index >= attached_send_rights_.Length()) {
+ return false;
+ }
+ // NOTE: This mutates the underlying array, replacing the send right with a
+ // null right.
+ *port = std::exchange(attached_send_rights_[index], nullptr);
+ return true;
+}
+
+uint32_t Message::num_send_rights() const {
+ return attached_send_rights_.Length();
+}
+#endif
+
+bool Message::WillBeRoutedExternally(
+ mojo::core::ports::UserMessageEvent& event) {
+ if (!attached_ports_.IsEmpty()) {
+ // Explicitly attach any ports which were attached to this Message to this
+ // UserMessageEvent before we route it externally so that they can be
+ // transferred correctly. These ports will be recovered if needed in
+ // `GetMessage`.
+ MOZ_DIAGNOSTIC_ASSERT(
+ event.num_ports() == 0,
+ "Must not have previously attached ports to the UserMessageEvent");
+ event.ReservePorts(attached_ports_.Length());
+ for (size_t i = 0; i < event.num_ports(); ++i) {
+ event.ports()[i] = attached_ports_[i].Release().name();
+ }
+ attached_ports_.Clear();
+ }
+ return true;
+}
+
+void Message::AssertAsLargeAsHeader() const {
+ MOZ_DIAGNOSTIC_ASSERT(size() >= sizeof(Header));
+ MOZ_DIAGNOSTIC_ASSERT(CurrentSize() >= sizeof(Header));
+ // Our buffers should agree with what our header specifies.
+ MOZ_DIAGNOSTIC_ASSERT(size() == CurrentSize());
+}
+
+} // namespace IPC
diff --git a/ipc/chromium/src/chrome/common/ipc_message.h b/ipc/chromium/src/chrome/common/ipc_message.h
new file mode 100644
index 0000000000..733ae9e493
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_message.h
@@ -0,0 +1,424 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef CHROME_COMMON_IPC_MESSAGE_H__
+#define CHROME_COMMON_IPC_MESSAGE_H__
+
+#include <string>
+
+#include "base/basictypes.h"
+#include "base/pickle.h"
+#include "mojo/core/ports/user_message.h"
+#include "mojo/core/ports/port_ref.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/TimeStamp.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/ipc/ScopedPort.h"
+#include "nsTArray.h"
+
+namespace mozilla {
+
+#ifdef FUZZING_SNAPSHOT
+namespace fuzzing {
+class IPCFuzzController;
+}
+#endif
+
+namespace ipc {
+class MiniTransceiver;
+}
+} // namespace mozilla
+
+namespace IPC {
+
+//------------------------------------------------------------------------------
+
+// Generated by IPDL compiler
+const char* StringFromIPCMessageType(uint32_t aMessageType);
+
+class Channel;
+class Message;
+class MessageReader;
+class MessageWriter;
+struct LogData;
+
+class Message : public mojo::core::ports::UserMessage, public Pickle {
+ public:
+ static const TypeInfo kUserMessageTypeInfo;
+
+ typedef uint32_t msgid_t;
+
+ enum NestedLevel {
+ NOT_NESTED = 1,
+ NESTED_INSIDE_SYNC = 2,
+ NESTED_INSIDE_CPOW = 3
+ };
+
+ enum PriorityValue {
+ NORMAL_PRIORITY = 0,
+ INPUT_PRIORITY = 1,
+ VSYNC_PRIORITY = 2,
+ MEDIUMHIGH_PRIORITY = 3,
+ CONTROL_PRIORITY = 4,
+ };
+
+ enum MessageCompression {
+ COMPRESSION_NONE,
+ COMPRESSION_ENABLED,
+ COMPRESSION_ALL
+ };
+
+ enum Sync {
+ SYNC = 0,
+ ASYNC = 1,
+ };
+
+ enum Constructor {
+ NOT_CONSTRUCTOR = 0,
+ CONSTRUCTOR = 1,
+ };
+
+ enum Reply {
+ NOT_REPLY = 0,
+ REPLY = 1,
+ };
+
+ enum LazySend {
+ EAGER_SEND = 0,
+ LAZY_SEND = 1,
+ };
+
+ // The hard limit of handles or file descriptors allowed in a single message.
+ static constexpr size_t MAX_DESCRIPTORS_PER_MESSAGE = 32767;
+
+ class HeaderFlags {
+ friend class Message;
+#ifdef FUZZING_SNAPSHOT
+ // IPCFuzzController calls various private API functions on the header.
+ friend class mozilla::fuzzing::IPCFuzzController;
+#endif
+
+ enum {
+ NESTED_MASK = 0x0003,
+ PRIO_MASK = 0x001C,
+ SYNC_BIT = 0x0020,
+ REPLY_BIT = 0x0040,
+ REPLY_ERROR_BIT = 0x0080,
+ LAZY_SEND_BIT = 0x0100,
+ COMPRESS_BIT = 0x0200,
+ COMPRESSALL_BIT = 0x0400,
+ CONSTRUCTOR_BIT = 0x0800,
+ RELAY_BIT = 0x1000,
+ };
+
+ public:
+ constexpr HeaderFlags() : mFlags(NOT_NESTED) {}
+
+ explicit constexpr HeaderFlags(NestedLevel level) : mFlags(level) {}
+
+ constexpr HeaderFlags(NestedLevel level, PriorityValue priority,
+ MessageCompression compression, LazySend lazy_send,
+ Constructor constructor, Sync sync, Reply reply)
+ : mFlags(level | (priority << 2) |
+ (compression == COMPRESSION_ENABLED ? COMPRESS_BIT
+ : compression == COMPRESSION_ALL ? COMPRESSALL_BIT
+ : 0) |
+ (lazy_send == LAZY_SEND ? LAZY_SEND_BIT : 0) |
+ (constructor == CONSTRUCTOR ? CONSTRUCTOR_BIT : 0) |
+ (sync == SYNC ? SYNC_BIT : 0) |
+ (reply == REPLY ? REPLY_BIT : 0)) {}
+
+ NestedLevel Level() const {
+ return static_cast<NestedLevel>(mFlags & NESTED_MASK);
+ }
+
+ PriorityValue Priority() const {
+ return static_cast<PriorityValue>((mFlags & PRIO_MASK) >> 2);
+ }
+
+ MessageCompression Compression() const {
+ return ((mFlags & COMPRESS_BIT) ? COMPRESSION_ENABLED
+ : (mFlags & COMPRESSALL_BIT) ? COMPRESSION_ALL
+ : COMPRESSION_NONE);
+ }
+
+ bool IsLazySend() const { return (mFlags & LAZY_SEND_BIT) != 0; }
+
+ bool IsConstructor() const { return (mFlags & CONSTRUCTOR_BIT) != 0; }
+ bool IsSync() const { return (mFlags & SYNC_BIT) != 0; }
+ bool IsReply() const { return (mFlags & REPLY_BIT) != 0; }
+
+ bool IsReplyError() const { return (mFlags & REPLY_ERROR_BIT) != 0; }
+ bool IsRelay() const { return (mFlags & RELAY_BIT) != 0; }
+
+ private:
+ void SetConstructor() { mFlags |= CONSTRUCTOR_BIT; }
+ void SetSync() { mFlags |= SYNC_BIT; }
+ void SetReply() { mFlags |= REPLY_BIT; }
+ void SetReplyError() { mFlags |= REPLY_ERROR_BIT; }
+ void SetRelay(bool relay) {
+ if (relay) {
+ mFlags |= RELAY_BIT;
+ } else {
+ mFlags &= ~RELAY_BIT;
+ }
+ }
+
+ uint32_t mFlags;
+ };
+
+ virtual ~Message();
+
+ // Initialize a message with a user-defined type, priority value, and
+ // destination WebView ID.
+ Message(int32_t routing_id, msgid_t type,
+ uint32_t segmentCapacity = 0, // 0 for the default capacity.
+ HeaderFlags flags = HeaderFlags());
+
+ Message(const char* data, int data_len);
+
+ Message(const Message&) = delete;
+ Message(Message&&) = delete;
+ Message& operator=(const Message&) = delete;
+ Message& operator=(Message&&) = delete;
+
+ // Helper method for the common case (default segmentCapacity, recording
+ // the write latency of messages) of IPDL message creation. This helps
+ // move the malloc and some of the parameter setting out of autogenerated
+ // code.
+ static mozilla::UniquePtr<Message> IPDLMessage(int32_t routing_id,
+ msgid_t type,
+ uint32_t segmentCapacity,
+ HeaderFlags flags);
+
+ // One-off constructors for special error-handling messages.
+ static mozilla::UniquePtr<Message> ForSyncDispatchError(NestedLevel level);
+
+ NestedLevel nested_level() const { return header()->flags.Level(); }
+
+ PriorityValue priority() const { return header()->flags.Priority(); }
+
+ bool is_constructor() const { return header()->flags.IsConstructor(); }
+
+ // True if this is a synchronous message.
+ bool is_sync() const { return header()->flags.IsSync(); }
+
+ MessageCompression compress_type() const {
+ return header()->flags.Compression();
+ }
+
+ bool is_lazy_send() const { return header()->flags.IsLazySend(); }
+
+ bool is_reply() const { return header()->flags.IsReply(); }
+
+ bool is_reply_error() const { return header()->flags.IsReplyError(); }
+
+ msgid_t type() const { return header()->type; }
+
+ int32_t routing_id() const { return header()->routing; }
+
+ void set_routing_id(int32_t new_id) { header()->routing = new_id; }
+
+ int32_t transaction_id() const { return header()->txid; }
+
+ void set_transaction_id(int32_t txid) { header()->txid = txid; }
+
+ int32_t seqno() const { return header()->seqno; }
+
+ void set_seqno(int32_t aSeqno) { header()->seqno = aSeqno; }
+
+ const char* name() const { return StringFromIPCMessageType(type()); }
+
+ uint32_t num_handles() const;
+
+ bool is_relay() const { return header()->flags.IsRelay(); }
+ void set_relay(bool new_relay) { header()->flags.SetRelay(new_relay); }
+
+ template <class T>
+ static bool Dispatch(const Message* msg, T* obj, void (T::*func)()) {
+ (obj->*func)();
+ return true;
+ }
+
+ template <class T>
+ static bool Dispatch(const Message* msg, T* obj, void (T::*func)() const) {
+ (obj->*func)();
+ return true;
+ }
+
+ template <class T>
+ static bool Dispatch(const Message* msg, T* obj,
+ void (T::*func)(const Message&)) {
+ (obj->*func)(*msg);
+ return true;
+ }
+
+ template <class T>
+ static bool Dispatch(const Message* msg, T* obj,
+ void (T::*func)(const Message&) const) {
+ (obj->*func)(*msg);
+ return true;
+ }
+
+ // We should not be sending messages that are smaller than our header size.
+ void AssertAsLargeAsHeader() const;
+
+ // UserMessage implementation
+ size_t GetSizeIfSerialized() const override { return size(); }
+ bool WillBeRoutedExternally(mojo::core::ports::UserMessageEvent&) override;
+
+ // Write the given footer bytes to the end of the current message. The
+ // footer's `data_len` will be padded to a multiple of 4 bytes.
+ void WriteFooter(const void* data, uint32_t data_len);
+ // Read a footer written with `WriteFooter` from the end of the message, given
+ // a buffer and the length of the footer. If `truncate` is true, the message
+ // will be truncated, removing the footer.
+ [[nodiscard]] bool ReadFooter(void* buffer, uint32_t buffer_len,
+ bool truncate);
+
+ uint32_t event_footer_size() const { return header()->event_footer_size; }
+
+ void set_event_footer_size(uint32_t size) {
+ header()->event_footer_size = size;
+ }
+
+ static int HeaderSize() { return sizeof(Header); }
+
+ // Figure out how big the message starting at range_start is. Returns 0 if
+ // there's no enough data to determine (i.e., if [range_start, range_end) does
+ // not contain enough of the message header to know the size).
+ static uint32_t MessageSize(const char* range_start, const char* range_end) {
+ return Pickle::MessageSize(HeaderSize(), range_start, range_end);
+ }
+
+ bool WriteFileHandle(mozilla::UniqueFileHandle handle);
+
+ // WARNING: This method is marked as `const` so it can be called when
+ // deserializing the message, but will mutate it, consuming the handle.
+ bool ConsumeFileHandle(PickleIterator* iter,
+ mozilla::UniqueFileHandle* handle) const;
+
+ // Called when receiving an IPC message to attach file handles which were
+ // received from IPC. Must only be called when there are no handles on this
+ // IPC::Message.
+ void SetAttachedFileHandles(nsTArray<mozilla::UniqueFileHandle> handles);
+
+#if defined(XP_DARWIN)
+ void set_fd_cookie(uint32_t cookie) { header()->cookie = cookie; }
+ uint32_t fd_cookie() const { return header()->cookie; }
+#endif
+
+ void WritePort(mozilla::ipc::ScopedPort port);
+
+ // This method consumes the port from the message, preventing the message's
+ // destructor from destroying the port and meaning that future attempts to
+ // read this port will instead produce an invalid port.
+ //
+ // WARNING: This method is marked as `const` so it can be called when
+ // deserializing the message, but will mutate the message.
+ bool ConsumePort(PickleIterator* iter, mozilla::ipc::ScopedPort* port) const;
+
+ // Called when loading an IPC message to attach ports which were recieved form
+ // IPC. Must only be called when there are no ports on this IPC::Message.
+ void SetAttachedPorts(nsTArray<mozilla::ipc::ScopedPort> ports);
+
+#if defined(XP_DARWIN)
+ bool WriteMachSendRight(mozilla::UniqueMachSendRight port);
+
+ // WARNING: This method is marked as `const` so it can be called when
+ // deserializing the message, but will mutate it, consuming the send rights.
+ bool ConsumeMachSendRight(PickleIterator* iter,
+ mozilla::UniqueMachSendRight* port) const;
+
+ uint32_t num_send_rights() const;
+#endif
+
+ uint32_t num_relayed_attachments() const {
+#if defined(XP_WIN)
+ return num_handles();
+#elif defined(XP_DARWIN)
+ return num_send_rights();
+#else
+ return 0;
+#endif
+ }
+
+#ifdef FUZZING_SNAPSHOT
+ bool IsFuzzMsg() const { return isFuzzMsg; }
+ void SetFuzzMsg() { isFuzzMsg = true; }
+#endif
+
+ friend class Channel;
+ friend class MessageReplyDeserializer;
+ friend class SyncMessage;
+ friend class mozilla::ipc::MiniTransceiver;
+
+#if !defined(XP_DARWIN) && !defined(FUZZING_SNAPSHOT)
+ protected:
+#endif
+
+ struct Header : Pickle::Header {
+ int32_t routing; // ID of the view that this message is destined for
+ msgid_t type; // specifies the user-defined message type
+ HeaderFlags flags; // specifies control flags for the message
+ uint32_t num_handles; // the number of handles included with this message
+#if defined(XP_DARWIN)
+ uint32_t cookie; // cookie to ACK that the descriptors have been read.
+ uint32_t num_send_rights; // the number of mach send rights included with
+ // this message
+#endif
+ // For sync messages, a transaction ID for message ordering.
+ int32_t txid;
+ // Sequence number
+ int32_t seqno;
+ // Size of the message's event footer
+ uint32_t event_footer_size;
+ };
+
+ Header* header() { return headerT<Header>(); }
+ const Header* header() const { return headerT<Header>(); }
+
+ // The set of file handles which are attached to this message.
+ //
+ // Mutable, as this array can be mutated during `ReadHandle` when
+ // deserializing a message.
+ mutable nsTArray<mozilla::UniqueFileHandle> attached_handles_;
+
+ // The set of mojo ports which are attached to this message.
+ //
+ // Mutable, as this array can be mutated during `ConsumePort` when
+ // deserializing a message.
+ mutable nsTArray<mozilla::ipc::ScopedPort> attached_ports_;
+
+#if defined(XP_DARWIN)
+ // The set of mach send rights which are attached to this message.
+ //
+ // Mutable, as this array can be mutated during `ConsumeMachSendRight` when
+ // deserializing a message.
+ mutable nsTArray<mozilla::UniqueMachSendRight> attached_send_rights_;
+#endif
+
+#ifdef FUZZING_SNAPSHOT
+ bool isFuzzMsg = false;
+#endif
+};
+
+//------------------------------------------------------------------------------
+
+} // namespace IPC
+
+enum SpecialRoutingIDs {
+ // indicates that we don't have a routing ID yet.
+ MSG_ROUTING_NONE = kint32min,
+
+ // indicates a general message not sent to a particular tab.
+ MSG_ROUTING_CONTROL = kint32max
+};
+
+#define IPC_REPLY_ID 0xFFF0 // Special message id for replies
+#define IPC_LOGGING_ID 0xFFF1 // Special message id for logging
+
+#endif // CHROME_COMMON_IPC_MESSAGE_H__
diff --git a/ipc/chromium/src/chrome/common/ipc_message_utils.cc b/ipc/chromium/src/chrome/common/ipc_message_utils.cc
new file mode 100644
index 0000000000..49cb277e5f
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_message_utils.cc
@@ -0,0 +1,105 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/ipc/SharedMemory.h"
+#include "mozilla/ipc/SharedMemoryBasic.h"
+
+namespace IPC {
+
+static uint32_t kShmemThreshold = 64 * 1024;
+
+MessageBufferWriter::MessageBufferWriter(MessageWriter* writer,
+ uint32_t full_len)
+ : writer_(writer) {
+ if (full_len > kShmemThreshold) {
+ shmem_ = new mozilla::ipc::SharedMemoryBasic();
+ if (!shmem_->Create(full_len)) {
+ writer->FatalError("SharedMemory::Create failed!");
+ return;
+ }
+ if (!shmem_->Map(full_len)) {
+ writer->FatalError("SharedMemory::Map failed");
+ return;
+ }
+ if (!shmem_->WriteHandle(writer)) {
+ writer->FatalError("SharedMemory::WriterHandle failed");
+ return;
+ }
+ buffer_ = reinterpret_cast<char*>(shmem_->memory());
+ }
+ remaining_ = full_len;
+}
+
+MessageBufferWriter::~MessageBufferWriter() {
+ if (remaining_ != 0) {
+ writer_->FatalError("didn't fully write message buffer");
+ }
+}
+
+bool MessageBufferWriter::WriteBytes(const void* data, uint32_t len) {
+ MOZ_RELEASE_ASSERT(len == remaining_ || (len % 4) == 0,
+ "all writes except for the final write must be a multiple "
+ "of 4 bytes in length due to padding");
+ if (len > remaining_) {
+ writer_->FatalError("MessageBufferWriter overrun");
+ return false;
+ }
+ remaining_ -= len;
+ // If we're serializing using a shared memory region, `buffer_` will be
+ // initialized to point into that region.
+ if (buffer_) {
+ memcpy(buffer_, data, len);
+ buffer_ += len;
+ return true;
+ }
+ return writer_->WriteBytes(data, len);
+}
+
+MessageBufferReader::MessageBufferReader(MessageReader* reader,
+ uint32_t full_len)
+ : reader_(reader) {
+ if (full_len > kShmemThreshold) {
+ shmem_ = new mozilla::ipc::SharedMemoryBasic();
+ if (!shmem_->ReadHandle(reader)) {
+ reader->FatalError("SharedMemory::ReadHandle failed!");
+ return;
+ }
+ if (!shmem_->Map(full_len)) {
+ reader->FatalError("SharedMemory::Map failed");
+ return;
+ }
+ buffer_ = reinterpret_cast<const char*>(shmem_->memory());
+ }
+ remaining_ = full_len;
+}
+
+MessageBufferReader::~MessageBufferReader() {
+ if (remaining_ != 0) {
+ reader_->FatalError("didn't fully write message buffer");
+ }
+}
+
+bool MessageBufferReader::ReadBytesInto(void* data, uint32_t len) {
+ MOZ_RELEASE_ASSERT(len == remaining_ || (len % 4) == 0,
+ "all reads except for the final read must be a multiple "
+ "of 4 bytes in length due to padding");
+ if (len > remaining_) {
+ reader_->FatalError("MessageBufferReader overrun");
+ return false;
+ }
+ remaining_ -= len;
+ // If we're serializing using a shared memory region, `buffer_` will be
+ // initialized to point into that region.
+ if (buffer_) {
+ memcpy(data, buffer_, len);
+ buffer_ += len;
+ return true;
+ }
+ return reader_->ReadBytesInto(data, len);
+}
+
+} // namespace IPC
diff --git a/ipc/chromium/src/chrome/common/ipc_message_utils.h b/ipc/chromium/src/chrome/common/ipc_message_utils.h
new file mode 100644
index 0000000000..a624aa174a
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/ipc_message_utils.h
@@ -0,0 +1,1092 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef CHROME_COMMON_IPC_MESSAGE_UTILS_H_
+#define CHROME_COMMON_IPC_MESSAGE_UTILS_H_
+
+#include <cstdint>
+#include <iterator>
+#include <map>
+#include <unordered_map>
+#include <string>
+#include <type_traits>
+#include <utility>
+#include <vector>
+#include "ErrorList.h"
+#include "base/basictypes.h"
+#include "base/compiler_specific.h"
+#include "base/logging.h"
+#include "base/pickle.h"
+#include "base/string_util.h"
+#include "chrome/common/ipc_message.h"
+#include "mozilla/CheckedInt.h"
+#include "mozilla/IntegerRange.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+#endif
+
+template <typename T>
+class RefPtr;
+template <typename T>
+class nsCOMPtr;
+
+namespace mozilla::ipc {
+class IProtocol;
+template <typename P>
+struct IPDLParamTraits;
+class SharedMemory;
+
+// Implemented in ProtocolUtils.cpp
+MOZ_NEVER_INLINE void PickleFatalError(const char* aMsg, IProtocol* aActor);
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+/**
+ * Context used to serialize into an IPC::Message. Provides relevant context
+ * used when serializing.
+ */
+class MOZ_STACK_CLASS MessageWriter final {
+ public:
+ explicit MessageWriter(Message& message,
+ mozilla::ipc::IProtocol* actor = nullptr)
+ : message_(message), actor_(actor) {}
+
+ MessageWriter(const MessageWriter&) = delete;
+ MessageWriter& operator=(const MessageWriter&) = delete;
+
+ mozilla::ipc::IProtocol* GetActor() const { return actor_; }
+
+#define FORWARD_WRITE(name, type) \
+ bool Write##name(const type& result) { return message_.Write##name(result); }
+
+ FORWARD_WRITE(Bool, bool)
+ FORWARD_WRITE(Int16, int16_t)
+ FORWARD_WRITE(UInt16, uint16_t)
+ FORWARD_WRITE(Int, int)
+ FORWARD_WRITE(Long, long)
+ FORWARD_WRITE(ULong, unsigned long)
+ FORWARD_WRITE(Int32, int32_t)
+ FORWARD_WRITE(UInt32, uint32_t)
+ FORWARD_WRITE(Int64, int64_t)
+ FORWARD_WRITE(UInt64, uint64_t)
+ FORWARD_WRITE(Double, double)
+ FORWARD_WRITE(IntPtr, intptr_t)
+ FORWARD_WRITE(UnsignedChar, unsigned char)
+ FORWARD_WRITE(String, std::string)
+ FORWARD_WRITE(WString, std::wstring)
+
+#undef FORWARD_WRITE
+
+ bool WriteData(const char* data, uint32_t length) {
+ return message_.WriteData(data, length);
+ }
+
+ bool WriteBytes(const void* data, uint32_t data_len) {
+ return message_.WriteBytes(data, data_len);
+ }
+
+ bool WriteBytesZeroCopy(void* data, uint32_t data_len, uint32_t capacity) {
+ return message_.WriteBytesZeroCopy(data, data_len, capacity);
+ }
+
+ bool WriteSentinel(uint32_t sentinel) {
+ return message_.WriteSentinel(sentinel);
+ }
+
+ bool WriteFileHandle(mozilla::UniqueFileHandle handle) {
+ return message_.WriteFileHandle(std::move(handle));
+ }
+
+ void WritePort(mozilla::ipc::ScopedPort port) {
+ message_.WritePort(std::move(port));
+ }
+
+#if defined(XP_DARWIN)
+ bool WriteMachSendRight(mozilla::UniqueMachSendRight port) {
+ return message_.WriteMachSendRight(std::move(port));
+ }
+#endif
+
+ void FatalError(const char* aErrorMsg) const {
+ mozilla::ipc::PickleFatalError(aErrorMsg, actor_);
+ }
+
+ private:
+ Message& message_;
+ mozilla::ipc::IProtocol* actor_;
+};
+
+/**
+ * Context used to read data from an IPC::Message. Provides relevant context
+ * used when deserializing and tracks iteration.
+ */
+class MOZ_STACK_CLASS MessageReader final {
+ public:
+ explicit MessageReader(const Message& message,
+ mozilla::ipc::IProtocol* actor = nullptr)
+ : message_(message), iter_(message), actor_(actor) {}
+
+ MessageReader(const MessageReader&) = delete;
+ MessageReader& operator=(const MessageReader&) = delete;
+
+ mozilla::ipc::IProtocol* GetActor() const { return actor_; }
+
+#define FORWARD_READ(name, type) \
+ [[nodiscard]] bool Read##name(type* result) { \
+ return message_.Read##name(&iter_, result); \
+ }
+
+ FORWARD_READ(Bool, bool)
+ FORWARD_READ(Int16, int16_t)
+ FORWARD_READ(UInt16, uint16_t)
+ FORWARD_READ(Short, short)
+ FORWARD_READ(Int, int)
+ FORWARD_READ(Long, long)
+ FORWARD_READ(ULong, unsigned long)
+ FORWARD_READ(Int32, int32_t)
+ FORWARD_READ(UInt32, uint32_t)
+ FORWARD_READ(Int64, int64_t)
+ FORWARD_READ(UInt64, uint64_t)
+ FORWARD_READ(Double, double)
+ FORWARD_READ(IntPtr, intptr_t)
+ FORWARD_READ(UnsignedChar, unsigned char)
+ FORWARD_READ(String, std::string)
+ FORWARD_READ(WString, std::wstring)
+
+ // Special version of ReadInt() which rejects negative values
+ FORWARD_READ(Length, int);
+
+#undef FORWARD_READ
+
+ [[nodiscard]] bool ReadBytesInto(void* data, uint32_t length) {
+ return message_.ReadBytesInto(&iter_, data, length);
+ }
+
+ [[nodiscard]] bool IgnoreBytes(uint32_t length) {
+ return message_.IgnoreBytes(&iter_, length);
+ }
+
+ [[nodiscard]] bool ReadSentinel(uint32_t sentinel) {
+ return message_.ReadSentinel(&iter_, sentinel);
+ }
+
+ bool IgnoreSentinel() { return message_.IgnoreSentinel(&iter_); }
+
+ bool HasBytesAvailable(uint32_t len) {
+ return message_.HasBytesAvailable(&iter_, len);
+ }
+
+ void EndRead() { message_.EndRead(iter_, message_.type()); }
+
+ [[nodiscard]] bool ConsumeFileHandle(mozilla::UniqueFileHandle* handle) {
+ return message_.ConsumeFileHandle(&iter_, handle);
+ }
+
+ [[nodiscard]] bool ConsumePort(mozilla::ipc::ScopedPort* port) {
+ return message_.ConsumePort(&iter_, port);
+ }
+
+#if defined(XP_DARWIN)
+ [[nodiscard]] bool ConsumeMachSendRight(mozilla::UniqueMachSendRight* port) {
+ return message_.ConsumeMachSendRight(&iter_, port);
+ }
+#endif
+
+ void FatalError(const char* aErrorMsg) const {
+ mozilla::ipc::PickleFatalError(aErrorMsg, actor_);
+ }
+
+ private:
+ const Message& message_;
+ PickleIterator iter_;
+ mozilla::ipc::IProtocol* actor_;
+};
+
+namespace detail {
+
+// Helper for checking `T::kHasDeprecatedReadParamPrivateConstructor` using a
+// fallback when the member isn't defined.
+template <typename T>
+inline constexpr auto HasDeprecatedReadParamPrivateConstructor(int)
+ -> decltype(T::kHasDeprecatedReadParamPrivateConstructor) {
+ return T::kHasDeprecatedReadParamPrivateConstructor;
+}
+
+template <typename T>
+inline constexpr bool HasDeprecatedReadParamPrivateConstructor(...) {
+ return false;
+}
+
+} // namespace detail
+
+/**
+ * Result type returned from some `ParamTraits<T>::Read` implementations, and
+ * from `IPC::ReadParam<T>(MessageReader*)`. Either contains the value or
+ * indicates a failure to deserialize.
+ *
+ * This type can be thought of as a variant on `Maybe<T>`, except that it
+ * unconditionally constructs the underlying value if it is default
+ * constructible. This helps keep code size down, especially when calling
+ * outparameter-based ReadParam implementations (bug 1815177).
+ */
+template <typename T,
+ bool = std::is_default_constructible_v<T> ||
+ detail::HasDeprecatedReadParamPrivateConstructor<T>(0)>
+class ReadResult {
+ public:
+ ReadResult() = default;
+
+ template <typename U, std::enable_if_t<std::is_convertible_v<U, T>, int> = 0>
+ MOZ_IMPLICIT ReadResult(U&& aData)
+ : mIsOk(true), mData(std::forward<U>(aData)) {}
+
+ template <typename... Args>
+ explicit ReadResult(std::in_place_t, Args&&... aArgs)
+ : mIsOk(true), mData(std::forward<Args>(aArgs)...) {}
+
+ ReadResult(const ReadResult&) = default;
+ ReadResult(ReadResult&&) = default;
+
+ template <typename U, std::enable_if_t<std::is_convertible_v<U, T>, int> = 0>
+ MOZ_IMPLICIT ReadResult& operator=(U&& aData) {
+ mIsOk = true;
+ mData = std::forward<U>(aData);
+ return *this;
+ }
+
+ ReadResult& operator=(const ReadResult&) = default;
+ ReadResult& operator=(ReadResult&&) noexcept = default;
+
+ // Check if the ReadResult contains a valid value.
+ explicit operator bool() const { return isOk(); }
+ bool isOk() const { return mIsOk; }
+
+ // Get the data from this ReadResult.
+ T& get() {
+ MOZ_ASSERT(mIsOk);
+ return mData;
+ }
+ const T& get() const {
+ MOZ_ASSERT(mIsOk);
+ return mData;
+ }
+
+ T& operator*() { return get(); }
+ const T& operator*() const { return get(); }
+
+ T* operator->() { return &get(); }
+ const T* operator->() const { return &get(); }
+
+ // Try to extract a `Maybe<T>` from this ReadResult.
+ mozilla::Maybe<T> TakeMaybe() {
+ if (mIsOk) {
+ mIsOk = false;
+ return mozilla::Some(std::move(mData));
+ }
+ return mozilla::Nothing();
+ }
+
+ // Get the underlying data from this ReadResult, even if not OK.
+ //
+ // This is only available for types which are default constructible, and is
+ // used to optimize old-style `ReadParam` calls.
+ T& GetStorage() { return mData; }
+
+ // Compliment to `GetStorage` used to set the ReadResult into an OK state
+ // without constructing the underlying value.
+ void SetOk(bool aIsOk) { mIsOk = aIsOk; }
+
+ private:
+ bool mIsOk = false;
+ T mData{};
+};
+
+template <typename T>
+class ReadResult<T, false> {
+ public:
+ ReadResult() = default;
+
+ template <typename U, std::enable_if_t<std::is_convertible_v<U, T>, int> = 0>
+ MOZ_IMPLICIT ReadResult(U&& aData)
+ : mData(std::in_place, std::forward<U>(aData)) {}
+
+ template <typename... Args>
+ explicit ReadResult(std::in_place_t, Args&&... aArgs)
+ : mData(std::in_place, std::forward<Args>(aArgs)...) {}
+
+ ReadResult(const ReadResult&) = default;
+ ReadResult(ReadResult&&) = default;
+
+ template <typename U, std::enable_if_t<std::is_convertible_v<U, T>, int> = 0>
+ MOZ_IMPLICIT ReadResult& operator=(U&& aData) {
+ mData.reset();
+ mData.emplace(std::forward<U>(aData));
+ return *this;
+ }
+
+ ReadResult& operator=(const ReadResult&) = default;
+ ReadResult& operator=(ReadResult&&) noexcept = default;
+
+ // Check if the ReadResult contains a valid value.
+ explicit operator bool() const { return isOk(); }
+ bool isOk() const { return mData.isSome(); }
+
+ // Get the data from this ReadResult.
+ T& get() { return mData.ref(); }
+ const T& get() const { return mData.ref(); }
+
+ T& operator*() { return get(); }
+ const T& operator*() const { return get(); }
+
+ T* operator->() { return &get(); }
+ const T* operator->() const { return &get(); }
+
+ // Try to extract a `Maybe<T>` from this ReadResult.
+ mozilla::Maybe<T> TakeMaybe() { return std::move(mData); }
+
+ // These methods are only available if the type is default constructible.
+ T& GetStorage() = delete;
+ void SetOk(bool aIsOk) = delete;
+
+ private:
+ mozilla::Maybe<T> mData;
+};
+
+//-----------------------------------------------------------------------------
+// An iterator class for reading the fields contained within a Message.
+
+class MessageIterator {
+ public:
+ explicit MessageIterator(const Message& m) : msg_(m), iter_(m) {}
+ int NextInt() const {
+ int val;
+ if (!msg_.ReadInt(&iter_, &val)) NOTREACHED();
+ return val;
+ }
+ intptr_t NextIntPtr() const {
+ intptr_t val;
+ if (!msg_.ReadIntPtr(&iter_, &val)) NOTREACHED();
+ return val;
+ }
+ const std::string NextString() const {
+ std::string val;
+ if (!msg_.ReadString(&iter_, &val)) NOTREACHED();
+ return val;
+ }
+ const std::wstring NextWString() const {
+ std::wstring val;
+ if (!msg_.ReadWString(&iter_, &val)) NOTREACHED();
+ return val;
+ }
+
+ private:
+ const Message& msg_;
+ mutable PickleIterator iter_;
+};
+
+//-----------------------------------------------------------------------------
+// ParamTraits specializations, etc.
+//
+// The full set of types ParamTraits is specialized upon contains *possibly*
+// repeated types: unsigned long may be uint32_t or size_t, unsigned long long
+// may be uint64_t or size_t, nsresult may be uint32_t, and so on. You can't
+// have ParamTraits<unsigned int> *and* ParamTraits<uint32_t> if unsigned int
+// is uint32_t -- that's multiple definitions, and you can only have one.
+//
+// You could use #ifs and macro conditions to avoid duplicates, but they'd be
+// hairy: heavily dependent upon OS and compiler author choices, forced to
+// address all conflicts by hand. Happily there's a better way. The basic
+// idea looks like this, where T -> U represents T inheriting from U:
+//
+// class ParamTraits<P>
+// |
+// --> class ParamTraits1<P>
+// |
+// --> class ParamTraits2<P>
+// |
+// --> class ParamTraitsN<P> // or however many levels
+//
+// The default specialization of ParamTraits{M}<P> is an empty class that
+// inherits from ParamTraits{M + 1}<P> (or nothing in the base case).
+//
+// Now partition the set of parameter types into sets without duplicates.
+// Assign each set of types to a level M. Then specialize ParamTraitsM for
+// each of those types. A reference to ParamTraits<P> will consist of some
+// number of empty classes inheriting in sequence, ending in a non-empty
+// ParamTraits{N}<P>. It's okay for the parameter types to be duplicative:
+// either name of a type will resolve to the same ParamTraits{N}<P>.
+//
+// The nice thing is that because templates are instantiated lazily, if we
+// indeed have uint32_t == unsigned int, say, with the former in level N and
+// the latter in M > N, ParamTraitsM<unsigned int> won't be created (as long as
+// nobody uses ParamTraitsM<unsigned int>, but why would you), and no duplicate
+// code will be compiled or extra symbols generated. It's as efficient at
+// runtime as manually figuring out and avoiding conflicts by #ifs.
+//
+// The scheme we follow below names the various classes according to the types
+// in them, and the number of ParamTraits levels is larger, but otherwise it's
+// exactly the above idea.
+//
+
+template <class P>
+struct ParamTraits;
+
+template <typename P>
+inline void WriteParam(MessageWriter* writer, P&& p) {
+ ParamTraits<std::decay_t<P>>::Write(writer, std::forward<P>(p));
+}
+
+namespace detail {
+
+template <typename P>
+inline constexpr auto ParamTraitsReadUsesOutParam()
+ -> decltype(ParamTraits<P>::Read(std::declval<MessageReader*>(),
+ std::declval<P*>())) {
+ return true;
+}
+
+template <typename P>
+inline constexpr auto ParamTraitsReadUsesOutParam()
+ -> decltype(ParamTraits<P>::Read(std::declval<MessageReader*>()), bool{}) {
+ return false;
+}
+
+} // namespace detail
+
+template <typename P>
+inline bool WARN_UNUSED_RESULT ReadParam(MessageReader* reader, P* p) {
+ if constexpr (!detail::ParamTraitsReadUsesOutParam<P>()) {
+ auto maybe = ParamTraits<P>::Read(reader);
+ if (maybe) {
+ *p = std::move(*maybe);
+ return true;
+ }
+ return false;
+ } else {
+ return ParamTraits<P>::Read(reader, p);
+ }
+}
+
+template <typename P>
+inline ReadResult<P> WARN_UNUSED_RESULT ReadParam(MessageReader* reader) {
+ if constexpr (!detail::ParamTraitsReadUsesOutParam<P>()) {
+ return ParamTraits<P>::Read(reader);
+ } else {
+ ReadResult<P> p;
+ p.SetOk(ParamTraits<P>::Read(reader, &p.GetStorage()));
+ return p;
+ }
+}
+
+class MOZ_STACK_CLASS MessageBufferWriter {
+ public:
+ // Create a MessageBufferWriter to write `full_len` bytes into `writer`.
+ // If the length exceeds a threshold, a shared memory region may be used
+ // instead of including the data inline.
+ //
+ // NOTE: This does _NOT_ write out the length of the buffer.
+ // NOTE: Data written this way _MUST_ be read using `MessageBufferReader`.
+ MessageBufferWriter(MessageWriter* writer, uint32_t full_len);
+ ~MessageBufferWriter();
+
+ MessageBufferWriter(const MessageBufferWriter&) = delete;
+ MessageBufferWriter& operator=(const MessageBufferWriter&) = delete;
+
+ // Write `len` bytes from `data` into the message.
+ //
+ // Exactly `full_len` bytes should be written across multiple calls before the
+ // `MessageBufferWriter` is destroyed.
+ //
+ // WARNING: all writes (other than the last write) must be multiples of 4
+ // bytes in length. Not doing this will lead to padding being introduced into
+ // the payload and break things. This can probably be improved in the future
+ // with deeper integration between `MessageBufferWriter` and `Pickle`.
+ bool WriteBytes(const void* data, uint32_t len);
+
+ private:
+ MessageWriter* writer_;
+ RefPtr<mozilla::ipc::SharedMemory> shmem_;
+ char* buffer_ = nullptr;
+ uint32_t remaining_ = 0;
+};
+
+class MOZ_STACK_CLASS MessageBufferReader {
+ public:
+ // Create a MessageBufferReader to read `full_len` bytes from `reader` which
+ // were written using `MessageBufferWriter`.
+ //
+ // NOTE: This may consume a shared memory region from the message, meaning
+ // that the same data cannot be read multiple times.
+ // NOTE: Data read this way _MUST_ be written using `MessageBufferWriter`.
+ MessageBufferReader(MessageReader* reader, uint32_t full_len);
+ ~MessageBufferReader();
+
+ MessageBufferReader(const MessageBufferReader&) = delete;
+ MessageBufferReader& operator=(const MessageBufferReader&) = delete;
+
+ // Read `count` bytes from the message into `data`.
+ //
+ // Exactly `full_len` bytes should be read across multiple calls before the
+ // `MessageBufferReader` is destroyed.
+ //
+ // WARNING: all reads (other than the last read) must be multiples of 4 bytes
+ // in length. Not doing this will lead to bytes being skipped in the payload
+ // and break things. This can probably be improved in the future with deeper
+ // integration between `MessageBufferReader` and `Pickle`.
+ [[nodiscard]] bool ReadBytesInto(void* data, uint32_t len);
+
+ private:
+ MessageReader* reader_;
+ RefPtr<mozilla::ipc::SharedMemory> shmem_;
+ const char* buffer_ = nullptr;
+ uint32_t remaining_ = 0;
+};
+
+// Whether or not it is safe to serialize the given type using
+// `WriteBytesOrShmem`.
+template <typename P>
+constexpr bool kUseWriteBytes =
+ !std::is_same_v<std::remove_const_t<std::remove_reference_t<P>>, bool> &&
+ (std::is_integral_v<std::remove_const_t<std::remove_reference_t<P>>> ||
+ std::is_floating_point_v<std::remove_const_t<std::remove_reference_t<P>>>);
+
+/**
+ * Helper for writing a contiguous sequence (such as for a string or array) into
+ * a message, with optimizations for basic integral and floating point types.
+ *
+ * Integral types will be copied into shared memory if the sequence exceeds 64k
+ * bytes in size.
+ *
+ * Values written with this method must be read with `ReadSequenceParam`.
+ *
+ * The type parameter specifies the semantics to use, and should generally
+ * either be `P&&` or `const P&`. The constness of the `data` argument should
+ * match this parameter.
+ */
+template <typename P>
+void WriteSequenceParam(MessageWriter* writer, std::remove_reference_t<P>* data,
+ size_t length) {
+ mozilla::CheckedUint32 ipc_length(length);
+ if (!ipc_length.isValid()) {
+ writer->FatalError("invalid length passed to WriteSequenceParam");
+ return;
+ }
+ writer->WriteUInt32(ipc_length.value());
+
+ if constexpr (kUseWriteBytes<P>) {
+ mozilla::CheckedUint32 byte_length =
+ ipc_length * sizeof(std::remove_reference_t<P>);
+ if (!byte_length.isValid()) {
+ writer->FatalError("invalid byte length in WriteSequenceParam");
+ return;
+ }
+ MessageBufferWriter buf_writer(writer, byte_length.value());
+ buf_writer.WriteBytes(data, byte_length.value());
+ } else {
+ auto* end = data + length;
+ for (auto* it = data; it != end; ++it) {
+ WriteParam(writer, std::forward<P>(*it));
+ }
+ }
+}
+
+template <typename P>
+bool ReadSequenceParamImpl(MessageReader* reader, P* data, uint32_t length) {
+ if (length == 0) {
+ return true;
+ }
+ if (!data) {
+ reader->FatalError("allocation failed in ReadSequenceParam");
+ return false;
+ }
+
+ if constexpr (kUseWriteBytes<P>) {
+ mozilla::CheckedUint32 byte_length(length);
+ byte_length *= sizeof(P);
+ if (!byte_length.isValid()) {
+ reader->FatalError("invalid byte length in ReadSequenceParam");
+ return false;
+ }
+ MessageBufferReader buf_reader(reader, byte_length.value());
+ return buf_reader.ReadBytesInto(data, byte_length.value());
+ } else {
+ P* end = data + length;
+ for (auto* it = data; it != end; ++it) {
+ if (!ReadParam(reader, it)) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
+
+template <typename P, typename I>
+bool ReadSequenceParamImpl(MessageReader* reader, mozilla::Maybe<I>&& data,
+ uint32_t length) {
+ static_assert(!kUseWriteBytes<P>,
+ "Cannot return an output iterator if !kUseWriteBytes<P>");
+ static_assert(
+ std::is_base_of_v<std::output_iterator_tag,
+ typename std::iterator_traits<I>::iterator_category>,
+ "must be Maybe<output iterator>");
+ if (length == 0) {
+ return true;
+ }
+ if (!data) {
+ reader->FatalError("allocation failed in ReadSequenceParam");
+ return false;
+ }
+
+ for (uint32_t i = 0; i < length; ++i) {
+ auto elt = ReadParam<P>(reader);
+ if (!elt) {
+ return false;
+ }
+ *data.ref() = std::move(*elt);
+ ++data.ref();
+ }
+ return true;
+}
+
+/**
+ * Helper for reading a contiguous sequence (such as a string or array) into a
+ * message which was previously written using `WriteSequenceParam`.
+ *
+ * The function argument `allocator` will be called with the length of the
+ * sequence, and must return either a pointer to the memory region which the
+ * sequence should be read into, or a Maybe of a C++ output iterator which will
+ * infallibly accept length elements, and append them to the output sequence.
+ *
+ * If the type satisfies kUseWriteBytes, output iterators are not supported.
+ */
+template <typename P, typename F>
+bool WARN_UNUSED_RESULT ReadSequenceParam(MessageReader* reader,
+ F&& allocator) {
+ uint32_t length = 0;
+ if (!reader->ReadUInt32(&length)) {
+ reader->FatalError("failed to read byte length in ReadSequenceParam");
+ return false;
+ }
+
+ return ReadSequenceParamImpl<P>(reader, allocator(length), length);
+}
+
+// Temporary fallback class to allow types to declare serialization using the
+// IPDLParamTraits type class. Will be removed once all remaining
+// IPDLParamTraits implementations are gone. (bug 1754009)
+
+template <class P>
+struct ParamTraitsIPDLFallback {
+ template <class R>
+ static auto Write(MessageWriter* writer, R&& p)
+ -> decltype(mozilla::ipc::IPDLParamTraits<P>::Write(writer,
+ writer->GetActor(),
+ std::forward<R>(p))) {
+ mozilla::ipc::IPDLParamTraits<P>::Write(writer, writer->GetActor(),
+ std::forward<R>(p));
+ }
+ template <class R>
+ static auto Read(MessageReader* reader, R* r)
+ -> decltype(mozilla::ipc::IPDLParamTraits<P>::Read(reader,
+ reader->GetActor(),
+ r)) {
+ return mozilla::ipc::IPDLParamTraits<P>::Read(reader, reader->GetActor(),
+ r);
+ }
+};
+
+// Fundamental types.
+
+template <class P>
+struct ParamTraitsFundamental : ParamTraitsIPDLFallback<P> {};
+
+template <>
+struct ParamTraitsFundamental<bool> {
+ typedef bool param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteBool(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadBool(r);
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<int> {
+ typedef int param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteInt(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadInt(r);
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<long> {
+ typedef long param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteLong(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadLong(r);
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<unsigned long> {
+ typedef unsigned long param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteULong(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadULong(r);
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<long long> {
+ typedef long long param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteBytes(&p, sizeof(param_type));
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadBytesInto(r, sizeof(*r));
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<unsigned long long> {
+ typedef unsigned long long param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteBytes(&p, sizeof(param_type));
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadBytesInto(r, sizeof(*r));
+ }
+};
+
+template <>
+struct ParamTraitsFundamental<double> {
+ typedef double param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteDouble(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadDouble(r);
+ }
+};
+
+// Fixed-size <stdint.h> types.
+
+template <class P>
+struct ParamTraitsFixed : ParamTraitsFundamental<P> {};
+
+template <>
+struct ParamTraitsFixed<int16_t> {
+ typedef int16_t param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteInt16(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadInt16(r);
+ }
+};
+
+template <>
+struct ParamTraitsFixed<uint16_t> {
+ typedef uint16_t param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteUInt16(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadUInt16(r);
+ }
+};
+
+template <>
+struct ParamTraitsFixed<uint32_t> {
+ typedef uint32_t param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteUInt32(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadUInt32(r);
+ }
+};
+
+template <>
+struct ParamTraitsFixed<int64_t> {
+ typedef int64_t param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteInt64(p);
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadInt64(r);
+ }
+};
+
+template <>
+struct ParamTraitsFixed<uint64_t> {
+ typedef uint64_t param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteInt64(static_cast<int64_t>(p));
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadInt64(reinterpret_cast<int64_t*>(r));
+ }
+};
+
+// std::* types.
+
+template <class P>
+struct ParamTraitsStd : ParamTraitsFixed<P> {};
+
+template <class T>
+struct ParamTraitsStd<std::basic_string<T>> {
+ typedef std::basic_string<T> param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ WriteSequenceParam<const T&>(writer, p.data(), p.size());
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return ReadSequenceParam<T>(reader, [&](uint32_t length) -> T* {
+ r->resize(length);
+ return r->data();
+ });
+ }
+};
+
+template <class K, class V>
+struct ParamTraitsStd<std::map<K, V>> {
+ typedef std::map<K, V> param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ WriteParam(writer, static_cast<int>(p.size()));
+ typename param_type::const_iterator iter;
+ for (iter = p.begin(); iter != p.end(); ++iter) {
+ WriteParam(writer, iter->first);
+ WriteParam(writer, iter->second);
+ }
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ int size;
+ if (!ReadParam(reader, &size) || size < 0) return false;
+ for (int i = 0; i < size; ++i) {
+ K k;
+ if (!ReadParam(reader, &k)) return false;
+ V& value = (*r)[k];
+ if (!ReadParam(reader, &value)) return false;
+ }
+ return true;
+ }
+};
+
+// Windows-specific types.
+
+template <class P>
+struct ParamTraitsWindows : ParamTraitsStd<P> {};
+
+#if defined(XP_WIN)
+template <>
+struct ParamTraitsWindows<HANDLE> {
+ static_assert(sizeof(HANDLE) == sizeof(intptr_t), "Wrong size for HANDLE?");
+
+ static void Write(MessageWriter* writer, HANDLE p) {
+ writer->WriteIntPtr(reinterpret_cast<intptr_t>(p));
+ }
+ static bool Read(MessageReader* reader, HANDLE* r) {
+ return reader->ReadIntPtr(reinterpret_cast<intptr_t*>(r));
+ }
+};
+
+template <>
+struct ParamTraitsWindows<HWND> {
+ static_assert(sizeof(HWND) == sizeof(intptr_t), "Wrong size for HWND?");
+
+ static void Write(MessageWriter* writer, HWND p) {
+ writer->WriteIntPtr(reinterpret_cast<intptr_t>(p));
+ }
+ static bool Read(MessageReader* reader, HWND* r) {
+ return reader->ReadIntPtr(reinterpret_cast<intptr_t*>(r));
+ }
+};
+#endif // defined(XP_WIN)
+
+// Various ipc/chromium types.
+
+template <class P>
+struct ParamTraitsIPC : ParamTraitsWindows<P> {};
+
+// `UniqueFileHandle` may be serialized over IPC channels. On the receiving
+// side, the UniqueFileHandle is a valid duplicate of the handle which was
+// transmitted.
+//
+// When sending a UniqueFileHandle, the handle must be valid at the time of
+// transmission. As transmission is asynchronous, this requires passing
+// ownership of the handle to IPC.
+//
+// A UniqueFileHandle may only be read once. After it has been read once, it
+// will be consumed, and future reads will return an invalid handle.
+template <>
+struct ParamTraitsIPC<mozilla::UniqueFileHandle> {
+ typedef mozilla::UniqueFileHandle param_type;
+ static void Write(MessageWriter* writer, param_type&& p) {
+ const bool valid = p != nullptr;
+ WriteParam(writer, valid);
+ if (valid) {
+ if (!writer->WriteFileHandle(std::move(p))) {
+ writer->FatalError("Too many file handles for one message!");
+ NOTREACHED() << "Too many file handles for one message!";
+ }
+ }
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ bool valid;
+ if (!ReadParam(reader, &valid)) {
+ reader->FatalError("Error reading file handle validity");
+ return false;
+ }
+
+ if (!valid) {
+ *r = nullptr;
+ return true;
+ }
+
+ if (!reader->ConsumeFileHandle(r)) {
+ reader->FatalError("File handle not found in message!");
+ return false;
+ }
+ return true;
+ }
+};
+
+#if defined(XP_DARWIN)
+// `UniqueMachSendRight` may be serialized over IPC channels. On the receiving
+// side, the UniqueMachSendRight is the local name of the right which was
+// transmitted.
+//
+// When sending a UniqueMachSendRight, the right must be valid at the time of
+// transmission. As transmission is asynchronous, this requires passing
+// ownership of the handle to IPC.
+//
+// A UniqueMachSendRight may only be read once. After it has been read once, it
+// will be consumed, and future reads will return an invalid right.
+template <>
+struct ParamTraitsIPC<mozilla::UniqueMachSendRight> {
+ typedef mozilla::UniqueMachSendRight param_type;
+ static void Write(MessageWriter* writer, param_type&& p) {
+ const bool valid = p != nullptr;
+ WriteParam(writer, valid);
+ if (valid) {
+ if (!writer->WriteMachSendRight(std::move(p))) {
+ writer->FatalError("Too many mach send rights for one message!");
+ NOTREACHED() << "Too many mach send rights for one message!";
+ }
+ }
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ bool valid;
+ if (!ReadParam(reader, &valid)) {
+ reader->FatalError("Error reading mach send right validity");
+ return false;
+ }
+
+ if (!valid) {
+ *r = nullptr;
+ return true;
+ }
+
+ if (!reader->ConsumeMachSendRight(r)) {
+ reader->FatalError("Mach send right not found in message!");
+ return false;
+ }
+ return true;
+ }
+};
+#endif
+
+// Mozilla-specific types.
+
+template <class P>
+struct ParamTraitsMozilla : ParamTraitsIPC<P> {};
+
+// Sending-only specialization for mozilla::Span<T const>. Uses an identical
+// serialization format as `const nsTArray<T>&`.
+template <class T>
+struct ParamTraitsMozilla<mozilla::Span<const T>> {
+ static void Write(MessageWriter* writer, mozilla::Span<const T> p) {
+ WriteSequenceParam<const T>(writer, p.Elements(), p.Length());
+ }
+};
+
+template <>
+struct ParamTraitsMozilla<nsresult> {
+ typedef nsresult param_type;
+ static void Write(MessageWriter* writer, const param_type& p) {
+ writer->WriteUInt32(static_cast<uint32_t>(p));
+ }
+ static bool Read(MessageReader* reader, param_type* r) {
+ return reader->ReadUInt32(reinterpret_cast<uint32_t*>(r));
+ }
+};
+
+// See comments for the IPDLParamTraits specializations for RefPtr<T> and
+// nsCOMPtr<T> for more details.
+template <class T>
+struct ParamTraitsMozilla<RefPtr<T>> {
+ static void Write(MessageWriter* writer, const RefPtr<T>& p) {
+ ParamTraits<T*>::Write(writer, p.get());
+ }
+
+ static bool Read(MessageReader* reader, RefPtr<T>* r) {
+ return ParamTraits<T*>::Read(reader, r);
+ }
+};
+
+template <class T>
+struct ParamTraitsMozilla<nsCOMPtr<T>> {
+ static void Write(MessageWriter* writer, const nsCOMPtr<T>& p) {
+ ParamTraits<T*>::Write(writer, p.get());
+ }
+
+ static bool Read(MessageReader* reader, nsCOMPtr<T>* r) {
+ RefPtr<T> refptr;
+ if (!ParamTraits<T*>::Read(reader, &refptr)) {
+ return false;
+ }
+ *r = std::move(refptr);
+ return true;
+ }
+};
+
+template <class T>
+struct ParamTraitsMozilla<mozilla::NotNull<T>> {
+ static void Write(MessageWriter* writer, const mozilla::NotNull<T>& p) {
+ ParamTraits<T>::Write(writer, p.get());
+ }
+
+ static ReadResult<mozilla::NotNull<T>> Read(MessageReader* reader) {
+ auto ptr = ReadParam<T>(reader);
+ if (!ptr) {
+ return {};
+ }
+ if (!*ptr) {
+ reader->FatalError("unexpected null value");
+ return {};
+ }
+ return mozilla::WrapNotNull(std::move(*ptr));
+ }
+};
+
+// Finally, ParamTraits itself.
+
+template <class P>
+struct ParamTraits : ParamTraitsMozilla<P> {};
+
+} // namespace IPC
+
+#endif // CHROME_COMMON_IPC_MESSAGE_UTILS_H_
diff --git a/ipc/chromium/src/chrome/common/mach_ipc_mac.cc b/ipc/chromium/src/chrome/common/mach_ipc_mac.cc
new file mode 100644
index 0000000000..2fa1a47fd3
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/mach_ipc_mac.cc
@@ -0,0 +1,93 @@
+// Copyright (c) 2006-2008 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.
+
+#include "chrome/common/mach_ipc_mac.h"
+
+#include "base/logging.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "nsDebug.h"
+
+namespace {
+// Struct for sending a Mach message with a single port.
+struct MachSinglePortMessage {
+ mach_msg_header_t header;
+ mach_msg_body_t body;
+ mach_msg_port_descriptor_t data;
+};
+
+// Struct for receiving a Mach message with a single port.
+struct MachSinglePortMessageTrailer : MachSinglePortMessage {
+ mach_msg_audit_trailer_t trailer;
+};
+} // namespace
+
+//==============================================================================
+kern_return_t MachSendPortSendRight(
+ mach_port_t endpoint, mach_port_t attachment,
+ mozilla::Maybe<mach_msg_timeout_t> opt_timeout,
+ mach_msg_type_name_t endpoint_disposition) {
+ mach_msg_option_t opts = MACH_SEND_MSG;
+ mach_msg_timeout_t timeout = MACH_MSG_TIMEOUT_NONE;
+ if (opt_timeout) {
+ opts |= MACH_SEND_TIMEOUT;
+ timeout = *opt_timeout;
+ }
+
+ MachSinglePortMessage send_msg{};
+ send_msg.header.msgh_bits =
+ MACH_MSGH_BITS(endpoint_disposition, 0) | MACH_MSGH_BITS_COMPLEX;
+ send_msg.header.msgh_size = sizeof(send_msg);
+ send_msg.header.msgh_remote_port = endpoint;
+ send_msg.header.msgh_local_port = MACH_PORT_NULL;
+ send_msg.header.msgh_reserved = 0;
+ send_msg.header.msgh_id = 0;
+ send_msg.body.msgh_descriptor_count = 1;
+ send_msg.data.name = attachment;
+ send_msg.data.disposition = MACH_MSG_TYPE_COPY_SEND;
+ send_msg.data.type = MACH_MSG_PORT_DESCRIPTOR;
+
+ return mach_msg(&send_msg.header, opts, send_msg.header.msgh_size, 0,
+ MACH_PORT_NULL, timeout, MACH_PORT_NULL);
+}
+
+//==============================================================================
+kern_return_t MachReceivePortSendRight(
+ const mozilla::UniqueMachReceiveRight& endpoint,
+ mozilla::Maybe<mach_msg_timeout_t> opt_timeout,
+ mozilla::UniqueMachSendRight* attachment, audit_token_t* audit_token) {
+ mach_msg_option_t opts = MACH_RCV_MSG |
+ MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) |
+ MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT);
+ mach_msg_timeout_t timeout = MACH_MSG_TIMEOUT_NONE;
+ if (opt_timeout) {
+ opts |= MACH_RCV_TIMEOUT;
+ timeout = *opt_timeout;
+ }
+
+ MachSinglePortMessageTrailer recv_msg{};
+ recv_msg.header.msgh_local_port = endpoint.get();
+ recv_msg.header.msgh_size = sizeof(recv_msg);
+
+ kern_return_t kr =
+ mach_msg(&recv_msg.header, opts, 0, recv_msg.header.msgh_size,
+ endpoint.get(), timeout, MACH_PORT_NULL);
+ if (kr != KERN_SUCCESS) {
+ return kr;
+ }
+
+ if (NS_WARN_IF(!(recv_msg.header.msgh_bits & MACH_MSGH_BITS_COMPLEX)) ||
+ NS_WARN_IF(recv_msg.body.msgh_descriptor_count != 1) ||
+ NS_WARN_IF(recv_msg.data.type != MACH_MSG_PORT_DESCRIPTOR) ||
+ NS_WARN_IF(recv_msg.data.disposition != MACH_MSG_TYPE_MOVE_SEND) ||
+ NS_WARN_IF(recv_msg.header.msgh_size != sizeof(MachSinglePortMessage))) {
+ mach_msg_destroy(&recv_msg.header);
+ return KERN_FAILURE; // Invalid message format
+ }
+
+ attachment->reset(recv_msg.data.name);
+ if (audit_token) {
+ *audit_token = recv_msg.trailer.msgh_audit;
+ }
+ return KERN_SUCCESS;
+}
diff --git a/ipc/chromium/src/chrome/common/mach_ipc_mac.h b/ipc/chromium/src/chrome/common/mach_ipc_mac.h
new file mode 100644
index 0000000000..c9af70c0c6
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/mach_ipc_mac.h
@@ -0,0 +1,40 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef BASE_MACH_IPC_MAC_H_
+#define BASE_MACH_IPC_MAC_H_
+
+#include <mach/mach.h>
+#include <mach/message.h>
+#include <servers/bootstrap.h>
+#include <sys/types.h>
+
+#include "mozilla/Maybe.h"
+#include "mozilla/Result.h"
+#include "mozilla/UniquePtrExtensions.h"
+
+//==============================================================================
+// Helper function for sending a minimal mach IPC messages with a single send
+// right attached. The endpoint will not be consumed unless the
+// `endpoint_disposition` argument is set to a consuming disposition, and
+// `KERN_SUCCESS` is returned.
+kern_return_t MachSendPortSendRight(
+ mach_port_t endpoint, mach_port_t attachment,
+ mozilla::Maybe<mach_msg_timeout_t> opt_timeout,
+ mach_msg_type_name_t endpoint_disposition = MACH_MSG_TYPE_COPY_SEND);
+
+//==============================================================================
+// Helper function for receiving a minimal mach IPC message with a single send
+// right attached.
+// If the `audit_token` parameter is provided, it will be populated with the
+// sender's audit token, which can be used to verify the identity of the sender.
+kern_return_t MachReceivePortSendRight(
+ const mozilla::UniqueMachReceiveRight& endpoint,
+ mozilla::Maybe<mach_msg_timeout_t> opt_timeout,
+ mozilla::UniqueMachSendRight* attachment,
+ audit_token_t* audit_token = nullptr);
+
+#endif // BASE_MACH_IPC_MAC_H_
diff --git a/ipc/chromium/src/chrome/common/mach_message_source_mac.cc b/ipc/chromium/src/chrome/common/mach_message_source_mac.cc
new file mode 100644
index 0000000000..d3be7efdb5
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/mach_message_source_mac.cc
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#include "chrome/common/mach_message_source_mac.h"
+
+#include "base/logging.h"
+
+MachMessageSource::MachMessageSource(mach_port_t port,
+ MachPortListener* msg_listener,
+ bool* success) {
+ DCHECK(msg_listener);
+ DCHECK(success);
+ DCHECK(port != MACH_PORT_NULL);
+
+ CFMachPortContext port_context = {0};
+ port_context.info = msg_listener;
+
+ scoped_cftyperef<CFMachPortRef> cf_mach_port_ref(CFMachPortCreateWithPort(
+ kCFAllocatorDefault, port, MachMessageSource::OnReceiveMachMessage,
+ &port_context, NULL));
+
+ if (cf_mach_port_ref.get() == NULL) {
+ CHROMIUM_LOG(WARNING) << "CFMachPortCreate failed";
+ *success = false;
+ return;
+ }
+
+ // Create a RL source.
+ machport_runloop_ref_.reset(CFMachPortCreateRunLoopSource(
+ kCFAllocatorDefault, cf_mach_port_ref.get(), 0));
+
+ if (machport_runloop_ref_.get() == NULL) {
+ CHROMIUM_LOG(WARNING) << "CFMachPortCreateRunLoopSource failed";
+ *success = false;
+ return;
+ }
+
+ CFRunLoopAddSource(CFRunLoopGetCurrent(), machport_runloop_ref_.get(),
+ kCFRunLoopCommonModes);
+ *success = true;
+}
+
+MachMessageSource::~MachMessageSource() {
+ CFRunLoopRemoveSource(CFRunLoopGetCurrent(), machport_runloop_ref_.get(),
+ kCFRunLoopCommonModes);
+}
+
+// static
+void MachMessageSource::OnReceiveMachMessage(CFMachPortRef port, void* msg,
+ CFIndex size, void* closure) {
+ MachPortListener* msg_listener = static_cast<MachPortListener*>(closure);
+ size_t msg_size = (size < 0) ? 0 : static_cast<size_t>(size);
+ DCHECK(msg && msg_size > 0); // this should never happen!
+
+ if (msg_listener && msg && msg_size > 0) {
+ msg_listener->OnMachMessageReceived(msg, msg_size);
+ }
+}
diff --git a/ipc/chromium/src/chrome/common/mach_message_source_mac.h b/ipc/chromium/src/chrome/common/mach_message_source_mac.h
new file mode 100644
index 0000000000..92ce0a73d4
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/mach_message_source_mac.h
@@ -0,0 +1,60 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2008 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.
+
+#ifndef CHROME_COMMON_MACH_MESSAGE_SOURCE_MAC_H_
+#define CHROME_COMMON_MACH_MESSAGE_SOURCE_MAC_H_
+
+#include <CoreServices/CoreServices.h>
+
+#include "base/scoped_cftyperef.h"
+
+// Handles registering and cleaning up after a CFRunloopSource for a Mach port.
+// Messages received on the port are piped through to a delegate.
+//
+// Example:
+// class MyListener : public MachMessageSource::MachPortListener {
+// public:
+// void OnMachMessageReceived(void* mach_msg, size_t size) {
+// printf("received message on Mach port\n");
+// }
+// };
+//
+// mach_port_t a_port = ...;
+// MyListener listener;
+// bool success = false;
+// MachMessageSource message_source(port, listener, &success);
+//
+// if (!success) {
+// exit(1); // Couldn't register mach runloop source.
+// }
+//
+// CFRunLoopRun(); // Process messages on runloop...
+class MachMessageSource {
+ public:
+ // Classes that want to listen on a Mach port can implement
+ // OnMachMessageReceived, |mach_msg| is a pointer to the raw message data and
+ // |size| is the buffer size;
+ class MachPortListener {
+ public:
+ virtual void OnMachMessageReceived(void* mach_msg, size_t size) = 0;
+ };
+
+ // |listener| is a week reference passed to CF, it needs to remain in
+ // existence till this object is destroeyd.
+ MachMessageSource(mach_port_t port, MachPortListener* listener,
+ bool* success);
+ ~MachMessageSource();
+
+ private:
+ // Called by CF when a new message arrives on the Mach port.
+ static void OnReceiveMachMessage(CFMachPortRef port, void* msg, CFIndex size,
+ void* closure);
+
+ scoped_cftyperef<CFRunLoopSourceRef> machport_runloop_ref_;
+ DISALLOW_COPY_AND_ASSIGN(MachMessageSource);
+};
+
+#endif // CHROME_COMMON_MACH_MESSAGE_SOURCE_MAC_H_
diff --git a/ipc/chromium/src/chrome/common/process_watcher.h b/ipc/chromium/src/chrome/common/process_watcher.h
new file mode 100644
index 0000000000..f1ccae6310
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/process_watcher.h
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#ifndef CHROME_COMMON_PROCESS_WATCHER_H_
+#define CHROME_COMMON_PROCESS_WATCHER_H_
+
+#include "base/basictypes.h"
+#include "base/process_util.h"
+
+class ProcessWatcher {
+ public:
+ // This method ensures that the specified process eventually terminates, and
+ // then it closes the given process handle.
+ //
+ // It assumes that the process has already been signalled to exit, and it
+ // begins by waiting a small amount of time for it to exit. If the process
+ // does not appear to have exited, then this function starts to become
+ // aggressive about ensuring that the process terminates.
+ //
+ // This method does not block the calling thread.
+ //
+ // NOTE: The process handle must have been opened with the PROCESS_TERMINATE
+ // and SYNCHRONIZE permissions.
+ //
+ static void EnsureProcessTerminated(base::ProcessHandle process_handle,
+ bool force = true);
+
+ private:
+ // Do not instantiate this class.
+ ProcessWatcher();
+
+ DISALLOW_COPY_AND_ASSIGN(ProcessWatcher);
+};
+
+#endif // CHROME_COMMON_PROCESS_WATCHER_H_
diff --git a/ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc b/ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc
new file mode 100644
index 0000000000..8f62dfdbda
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/process_watcher_posix_sigchld.cc
@@ -0,0 +1,257 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <errno.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <time.h>
+
+#include "base/eintr_wrapper.h"
+#include "base/message_loop.h"
+#include "base/process_util.h"
+#include "prenv.h"
+
+#include "chrome/common/process_watcher.h"
+
+// Maximum amount of time (in milliseconds) to wait for the process to exit.
+// XXX/cjones: fairly arbitrary, chosen to match process_watcher_win.cc
+static constexpr int kMaxWaitMs = 2000;
+
+// This is also somewhat arbitrary, but loosely based on Try results.
+// See also toolkit.asyncshutdown.crash_timeout (currently 60s) after
+// which the parent process will be killed.
+#ifdef MOZ_CODE_COVERAGE
+// Code coverage instrumentation can be slow (especially when writing
+// out data, which has to take a lock on the data files).
+static constexpr int kShutdownWaitMs = 80000;
+#elif defined(MOZ_ASAN) || defined(MOZ_TSAN)
+// Sanitizers slow things down in some cases; see bug 1806224.
+static constexpr int kShutdownWaitMs = 40000;
+#else
+static constexpr int kShutdownWaitMs = 8000;
+#endif
+
+namespace {
+
+class ChildReaper : public base::MessagePumpLibevent::SignalEvent,
+ public base::MessagePumpLibevent::SignalWatcher {
+ public:
+ explicit ChildReaper(pid_t process) : process_(process) {}
+
+ virtual ~ChildReaper() {
+ // subclasses should have cleaned up |process_| already
+ DCHECK(!process_);
+
+ // StopCatching() is implicit
+ }
+
+ virtual void OnSignal(int sig) override {
+ DCHECK(SIGCHLD == sig);
+ DCHECK(process_);
+
+ // this may be the SIGCHLD for a process other than |process_|
+ if (base::IsProcessDead(process_)) {
+ process_ = 0;
+ StopCatching();
+ }
+ }
+
+ protected:
+ void WaitForChildExit() {
+ CHECK(process_);
+ while (!base::IsProcessDead(process_, true)) {
+ // It doesn't matter if this is interrupted; we just need to
+ // wait for some amount of time while the other process status
+ // event is (hopefully) handled. This is used only during an
+ // error case at shutdown, so a 1s wait won't be too noticeable.
+ sleep(1);
+ }
+ }
+
+ pid_t process_;
+
+ private:
+ ChildReaper(const ChildReaper&) = delete;
+
+ const ChildReaper& operator=(const ChildReaper&) = delete;
+};
+
+// Fear the reaper
+class ChildGrimReaper : public ChildReaper, public mozilla::Runnable {
+ public:
+ explicit ChildGrimReaper(pid_t process)
+ : ChildReaper(process), mozilla::Runnable("ChildGrimReaper") {}
+
+ virtual ~ChildGrimReaper() {
+ if (process_) KillProcess();
+ }
+
+ NS_IMETHOD Run() override {
+ // we may have already been signaled by the time this runs
+ if (process_) KillProcess();
+
+ return NS_OK;
+ }
+
+ private:
+ void KillProcess() {
+ DCHECK(process_);
+
+ if (base::IsProcessDead(process_)) {
+ process_ = 0;
+ return;
+ }
+
+ if (0 == kill(process_, SIGKILL)) {
+ // XXX this will block for whatever amount of time it takes the
+ // XXX OS to tear down the process's resources. might need to
+ // XXX rethink this if it proves expensive
+ WaitForChildExit();
+ } else {
+ CHROMIUM_LOG(ERROR) << "Failed to deliver SIGKILL to " << process_ << "!"
+ << "(" << errno << ").";
+ }
+ process_ = 0;
+ }
+
+ ChildGrimReaper(const ChildGrimReaper&) = delete;
+
+ const ChildGrimReaper& operator=(const ChildGrimReaper&) = delete;
+};
+
+class ChildLaxReaper : public ChildReaper,
+ public MessageLoop::DestructionObserver {
+ public:
+ explicit ChildLaxReaper(pid_t process) : ChildReaper(process) {}
+
+ virtual ~ChildLaxReaper() {
+ // WillDestroyCurrentMessageLoop() should have reaped process_ already
+ DCHECK(!process_);
+ }
+
+ virtual void OnSignal(int sig) override {
+ ChildReaper::OnSignal(sig);
+
+ if (!process_) {
+ MessageLoop::current()->RemoveDestructionObserver(this);
+ delete this;
+ }
+ }
+
+ virtual void WillDestroyCurrentMessageLoop() override {
+ DCHECK(process_);
+ if (!process_) {
+ return;
+ }
+
+ // Exception for the fake hang tests in ipc/glue/test/browser
+ if (!PR_GetEnv("MOZ_TEST_CHILD_EXIT_HANG")) {
+ CrashProcessIfHanging();
+ }
+ if (process_) {
+ WaitForChildExit();
+ process_ = 0;
+ }
+
+ // XXX don't think this is necessary, since destruction can only
+ // be observed once, but can't hurt
+ MessageLoop::current()->RemoveDestructionObserver(this);
+ delete this;
+ }
+
+ private:
+ ChildLaxReaper(const ChildLaxReaper&) = delete;
+
+ void CrashProcessIfHanging() {
+ if (base::IsProcessDead(process_)) {
+ process_ = 0;
+ return;
+ }
+
+ // If child processes seems to be hanging on shutdown, wait for a
+ // reasonable time. The wait is global instead of per-process
+ // because the child processes should be shutting down in
+ // parallel, and also we're potentially racing global timeouts
+ // like nsTerminator. (The counter doesn't need to be atomic;
+ // this is always called on the I/O thread.)
+ static int sWaitMs = kShutdownWaitMs;
+ if (sWaitMs > 0) {
+ CHROMIUM_LOG(WARNING)
+ << "Process " << process_
+ << " may be hanging at shutdown; will wait for up to " << sWaitMs
+ << "ms";
+ }
+ // There isn't a way to do a time-limited wait that's both
+ // portable and doesn't require messing with signals. Instead, we
+ // sleep in short increments and poll the process status.
+ while (sWaitMs > 0) {
+ static constexpr int kWaitTickMs = 200;
+ struct timespec ts = {kWaitTickMs / 1000, (kWaitTickMs % 1000) * 1000000};
+ HANDLE_EINTR(nanosleep(&ts, &ts));
+ sWaitMs -= kWaitTickMs;
+
+ if (base::IsProcessDead(process_)) {
+ process_ = 0;
+ return;
+ }
+ }
+
+ // We want TreeHerder to flag this log line as an error, so that
+ // this is more obviously a deliberate crash; "fatal error" is one
+ // of the strings it looks for.
+ CHROMIUM_LOG(ERROR)
+ << "Process " << process_
+ << " hanging at shutdown; attempting crash report (fatal error).";
+
+ kill(process_, SIGABRT);
+ }
+
+ const ChildLaxReaper& operator=(const ChildLaxReaper&) = delete;
+};
+
+} // namespace
+
+/**
+ * Do everything possible to ensure that |process| has been reaped
+ * before this process exits.
+ *
+ * |grim| decides how strict to be with the child's shutdown.
+ *
+ * | child exit timeout | upon parent shutdown:
+ * +--------------------+----------------------------------
+ * force=true | 2 seconds | kill(child, SIGKILL)
+ * force=false | infinite | waitpid(child)
+ *
+ * If a child process doesn't shut down properly, and |grim=false|
+ * used, then the parent will wait on the child forever. So,
+ * |force=false| is expected to be used when an external entity can be
+ * responsible for terminating hung processes, e.g. automated test
+ * harnesses.
+ */
+void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process,
+ bool force) {
+ DCHECK(process != base::GetCurrentProcId());
+ DCHECK(process > 0);
+
+ if (base::IsProcessDead(process)) return;
+
+ MessageLoopForIO* loop = MessageLoopForIO::current();
+ if (force) {
+ RefPtr<ChildGrimReaper> reaper = new ChildGrimReaper(process);
+
+ loop->CatchSignal(SIGCHLD, reaper, reaper);
+ // |loop| takes ownership of |reaper|
+ loop->PostDelayedTask(reaper.forget(), kMaxWaitMs);
+ } else {
+ ChildLaxReaper* reaper = new ChildLaxReaper(process);
+
+ loop->CatchSignal(SIGCHLD, reaper, reaper);
+ // |reaper| destroys itself after destruction notification
+ loop->AddDestructionObserver(reaper);
+ }
+}
diff --git a/ipc/chromium/src/chrome/common/process_watcher_win.cc b/ipc/chromium/src/chrome/common/process_watcher_win.cc
new file mode 100644
index 0000000000..aa05ca4d68
--- /dev/null
+++ b/ipc/chromium/src/chrome/common/process_watcher_win.cc
@@ -0,0 +1,252 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2006-2008 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.
+
+#include "chrome/common/process_watcher.h"
+
+#include <algorithm>
+#include <processthreadsapi.h>
+#include <synchapi.h>
+#include "base/message_loop.h"
+#include "base/object_watcher.h"
+#include "prenv.h"
+
+// Maximum amount of time (in milliseconds) to wait for the process to exit.
+static constexpr int kWaitInterval = 2000;
+
+// This is somewhat arbitrary, but based on Try run results. When
+// changing this, be aware of toolkit.asyncshutdown.crash_timeout
+// (currently 60s), after which the parent process will be killed.
+#ifdef MOZ_CODE_COVERAGE
+// Child processes seem to take longer to shut down on ccov builds, at
+// least in the wdspec tests; ~20s has been observed, and we'll spam
+// false positives unless this is increased.
+static constexpr DWORD kShutdownWaitMs = 80000;
+#elif defined(MOZ_ASAN) || defined(MOZ_TSAN)
+// Sanitizers also slow things down in some cases; see bug 1806224.
+static constexpr DWORD kShutdownWaitMs = 40000;
+#else
+static constexpr DWORD kShutdownWaitMs = 20000;
+#endif
+
+namespace {
+
+static bool IsProcessDead(base::ProcessHandle process) {
+ return WaitForSingleObject(process, 0) == WAIT_OBJECT_0;
+}
+
+class ChildReaper : public mozilla::Runnable,
+ public base::ObjectWatcher::Delegate,
+ public MessageLoop::DestructionObserver {
+ public:
+ explicit ChildReaper(base::ProcessHandle process, bool force)
+ : mozilla::Runnable("ChildReaper"), process_(process), force_(force) {
+ watcher_.StartWatching(process_, this);
+ }
+
+ virtual ~ChildReaper() {
+ if (process_) {
+ KillProcess();
+ DCHECK(!process_) << "Make sure to close the handle.";
+ }
+ }
+
+ // MessageLoop::DestructionObserver -----------------------------------------
+
+ virtual void WillDestroyCurrentMessageLoop() {
+ MOZ_ASSERT(!force_);
+ if (process_) {
+ // Exception for the fake hang tests in ipc/glue/test/browser
+ if (!PR_GetEnv("MOZ_TEST_CHILD_EXIT_HANG")) {
+ CrashProcessIfHanging();
+ }
+ WaitForSingleObject(process_, INFINITE);
+ base::CloseProcessHandle(process_);
+ process_ = 0;
+
+ MessageLoop::current()->RemoveDestructionObserver(this);
+ delete this;
+ }
+ }
+
+ // Task ---------------------------------------------------------------------
+
+ NS_IMETHOD Run() override {
+ MOZ_ASSERT(force_);
+ if (process_) {
+ KillProcess();
+ }
+ return NS_OK;
+ }
+
+ // MessageLoop::Watcher -----------------------------------------------------
+
+ virtual void OnObjectSignaled(HANDLE object) {
+ // When we're called from KillProcess, the ObjectWatcher may still be
+ // watching. the process handle, so make sure it has stopped.
+ watcher_.StopWatching();
+
+ base::CloseProcessHandle(process_);
+ process_ = 0;
+
+ if (!force_) {
+ MessageLoop::current()->RemoveDestructionObserver(this);
+ delete this;
+ }
+ }
+
+ private:
+ void KillProcess() {
+ MOZ_ASSERT(force_);
+
+ // OK, time to get frisky. We don't actually care when the process
+ // terminates. We just care that it eventually terminates, and that's what
+ // TerminateProcess should do for us. Don't check for the result code since
+ // it fails quite often. This should be investigated eventually.
+ TerminateProcess(process_, base::PROCESS_END_PROCESS_WAS_HUNG);
+
+ // Now, just cleanup as if the process exited normally.
+ OnObjectSignaled(process_);
+ }
+
+ void CrashProcessIfHanging() {
+ if (IsProcessDead(process_)) {
+ return;
+ }
+ DWORD pid = GetProcessId(process_);
+ DCHECK(pid != 0);
+
+ // If child processes seems to be hanging on shutdown, wait for a
+ // reasonable time. The wait is global instead of per-process
+ // because the child processes should be shutting down in
+ // parallel, and also we're potentially racing global timeouts
+ // like nsTerminator. (The counter doesn't need to be atomic;
+ // this is always called on the I/O thread.)
+ static DWORD sWaitMs = kShutdownWaitMs;
+ if (sWaitMs > 0) {
+ CHROMIUM_LOG(WARNING)
+ << "Process " << pid
+ << " may be hanging at shutdown; will wait for up to " << sWaitMs
+ << "ms";
+ }
+ const auto beforeWait = mozilla::TimeStamp::NowLoRes();
+ const DWORD waitStatus = WaitForSingleObject(process_, sWaitMs);
+
+ const double elapsed =
+ (mozilla::TimeStamp::NowLoRes() - beforeWait).ToMilliseconds();
+ sWaitMs -= static_cast<DWORD>(
+ std::clamp(elapsed, 0.0, static_cast<double>(sWaitMs)));
+
+ switch (waitStatus) {
+ case WAIT_TIMEOUT:
+ // The process is still running.
+ break;
+ case WAIT_OBJECT_0:
+ // The process exited.
+ return;
+ case WAIT_FAILED:
+ CHROMIUM_LOG(ERROR) << "Waiting for process " << pid
+ << " failed; error " << GetLastError();
+ DCHECK(false) << "WaitForSingleObject failed";
+ // Process status unclear; assume it's gone.
+ return;
+ default:
+ DCHECK(false) << "WaitForSingleObject returned " << waitStatus;
+ // Again, not clear what's happening so avoid touching the process
+ return;
+ }
+
+ // We want TreeHerder to flag this log line as an error, so that
+ // this is more obviously a deliberate crash; "fatal error" is one
+ // of the strings it looks for.
+ CHROMIUM_LOG(ERROR)
+ << "Process " << pid
+ << " hanging at shutdown; attempting crash report (fatal error)";
+
+ // We're going to use CreateRemoteThread to call DbgBreakPoint in
+ // the target process; it's in a "known DLL" so it should be at
+ // the same address in all processes. (Normal libraries, like
+ // xul.dll, are usually at the same address but can be relocated
+ // in case of conflict.)
+ //
+ // DbgBreakPoint doesn't take an argument, so we can give it an
+ // arbitrary value to make it easier to identify these crash
+ // reports. (reinterpret_cast isn't constexpr, so this is
+ // declared as an integer and cast to the required type later.)
+ // The primary use case for all of this is in CI, where we'll also
+ // have log messages, but if these crashes end up in Socorro in
+ // significant numbers then we'll be able to look for this value.
+ static constexpr uint64_t kIpcMagic = 0x43504900435049;
+
+ const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
+ if (!ntdll) {
+ CHROMIUM_LOG(ERROR) << "couldn't find ntdll.dll: error "
+ << GetLastError();
+ return;
+ }
+ const auto dbgBreak = reinterpret_cast<LPTHREAD_START_ROUTINE>(
+ GetProcAddress(ntdll, "DbgBreakPoint"));
+ if (!dbgBreak) {
+ CHROMIUM_LOG(ERROR) << "couldn't find DbgBreakPoint: error "
+ << GetLastError();
+ return;
+ }
+
+ const DWORD rights = PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
+ PROCESS_VM_OPERATION | PROCESS_VM_WRITE |
+ PROCESS_VM_READ;
+ HANDLE process_priv = nullptr;
+ if (!DuplicateHandle(GetCurrentProcess(), process_, GetCurrentProcess(),
+ &process_priv, rights, /* inherit */ FALSE,
+ /* options */ 0)) {
+ const auto error = GetLastError();
+ CHROMIUM_LOG(ERROR) << "OpenProcess: error " << error;
+ } else {
+ DCHECK(process_priv);
+ HANDLE thread =
+ CreateRemoteThread(process_priv, /* sec attr */ nullptr,
+ /* stack */ 0, dbgBreak, (LPVOID)kIpcMagic,
+ /* flags */ 0, nullptr);
+ if (!thread) {
+ const auto error = GetLastError();
+ CHROMIUM_LOG(ERROR) << "CreateRemoteThread: error " << error;
+ } else {
+ CloseHandle(thread);
+ }
+ CloseHandle(process_priv);
+ }
+ }
+
+ // The process that we are watching.
+ base::ProcessHandle process_;
+
+ base::ObjectWatcher watcher_;
+
+ bool force_;
+
+ DISALLOW_EVIL_CONSTRUCTORS(ChildReaper);
+};
+
+} // namespace
+
+// static
+void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process,
+ bool force) {
+ DCHECK(process != GetCurrentProcess());
+
+ // If already signaled, then we are done!
+ if (IsProcessDead(process)) {
+ base::CloseProcessHandle(process);
+ return;
+ }
+
+ MessageLoopForIO* loop = MessageLoopForIO::current();
+ if (force) {
+ RefPtr<mozilla::Runnable> task = new ChildReaper(process, force);
+ loop->PostDelayedTask(task.forget(), kWaitInterval);
+ } else {
+ loop->AddDestructionObserver(new ChildReaper(process, force));
+ }
+}
diff --git a/ipc/chromium/src/mojo/core/ports/event.cc b/ipc/chromium/src/mojo/core/ports/event.cc
new file mode 100644
index 0000000000..5caec8ae55
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/event.cc
@@ -0,0 +1,565 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/event.h"
+
+#include <stdint.h>
+#include <string.h>
+
+#include "base/logging.h"
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/user_message.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/CheckedInt.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+namespace {
+
+const size_t kPortsMessageAlignment = 8;
+
+#pragma pack(push, 1)
+
+struct SerializedHeader {
+ Event::Type type;
+ uint32_t padding;
+ PortName port_name;
+ PortName from_port;
+ uint64_t control_sequence_num;
+};
+
+struct UserMessageEventData {
+ uint64_t sequence_num;
+ uint32_t num_ports;
+ uint32_t padding;
+};
+
+struct ObserveProxyEventData {
+ NodeName proxy_node_name;
+ PortName proxy_port_name;
+ NodeName proxy_target_node_name;
+ PortName proxy_target_port_name;
+};
+
+struct ObserveProxyAckEventData {
+ uint64_t last_sequence_num;
+};
+
+struct ObserveClosureEventData {
+ uint64_t last_sequence_num;
+};
+
+struct MergePortEventData {
+ PortName new_port_name;
+ Event::PortDescriptor new_port_descriptor;
+};
+
+struct UserMessageReadAckRequestEventData {
+ uint64_t sequence_num_to_acknowledge;
+};
+
+struct UserMessageReadAckEventData {
+ uint64_t sequence_num_acknowledged;
+};
+
+struct UpdatePreviousPeerEventData {
+ NodeName new_node_name;
+ PortName new_port_name;
+};
+
+#pragma pack(pop)
+
+static_assert(sizeof(Event::PortDescriptor) % kPortsMessageAlignment == 0,
+ "Invalid PortDescriptor size.");
+
+static_assert(sizeof(SerializedHeader) % kPortsMessageAlignment == 0,
+ "Invalid SerializedHeader size.");
+
+static_assert(sizeof(UserMessageEventData) % kPortsMessageAlignment == 0,
+ "Invalid UserEventData size.");
+
+static_assert(sizeof(ObserveProxyEventData) % kPortsMessageAlignment == 0,
+ "Invalid ObserveProxyEventData size.");
+
+static_assert(sizeof(ObserveProxyAckEventData) % kPortsMessageAlignment == 0,
+ "Invalid ObserveProxyAckEventData size.");
+
+static_assert(sizeof(ObserveClosureEventData) % kPortsMessageAlignment == 0,
+ "Invalid ObserveClosureEventData size.");
+
+static_assert(sizeof(MergePortEventData) % kPortsMessageAlignment == 0,
+ "Invalid MergePortEventData size.");
+
+static_assert(sizeof(UserMessageReadAckRequestEventData) %
+ kPortsMessageAlignment ==
+ 0,
+ "Invalid UserMessageReadAckRequestEventData size.");
+
+static_assert(sizeof(UserMessageReadAckEventData) % kPortsMessageAlignment == 0,
+ "Invalid UserMessageReadAckEventData size.");
+
+static_assert(sizeof(UpdatePreviousPeerEventData) % kPortsMessageAlignment == 0,
+ "Invalid UpdatePreviousPeerEventData size.");
+
+} // namespace
+
+Event::PortDescriptor::PortDescriptor() { memset(padding, 0, sizeof(padding)); }
+
+Event::~Event() = default;
+
+// static
+ScopedEvent Event::Deserialize(const void* buffer, size_t num_bytes) {
+ if (num_bytes < sizeof(SerializedHeader)) {
+ return nullptr;
+ }
+
+ const auto* header = static_cast<const SerializedHeader*>(buffer);
+ const PortName& port_name = header->port_name;
+ const PortName& from_port = header->from_port;
+ const uint64_t control_sequence_num = header->control_sequence_num;
+ const size_t data_size = num_bytes - sizeof(*header);
+ switch (header->type) {
+ case Type::kUserMessage:
+ return UserMessageEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kPortAccepted:
+ return PortAcceptedEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kObserveProxy:
+ return ObserveProxyEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kObserveProxyAck:
+ return ObserveProxyAckEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kObserveClosure:
+ return ObserveClosureEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kMergePort:
+ return MergePortEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kUserMessageReadAckRequest:
+ return UserMessageReadAckRequestEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kUserMessageReadAck:
+ return UserMessageReadAckEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ case Type::kUpdatePreviousPeer:
+ return UpdatePreviousPeerEvent::Deserialize(
+ port_name, from_port, control_sequence_num, header + 1, data_size);
+ default:
+ DVLOG(2) << "Ingoring unknown port event type: "
+ << static_cast<uint32_t>(header->type);
+ return nullptr;
+ }
+}
+
+Event::Event(Type type, const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num)
+ : type_(type),
+ port_name_(port_name),
+ from_port_(from_port),
+ control_sequence_num_(control_sequence_num) {}
+
+size_t Event::GetSerializedSize() const {
+ return sizeof(SerializedHeader) + GetSerializedDataSize();
+}
+
+void Event::Serialize(void* buffer) const {
+ auto* header = static_cast<SerializedHeader*>(buffer);
+ header->type = type_;
+ header->padding = 0;
+ header->port_name = port_name_;
+ header->from_port = from_port_;
+ header->control_sequence_num = control_sequence_num_;
+ SerializeData(header + 1);
+}
+
+ScopedEvent Event::CloneForBroadcast() const { return nullptr; }
+
+UserMessageEvent::~UserMessageEvent() = default;
+
+UserMessageEvent::UserMessageEvent(size_t num_ports)
+ : Event(Type::kUserMessage, kInvalidPortName, kInvalidPortName, -1) {
+ ReservePorts(num_ports);
+}
+
+void UserMessageEvent::AttachMessage(mozilla::UniquePtr<UserMessage> message) {
+ DCHECK(!message_);
+ message_ = std::move(message);
+}
+
+void UserMessageEvent::ReservePorts(size_t num_ports) {
+ port_descriptors_.resize(num_ports);
+ ports_.resize(num_ports);
+}
+
+bool UserMessageEvent::NotifyWillBeRoutedExternally() {
+ DCHECK(message_);
+ return message_->WillBeRoutedExternally(*this);
+}
+
+// static
+ScopedEvent UserMessageEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(UserMessageEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const UserMessageEventData*>(buffer);
+ mozilla::CheckedInt<size_t> port_data_size = data->num_ports;
+ port_data_size *= sizeof(PortDescriptor) + sizeof(PortName);
+ if (!port_data_size.isValid()) {
+ return nullptr;
+ }
+
+ mozilla::CheckedInt<size_t> total_size = port_data_size.value();
+ total_size += sizeof(UserMessageEventData);
+ if (!total_size.isValid() || num_bytes < total_size.value()) {
+ return nullptr;
+ }
+
+ auto event = mozilla::WrapUnique(new UserMessageEvent(
+ port_name, from_port, control_sequence_num, data->sequence_num));
+ event->ReservePorts(data->num_ports);
+ const auto* in_descriptors =
+ reinterpret_cast<const PortDescriptor*>(data + 1);
+ std::copy(in_descriptors, in_descriptors + data->num_ports,
+ event->port_descriptors());
+
+ const auto* in_names =
+ reinterpret_cast<const PortName*>(in_descriptors + data->num_ports);
+ std::copy(in_names, in_names + data->num_ports, event->ports());
+ return event;
+}
+
+UserMessageEvent::UserMessageEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t sequence_num)
+ : Event(Type::kUserMessage, port_name, from_port, control_sequence_num),
+ sequence_num_(sequence_num) {}
+
+size_t UserMessageEvent::GetSizeIfSerialized() const {
+ if (!message_) {
+ return 0;
+ }
+ return message_->GetSizeIfSerialized();
+}
+
+size_t UserMessageEvent::GetSerializedDataSize() const {
+ DCHECK_EQ(ports_.size(), port_descriptors_.size());
+ mozilla::CheckedInt<size_t> size = sizeof(UserMessageEventData);
+ mozilla::CheckedInt<size_t> ports_size =
+ sizeof(PortDescriptor) + sizeof(PortName);
+ ports_size *= ports_.size();
+ mozilla::CheckedInt<size_t> combined = size + ports_size;
+ MOZ_RELEASE_ASSERT(combined.isValid());
+ return combined.value();
+}
+
+void UserMessageEvent::SerializeData(void* buffer) const {
+ DCHECK_EQ(ports_.size(), port_descriptors_.size());
+ auto* data = static_cast<UserMessageEventData*>(buffer);
+ data->sequence_num = sequence_num_;
+ mozilla::CheckedInt<uint32_t> num_ports{ports_.size()};
+ DCHECK(num_ports.isValid());
+ data->num_ports = num_ports.value();
+ data->padding = 0;
+
+ auto* ports_data = reinterpret_cast<PortDescriptor*>(data + 1);
+ std::copy(port_descriptors_.begin(), port_descriptors_.end(), ports_data);
+
+ auto* port_names_data =
+ reinterpret_cast<PortName*>(ports_data + ports_.size());
+ std::copy(ports_.begin(), ports_.end(), port_names_data);
+}
+
+PortAcceptedEvent::PortAcceptedEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num)
+ : Event(Type::kPortAccepted, port_name, from_port, control_sequence_num) {}
+
+PortAcceptedEvent::~PortAcceptedEvent() = default;
+
+// static
+ScopedEvent PortAcceptedEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ return mozilla::MakeUnique<PortAcceptedEvent>(port_name, from_port,
+ control_sequence_num);
+}
+
+size_t PortAcceptedEvent::GetSerializedDataSize() const { return 0; }
+
+void PortAcceptedEvent::SerializeData(void* buffer) const {}
+
+ObserveProxyEvent::ObserveProxyEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const NodeName& proxy_node_name,
+ const PortName& proxy_port_name,
+ const NodeName& proxy_target_node_name,
+ const PortName& proxy_target_port_name)
+ : Event(Type::kObserveProxy, port_name, from_port, control_sequence_num),
+ proxy_node_name_(proxy_node_name),
+ proxy_port_name_(proxy_port_name),
+ proxy_target_node_name_(proxy_target_node_name),
+ proxy_target_port_name_(proxy_target_port_name) {}
+
+ObserveProxyEvent::~ObserveProxyEvent() = default;
+
+// static
+ScopedEvent ObserveProxyEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(ObserveProxyEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const ObserveProxyEventData*>(buffer);
+ return mozilla::MakeUnique<ObserveProxyEvent>(
+ port_name, from_port, control_sequence_num, data->proxy_node_name,
+ data->proxy_port_name, data->proxy_target_node_name,
+ data->proxy_target_port_name);
+}
+
+size_t ObserveProxyEvent::GetSerializedDataSize() const {
+ return sizeof(ObserveProxyEventData);
+}
+
+void ObserveProxyEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<ObserveProxyEventData*>(buffer);
+ data->proxy_node_name = proxy_node_name_;
+ data->proxy_port_name = proxy_port_name_;
+ data->proxy_target_node_name = proxy_target_node_name_;
+ data->proxy_target_port_name = proxy_target_port_name_;
+}
+
+ScopedEvent ObserveProxyEvent::CloneForBroadcast() const {
+ // Don't broadcast events targeted at specific ports. Otherwise a malicious
+ // node can use this to bypass sender verification.
+ if (port_name() != kInvalidPortName) {
+ return nullptr;
+ }
+ return mozilla::MakeUnique<ObserveProxyEvent>(
+ port_name(), from_port(), control_sequence_num(), proxy_node_name_,
+ proxy_port_name_, proxy_target_node_name_, proxy_target_port_name_);
+}
+
+ObserveProxyAckEvent::ObserveProxyAckEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t last_sequence_num)
+ : Event(Type::kObserveProxyAck, port_name, from_port, control_sequence_num),
+ last_sequence_num_(last_sequence_num) {}
+
+ObserveProxyAckEvent::~ObserveProxyAckEvent() = default;
+
+// static
+ScopedEvent ObserveProxyAckEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(ObserveProxyAckEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const ObserveProxyAckEventData*>(buffer);
+ return mozilla::MakeUnique<ObserveProxyAckEvent>(
+ port_name, from_port, control_sequence_num, data->last_sequence_num);
+}
+
+size_t ObserveProxyAckEvent::GetSerializedDataSize() const {
+ return sizeof(ObserveProxyAckEventData);
+}
+
+void ObserveProxyAckEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<ObserveProxyAckEventData*>(buffer);
+ data->last_sequence_num = last_sequence_num_;
+}
+
+ObserveClosureEvent::ObserveClosureEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t last_sequence_num)
+ : Event(Type::kObserveClosure, port_name, from_port, control_sequence_num),
+ last_sequence_num_(last_sequence_num) {}
+
+ObserveClosureEvent::~ObserveClosureEvent() = default;
+
+// static
+ScopedEvent ObserveClosureEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(ObserveClosureEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const ObserveClosureEventData*>(buffer);
+ return mozilla::MakeUnique<ObserveClosureEvent>(
+ port_name, from_port, control_sequence_num, data->last_sequence_num);
+}
+
+size_t ObserveClosureEvent::GetSerializedDataSize() const {
+ return sizeof(ObserveClosureEventData);
+}
+
+void ObserveClosureEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<ObserveClosureEventData*>(buffer);
+ data->last_sequence_num = last_sequence_num_;
+}
+
+MergePortEvent::MergePortEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const PortName& new_port_name,
+ const PortDescriptor& new_port_descriptor)
+ : Event(Type::kMergePort, port_name, from_port, control_sequence_num),
+ new_port_name_(new_port_name),
+ new_port_descriptor_(new_port_descriptor) {}
+
+MergePortEvent::~MergePortEvent() = default;
+
+// static
+ScopedEvent MergePortEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes) {
+ if (num_bytes < sizeof(MergePortEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const MergePortEventData*>(buffer);
+ return mozilla::MakeUnique<MergePortEvent>(
+ port_name, from_port, control_sequence_num, data->new_port_name,
+ data->new_port_descriptor);
+}
+
+size_t MergePortEvent::GetSerializedDataSize() const {
+ return sizeof(MergePortEventData);
+}
+
+void MergePortEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<MergePortEventData*>(buffer);
+ data->new_port_name = new_port_name_;
+ data->new_port_descriptor = new_port_descriptor_;
+}
+
+UserMessageReadAckRequestEvent::UserMessageReadAckRequestEvent(
+ const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num, uint64_t sequence_num_to_acknowledge)
+ : Event(Type::kUserMessageReadAckRequest, port_name, from_port,
+ control_sequence_num),
+ sequence_num_to_acknowledge_(sequence_num_to_acknowledge) {}
+
+UserMessageReadAckRequestEvent::~UserMessageReadAckRequestEvent() = default;
+
+// static
+ScopedEvent UserMessageReadAckRequestEvent::Deserialize(
+ const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num, const void* buffer, size_t num_bytes) {
+ if (num_bytes < sizeof(UserMessageReadAckRequestEventData)) {
+ return nullptr;
+ }
+
+ const auto* data =
+ static_cast<const UserMessageReadAckRequestEventData*>(buffer);
+ return mozilla::MakeUnique<UserMessageReadAckRequestEvent>(
+ port_name, from_port, control_sequence_num,
+ data->sequence_num_to_acknowledge);
+}
+
+size_t UserMessageReadAckRequestEvent::GetSerializedDataSize() const {
+ return sizeof(UserMessageReadAckRequestEventData);
+}
+
+void UserMessageReadAckRequestEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<UserMessageReadAckRequestEventData*>(buffer);
+ data->sequence_num_to_acknowledge = sequence_num_to_acknowledge_;
+}
+
+UserMessageReadAckEvent::UserMessageReadAckEvent(
+ const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num, uint64_t sequence_num_acknowledged)
+ : Event(Type::kUserMessageReadAck, port_name, from_port,
+ control_sequence_num),
+ sequence_num_acknowledged_(sequence_num_acknowledged) {}
+
+UserMessageReadAckEvent::~UserMessageReadAckEvent() = default;
+
+// static
+ScopedEvent UserMessageReadAckEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(UserMessageReadAckEventData)) {
+ return nullptr;
+ }
+
+ const auto* data = static_cast<const UserMessageReadAckEventData*>(buffer);
+ return mozilla::MakeUnique<UserMessageReadAckEvent>(
+ port_name, from_port, control_sequence_num,
+ data->sequence_num_acknowledged);
+}
+
+size_t UserMessageReadAckEvent::GetSerializedDataSize() const {
+ return sizeof(UserMessageReadAckEventData);
+}
+
+void UserMessageReadAckEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<UserMessageReadAckEventData*>(buffer);
+ data->sequence_num_acknowledged = sequence_num_acknowledged_;
+}
+
+UpdatePreviousPeerEvent::UpdatePreviousPeerEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const NodeName& new_node_name,
+ const PortName& new_port_name)
+ : Event(Type::kUpdatePreviousPeer, port_name, from_port,
+ control_sequence_num),
+ new_node_name_(new_node_name),
+ new_port_name_(new_port_name) {}
+
+UpdatePreviousPeerEvent::~UpdatePreviousPeerEvent() = default;
+
+// static
+ScopedEvent UpdatePreviousPeerEvent::Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer,
+ size_t num_bytes) {
+ if (num_bytes < sizeof(UpdatePreviousPeerEventData)) return nullptr;
+ const auto* data = static_cast<const UpdatePreviousPeerEventData*>(buffer);
+ return mozilla::MakeUnique<UpdatePreviousPeerEvent>(
+ port_name, from_port, control_sequence_num, data->new_node_name,
+ data->new_port_name);
+}
+
+size_t UpdatePreviousPeerEvent::GetSerializedDataSize() const {
+ return sizeof(UpdatePreviousPeerEventData);
+}
+
+void UpdatePreviousPeerEvent::SerializeData(void* buffer) const {
+ auto* data = static_cast<UpdatePreviousPeerEventData*>(buffer);
+ data->new_node_name = new_node_name_;
+ data->new_port_name = new_port_name_;
+}
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/event.h b/ipc/chromium/src/mojo/core/ports/event.h
new file mode 100644
index 0000000000..e0b6027e0b
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/event.h
@@ -0,0 +1,393 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_EVENT_H_
+#define MOJO_CORE_PORTS_EVENT_H_
+
+#include <stdint.h>
+
+#include <memory>
+#include <vector>
+
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/user_message.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class Event;
+
+using ScopedEvent = mozilla::UniquePtr<Event>;
+
+// A Event is the fundamental unit of operation and communication within and
+// between Nodes.
+class Event {
+ public:
+ enum Type : uint32_t {
+ // A user message event contains arbitrary user-specified payload data
+ // which may include any number of ports and/or system handles (e.g. FDs).
+ kUserMessage,
+
+ // When a Node receives a user message with one or more ports attached, it
+ // sends back an instance of this event for every attached port to indicate
+ // that the port has been accepted by its destination node.
+ kPortAccepted,
+
+ // This event begins circulation any time a port enters a proxying state. It
+ // may be re-circulated in certain edge cases, but the ultimate purpose of
+ // the event is to ensure that every port along a route is (if necessary)
+ // aware that the proxying port is indeed proxying (and to where) so that it
+ // can begin to be bypassed along the route.
+ kObserveProxy,
+
+ // An event used to acknowledge to a proxy that all concerned nodes and
+ // ports are aware of its proxying state and that no more user messages will
+ // be routed to it beyond a given final sequence number.
+ kObserveProxyAck,
+
+ // Indicates that a port has been closed. This event fully circulates a
+ // route to ensure that all ports are aware of closure.
+ kObserveClosure,
+
+ // Used to request the merging of two routes via two sacrificial receiving
+ // ports, one from each route.
+ kMergePort,
+
+ // Used to request that the conjugate port acknowledges read messages by
+ // sending back a UserMessageReadAck.
+ kUserMessageReadAckRequest,
+
+ // Used to acknowledge read messages to the conjugate.
+ kUserMessageReadAck,
+
+ // Used to update the previous node and port name of a port.
+ kUpdatePreviousPeer,
+ };
+
+#pragma pack(push, 1)
+ struct PortDescriptor {
+ PortDescriptor();
+
+ NodeName peer_node_name;
+ PortName peer_port_name;
+ NodeName referring_node_name;
+ PortName referring_port_name;
+ uint64_t next_sequence_num_to_send;
+ uint64_t next_sequence_num_to_receive;
+ uint64_t last_sequence_num_to_receive;
+ bool peer_closed;
+ char padding[7];
+ };
+#pragma pack(pop)
+ virtual ~Event();
+
+ static ScopedEvent Deserialize(const void* buffer, size_t num_bytes);
+
+ template <typename T>
+ static mozilla::UniquePtr<T> Cast(ScopedEvent* event) {
+ return mozilla::WrapUnique(static_cast<T*>(event->release()));
+ }
+
+ Type type() const { return type_; }
+ const PortName& port_name() const { return port_name_; }
+ void set_port_name(const PortName& port_name) { port_name_ = port_name; }
+
+ size_t GetSerializedSize() const;
+ void Serialize(void* buffer) const;
+ virtual ScopedEvent CloneForBroadcast() const;
+
+ const PortName& from_port() const { return from_port_; }
+ void set_from_port(const PortName& from_port) { from_port_ = from_port; }
+
+ uint64_t control_sequence_num() const { return control_sequence_num_; }
+ void set_control_sequence_num(uint64_t control_sequence_num) {
+ control_sequence_num_ = control_sequence_num;
+ }
+
+ protected:
+ Event(Type type, const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num);
+
+ virtual size_t GetSerializedDataSize() const = 0;
+ virtual void SerializeData(void* buffer) const = 0;
+
+ private:
+ const Type type_;
+ PortName port_name_;
+ PortName from_port_;
+ uint64_t control_sequence_num_;
+
+ DISALLOW_COPY_AND_ASSIGN(Event);
+};
+
+class UserMessageEvent : public Event {
+ public:
+ explicit UserMessageEvent(size_t num_ports);
+ ~UserMessageEvent() override;
+
+ bool HasMessage() const { return !!message_; }
+ void AttachMessage(mozilla::UniquePtr<UserMessage> message);
+
+ template <typename T>
+ T* GetMessage() {
+ DCHECK(HasMessage());
+ DCHECK_EQ(&T::kUserMessageTypeInfo, message_->type_info());
+ return static_cast<T*>(message_.get());
+ }
+
+ template <typename T>
+ const T* GetMessage() const {
+ DCHECK(HasMessage());
+ DCHECK_EQ(&T::kUserMessageTypeInfo, message_->type_info());
+ return static_cast<const T*>(message_.get());
+ }
+
+ template <typename T>
+ mozilla::UniquePtr<T> TakeMessage() {
+ DCHECK(HasMessage());
+ DCHECK_EQ(&T::kUserMessageTypeInfo, message_->type_info());
+ return mozilla::UniquePtr<T>{static_cast<T*>(message_.release())};
+ }
+
+ void ReservePorts(size_t num_ports);
+ bool NotifyWillBeRoutedExternally();
+
+ uint64_t sequence_num() const { return sequence_num_; }
+ void set_sequence_num(uint64_t sequence_num) { sequence_num_ = sequence_num; }
+
+ size_t num_ports() const { return ports_.size(); }
+ PortDescriptor* port_descriptors() { return port_descriptors_.data(); }
+ PortName* ports() { return ports_.data(); }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ size_t GetSizeIfSerialized() const;
+
+ private:
+ UserMessageEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num, uint64_t sequence_num);
+
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ uint64_t sequence_num_ = 0;
+ std::vector<PortDescriptor> port_descriptors_;
+ std::vector<PortName> ports_;
+ mozilla::UniquePtr<UserMessage> message_;
+
+ DISALLOW_COPY_AND_ASSIGN(UserMessageEvent);
+};
+
+class PortAcceptedEvent : public Event {
+ public:
+ PortAcceptedEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num);
+ ~PortAcceptedEvent() override;
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ DISALLOW_COPY_AND_ASSIGN(PortAcceptedEvent);
+};
+
+class ObserveProxyEvent : public Event {
+ public:
+ ObserveProxyEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num,
+ const NodeName& proxy_node_name,
+ const PortName& proxy_port_name,
+ const NodeName& proxy_target_node_name,
+ const PortName& proxy_target_port_name);
+ ~ObserveProxyEvent() override;
+
+ const NodeName& proxy_node_name() const { return proxy_node_name_; }
+ const PortName& proxy_port_name() const { return proxy_port_name_; }
+ const NodeName& proxy_target_node_name() const {
+ return proxy_target_node_name_;
+ }
+ const PortName& proxy_target_port_name() const {
+ return proxy_target_port_name_;
+ }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+ ScopedEvent CloneForBroadcast() const override;
+
+ const NodeName proxy_node_name_;
+ const PortName proxy_port_name_;
+ const NodeName proxy_target_node_name_;
+ const PortName proxy_target_port_name_;
+
+ DISALLOW_COPY_AND_ASSIGN(ObserveProxyEvent);
+};
+
+class ObserveProxyAckEvent : public Event {
+ public:
+ ObserveProxyAckEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t last_sequence_num);
+ ~ObserveProxyAckEvent() override;
+
+ uint64_t last_sequence_num() const { return last_sequence_num_; }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ const uint64_t last_sequence_num_;
+
+ DISALLOW_COPY_AND_ASSIGN(ObserveProxyAckEvent);
+};
+
+class ObserveClosureEvent : public Event {
+ public:
+ ObserveClosureEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t last_sequence_num);
+ ~ObserveClosureEvent() override;
+
+ uint64_t last_sequence_num() const { return last_sequence_num_; }
+ void set_last_sequence_num(uint64_t last_sequence_num) {
+ last_sequence_num_ = last_sequence_num;
+ }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ uint64_t last_sequence_num_;
+
+ DISALLOW_COPY_AND_ASSIGN(ObserveClosureEvent);
+};
+
+class MergePortEvent : public Event {
+ public:
+ MergePortEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num, const PortName& new_port_name,
+ const PortDescriptor& new_port_descriptor);
+ ~MergePortEvent() override;
+
+ const PortName& new_port_name() const { return new_port_name_; }
+ const PortDescriptor& new_port_descriptor() const {
+ return new_port_descriptor_;
+ }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ const PortName new_port_name_;
+ const PortDescriptor new_port_descriptor_;
+
+ DISALLOW_COPY_AND_ASSIGN(MergePortEvent);
+};
+
+class UserMessageReadAckRequestEvent : public Event {
+ public:
+ UserMessageReadAckRequestEvent(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t sequence_num_to_acknowledge);
+ ~UserMessageReadAckRequestEvent() override;
+
+ uint64_t sequence_num_to_acknowledge() const {
+ return sequence_num_to_acknowledge_;
+ }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ uint64_t sequence_num_to_acknowledge_;
+};
+
+class UserMessageReadAckEvent : public Event {
+ public:
+ UserMessageReadAckEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num,
+ uint64_t sequence_num_acknowledged);
+ ~UserMessageReadAckEvent() override;
+
+ uint64_t sequence_num_acknowledged() const {
+ return sequence_num_acknowledged_;
+ }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ uint64_t sequence_num_acknowledged_;
+};
+
+class UpdatePreviousPeerEvent : public Event {
+ public:
+ UpdatePreviousPeerEvent(const PortName& port_name, const PortName& from_port,
+ uint64_t control_sequence_num,
+ const NodeName& new_node_name,
+ const PortName& new_port_name);
+ ~UpdatePreviousPeerEvent() override;
+
+ const NodeName& new_node_name() const { return new_node_name_; }
+
+ const PortName& new_port_name() const { return new_port_name_; }
+
+ static ScopedEvent Deserialize(const PortName& port_name,
+ const PortName& from_port,
+ uint64_t control_sequence_num,
+ const void* buffer, size_t num_bytes);
+
+ private:
+ size_t GetSerializedDataSize() const override;
+ void SerializeData(void* buffer) const override;
+
+ const NodeName new_node_name_;
+ const PortName new_port_name_;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_EVENT_H_
diff --git a/ipc/chromium/src/mojo/core/ports/message_filter.h b/ipc/chromium/src/mojo/core/ports/message_filter.h
new file mode 100644
index 0000000000..21f8c1c869
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/message_filter.h
@@ -0,0 +1,29 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_MESSAGE_FILTER_H_
+#define MOJO_CORE_PORTS_MESSAGE_FILTER_H_
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class UserMessageEvent;
+
+// An interface which can be implemented to user message events according to
+// arbitrary policy.
+class MessageFilter {
+ public:
+ virtual ~MessageFilter() = default;
+
+ // Returns true if |message| should be accepted by whomever is applying this
+ // filter. See MessageQueue::GetNextMessage(), for example.
+ virtual bool Match(const UserMessageEvent& message) = 0;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_MESSAGE_FILTER_H_
diff --git a/ipc/chromium/src/mojo/core/ports/message_queue.cc b/ipc/chromium/src/mojo/core/ports/message_queue.cc
new file mode 100644
index 0000000000..24c5c7fa91
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/message_queue.cc
@@ -0,0 +1,97 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/message_queue.h"
+
+#include <algorithm>
+
+#include "base/compiler_specific.h"
+#include "base/logging.h"
+#include "mojo/core/ports/message_filter.h"
+#include "mozilla/Likely.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+// Used by std::{push,pop}_heap functions
+inline bool operator<(const mozilla::UniquePtr<UserMessageEvent>& a,
+ const mozilla::UniquePtr<UserMessageEvent>& b) {
+ return a->sequence_num() > b->sequence_num();
+}
+
+MessageQueue::MessageQueue() : MessageQueue(kInitialSequenceNum) {}
+
+MessageQueue::MessageQueue(uint64_t next_sequence_num)
+ : next_sequence_num_(next_sequence_num) {
+ // The message queue is blocked waiting for a message with sequence number
+ // equal to |next_sequence_num|.
+}
+
+MessageQueue::~MessageQueue() {
+#ifdef DEBUG
+ size_t num_leaked_ports = 0;
+ for (const auto& message : heap_) {
+ num_leaked_ports += message->num_ports();
+ }
+ if (num_leaked_ports > 0) {
+ DVLOG(1) << "Leaking " << num_leaked_ports
+ << " ports in unreceived messages";
+ }
+#endif
+}
+
+bool MessageQueue::HasNextMessage() const {
+ return !heap_.empty() && heap_[0]->sequence_num() == next_sequence_num_;
+}
+
+void MessageQueue::GetNextMessage(mozilla::UniquePtr<UserMessageEvent>* message,
+ MessageFilter* filter) {
+ if (!HasNextMessage() || (filter && !filter->Match(*heap_[0]))) {
+ message->reset();
+ return;
+ }
+
+ std::pop_heap(heap_.begin(), heap_.end());
+ *message = std::move(heap_.back());
+ total_queued_bytes_ -= (*message)->GetSizeIfSerialized();
+ heap_.pop_back();
+
+ // We keep the capacity of |heap_| in check so that a large batch of incoming
+ // messages doesn't permanently wreck available memory. The choice of interval
+ // here is somewhat arbitrary.
+ constexpr size_t kHeapMinimumShrinkSize = 16;
+ constexpr size_t kHeapShrinkInterval = 512;
+ if (MOZ_UNLIKELY(heap_.size() > kHeapMinimumShrinkSize &&
+ heap_.size() % kHeapShrinkInterval == 0)) {
+ heap_.shrink_to_fit();
+ }
+}
+
+void MessageQueue::AcceptMessage(mozilla::UniquePtr<UserMessageEvent> message,
+ bool* has_next_message) {
+ // TODO: Handle sequence number roll-over.
+
+ total_queued_bytes_ += message->GetSizeIfSerialized();
+ heap_.emplace_back(std::move(message));
+ std::push_heap(heap_.begin(), heap_.end());
+
+ if (!signalable_) {
+ *has_next_message = false;
+ } else {
+ *has_next_message = (heap_[0]->sequence_num() == next_sequence_num_);
+ }
+}
+
+void MessageQueue::TakeAllMessages(
+ std::vector<mozilla::UniquePtr<UserMessageEvent>>* messages) {
+ *messages = std::move(heap_);
+ total_queued_bytes_ = 0;
+}
+
+void MessageQueue::MessageProcessed() { next_sequence_num_++; }
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/message_queue.h b/ipc/chromium/src/mojo/core/ports/message_queue.h
new file mode 100644
index 0000000000..c8c56da8b3
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/message_queue.h
@@ -0,0 +1,88 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_MESSAGE_QUEUE_H_
+#define MOJO_CORE_PORTS_MESSAGE_QUEUE_H_
+
+#include <stdint.h>
+
+#include <limits>
+#include <memory>
+#include <vector>
+
+#include "mojo/core/ports/event.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+constexpr uint64_t kInitialSequenceNum = 1;
+constexpr uint64_t kInvalidSequenceNum = std::numeric_limits<uint64_t>::max();
+
+class MessageFilter;
+
+// An incoming message queue for a port. MessageQueue keeps track of the highest
+// known sequence number and can indicate whether the next sequential message is
+// available. Thus the queue enforces message ordering for the consumer without
+// enforcing it for the producer (see AcceptMessage() below.)
+class MessageQueue {
+ public:
+ explicit MessageQueue();
+ explicit MessageQueue(uint64_t next_sequence_num);
+ ~MessageQueue();
+
+ MessageQueue(const MessageQueue&) = delete;
+ void operator=(const MessageQueue&) = delete;
+
+ void set_signalable(bool value) { signalable_ = value; }
+
+ uint64_t next_sequence_num() const { return next_sequence_num_; }
+
+ bool HasNextMessage() const;
+
+ // Gives ownership of the message. If |filter| is non-null, the next message
+ // will only be retrieved if the filter successfully matches it.
+ void GetNextMessage(mozilla::UniquePtr<UserMessageEvent>* message,
+ MessageFilter* filter);
+
+ // Mark the message from |GetNextMessage| as processed.
+ void MessageProcessed();
+
+ // Takes ownership of the message. Note: Messages are ordered, so while we
+ // have added a message to the queue, we may still be waiting on a message
+ // ahead of this one before we can let any of the messages be returned by
+ // GetNextMessage.
+ //
+ // Furthermore, once has_next_message is set to true, it will remain false
+ // until GetNextMessage is called enough times to return a null message.
+ // In other words, has_next_message acts like an edge trigger.
+ //
+ void AcceptMessage(mozilla::UniquePtr<UserMessageEvent> message,
+ bool* has_next_message);
+
+ // Takes all messages from this queue. Used to safely destroy queued messages
+ // without holding any Port lock.
+ void TakeAllMessages(
+ std::vector<mozilla::UniquePtr<UserMessageEvent>>* messages);
+
+ // The number of messages queued here, regardless of whether the next expected
+ // message has arrived yet.
+ size_t queued_message_count() const { return heap_.size(); }
+
+ // The aggregate memory size in bytes of all messages queued here, regardless
+ // of whether the next expected message has arrived yet.
+ size_t queued_num_bytes() const { return total_queued_bytes_; }
+
+ private:
+ std::vector<mozilla::UniquePtr<UserMessageEvent>> heap_;
+ uint64_t next_sequence_num_;
+ bool signalable_ = true;
+ size_t total_queued_bytes_ = 0;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_MESSAGE_QUEUE_H_
diff --git a/ipc/chromium/src/mojo/core/ports/name.cc b/ipc/chromium/src/mojo/core/ports/name.cc
new file mode 100644
index 0000000000..17a787d933
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/name.cc
@@ -0,0 +1,54 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/name.h"
+#include "chrome/common/ipc_message_utils.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+std::ostream& operator<<(std::ostream& stream, const Name& name) {
+ std::ios::fmtflags flags(stream.flags());
+ stream << std::hex << std::uppercase << name.v1;
+ if (name.v2 != 0) {
+ stream << '.' << name.v2;
+ }
+ stream.flags(flags);
+ return stream;
+}
+
+mozilla::Logger& operator<<(mozilla::Logger& log, const Name& name) {
+ log.printf("%" PRIX64, name.v1);
+ if (name.v2 != 0) {
+ log.printf(".%" PRIX64, name.v2);
+ }
+ return log;
+}
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+void IPC::ParamTraits<mojo::core::ports::PortName>::Write(
+ MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.v1);
+ WriteParam(aWriter, aParam.v2);
+}
+
+bool IPC::ParamTraits<mojo::core::ports::PortName>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ return ReadParam(aReader, &aResult->v1) && ReadParam(aReader, &aResult->v2);
+}
+
+void IPC::ParamTraits<mojo::core::ports::NodeName>::Write(
+ MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.v1);
+ WriteParam(aWriter, aParam.v2);
+}
+
+bool IPC::ParamTraits<mojo::core::ports::NodeName>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ return ReadParam(aReader, &aResult->v1) && ReadParam(aReader, &aResult->v2);
+}
diff --git a/ipc/chromium/src/mojo/core/ports/name.h b/ipc/chromium/src/mojo/core/ports/name.h
new file mode 100644
index 0000000000..0e668ebc40
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/name.h
@@ -0,0 +1,122 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_NAME_H_
+#define MOJO_CORE_PORTS_NAME_H_
+
+#include <stdint.h>
+
+#include <ostream>
+#include <tuple>
+
+#include "base/logging.h"
+#include "mozilla/HashFunctions.h"
+#include "nsHashKeys.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+struct Name {
+ constexpr Name(uint64_t v1, uint64_t v2) : v1(v1), v2(v2) {}
+ uint64_t v1, v2;
+};
+
+inline bool operator==(const Name& a, const Name& b) {
+ return a.v1 == b.v1 && a.v2 == b.v2;
+}
+
+inline bool operator!=(const Name& a, const Name& b) { return !(a == b); }
+
+inline bool operator<(const Name& a, const Name& b) {
+ return std::tie(a.v1, a.v2) < std::tie(b.v1, b.v2);
+}
+
+std::ostream& operator<<(std::ostream& stream, const Name& name);
+mozilla::Logger& operator<<(mozilla::Logger& log, const Name& name);
+
+struct PortName : Name {
+ constexpr PortName() : Name(0, 0) {}
+ constexpr PortName(uint64_t v1, uint64_t v2) : Name(v1, v2) {}
+};
+
+constexpr PortName kInvalidPortName{0, 0};
+
+struct NodeName : Name {
+ constexpr NodeName() : Name(0, 0) {}
+ constexpr NodeName(uint64_t v1, uint64_t v2) : Name(v1, v2) {}
+};
+
+constexpr NodeName kInvalidNodeName{0, 0};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+namespace mozilla {
+
+template <>
+inline PLDHashNumber Hash<mojo::core::ports::PortName>(
+ const mojo::core::ports::PortName& aValue) {
+ return mozilla::HashGeneric(aValue.v1, aValue.v2);
+}
+
+template <>
+inline PLDHashNumber Hash<mojo::core::ports::NodeName>(
+ const mojo::core::ports::NodeName& aValue) {
+ return mozilla::HashGeneric(aValue.v1, aValue.v2);
+}
+
+using PortNameHashKey = nsGenericHashKey<mojo::core::ports::PortName>;
+using NodeNameHashKey = nsGenericHashKey<mojo::core::ports::NodeName>;
+
+} // namespace mozilla
+
+namespace std {
+
+template <>
+struct hash<mojo::core::ports::PortName> {
+ std::size_t operator()(const mojo::core::ports::PortName& name) const {
+ // FIXME: PLDHashNumber is only 32-bits
+ return mozilla::Hash(name);
+ }
+};
+
+template <>
+struct hash<mojo::core::ports::NodeName> {
+ std::size_t operator()(const mojo::core::ports::NodeName& name) const {
+ // FIXME: PLDHashNumber is only 32-bits
+ return mozilla::Hash(name);
+ }
+};
+
+} // namespace std
+
+class PickleIterator;
+
+namespace IPC {
+
+template <typename T>
+struct ParamTraits;
+class Message;
+class MessageReader;
+class MessageWriter;
+
+template <>
+struct ParamTraits<mojo::core::ports::PortName> {
+ using paramType = mojo::core::ports::PortName;
+ static void Write(MessageWriter* aWriter, const paramType& aParam);
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+template <>
+struct ParamTraits<mojo::core::ports::NodeName> {
+ using paramType = mojo::core::ports::NodeName;
+ static void Write(MessageWriter* aWriter, const paramType& aParam);
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+} // namespace IPC
+
+#endif // MOJO_CORE_PORTS_NAME_H_
diff --git a/ipc/chromium/src/mojo/core/ports/node.cc b/ipc/chromium/src/mojo/core/ports/node.cc
new file mode 100644
index 0000000000..63e58c9928
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/node.cc
@@ -0,0 +1,2130 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/node.h"
+
+#include <string.h>
+
+#include <algorithm>
+#include <atomic>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "mozilla/Mutex.h"
+#include "mozilla/RandomNum.h"
+#include "nsTArray.h"
+
+#include "base/logging.h"
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/node_delegate.h"
+#include "mojo/core/ports/port_locker.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+namespace {
+
+int DebugError(const char* message, int error_code) {
+ NOTREACHED() << "Oops: " << message;
+ return error_code;
+}
+
+#define OOPS(x) DebugError(#x, x)
+
+bool CanAcceptMoreMessages(const Port* port) {
+ // Have we already doled out the last message (i.e., do we expect to NOT
+ // receive further messages)?
+ uint64_t next_sequence_num = port->message_queue.next_sequence_num();
+ if (port->state == Port::kClosed) {
+ return false;
+ }
+ if (port->peer_closed || port->remove_proxy_on_last_message) {
+ if (port->peer_lost_unexpectedly) {
+ return port->message_queue.HasNextMessage();
+ }
+ if (port->last_sequence_num_to_receive == next_sequence_num - 1) {
+ return false;
+ }
+ }
+ return true;
+}
+
+void GenerateRandomPortName(PortName* name) {
+ // FIXME: Chrome uses a cache to avoid extra calls to the system RNG when
+ // generating port names to keep this overhead down. If this method starts
+ // showing up on profiles we should consider doing the same.
+ *name = PortName{mozilla::RandomUint64OrDie(), mozilla::RandomUint64OrDie()};
+}
+
+} // namespace
+
+Node::Node(const NodeName& name, NodeDelegate* delegate)
+ : name_(name), delegate_(this, delegate) {}
+
+Node::~Node() {
+ if (!ports_.empty()) {
+ DLOG(WARNING) << "Unclean shutdown for node " << name_;
+ }
+}
+
+bool Node::CanShutdownCleanly(ShutdownPolicy policy) {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_lock(ports_lock_);
+
+ if (policy == ShutdownPolicy::DONT_ALLOW_LOCAL_PORTS) {
+#ifdef DEBUG
+ for (auto& entry : ports_) {
+ DVLOG(2) << "Port " << entry.first << " referencing node "
+ << entry.second->peer_node_name << " is blocking shutdown of "
+ << "node " << name_ << " (state=" << entry.second->state << ")";
+ }
+#endif
+ return ports_.empty();
+ }
+
+ DCHECK_EQ(policy, ShutdownPolicy::ALLOW_LOCAL_PORTS);
+
+ // NOTE: This is not efficient, though it probably doesn't need to be since
+ // relatively few ports should be open during shutdown and shutdown doesn't
+ // need to be blazingly fast.
+ bool can_shutdown = true;
+ for (auto& entry : ports_) {
+ PortRef port_ref(entry.first, entry.second);
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->peer_node_name != name_ && port->state != Port::kReceiving) {
+ can_shutdown = false;
+#ifdef DEBUG
+ DVLOG(2) << "Port " << entry.first << " referencing node "
+ << port->peer_node_name << " is blocking shutdown of "
+ << "node " << name_ << " (state=" << port->state << ")";
+#else
+ // Exit early when not debugging.
+ break;
+#endif
+ }
+ }
+
+ return can_shutdown;
+}
+
+int Node::GetPort(const PortName& port_name, PortRef* port_ref) {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock lock(ports_lock_);
+ auto iter = ports_.find(port_name);
+ if (iter == ports_.end()) {
+ return ERROR_PORT_UNKNOWN;
+ }
+
+#if defined(ANDROID) && defined(__aarch64__)
+ // Workaround for https://crbug.com/665869.
+ std::atomic_thread_fence(std::memory_order_seq_cst);
+#endif
+
+ *port_ref = PortRef(port_name, iter->second);
+ return OK;
+}
+
+int Node::CreateUninitializedPort(PortRef* port_ref) {
+ PortName port_name;
+ GenerateRandomPortName(&port_name);
+
+ RefPtr<Port> port(new Port(kInitialSequenceNum, kInitialSequenceNum));
+ int rv = AddPortWithName(port_name, port);
+ if (rv != OK) {
+ return rv;
+ }
+
+ *port_ref = PortRef(port_name, std::move(port));
+ return OK;
+}
+
+int Node::InitializePort(const PortRef& port_ref,
+ const NodeName& peer_node_name,
+ const PortName& peer_port_name,
+ const NodeName& prev_node_name,
+ const PortName& prev_port_name) {
+ {
+ // Must be acquired for UpdatePortPeerAddress below.
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_lock(ports_lock_);
+
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kUninitialized) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ port->state = Port::kReceiving;
+ UpdatePortPeerAddress(port_ref.name(), port, peer_node_name,
+ peer_port_name);
+
+ port->prev_node_name = prev_node_name;
+ port->prev_port_name = prev_port_name;
+ }
+
+ delegate_->PortStatusChanged(port_ref);
+
+ return OK;
+}
+
+int Node::CreatePortPair(PortRef* port0_ref, PortRef* port1_ref) {
+ int rv;
+
+ rv = CreateUninitializedPort(port0_ref);
+ if (rv != OK) {
+ return rv;
+ }
+
+ rv = CreateUninitializedPort(port1_ref);
+ if (rv != OK) {
+ return rv;
+ }
+
+ rv = InitializePort(*port0_ref, name_, port1_ref->name(), name_,
+ port1_ref->name());
+ if (rv != OK) {
+ return rv;
+ }
+
+ rv = InitializePort(*port1_ref, name_, port0_ref->name(), name_,
+ port0_ref->name());
+ if (rv != OK) {
+ return rv;
+ }
+
+ return OK;
+}
+
+int Node::SetUserData(const PortRef& port_ref, RefPtr<UserData> user_data) {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state == Port::kClosed) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ port->user_data = std::move(user_data);
+
+ return OK;
+}
+
+int Node::GetUserData(const PortRef& port_ref, RefPtr<UserData>* user_data) {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state == Port::kClosed) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ *user_data = port->user_data;
+
+ return OK;
+}
+
+int Node::ClosePort(const PortRef& port_ref) {
+ std::vector<mozilla::UniquePtr<UserMessageEvent>> undelivered_messages;
+ NodeName peer_node_name;
+ PortName peer_port_name;
+ uint64_t sequence_num = 0;
+ uint64_t last_sequence_num = 0;
+ bool was_initialized = false;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ switch (port->state) {
+ case Port::kUninitialized:
+ break;
+
+ case Port::kReceiving:
+ was_initialized = true;
+ port->state = Port::kClosed;
+
+ // We pass along the sequence number of the last message sent from this
+ // port to allow the peer to have the opportunity to consume all inbound
+ // messages before notifying the embedder that this port is closed.
+ last_sequence_num = port->next_sequence_num_to_send - 1;
+
+ peer_node_name = port->peer_node_name;
+ peer_port_name = port->peer_port_name;
+
+ sequence_num = port->next_control_sequence_num_to_send++;
+
+ // If the port being closed still has unread messages, then we need to
+ // take care to close those ports so as to avoid leaking memory.
+ port->message_queue.TakeAllMessages(&undelivered_messages);
+ port->TakePendingMessages(undelivered_messages);
+ break;
+
+ default:
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+ }
+
+ ErasePort(port_ref.name());
+
+ if (was_initialized) {
+ DVLOG(2) << "Sending ObserveClosure from " << port_ref.name() << "@"
+ << name_ << " to " << peer_port_name << "@" << peer_node_name;
+ delegate_->ForwardEvent(
+ peer_node_name,
+ mozilla::MakeUnique<ObserveClosureEvent>(
+ peer_port_name, port_ref.name(), sequence_num, last_sequence_num));
+ for (const auto& message : undelivered_messages) {
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ PortRef ref;
+ if (GetPort(message->ports()[i], &ref) == OK) {
+ ClosePort(ref);
+ }
+ }
+ }
+ }
+ return OK;
+}
+
+int Node::GetStatus(const PortRef& port_ref, PortStatus* port_status) {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kReceiving) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ // TODO(sroettger): include messages pending sender verification here?
+ port_status->has_messages = port->message_queue.HasNextMessage();
+ port_status->receiving_messages = CanAcceptMoreMessages(port);
+ port_status->peer_closed = port->peer_closed;
+ port_status->peer_remote = port->peer_node_name != name_;
+ port_status->queued_message_count =
+ port->message_queue.queued_message_count();
+ port_status->queued_num_bytes = port->message_queue.queued_num_bytes();
+ port_status->unacknowledged_message_count =
+ port->next_sequence_num_to_send - port->last_sequence_num_acknowledged -
+ 1;
+
+#ifdef FUZZING_SNAPSHOT
+ port_status->peer_node_name = port->peer_node_name;
+#endif
+
+ return OK;
+}
+
+int Node::GetMessage(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageEvent>* message,
+ MessageFilter* filter) {
+ *message = nullptr;
+
+ DVLOG(4) << "GetMessage for " << port_ref.name() << "@" << name_;
+
+ NodeName peer_node_name;
+ ScopedEvent ack_event;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ // This could also be treated like the port being unknown since the
+ // embedder should no longer be referring to a port that has been sent.
+ if (port->state != Port::kReceiving) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ // Let the embedder get messages until there are no more before reporting
+ // that the peer closed its end.
+ if (!CanAcceptMoreMessages(port)) {
+ return ERROR_PORT_PEER_CLOSED;
+ }
+
+ port->message_queue.GetNextMessage(message, filter);
+ if (*message &&
+ (*message)->sequence_num() == port->sequence_num_to_acknowledge) {
+ peer_node_name = port->peer_node_name;
+ ack_event = mozilla::MakeUnique<UserMessageReadAckEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++,
+ port->sequence_num_to_acknowledge);
+ }
+ if (*message) {
+ // Message will be passed to the user, no need to block the queue.
+ port->message_queue.MessageProcessed();
+ }
+ }
+
+ if (ack_event) {
+ delegate_->ForwardEvent(peer_node_name, std::move(ack_event));
+ }
+
+ // Allow referenced ports to trigger PortStatusChanged calls.
+ if (*message) {
+ for (size_t i = 0; i < (*message)->num_ports(); ++i) {
+ PortRef new_port_ref;
+ int rv = GetPort((*message)->ports()[i], &new_port_ref);
+
+ DCHECK_EQ(OK, rv) << "Port " << new_port_ref.name() << "@" << name_
+ << " does not exist!";
+
+ SinglePortLocker locker(&new_port_ref);
+ DCHECK_EQ(locker.port()->state, Port::kReceiving);
+ locker.port()->message_queue.set_signalable(true);
+ }
+
+ // The user may retransmit this message from another port. We reset the
+ // sequence number so that the message will get a new one if that happens.
+ (*message)->set_sequence_num(0);
+ }
+
+ return OK;
+}
+
+int Node::SendUserMessage(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageEvent> message) {
+ int rv = SendUserMessageInternal(port_ref, &message);
+ if (rv != OK) {
+ // If send failed, close all carried ports. Note that we're careful not to
+ // close the sending port itself if it happened to be one of the encoded
+ // ports (an invalid but possible condition.)
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ if (message->ports()[i] == port_ref.name()) {
+ continue;
+ }
+
+ PortRef port;
+ if (GetPort(message->ports()[i], &port) == OK) {
+ ClosePort(port);
+ }
+ }
+ }
+ return rv;
+}
+
+int Node::SetAcknowledgeRequestInterval(
+ const PortRef& port_ref, uint64_t sequence_num_acknowledge_interval) {
+ NodeName peer_node_name;
+ PortName peer_port_name;
+ uint64_t sequence_num_to_request_ack = 0;
+ uint64_t sequence_num = 0;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kReceiving) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ port->sequence_num_acknowledge_interval = sequence_num_acknowledge_interval;
+ if (!sequence_num_acknowledge_interval) {
+ return OK;
+ }
+
+ peer_node_name = port->peer_node_name;
+ peer_port_name = port->peer_port_name;
+
+ sequence_num_to_request_ack = port->last_sequence_num_acknowledged +
+ sequence_num_acknowledge_interval;
+ sequence_num = port->next_control_sequence_num_to_send++;
+ }
+
+ delegate_->ForwardEvent(peer_node_name,
+ mozilla::MakeUnique<UserMessageReadAckRequestEvent>(
+ peer_port_name, port_ref.name(), sequence_num,
+ sequence_num_to_request_ack));
+ return OK;
+}
+
+bool Node::IsEventFromPreviousPeer(const Event& event) {
+ switch (event.type()) {
+ case Event::Type::kUserMessage:
+ return true;
+ case Event::Type::kPortAccepted:
+ // PortAccepted is sent by the next peer
+ return false;
+ case Event::Type::kObserveProxy:
+ // ObserveProxy with an invalid port name is a broadcast event
+ return event.port_name() != kInvalidPortName;
+ case Event::Type::kObserveProxyAck:
+ return true;
+ case Event::Type::kObserveClosure:
+ return true;
+ case Event::Type::kMergePort:
+ // MergePort is not from the previous peer
+ return false;
+ case Event::Type::kUserMessageReadAckRequest:
+ return true;
+ case Event::Type::kUserMessageReadAck:
+ return true;
+ case Event::Type::kUpdatePreviousPeer:
+ return true;
+ default:
+ // No need to check unknown message types since AcceptPeer will return
+ // an error.
+ return false;
+ }
+}
+
+int Node::AcceptEventInternal(const PortRef& port_ref,
+ const NodeName& from_node, ScopedEvent event) {
+ switch (event->type()) {
+ case Event::Type::kUserMessage:
+ return OnUserMessage(port_ref, from_node,
+ Event::Cast<UserMessageEvent>(&event));
+ case Event::Type::kPortAccepted:
+ return OnPortAccepted(port_ref, Event::Cast<PortAcceptedEvent>(&event));
+ case Event::Type::kObserveProxy:
+ return OnObserveProxy(port_ref, Event::Cast<ObserveProxyEvent>(&event));
+ case Event::Type::kObserveProxyAck:
+ return OnObserveProxyAck(port_ref,
+ Event::Cast<ObserveProxyAckEvent>(&event));
+ case Event::Type::kObserveClosure:
+ return OnObserveClosure(port_ref,
+ Event::Cast<ObserveClosureEvent>(&event));
+ case Event::Type::kMergePort:
+ return OnMergePort(port_ref, Event::Cast<MergePortEvent>(&event));
+ case Event::Type::kUserMessageReadAckRequest:
+ return OnUserMessageReadAckRequest(
+ port_ref, Event::Cast<UserMessageReadAckRequestEvent>(&event));
+ case Event::Type::kUserMessageReadAck:
+ return OnUserMessageReadAck(port_ref,
+ Event::Cast<UserMessageReadAckEvent>(&event));
+ case Event::Type::kUpdatePreviousPeer:
+ return OnUpdatePreviousPeer(port_ref,
+ Event::Cast<UpdatePreviousPeerEvent>(&event));
+ }
+ return OOPS(ERROR_NOT_IMPLEMENTED);
+}
+
+int Node::AcceptEvent(const NodeName& from_node, ScopedEvent event) {
+ PortRef port_ref;
+ GetPort(event->port_name(), &port_ref);
+
+ DVLOG(2) << "AcceptEvent type: " << event->type() << ", "
+ << event->from_port() << "@" << from_node << " => "
+ << port_ref.name() << "@" << name_
+ << " seq nr: " << event->control_sequence_num() << " port valid? "
+ << port_ref.is_valid();
+
+ if (!IsEventFromPreviousPeer(*event)) {
+ DCHECK_EQ(event->control_sequence_num(), kInvalidSequenceNum);
+ // Some events are not coming from the previous peer, e.g. broadcasts or
+ // PortAccepted events. No need to check the sequence number or sender.
+ return AcceptEventInternal(port_ref, from_node, std::move(event));
+ }
+
+ DCHECK_NE(event->control_sequence_num(), kInvalidSequenceNum);
+
+ if (!port_ref.is_valid()) {
+ // If we don't have a valid port, there's nothing for us to check. However,
+ // we pass the ref on to AcceptEventInternal to make sure there's no race
+ // where it becomes valid and we skipped the peer check.
+ return AcceptEventInternal(port_ref, from_node, std::move(event));
+ }
+
+ // Before processing the event, verify the sender and sequence number.
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (!port->IsNextEvent(from_node, *event)) {
+ DVLOG(2) << "Buffering event (type " << event->type()
+ << "): " << event->from_port() << "@" << from_node << " => "
+ << port_ref.name() << "@" << name_
+ << " seq nr: " << event->control_sequence_num() << " / "
+ << port->next_control_sequence_num_to_receive << ", want "
+ << port->prev_port_name << "@" << port->prev_node_name;
+
+ port->BufferEvent(from_node, std::move(event));
+ return OK;
+ }
+ }
+
+ int ret = AcceptEventInternal(port_ref, from_node, std::move(event));
+
+ // More events might have been enqueued during processing.
+ while (true) {
+ ScopedEvent next_event;
+ NodeName next_from_node;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ // We always increment the control sequence number after we finished
+ // processing the event. That way we ensure that the events are handled
+ // in order without keeping a lock the whole time.
+ port->next_control_sequence_num_to_receive++;
+ port->NextEvent(&next_from_node, &next_event);
+
+ if (next_event) {
+ DVLOG(2) << "Handling buffered event (type " << next_event->type()
+ << "): " << next_event->from_port() << "@" << next_from_node
+ << " => " << port_ref.name() << "@" << name_
+ << " seq nr: " << next_event->control_sequence_num() << " / "
+ << port->next_control_sequence_num_to_receive;
+ }
+ }
+ if (!next_event) {
+ break;
+ }
+ AcceptEventInternal(port_ref, next_from_node, std::move(next_event));
+ }
+
+ return ret;
+}
+
+int Node::MergePorts(const PortRef& port_ref,
+ const NodeName& destination_node_name,
+ const PortName& destination_port_name) {
+ PortName new_port_name;
+ Event::PortDescriptor new_port_descriptor;
+ PendingUpdatePreviousPeer pending_update_event{.from_port = port_ref.name()};
+ {
+ // Must be held for ConvertToProxy.
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_locker(ports_lock_);
+
+ SinglePortLocker locker(&port_ref);
+
+ DVLOG(1) << "Sending MergePort from " << port_ref.name() << "@" << name_
+ << " to " << destination_port_name << "@" << destination_node_name;
+
+ // Send the port-to-merge over to the destination node so it can be merged
+ // into the port cycle atomically there.
+ new_port_name = port_ref.name();
+ ConvertToProxy(locker.port(), destination_node_name, &new_port_name,
+ &new_port_descriptor, &pending_update_event);
+ }
+
+ delegate_->ForwardEvent(
+ pending_update_event.receiver,
+ mozilla::MakeUnique<UpdatePreviousPeerEvent>(
+ pending_update_event.port, pending_update_event.from_port,
+ pending_update_event.sequence_num, pending_update_event.new_prev_node,
+ pending_update_event.new_prev_port));
+
+ if (new_port_descriptor.peer_node_name == name_ &&
+ destination_node_name != name_) {
+ // Ensure that the locally retained peer of the new proxy gets a status
+ // update so it notices that its peer is now remote.
+ PortRef local_peer;
+ if (GetPort(new_port_descriptor.peer_port_name, &local_peer) == OK) {
+ delegate_->PortStatusChanged(local_peer);
+ }
+ }
+
+ delegate_->ForwardEvent(
+ destination_node_name,
+ mozilla::MakeUnique<MergePortEvent>(destination_port_name,
+ kInvalidPortName, kInvalidSequenceNum,
+ new_port_name, new_port_descriptor));
+ return OK;
+}
+
+int Node::MergeLocalPorts(const PortRef& port0_ref, const PortRef& port1_ref) {
+ DVLOG(1) << "Merging local ports " << port0_ref.name() << "@" << name_
+ << " and " << port1_ref.name() << "@" << name_;
+ return MergePortsInternal(port0_ref, port1_ref,
+ true /* allow_close_on_bad_state */);
+}
+
+int Node::LostConnectionToNode(const NodeName& node_name) {
+ // We can no longer send events to the given node. We also can't expect any
+ // PortAccepted events.
+
+ DVLOG(1) << "Observing lost connection from node " << name_ << " to node "
+ << node_name;
+
+ DestroyAllPortsWithPeer(node_name, kInvalidPortName);
+ return OK;
+}
+
+int Node::OnUserMessage(const PortRef& port_ref, const NodeName& from_node,
+ mozilla::UniquePtr<UserMessageEvent> message) {
+#ifdef DEBUG
+ std::ostringstream ports_buf;
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ if (i > 0) {
+ ports_buf << ",";
+ }
+ ports_buf << message->ports()[i];
+ }
+
+ DVLOG(4) << "OnUserMessage " << message->sequence_num()
+ << " [ports=" << ports_buf.str() << "] at " << message->port_name()
+ << "@" << name_;
+#endif
+
+ // Even if this port does not exist, cannot receive anymore messages or is
+ // buffering or proxying messages, we still need these ports to be bound to
+ // this node. When the message is forwarded, these ports will get transferred
+ // following the usual method. If the message cannot be accepted, then the
+ // newly bound ports will simply be closed.
+ if (from_node != name_) {
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ Event::PortDescriptor& descriptor = message->port_descriptors()[i];
+ int rv = AcceptPort(message->ports()[i], descriptor);
+ if (rv != OK) {
+ return rv;
+ }
+ }
+ }
+
+ bool has_next_message = false;
+ bool message_accepted = false;
+ bool should_forward_messages = false;
+ if (port_ref.is_valid()) {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ // Reject spurious messages if we've already received the last expected
+ // message.
+ if (CanAcceptMoreMessages(port)) {
+ message_accepted = true;
+ port->message_queue.AcceptMessage(std::move(message), &has_next_message);
+
+ if (port->state == Port::kBuffering) {
+ has_next_message = false;
+ } else if (port->state == Port::kProxying) {
+ has_next_message = false;
+ should_forward_messages = true;
+ }
+ }
+ }
+
+ if (should_forward_messages) {
+ int rv = ForwardUserMessagesFromProxy(port_ref);
+ if (rv != OK) {
+ return rv;
+ }
+ TryRemoveProxy(port_ref);
+ }
+
+ if (!message_accepted) {
+ DVLOG(2) << "Message not accepted!\n";
+ // Close all newly accepted ports as they are effectively orphaned.
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ PortRef attached_port_ref;
+ if (GetPort(message->ports()[i], &attached_port_ref) == OK) {
+ ClosePort(attached_port_ref);
+ } else {
+ DLOG(WARNING) << "Cannot close non-existent port!\n";
+ }
+ }
+ } else if (has_next_message) {
+ delegate_->PortStatusChanged(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::OnPortAccepted(const PortRef& port_ref,
+ mozilla::UniquePtr<PortAcceptedEvent> event) {
+ if (!port_ref.is_valid()) {
+ return ERROR_PORT_UNKNOWN;
+ }
+
+#ifdef DEBUG
+ {
+ SinglePortLocker locker(&port_ref);
+ DVLOG(2) << "PortAccepted at " << port_ref.name() << "@" << name_
+ << " pointing to " << locker.port()->peer_port_name << "@"
+ << locker.port()->peer_node_name;
+ }
+#endif
+
+ return BeginProxying(port_ref);
+}
+
+int Node::OnObserveProxy(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveProxyEvent> event) {
+ if (event->port_name() == kInvalidPortName) {
+ // An ObserveProxy with an invalid target port name is a broadcast used to
+ // inform ports when their peer (which was itself a proxy) has become
+ // defunct due to unexpected node disconnection.
+ //
+ // Receiving ports affected by this treat it as equivalent to peer closure.
+ // Proxies affected by this can be removed and will in turn broadcast their
+ // own death with a similar message.
+ DCHECK_EQ(event->proxy_target_node_name(), kInvalidNodeName);
+ DCHECK_EQ(event->proxy_target_port_name(), kInvalidPortName);
+ DestroyAllPortsWithPeer(event->proxy_node_name(), event->proxy_port_name());
+ return OK;
+ }
+
+ // The port may have already been closed locally, in which case the
+ // ObserveClosure message will contain the last_sequence_num field.
+ // We can then silently ignore this message.
+ if (!port_ref.is_valid()) {
+ DVLOG(1) << "ObserveProxy: " << event->port_name() << "@" << name_
+ << " not found";
+ return OK;
+ }
+
+ DVLOG(2) << "ObserveProxy at " << port_ref.name() << "@" << name_
+ << ", proxy at " << event->proxy_port_name() << "@"
+ << event->proxy_node_name() << " pointing to "
+ << event->proxy_target_port_name() << "@"
+ << event->proxy_target_node_name();
+
+ bool peer_changed = false;
+ ScopedEvent event_to_forward;
+ NodeName event_target_node;
+ {
+ // Must be acquired for UpdatePortPeerAddress below.
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_locker(ports_lock_);
+
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ if (port->peer_node_name == event->proxy_node_name() &&
+ port->peer_port_name == event->proxy_port_name()) {
+ if (port->state == Port::kReceiving) {
+ // Updating the port peer will reset the sequence num. Grab it now;
+ uint64_t sequence_num = port->next_control_sequence_num_to_send++;
+ UpdatePortPeerAddress(port_ref.name(), port,
+ event->proxy_target_node_name(),
+ event->proxy_target_port_name());
+ event_target_node = event->proxy_node_name();
+ event_to_forward = mozilla::MakeUnique<ObserveProxyAckEvent>(
+ event->proxy_port_name(), port_ref.name(), sequence_num,
+ port->next_sequence_num_to_send - 1);
+ peer_changed = true;
+ DVLOG(2) << "Forwarding ObserveProxyAck from " << event->port_name()
+ << "@" << name_ << " to " << event->proxy_port_name() << "@"
+ << event_target_node;
+ } else {
+ // As a proxy ourselves, we don't know how to honor the ObserveProxy
+ // event or to populate the last_sequence_num field of ObserveProxyAck.
+ // Afterall, another port could be sending messages to our peer now
+ // that we've sent out our own ObserveProxy event. Instead, we will
+ // send an ObserveProxyAck indicating that the ObserveProxy event
+ // should be re-sent (last_sequence_num set to kInvalidSequenceNum).
+ // However, this has to be done after we are removed as a proxy.
+ // Otherwise, we might just find ourselves back here again, which
+ // would be akin to a busy loop.
+
+ DVLOG(2) << "Delaying ObserveProxyAck to " << event->proxy_port_name()
+ << "@" << event->proxy_node_name();
+
+ port->send_on_proxy_removal =
+ mozilla::MakeUnique<std::pair<NodeName, ScopedEvent>>(
+ event->proxy_node_name(),
+ mozilla::MakeUnique<ObserveProxyAckEvent>(
+ event->proxy_port_name(), port_ref.name(),
+ kInvalidSequenceNum, kInvalidSequenceNum));
+ }
+ } else {
+ // Forward this event along to our peer. Eventually, it should find the
+ // port referring to the proxy.
+ event_target_node = port->peer_node_name;
+ event->set_port_name(port->peer_port_name);
+ event->set_from_port(port_ref.name());
+ event->set_control_sequence_num(
+ port->next_control_sequence_num_to_send++);
+ if (port->state == Port::kBuffering) {
+ port->control_message_queue.push_back(
+ {event_target_node, std::move(event)});
+ } else {
+ event_to_forward = std::move(event);
+ }
+ }
+ }
+
+ if (event_to_forward) {
+ delegate_->ForwardEvent(event_target_node, std::move(event_to_forward));
+ }
+
+ if (peer_changed) {
+ // Re-send ack and/or ack requests, as the previous peer proxy may not have
+ // forwarded the previous request before it died.
+ MaybeResendAck(port_ref);
+ MaybeResendAckRequest(port_ref);
+
+ delegate_->PortStatusChanged(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::OnObserveProxyAck(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveProxyAckEvent> event) {
+ DVLOG(2) << "ObserveProxyAck at " << event->port_name() << "@" << name_
+ << " (last_sequence_num=" << event->last_sequence_num() << ")";
+
+ if (!port_ref.is_valid()) {
+ return ERROR_PORT_UNKNOWN; // The port may have observed closure first.
+ }
+
+ bool try_remove_proxy_immediately;
+ bool erase_port = false;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ if (port->state == Port::kProxying) {
+ // If the last sequence number is invalid, this is a signal that we need
+ // to retransmit the ObserveProxy event for this port rather than flagging
+ // the the proxy for removal ASAP.
+ try_remove_proxy_immediately =
+ event->last_sequence_num() != kInvalidSequenceNum;
+ if (try_remove_proxy_immediately) {
+ // We can now remove this port once we have received and forwarded the
+ // last message addressed to this port.
+ port->remove_proxy_on_last_message = true;
+ port->last_sequence_num_to_receive = event->last_sequence_num();
+ }
+ } else if (port->state == Port::kClosed) {
+ erase_port = true;
+ } else {
+ return OOPS(ERROR_PORT_STATE_UNEXPECTED);
+ }
+ }
+
+ if (erase_port) {
+ ErasePort(port_ref.name());
+ return OK;
+ }
+
+ if (try_remove_proxy_immediately) {
+ TryRemoveProxy(port_ref);
+ } else {
+ InitiateProxyRemoval(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::OnObserveClosure(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveClosureEvent> event) {
+ // OK if the port doesn't exist, as it may have been closed already.
+ if (!port_ref.is_valid()) {
+ return OK;
+ }
+
+ // This message tells the port that it should no longer expect more messages
+ // beyond last_sequence_num. This message is forwarded along until we reach
+ // the receiving end, and this message serves as an equivalent to
+ // ObserveProxyAck.
+
+ bool notify_delegate = false;
+ NodeName peer_node_name;
+ bool try_remove_proxy = false;
+ bool erase_port = false;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ port->peer_closed = true;
+ port->last_sequence_num_to_receive = event->last_sequence_num();
+
+ DVLOG(2) << "ObserveClosure at " << port_ref.name() << "@" << name_
+ << " (state=" << port->state << ") pointing to "
+ << port->peer_port_name << "@" << port->peer_node_name
+ << " (last_sequence_num=" << event->last_sequence_num() << ")";
+
+ // We always forward ObserveClosure, even beyond the receiving port which
+ // cares about it. This ensures that any dead-end proxies beyond that port
+ // are notified to remove themselves.
+
+ if (port->state == Port::kReceiving) {
+ notify_delegate = true;
+
+ // When forwarding along the other half of the port cycle, this will only
+ // reach dead-end proxies. Tell them we've sent our last message so they
+ // can go away.
+ //
+ // TODO: Repurposing ObserveClosure for this has the desired result but
+ // may be semantically confusing since the forwarding port is not actually
+ // closed. Consider replacing this with a new event type.
+ event->set_last_sequence_num(port->next_sequence_num_to_send - 1);
+
+ // Treat the closure as an acknowledge that all sent messages have been
+ // read from the other end.
+ port->last_sequence_num_acknowledged =
+ port->next_sequence_num_to_send - 1;
+ } else if (port->state == Port::kClosed) {
+ // This is the ack for a closed proxy port notification. Now it's fine to
+ // delete the port.
+ erase_port = true;
+ } else {
+ // We haven't yet reached the receiving peer of the closed port, so we'll
+ // forward the message along as-is.
+ // See about removing the port if it is a proxy as our peer won't be able
+ // to participate in proxy removal.
+ port->remove_proxy_on_last_message = true;
+ if (port->state == Port::kProxying) {
+ try_remove_proxy = true;
+ }
+ }
+
+ DVLOG(2) << "Forwarding ObserveClosure from " << port_ref.name() << "@"
+ << name_ << " to peer " << port->peer_port_name << "@"
+ << port->peer_node_name
+ << " (last_sequence_num=" << event->last_sequence_num() << ")";
+
+ event->set_port_name(port->peer_port_name);
+ event->set_from_port(port_ref.name());
+ event->set_control_sequence_num(port->next_control_sequence_num_to_send++);
+ peer_node_name = port->peer_node_name;
+
+ if (port->state == Port::kBuffering) {
+ port->control_message_queue.push_back({peer_node_name, std::move(event)});
+ }
+ }
+
+ if (try_remove_proxy) {
+ TryRemoveProxy(port_ref);
+ }
+
+ if (erase_port) {
+ ErasePort(port_ref.name());
+ }
+
+ if (event) {
+ delegate_->ForwardEvent(peer_node_name, std::move(event));
+ }
+
+ if (notify_delegate) {
+ delegate_->PortStatusChanged(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::OnMergePort(const PortRef& port_ref,
+ mozilla::UniquePtr<MergePortEvent> event) {
+ DVLOG(1) << "MergePort at " << port_ref.name() << "@" << name_
+ << " merging with proxy " << event->new_port_name() << "@" << name_
+ << " pointing to " << event->new_port_descriptor().peer_port_name
+ << "@" << event->new_port_descriptor().peer_node_name
+ << " referred by "
+ << event->new_port_descriptor().referring_port_name << "@"
+ << event->new_port_descriptor().referring_node_name;
+
+ // Accept the new port. This is now the receiving end of the other port cycle
+ // to be merged with ours. Note that we always attempt to accept the new port
+ // first as otherwise its peer receiving port could be left stranded
+ // indefinitely.
+ if (AcceptPort(event->new_port_name(), event->new_port_descriptor()) != OK) {
+ if (port_ref.is_valid()) {
+ ClosePort(port_ref);
+ }
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ PortRef new_port_ref;
+ GetPort(event->new_port_name(), &new_port_ref);
+ if (!port_ref.is_valid() && new_port_ref.is_valid()) {
+ ClosePort(new_port_ref);
+ return ERROR_PORT_UNKNOWN;
+ }
+ if (port_ref.is_valid() && !new_port_ref.is_valid()) {
+ ClosePort(port_ref);
+ return ERROR_PORT_UNKNOWN;
+ }
+
+ bool peer_allowed = true;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (!port->pending_merge_peer) {
+ CHROMIUM_LOG(ERROR) << "MergePort called on unexpected port: "
+ << event->port_name();
+ peer_allowed = false;
+ } else {
+ port->pending_merge_peer = false;
+ }
+ }
+ if (!peer_allowed) {
+ ClosePort(port_ref);
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ return MergePortsInternal(port_ref, new_port_ref,
+ false /* allow_close_on_bad_state */);
+}
+
+int Node::OnUserMessageReadAckRequest(
+ const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageReadAckRequestEvent> event) {
+ DVLOG(1) << "AckRequest " << port_ref.name() << "@" << name_ << " sequence "
+ << event->sequence_num_to_acknowledge();
+
+ if (!port_ref.is_valid()) {
+ return ERROR_PORT_UNKNOWN;
+ }
+
+ NodeName peer_node_name;
+ mozilla::UniquePtr<Event> event_to_send;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ peer_node_name = port->peer_node_name;
+ if (port->state == Port::kProxying) {
+ // Proxies simply forward the ack request to their peer.
+ event->set_port_name(port->peer_port_name);
+ event->set_from_port(port_ref.name());
+ event->set_control_sequence_num(
+ port->next_control_sequence_num_to_send++);
+ event_to_send = std::move(event);
+ } else {
+ uint64_t current_sequence_num =
+ port->message_queue.next_sequence_num() - 1;
+ // Either this is requesting an ack for a sequence number already read, or
+ // else for a sequence number that is yet to be read.
+ if (current_sequence_num >= event->sequence_num_to_acknowledge()) {
+ // If the current sequence number to read already exceeds the ack
+ // request, send an ack immediately.
+ event_to_send = mozilla::MakeUnique<UserMessageReadAckEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++, current_sequence_num);
+
+ if (port->state == Port::kBuffering) {
+ port->control_message_queue.push_back(
+ {peer_node_name, std::move(event_to_send)});
+ }
+
+ // This might be a late or duplicate acknowledge request, that's
+ // requesting acknowledge for an already read message. There may already
+ // have been a request for future reads, so take care not to back up
+ // the requested acknowledge counter.
+ if (current_sequence_num > port->sequence_num_to_acknowledge) {
+ port->sequence_num_to_acknowledge = current_sequence_num;
+ }
+ } else {
+ // This is request to ack a sequence number that hasn't been read yet.
+ // The state of the port can either be that it already has a
+ // future-requested ack, or not. Because ack requests aren't guaranteed
+ // to arrive in order, store the earlier of the current queued request
+ // and the new one, if one was already requested.
+ bool has_queued_ack_request =
+ port->sequence_num_to_acknowledge > current_sequence_num;
+ if (!has_queued_ack_request ||
+ port->sequence_num_to_acknowledge >
+ event->sequence_num_to_acknowledge()) {
+ port->sequence_num_to_acknowledge =
+ event->sequence_num_to_acknowledge();
+ }
+ return OK;
+ }
+ }
+ }
+
+ if (event_to_send) {
+ delegate_->ForwardEvent(peer_node_name, std::move(event_to_send));
+ }
+
+ return OK;
+}
+
+int Node::OnUserMessageReadAck(
+ const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageReadAckEvent> event) {
+ DVLOG(1) << "Acknowledge " << port_ref.name() << "@" << name_ << " sequence "
+ << event->sequence_num_acknowledged();
+
+ NodeName peer_node_name;
+ ScopedEvent ack_request_event;
+ if (port_ref.is_valid()) {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ if (event->sequence_num_acknowledged() >= port->next_sequence_num_to_send) {
+ // TODO(http://crbug.com/980952): This is a malformed event.
+ // This could return a new error "ERROR_MALFORMED_EVENT" which the
+ // delegate could use as a signal to drop the peer node.
+ return OK;
+ }
+
+ // Keep the largest acknowledge seen.
+ if (event->sequence_num_acknowledged() <=
+ port->last_sequence_num_acknowledged) {
+ // The acknowledge was late or a duplicate, it's safe to ignore it.
+ return OK;
+ }
+
+ port->last_sequence_num_acknowledged = event->sequence_num_acknowledged();
+ // Send another ack request if the interval is non-zero and the peer has
+ // not been closed.
+ if (port->sequence_num_acknowledge_interval && !port->peer_closed) {
+ peer_node_name = port->peer_node_name;
+ ack_request_event = mozilla::MakeUnique<UserMessageReadAckRequestEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++,
+ port->last_sequence_num_acknowledged +
+ port->sequence_num_acknowledge_interval);
+ DCHECK_NE(port->state, Port::kBuffering);
+ }
+ }
+ if (ack_request_event) {
+ delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event));
+ }
+
+ if (port_ref.is_valid()) {
+ delegate_->PortStatusChanged(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::OnUpdatePreviousPeer(
+ const PortRef& port_ref,
+ mozilla::UniquePtr<UpdatePreviousPeerEvent> event) {
+ DVLOG(1) << "OnUpdatePreviousPeer port: " << event->port_name()
+ << " changing to " << event->new_node_name()
+ << ", port: " << event->from_port() << " => "
+ << event->new_port_name();
+
+ if (!port_ref.is_valid()) {
+ return ERROR_PORT_UNKNOWN;
+ }
+
+ const NodeName& new_node_name = event->new_node_name();
+ const PortName& new_port_name = event->new_port_name();
+ DCHECK_NE(new_node_name, kInvalidNodeName);
+ DCHECK_NE(new_port_name, kInvalidPortName);
+ if (new_node_name == kInvalidNodeName || new_port_name == kInvalidPortName) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+
+ port->prev_node_name = new_node_name;
+ port->prev_port_name = new_port_name;
+ // The sequence number will get incremented after this event has been
+ // handled.
+ port->next_control_sequence_num_to_receive = kInitialSequenceNum - 1;
+ }
+
+ return OK;
+}
+
+int Node::AddPortWithName(const PortName& port_name, RefPtr<Port> port) {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock lock(ports_lock_);
+ if (port->peer_port_name != kInvalidPortName) {
+ DCHECK_NE(kInvalidNodeName, port->peer_node_name);
+ peer_port_maps_[port->peer_node_name][port->peer_port_name].emplace(
+ port_name, PortRef(port_name, port));
+ }
+ if (!ports_.emplace(port_name, std::move(port)).second) {
+ return OOPS(ERROR_PORT_EXISTS); // Suggests a bad UUID generator.
+ }
+ DVLOG(2) << "Created port " << port_name << "@" << name_;
+ return OK;
+}
+
+void Node::ErasePort(const PortName& port_name) {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ RefPtr<Port> port;
+ {
+ mozilla::MutexAutoLock lock(ports_lock_);
+ auto it = ports_.find(port_name);
+ if (it == ports_.end()) {
+ return;
+ }
+ port = std::move(it->second);
+ ports_.erase(it);
+
+ RemoveFromPeerPortMap(port_name, port.get());
+ }
+ // NOTE: We are careful not to release the port's messages while holding any
+ // locks, since they may run arbitrary user code upon destruction.
+ std::vector<mozilla::UniquePtr<UserMessageEvent>> messages;
+ {
+ PortRef port_ref(port_name, std::move(port));
+ SinglePortLocker locker(&port_ref);
+ locker.port()->message_queue.TakeAllMessages(&messages);
+ }
+ DVLOG(2) << "Deleted port " << port_name << "@" << name_;
+}
+
+int Node::SendUserMessageInternal(
+ const PortRef& port_ref, mozilla::UniquePtr<UserMessageEvent>* message) {
+ mozilla::UniquePtr<UserMessageEvent>& m = *message;
+
+ m->set_from_port(port_ref.name());
+
+ for (size_t i = 0; i < m->num_ports(); ++i) {
+ if (m->ports()[i] == port_ref.name()) {
+ return ERROR_PORT_CANNOT_SEND_SELF;
+ }
+ }
+
+ NodeName target_node;
+ int rv = PrepareToForwardUserMessage(port_ref, Port::kReceiving,
+ false /* ignore_closed_peer */, m.get(),
+ &target_node);
+ if (rv != OK) {
+ return rv;
+ }
+
+ // Beyond this point there's no sense in returning anything but OK. Even if
+ // message forwarding or acceptance fails, there's nothing the embedder can
+ // do to recover. Assume that failure beyond this point must be treated as a
+ // transport failure.
+
+ DCHECK_NE(kInvalidNodeName, target_node);
+ if (target_node != name_) {
+ delegate_->ForwardEvent(target_node, std::move(m));
+ return OK;
+ }
+
+ int accept_result = AcceptEvent(name_, std::move(m));
+ if (accept_result != OK) {
+ // See comment above for why we don't return an error in this case.
+ DVLOG(2) << "AcceptEvent failed: " << accept_result;
+ }
+
+ return OK;
+}
+
+int Node::MergePortsInternal(const PortRef& port0_ref, const PortRef& port1_ref,
+ bool allow_close_on_bad_state) {
+ const PortRef* port_refs[2] = {&port0_ref, &port1_ref};
+ PendingUpdatePreviousPeer pending_update_events[2];
+ uint64_t original_sequence_number[2];
+ {
+ // Needed to swap peer map entries below.
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::ReleasableMutexAutoLock ports_locker(ports_lock_);
+
+ mozilla::Maybe<PortLocker> locker(std::in_place, port_refs, size_t(2));
+ auto* port0 = locker->GetPort(port0_ref);
+ auto* port1 = locker->GetPort(port1_ref);
+
+ // There are several conditions which must be met before we'll consider
+ // merging two ports:
+ //
+ // - They must both be in the kReceiving state
+ // - They must not be each other's peer
+ // - They must have never sent a user message
+ //
+ // If any of these criteria are not met, we fail early.
+ if (port0->state != Port::kReceiving || port1->state != Port::kReceiving ||
+ (port0->peer_node_name == name_ &&
+ port0->peer_port_name == port1_ref.name()) ||
+ (port1->peer_node_name == name_ &&
+ port1->peer_port_name == port0_ref.name()) ||
+ port0->next_sequence_num_to_send != kInitialSequenceNum ||
+ port1->next_sequence_num_to_send != kInitialSequenceNum) {
+ // On failure, we only close a port if it was at least properly in the
+ // |kReceiving| state. This avoids getting the system in an inconsistent
+ // state by e.g. closing a proxy abruptly.
+ //
+ // Note that we must release the port locks before closing ports.
+ const bool close_port0 =
+ port0->state == Port::kReceiving || allow_close_on_bad_state;
+ const bool close_port1 =
+ port1->state == Port::kReceiving || allow_close_on_bad_state;
+ locker.reset();
+ ports_locker.Unlock();
+ if (close_port0) {
+ ClosePort(port0_ref);
+ }
+ if (close_port1) {
+ ClosePort(port1_ref);
+ }
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+
+ pending_update_events[0] = {
+ .receiver = port0->peer_node_name,
+ .port = port0->peer_port_name,
+ .from_port = port0_ref.name(),
+ .sequence_num = port0->next_control_sequence_num_to_send++,
+ .new_prev_node = name_,
+ .new_prev_port = port1_ref.name()};
+ pending_update_events[1] = {
+ .receiver = port1->peer_node_name,
+ .port = port1->peer_port_name,
+ .from_port = port1_ref.name(),
+ .sequence_num = port1->next_control_sequence_num_to_send++,
+ .new_prev_node = name_,
+ .new_prev_port = port0_ref.name()};
+
+ // Swap the ports' peer information and switch them both to proxying mode.
+ SwapPortPeers(port0_ref.name(), port0, port1_ref.name(), port1);
+ port0->state = Port::kProxying;
+ port1->state = Port::kProxying;
+ original_sequence_number[0] = port0->next_control_sequence_num_to_send;
+ original_sequence_number[1] = port1->next_control_sequence_num_to_send;
+ port0->next_control_sequence_num_to_send = kInitialSequenceNum;
+ port1->next_control_sequence_num_to_send = kInitialSequenceNum;
+ if (port0->peer_closed) {
+ port0->remove_proxy_on_last_message = true;
+ }
+ if (port1->peer_closed) {
+ port1->remove_proxy_on_last_message = true;
+ }
+ }
+
+ // Flush any queued messages from the new proxies and, if successful, complete
+ // the merge by initiating proxy removals.
+ if (ForwardUserMessagesFromProxy(port0_ref) == OK &&
+ ForwardUserMessagesFromProxy(port1_ref) == OK) {
+ // Send the prev peer updates out after the forwarding the user messages
+ // succeeded. Otherwise, we won't be able to restore the previous state
+ // below.
+ for (const auto& pending_update_event : pending_update_events) {
+ delegate_->ForwardEvent(
+ pending_update_event.receiver,
+ mozilla::MakeUnique<UpdatePreviousPeerEvent>(
+ pending_update_event.port, pending_update_event.from_port,
+ pending_update_event.sequence_num,
+ pending_update_event.new_prev_node,
+ pending_update_event.new_prev_port));
+ }
+
+ for (const auto* const port_ref : port_refs) {
+ bool try_remove_proxy_immediately = false;
+ ScopedEvent closure_event;
+ NodeName closure_event_target_node;
+ {
+ SinglePortLocker locker(port_ref);
+ auto* port = locker.port();
+ DCHECK_EQ(port->state, Port::kProxying);
+ try_remove_proxy_immediately = port->remove_proxy_on_last_message;
+ if (try_remove_proxy_immediately || port->peer_closed) {
+ // If either end of the port cycle is closed, we propagate an
+ // ObserveClosure event.
+ closure_event_target_node = port->peer_node_name;
+ closure_event = mozilla::MakeUnique<ObserveClosureEvent>(
+ port->peer_port_name, port_ref->name(),
+ port->next_control_sequence_num_to_send++,
+ port->last_sequence_num_to_receive);
+ }
+ }
+ if (try_remove_proxy_immediately) {
+ TryRemoveProxy(*port_ref);
+ } else {
+ InitiateProxyRemoval(*port_ref);
+ }
+
+ if (closure_event) {
+ delegate_->ForwardEvent(closure_event_target_node,
+ std::move(closure_event));
+ }
+ }
+
+ return OK;
+ }
+
+ // If we failed to forward proxied messages, we keep the system in a
+ // consistent state by undoing the peer swap and closing the ports.
+ {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_locker(ports_lock_);
+ PortLocker locker(port_refs, 2);
+ auto* port0 = locker.GetPort(port0_ref);
+ auto* port1 = locker.GetPort(port1_ref);
+ SwapPortPeers(port0_ref.name(), port0, port1_ref.name(), port1);
+ port0->remove_proxy_on_last_message = false;
+ port1->remove_proxy_on_last_message = false;
+ DCHECK_EQ(Port::kProxying, port0->state);
+ DCHECK_EQ(Port::kProxying, port1->state);
+ port0->state = Port::kReceiving;
+ port1->state = Port::kReceiving;
+ port0->next_control_sequence_num_to_send = original_sequence_number[0];
+ port1->next_control_sequence_num_to_send = original_sequence_number[1];
+ }
+
+ ClosePort(port0_ref);
+ ClosePort(port1_ref);
+ return ERROR_PORT_STATE_UNEXPECTED;
+}
+
+void Node::ConvertToProxy(Port* port, const NodeName& to_node_name,
+ PortName* port_name,
+ Event::PortDescriptor* port_descriptor,
+ PendingUpdatePreviousPeer* pending_update) {
+ port->AssertLockAcquired();
+ PortName local_port_name = *port_name;
+
+ PortName new_port_name;
+ GenerateRandomPortName(&new_port_name);
+
+ pending_update->receiver = port->peer_node_name;
+ pending_update->port = port->peer_port_name;
+ pending_update->sequence_num = port->next_control_sequence_num_to_send++;
+ pending_update->new_prev_node = to_node_name;
+ pending_update->new_prev_port = new_port_name;
+
+ // Make sure we don't send messages to the new peer until after we know it
+ // exists. In the meantime, just buffer messages locally.
+ DCHECK_EQ(port->state, Port::kReceiving);
+ port->state = Port::kBuffering;
+
+ // If we already know our peer is closed, we already know this proxy can
+ // be removed once it receives and forwards its last expected message.
+ if (port->peer_closed) {
+ port->remove_proxy_on_last_message = true;
+ }
+
+ *port_name = new_port_name;
+
+ port_descriptor->peer_node_name = port->peer_node_name;
+ port_descriptor->peer_port_name = port->peer_port_name;
+ port_descriptor->referring_node_name = name_;
+ port_descriptor->referring_port_name = local_port_name;
+ port_descriptor->next_sequence_num_to_send = port->next_sequence_num_to_send;
+ port_descriptor->next_sequence_num_to_receive =
+ port->message_queue.next_sequence_num();
+ port_descriptor->last_sequence_num_to_receive =
+ port->last_sequence_num_to_receive;
+ port_descriptor->peer_closed = port->peer_closed;
+ memset(port_descriptor->padding, 0, sizeof(port_descriptor->padding));
+
+ // Configure the local port to point to the new port.
+ UpdatePortPeerAddress(local_port_name, port, to_node_name, new_port_name);
+}
+
+int Node::AcceptPort(const PortName& port_name,
+ const Event::PortDescriptor& port_descriptor) {
+ RefPtr<Port> port =
+ mozilla::MakeRefPtr<Port>(port_descriptor.next_sequence_num_to_send,
+ port_descriptor.next_sequence_num_to_receive);
+ port->state = Port::kReceiving;
+ port->peer_node_name = port_descriptor.peer_node_name;
+ port->peer_port_name = port_descriptor.peer_port_name;
+ port->next_control_sequence_num_to_send = kInitialSequenceNum;
+ port->next_control_sequence_num_to_receive = kInitialSequenceNum;
+ port->prev_node_name = port_descriptor.referring_node_name;
+ port->prev_port_name = port_descriptor.referring_port_name;
+ port->last_sequence_num_to_receive =
+ port_descriptor.last_sequence_num_to_receive;
+ port->peer_closed = port_descriptor.peer_closed;
+
+ DVLOG(2) << "Accepting port " << port_name
+ << " [peer_closed=" << port->peer_closed
+ << "; last_sequence_num_to_receive="
+ << port->last_sequence_num_to_receive << "]";
+
+ // A newly accepted port is not signalable until the message referencing the
+ // new port finds its way to the consumer (see GetMessage).
+ port->message_queue.set_signalable(false);
+
+ int rv = AddPortWithName(port_name, std::move(port));
+ if (rv != OK) {
+ return rv;
+ }
+
+ // Allow referring port to forward messages.
+ delegate_->ForwardEvent(port_descriptor.referring_node_name,
+ mozilla::MakeUnique<PortAcceptedEvent>(
+ port_descriptor.referring_port_name,
+ kInvalidPortName, kInvalidSequenceNum));
+ return OK;
+}
+
+int Node::PrepareToForwardUserMessage(const PortRef& forwarding_port_ref,
+ Port::State expected_port_state,
+ bool ignore_closed_peer,
+ UserMessageEvent* message,
+ NodeName* forward_to_node) {
+ bool target_is_remote = false;
+ std::vector<PendingUpdatePreviousPeer> peer_update_events;
+
+ for (;;) {
+ NodeName target_node_name;
+ {
+ SinglePortLocker locker(&forwarding_port_ref);
+ target_node_name = locker.port()->peer_node_name;
+ }
+
+ // NOTE: This may call out to arbitrary user code, so it's important to call
+ // it only while no port locks are held on the calling thread.
+ if (target_node_name != name_) {
+ if (!message->NotifyWillBeRoutedExternally()) {
+ CHROMIUM_LOG(ERROR)
+ << "NotifyWillBeRoutedExternally failed unexpectedly.";
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+ }
+
+ // Must be held because ConvertToProxy needs to update |peer_port_maps_|.
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_locker(ports_lock_);
+
+ // Simultaneously lock the forwarding port as well as all attached ports.
+ AutoTArray<PortRef, 4> attached_port_refs;
+ AutoTArray<const PortRef*, 5> ports_to_lock;
+ attached_port_refs.SetCapacity(message->num_ports());
+ ports_to_lock.SetCapacity(message->num_ports() + 1);
+ ports_to_lock.AppendElement(&forwarding_port_ref);
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ const PortName& attached_port_name = message->ports()[i];
+ auto iter = ports_.find(attached_port_name);
+ DCHECK(iter != ports_.end());
+ attached_port_refs.AppendElement(
+ PortRef(attached_port_name, iter->second));
+ ports_to_lock.AppendElement(&attached_port_refs[i]);
+ }
+ PortLocker locker(ports_to_lock.Elements(), ports_to_lock.Length());
+ auto* forwarding_port = locker.GetPort(forwarding_port_ref);
+
+ if (forwarding_port->peer_node_name != target_node_name) {
+ // The target node has already changed since we last held the lock.
+ if (target_node_name == name_) {
+ // If the target node was previously this local node, we need to restart
+ // the loop, since that means we may now route the message externally.
+ continue;
+ }
+
+ target_node_name = forwarding_port->peer_node_name;
+ }
+ target_is_remote = target_node_name != name_;
+
+ if (forwarding_port->state != expected_port_state) {
+ return ERROR_PORT_STATE_UNEXPECTED;
+ }
+ if (forwarding_port->peer_closed && !ignore_closed_peer) {
+ return ERROR_PORT_PEER_CLOSED;
+ }
+
+ // Messages may already have a sequence number if they're being forwarded by
+ // a proxy. Otherwise, use the next outgoing sequence number.
+ if (message->sequence_num() == 0) {
+ message->set_sequence_num(forwarding_port->next_sequence_num_to_send++);
+ }
+#ifdef DEBUG
+ std::ostringstream ports_buf;
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ if (i > 0) {
+ ports_buf << ",";
+ }
+ ports_buf << message->ports()[i];
+ }
+#endif
+
+ if (message->num_ports() > 0) {
+ // Sanity check to make sure we can actually send all the attached ports.
+ // They must all be in the |kReceiving| state and must not be the sender's
+ // own peer.
+ DCHECK_EQ(message->num_ports(), attached_port_refs.Length());
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ auto* attached_port = locker.GetPort(attached_port_refs[i]);
+ int error = OK;
+ if (attached_port->state != Port::kReceiving) {
+ error = ERROR_PORT_STATE_UNEXPECTED;
+ } else if (attached_port_refs[i].name() ==
+ forwarding_port->peer_port_name) {
+ error = ERROR_PORT_CANNOT_SEND_PEER;
+ }
+
+ if (error != OK) {
+ // Not going to send. Backpedal on the sequence number.
+ forwarding_port->next_sequence_num_to_send--;
+ return error;
+ }
+ }
+
+ if (target_is_remote) {
+ // We only bother to proxy and rewrite ports in the event if it's
+ // going to be routed to an external node. This substantially reduces
+ // the amount of port churn in the system, as many port-carrying
+ // events are routed at least 1 or 2 intra-node hops before (if ever)
+ // being routed externally.
+ Event::PortDescriptor* port_descriptors = message->port_descriptors();
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ auto* port = locker.GetPort(attached_port_refs[i]);
+ PendingUpdatePreviousPeer update_event = {
+ .from_port = attached_port_refs[i].name()};
+ ConvertToProxy(port, target_node_name, message->ports() + i,
+ port_descriptors + i, &update_event);
+ peer_update_events.push_back(update_event);
+ }
+ }
+ }
+
+#ifdef DEBUG
+ DVLOG(4) << "Sending message " << message->sequence_num()
+ << " [ports=" << ports_buf.str() << "]"
+ << " from " << forwarding_port_ref.name() << "@" << name_ << " to "
+ << forwarding_port->peer_port_name << "@" << target_node_name;
+#endif
+
+ *forward_to_node = target_node_name;
+ message->set_port_name(forwarding_port->peer_port_name);
+ message->set_from_port(forwarding_port_ref.name());
+ message->set_control_sequence_num(
+ forwarding_port->next_control_sequence_num_to_send++);
+ break;
+ }
+
+ for (auto& pending_update_event : peer_update_events) {
+ delegate_->ForwardEvent(
+ pending_update_event.receiver,
+ mozilla::MakeUnique<UpdatePreviousPeerEvent>(
+ pending_update_event.port, pending_update_event.from_port,
+ pending_update_event.sequence_num,
+ pending_update_event.new_prev_node,
+ pending_update_event.new_prev_port));
+ }
+
+ if (target_is_remote) {
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ // For any ports that were converted to proxies above, make sure their
+ // prior local peer (if applicable) receives a status update so it can be
+ // made aware of its peer's location.
+ const Event::PortDescriptor& descriptor = message->port_descriptors()[i];
+ if (descriptor.peer_node_name == name_) {
+ PortRef local_peer;
+ if (GetPort(descriptor.peer_port_name, &local_peer) == OK) {
+ delegate_->PortStatusChanged(local_peer);
+ }
+ }
+ }
+ }
+
+ return OK;
+}
+
+int Node::BeginProxying(const PortRef& port_ref) {
+ std::vector<std::pair<NodeName, ScopedEvent>> control_message_queue;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kBuffering) {
+ return OOPS(ERROR_PORT_STATE_UNEXPECTED);
+ }
+ port->state = Port::kProxying;
+ std::swap(port->control_message_queue, control_message_queue);
+ }
+
+ for (auto& [control_message_node_name, control_message_event] :
+ control_message_queue) {
+ delegate_->ForwardEvent(control_message_node_name,
+ std::move(control_message_event));
+ }
+ control_message_queue.clear();
+
+ int rv = ForwardUserMessagesFromProxy(port_ref);
+ if (rv != OK) {
+ return rv;
+ }
+
+ // Forward any pending acknowledge request.
+ MaybeForwardAckRequest(port_ref);
+
+ bool try_remove_proxy_immediately;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kProxying) {
+ return OOPS(ERROR_PORT_STATE_UNEXPECTED);
+ }
+
+ try_remove_proxy_immediately = port->remove_proxy_on_last_message;
+ }
+
+ if (try_remove_proxy_immediately) {
+ TryRemoveProxy(port_ref);
+ } else {
+ InitiateProxyRemoval(port_ref);
+ }
+
+ return OK;
+}
+
+int Node::ForwardUserMessagesFromProxy(const PortRef& port_ref) {
+ for (;;) {
+ // NOTE: We forward messages in sequential order here so that we maintain
+ // the message queue's notion of next sequence number. That's useful for the
+ // proxy removal process as we can tell when this port has seen all of the
+ // messages it is expected to see.
+ mozilla::UniquePtr<UserMessageEvent> message;
+ {
+ SinglePortLocker locker(&port_ref);
+ locker.port()->message_queue.GetNextMessage(&message, nullptr);
+ if (!message) {
+ break;
+ }
+ }
+
+ NodeName target_node;
+ int rv = PrepareToForwardUserMessage(port_ref, Port::kProxying,
+ true /* ignore_closed_peer */,
+ message.get(), &target_node);
+ {
+ // Mark the message as processed after we ran PrepareToForwardUserMessage.
+ // This is important to prevent another thread from deleting the port
+ // before we grabbed a sequence number for the message.
+ SinglePortLocker locker(&port_ref);
+ locker.port()->message_queue.MessageProcessed();
+ }
+ if (rv != OK) {
+ return rv;
+ }
+
+ delegate_->ForwardEvent(target_node, std::move(message));
+ }
+ return OK;
+}
+
+void Node::InitiateProxyRemoval(const PortRef& port_ref) {
+ NodeName peer_node_name;
+ PortName peer_port_name;
+ uint64_t sequence_num;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state == Port::kClosed) {
+ return;
+ }
+ peer_node_name = port->peer_node_name;
+ peer_port_name = port->peer_port_name;
+ sequence_num = port->next_control_sequence_num_to_send++;
+ DCHECK_EQ(port->state, Port::kProxying);
+ }
+
+ // To remove this node, we start by notifying the connected graph that we are
+ // a proxy. This allows whatever port is referencing this node to skip it.
+ // Eventually, this node will receive ObserveProxyAck (or ObserveClosure if
+ // the peer was closed in the meantime).
+ delegate_->ForwardEvent(
+ peer_node_name, mozilla::MakeUnique<ObserveProxyEvent>(
+ peer_port_name, port_ref.name(), sequence_num, name_,
+ port_ref.name(), peer_node_name, peer_port_name));
+}
+
+void Node::TryRemoveProxy(const PortRef& port_ref) {
+ bool should_erase = false;
+ NodeName removal_target_node;
+ ScopedEvent removal_event;
+ PendingUpdatePreviousPeer pending_update_event;
+
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state == Port::kClosed) {
+ return;
+ }
+ DCHECK_EQ(port->state, Port::kProxying);
+
+ // Make sure we have seen ObserveProxyAck before removing the port.
+ if (!port->remove_proxy_on_last_message) {
+ return;
+ }
+
+ if (!CanAcceptMoreMessages(port)) {
+ DCHECK_EQ(port->message_queue.queued_message_count(), 0lu);
+ should_erase = true;
+ if (port->send_on_proxy_removal) {
+ removal_target_node = port->send_on_proxy_removal->first;
+ removal_event = std::move(port->send_on_proxy_removal->second);
+ if (removal_event) {
+ removal_event->set_control_sequence_num(
+ port->next_control_sequence_num_to_send++);
+ DCHECK_EQ(removal_target_node, port->peer_node_name);
+ DCHECK_EQ(removal_event->port_name(), port->peer_port_name);
+ }
+ }
+ // Tell the peer_node to accept messages from prev_node from now.
+ pending_update_event = {
+ .receiver = port->peer_node_name,
+ .port = port->peer_port_name,
+ .from_port = port_ref.name(),
+ .sequence_num = port->next_control_sequence_num_to_send++,
+ .new_prev_node = port->prev_node_name,
+ .new_prev_port = port->prev_port_name};
+ } else {
+ DVLOG(2) << "Cannot remove port " << port_ref.name() << "@" << name_
+ << " now; waiting for more messages";
+ }
+ }
+
+ if (should_erase) {
+ delegate_->ForwardEvent(
+ pending_update_event.receiver,
+ mozilla::MakeUnique<UpdatePreviousPeerEvent>(
+ pending_update_event.port, pending_update_event.from_port,
+ pending_update_event.sequence_num,
+ pending_update_event.new_prev_node,
+ pending_update_event.new_prev_port));
+ ErasePort(port_ref.name());
+ }
+
+ if (removal_event) {
+ delegate_->ForwardEvent(removal_target_node, std::move(removal_event));
+ }
+}
+
+void Node::DestroyAllPortsWithPeer(const NodeName& node_name,
+ const PortName& port_name) {
+ // Wipes out all ports whose peer node matches |node_name| and whose peer port
+ // matches |port_name|. If |port_name| is |kInvalidPortName|, only the peer
+ // node is matched.
+
+ std::vector<PortRef> ports_to_notify;
+ std::vector<PortName> dead_proxies_to_broadcast;
+ std::vector<mozilla::UniquePtr<UserMessageEvent>> undelivered_messages;
+ std::vector<std::pair<NodeName, ScopedEvent>> closure_events;
+
+ {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock ports_lock(ports_lock_);
+
+ auto node_peer_port_map_iter = peer_port_maps_.find(node_name);
+ if (node_peer_port_map_iter == peer_port_maps_.end()) {
+ return;
+ }
+
+ auto& node_peer_port_map = node_peer_port_map_iter->second;
+ auto peer_ports_begin = node_peer_port_map.begin();
+ auto peer_ports_end = node_peer_port_map.end();
+ if (port_name != kInvalidPortName) {
+ // If |port_name| is given, we limit the set of local ports to the ones
+ // with that specific port as their peer.
+ peer_ports_begin = node_peer_port_map.find(port_name);
+ if (peer_ports_begin == node_peer_port_map.end()) {
+ return;
+ }
+
+ peer_ports_end = peer_ports_begin;
+ ++peer_ports_end;
+ }
+
+ for (auto peer_port_iter = peer_ports_begin;
+ peer_port_iter != peer_ports_end; ++peer_port_iter) {
+ auto& local_ports = peer_port_iter->second;
+ // NOTE: This inner loop almost always has only one element. There are
+ // relatively short-lived cases where more than one local port points to
+ // the same peer, and this only happens when extra ports are bypassed
+ // proxies waiting to be torn down.
+ for (auto& local_port : local_ports) {
+ auto& local_port_ref = local_port.second;
+
+ SinglePortLocker locker(&local_port_ref);
+ auto* port = locker.port();
+
+ if (port_name != kInvalidPortName) {
+ // If this is a targeted observe dead proxy event, send out an
+ // ObserveClosure to acknowledge it.
+ closure_events.push_back(
+ std::pair{port->peer_node_name,
+ mozilla::MakeUnique<ObserveClosureEvent>(
+ port->peer_port_name, local_port_ref.name(),
+ port->next_control_sequence_num_to_send++,
+ port->last_sequence_num_to_receive)});
+ }
+
+ if (!port->peer_closed) {
+ // Treat this as immediate peer closure. It's an exceptional
+ // condition akin to a broken pipe, so we don't care about losing
+ // messages.
+
+ port->peer_closed = true;
+ port->peer_lost_unexpectedly = true;
+ if (port->state == Port::kReceiving) {
+ ports_to_notify.push_back(local_port_ref);
+ }
+ }
+
+ // We don't expect to forward any further messages, and we don't
+ // expect to receive a Port{Accepted,Rejected} event. Because we're
+ // a proxy with no active peer, we cannot use the normal proxy removal
+ // procedure of forward-propagating an ObserveProxy. Instead we
+ // broadcast our own death so it can be back-propagated. This is
+ // inefficient but rare.
+ if (port->state == Port::kBuffering || port->state == Port::kProxying) {
+ port->state = Port::kClosed;
+ dead_proxies_to_broadcast.push_back(local_port_ref.name());
+ std::vector<mozilla::UniquePtr<UserMessageEvent>> messages;
+ port->message_queue.TakeAllMessages(&messages);
+ port->TakePendingMessages(messages);
+ for (auto& message : messages) {
+ undelivered_messages.emplace_back(std::move(message));
+ }
+ }
+ }
+ }
+ }
+
+ for (auto& [closure_event_target_node, closure_event] : closure_events) {
+ delegate_->ForwardEvent(closure_event_target_node,
+ std::move(closure_event));
+ }
+
+ // Wake up any receiving ports who have just observed simulated peer closure.
+ for (const auto& port : ports_to_notify) {
+ delegate_->PortStatusChanged(port);
+ }
+
+ for (const auto& proxy_name : dead_proxies_to_broadcast) {
+ // Broadcast an event signifying that this proxy is no longer functioning.
+ delegate_->BroadcastEvent(mozilla::MakeUnique<ObserveProxyEvent>(
+ kInvalidPortName, kInvalidPortName, kInvalidSequenceNum, name_,
+ proxy_name, kInvalidNodeName, kInvalidPortName));
+
+ // Also process death locally since the port that points this closed one
+ // could be on the current node.
+ // Note: Although this is recursive, only a single port is involved which
+ // limits the expected branching to 1.
+ DestroyAllPortsWithPeer(name_, proxy_name);
+ }
+
+ // Close any ports referenced by undelivered messages.
+ for (const auto& message : undelivered_messages) {
+ for (size_t i = 0; i < message->num_ports(); ++i) {
+ PortRef ref;
+ if (GetPort(message->ports()[i], &ref) == OK) {
+ ClosePort(ref);
+ }
+ }
+ }
+}
+
+void Node::UpdatePortPeerAddress(const PortName& local_port_name,
+ Port* local_port,
+ const NodeName& new_peer_node,
+ const PortName& new_peer_port) {
+ ports_lock_.AssertCurrentThreadOwns();
+ local_port->AssertLockAcquired();
+
+ RemoveFromPeerPortMap(local_port_name, local_port);
+ local_port->peer_node_name = new_peer_node;
+ local_port->peer_port_name = new_peer_port;
+ local_port->next_control_sequence_num_to_send = kInitialSequenceNum;
+ if (new_peer_port != kInvalidPortName) {
+ peer_port_maps_[new_peer_node][new_peer_port].emplace(
+ local_port_name, PortRef(local_port_name, RefPtr<Port>{local_port}));
+ }
+}
+
+void Node::RemoveFromPeerPortMap(const PortName& local_port_name,
+ Port* local_port) {
+ if (local_port->peer_port_name == kInvalidPortName) {
+ return;
+ }
+
+ auto node_iter = peer_port_maps_.find(local_port->peer_node_name);
+ if (node_iter == peer_port_maps_.end()) {
+ return;
+ }
+
+ auto& node_peer_port_map = node_iter->second;
+ auto ports_iter = node_peer_port_map.find(local_port->peer_port_name);
+ if (ports_iter == node_peer_port_map.end()) {
+ return;
+ }
+
+ auto& local_ports_with_this_peer = ports_iter->second;
+ local_ports_with_this_peer.erase(local_port_name);
+ if (local_ports_with_this_peer.empty()) {
+ node_peer_port_map.erase(ports_iter);
+ }
+ if (node_peer_port_map.empty()) {
+ peer_port_maps_.erase(node_iter);
+ }
+}
+
+void Node::SwapPortPeers(const PortName& port0_name, Port* port0,
+ const PortName& port1_name, Port* port1) {
+ ports_lock_.AssertCurrentThreadOwns();
+ port0->AssertLockAcquired();
+ port1->AssertLockAcquired();
+
+ auto& peer0_ports =
+ peer_port_maps_[port0->peer_node_name][port0->peer_port_name];
+ auto& peer1_ports =
+ peer_port_maps_[port1->peer_node_name][port1->peer_port_name];
+ peer0_ports.erase(port0_name);
+ peer1_ports.erase(port1_name);
+ peer0_ports.emplace(port1_name, PortRef(port1_name, RefPtr<Port>{port1}));
+ peer1_ports.emplace(port0_name, PortRef(port0_name, RefPtr<Port>{port0}));
+
+ std::swap(port0->peer_node_name, port1->peer_node_name);
+ std::swap(port0->peer_port_name, port1->peer_port_name);
+}
+
+void Node::MaybeResendAckRequest(const PortRef& port_ref) {
+ NodeName peer_node_name;
+ ScopedEvent ack_request_event;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kReceiving) {
+ return;
+ }
+
+ if (!port->sequence_num_acknowledge_interval) {
+ return;
+ }
+
+ peer_node_name = port->peer_node_name;
+ ack_request_event = mozilla::MakeUnique<UserMessageReadAckRequestEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++,
+ port->last_sequence_num_acknowledged +
+ port->sequence_num_acknowledge_interval);
+ }
+
+ delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event));
+}
+
+void Node::MaybeForwardAckRequest(const PortRef& port_ref) {
+ NodeName peer_node_name;
+ ScopedEvent ack_request_event;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kProxying) {
+ return;
+ }
+
+ if (!port->sequence_num_to_acknowledge) {
+ return;
+ }
+
+ peer_node_name = port->peer_node_name;
+ ack_request_event = mozilla::MakeUnique<UserMessageReadAckRequestEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++,
+ port->sequence_num_to_acknowledge);
+
+ port->sequence_num_to_acknowledge = 0;
+ }
+
+ delegate_->ForwardEvent(peer_node_name, std::move(ack_request_event));
+}
+
+void Node::MaybeResendAck(const PortRef& port_ref) {
+ NodeName peer_node_name;
+ ScopedEvent ack_event;
+ {
+ SinglePortLocker locker(&port_ref);
+ auto* port = locker.port();
+ if (port->state != Port::kReceiving) {
+ return;
+ }
+
+ uint64_t last_sequence_num_read =
+ port->message_queue.next_sequence_num() - 1;
+ if (!port->sequence_num_to_acknowledge || !last_sequence_num_read) {
+ return;
+ }
+
+ peer_node_name = port->peer_node_name;
+ ack_event = mozilla::MakeUnique<UserMessageReadAckEvent>(
+ port->peer_port_name, port_ref.name(),
+ port->next_control_sequence_num_to_send++, last_sequence_num_read);
+ }
+
+ delegate_->ForwardEvent(peer_node_name, std::move(ack_event));
+}
+
+Node::DelegateHolder::DelegateHolder(Node* node, NodeDelegate* delegate)
+ : node_(node), delegate_(delegate) {
+ DCHECK(node_);
+}
+
+Node::DelegateHolder::~DelegateHolder() = default;
+
+#ifdef DEBUG
+void Node::DelegateHolder::EnsureSafeDelegateAccess() const {
+ PortLocker::AssertNoPortsLockedOnCurrentThread();
+ mozilla::MutexAutoLock lock(node_->ports_lock_);
+}
+#endif
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/node.h b/ipc/chromium/src/mojo/core/ports/node.h
new file mode 100644
index 0000000000..9dbbd2a337
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/node.h
@@ -0,0 +1,355 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_NODE_H_
+#define MOJO_CORE_PORTS_NODE_H_
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include <unordered_map>
+
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/port.h"
+#include "mojo/core/ports/port_ref.h"
+#include "mojo/core/ports/user_data.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/RefPtr.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+enum : int {
+ OK = 0,
+ ERROR_PORT_UNKNOWN = -10,
+ ERROR_PORT_EXISTS = -11,
+ ERROR_PORT_STATE_UNEXPECTED = -12,
+ ERROR_PORT_CANNOT_SEND_SELF = -13,
+ ERROR_PORT_PEER_CLOSED = -14,
+ ERROR_PORT_CANNOT_SEND_PEER = -15,
+ ERROR_NOT_IMPLEMENTED = -100,
+};
+
+struct PortStatus {
+ bool has_messages;
+ bool receiving_messages;
+ bool peer_closed;
+ bool peer_remote;
+ size_t queued_message_count;
+ size_t queued_num_bytes;
+ size_t unacknowledged_message_count;
+#ifdef FUZZING_SNAPSHOT
+ NodeName peer_node_name;
+#endif
+};
+
+struct PendingUpdatePreviousPeer {
+ NodeName receiver;
+ PortName port;
+ PortName from_port;
+ uint64_t sequence_num;
+ NodeName new_prev_node;
+ PortName new_prev_port;
+};
+
+class MessageFilter;
+class NodeDelegate;
+
+// A Node maintains a collection of Ports (see port.h) indexed by unique 128-bit
+// addresses (names), performing routing and processing of events among the
+// Ports within the Node and to or from other Nodes in the system. Typically
+// (and practically, in all uses today) there is a single Node per system
+// process. Thus a Node boundary effectively models a process boundary.
+//
+// New Ports can be created uninitialized using CreateUninitializedPort (and
+// later initialized using InitializePort), or created in a fully initialized
+// state using CreatePortPair(). Initialized ports have exactly one conjugate
+// port which is the ultimate receiver of any user messages sent by that port.
+// See SendUserMessage().
+//
+// In addition to routing user message events, various control events are used
+// by Nodes to coordinate Port behavior and lifetime within and across Nodes.
+// See Event documentation for description of different types of events used by
+// a Node to coordinate behavior.
+class Node {
+ public:
+ enum class ShutdownPolicy {
+ DONT_ALLOW_LOCAL_PORTS,
+ ALLOW_LOCAL_PORTS,
+ };
+
+ // Does not take ownership of the delegate.
+ Node(const NodeName& name, NodeDelegate* delegate);
+ ~Node();
+
+ Node(const Node&) = delete;
+ void operator=(const Node&) = delete;
+
+ // Returns true iff there are no open ports referring to another node or ports
+ // in the process of being transferred from this node to another. If this
+ // returns false, then to ensure clean shutdown, it is necessary to keep the
+ // node alive and continue routing messages to it via AcceptMessage. This
+ // method may be called again after AcceptMessage to check if the Node is now
+ // ready to be destroyed.
+ //
+ // If |policy| is set to |ShutdownPolicy::ALLOW_LOCAL_PORTS|, this will return
+ // |true| even if some ports remain alive, as long as none of them are proxies
+ // to another node.
+ bool CanShutdownCleanly(
+ ShutdownPolicy policy = ShutdownPolicy::DONT_ALLOW_LOCAL_PORTS);
+
+ // Lookup the named port.
+ int GetPort(const PortName& port_name, PortRef* port_ref);
+
+ // Creates a port on this node. Before the port can be used, it must be
+ // initialized using InitializePort. This method is useful for bootstrapping
+ // a connection between two nodes. Generally, ports are created using
+ // CreatePortPair instead.
+ int CreateUninitializedPort(PortRef* port_ref);
+
+ // Initializes a newly created port.
+ int InitializePort(const PortRef& port_ref, const NodeName& peer_node_name,
+ const PortName& peer_port_name,
+ const NodeName& prev_node_name,
+ const PortName& prev_port_name);
+
+ // Generates a new connected pair of ports bound to this node. These ports
+ // are initialized and ready to go.
+ int CreatePortPair(PortRef* port0_ref, PortRef* port1_ref);
+
+ // User data associated with the port.
+ int SetUserData(const PortRef& port_ref, RefPtr<UserData> user_data);
+ int GetUserData(const PortRef& port_ref, RefPtr<UserData>* user_data);
+
+ // Prevents further messages from being sent from this port or delivered to
+ // this port. The port is removed, and the port's peer is notified of the
+ // closure after it has consumed all pending messages.
+ int ClosePort(const PortRef& port_ref);
+
+ // Returns the current status of the port.
+ int GetStatus(const PortRef& port_ref, PortStatus* port_status);
+
+ // Returns the next available message on the specified port or returns a null
+ // message if there are none available. Returns ERROR_PORT_PEER_CLOSED to
+ // indicate that this port's peer has closed. In such cases GetMessage may
+ // be called until it yields a null message, indicating that no more messages
+ // may be read from the port.
+ //
+ // If |filter| is non-null, the next available message is returned only if it
+ // is matched by the filter. If the provided filter does not match the next
+ // available message, GetMessage() behaves as if there is no message
+ // available. Ownership of |filter| is not taken, and it must outlive the
+ // extent of this call.
+ int GetMessage(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageEvent>* message,
+ MessageFilter* filter);
+
+ // Sends a message from the specified port to its peer. Note that the message
+ // notification may arrive synchronously (via PortStatusChanged() on the
+ // delegate) if the peer is local to this Node.
+ int SendUserMessage(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageEvent> message);
+
+ // Makes the port send acknowledge requests to its conjugate to acknowledge
+ // at least every |sequence_number_acknowledge_interval| messages as they're
+ // read from the conjugate. The number of unacknowledged messages is exposed
+ // in the |unacknowledged_message_count| field of PortStatus. This allows
+ // bounding the number of unread and/or in-transit messages from this port
+ // to its conjugate between zero and |unacknowledged_message_count|.
+ int SetAcknowledgeRequestInterval(const PortRef& port_ref,
+ uint64_t sequence_num_acknowledge_interval);
+
+ // Corresponding to NodeDelegate::ForwardEvent.
+ int AcceptEvent(const NodeName& from_node, ScopedEvent event);
+
+ // Called to merge two ports with each other. If you have two independent
+ // port pairs A <=> B and C <=> D, the net result of merging B and C is a
+ // single connected port pair A <=> D.
+ //
+ // Note that the behavior of this operation is undefined if either port to be
+ // merged (B or C above) has ever been read from or written to directly, and
+ // this must ONLY be called on one side of the merge, though it doesn't matter
+ // which side.
+ //
+ // It is safe for the non-merged peers (A and D above) to be transferred,
+ // closed, and/or written to before, during, or after the merge.
+ int MergePorts(const PortRef& port_ref, const NodeName& destination_node_name,
+ const PortName& destination_port_name);
+
+ // Like above but merges two ports local to this node. Because both ports are
+ // local this can also verify that neither port has been written to before the
+ // merge. If this fails for any reason, both ports are closed. Otherwise OK
+ // is returned and the ports' receiving peers are connected to each other.
+ int MergeLocalPorts(const PortRef& port0_ref, const PortRef& port1_ref);
+
+ // Called to inform this node that communication with another node is lost
+ // indefinitely. This triggers cleanup of ports bound to this node.
+ int LostConnectionToNode(const NodeName& node_name);
+
+ private:
+ // Helper to ensure that a Node always calls into its delegate safely, i.e.
+ // without holding any internal locks.
+ class DelegateHolder {
+ public:
+ DelegateHolder(Node* node, NodeDelegate* delegate);
+ ~DelegateHolder();
+
+ DelegateHolder(const DelegateHolder&) = delete;
+ void operator=(const DelegateHolder&) = delete;
+
+ NodeDelegate* operator->() const {
+ EnsureSafeDelegateAccess();
+ return delegate_;
+ }
+
+ private:
+#ifdef DEBUG
+ void EnsureSafeDelegateAccess() const;
+#else
+ void EnsureSafeDelegateAccess() const {}
+#endif
+
+ Node* const node_;
+ NodeDelegate* const delegate_;
+ };
+
+ int OnUserMessage(const PortRef& port_ref, const NodeName& from_node,
+ mozilla::UniquePtr<UserMessageEvent> message);
+ int OnPortAccepted(const PortRef& port_ref,
+ mozilla::UniquePtr<PortAcceptedEvent> event);
+ int OnObserveProxy(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveProxyEvent> event);
+ int OnObserveProxyAck(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveProxyAckEvent> event);
+ int OnObserveClosure(const PortRef& port_ref,
+ mozilla::UniquePtr<ObserveClosureEvent> event);
+ int OnMergePort(const PortRef& port_ref,
+ mozilla::UniquePtr<MergePortEvent> event);
+ int OnUserMessageReadAckRequest(
+ const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageReadAckRequestEvent> event);
+ int OnUserMessageReadAck(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageReadAckEvent> event);
+ int OnUpdatePreviousPeer(const PortRef& port_ref,
+ mozilla::UniquePtr<UpdatePreviousPeerEvent> event);
+
+ int AddPortWithName(const PortName& port_name, RefPtr<Port> port);
+ void ErasePort(const PortName& port_name);
+
+ // Check if the event is sent by the previous peer of the port to decide if
+ // we can check the sequence number.
+ // This is not the case for example for PortAccepted or broadcasted events.
+ bool IsEventFromPreviousPeer(const Event& event);
+
+ int AcceptEventInternal(const PortRef& port_ref, const NodeName& from_node,
+ ScopedEvent event);
+
+ int SendUserMessageInternal(const PortRef& port_ref,
+ mozilla::UniquePtr<UserMessageEvent>* message);
+ int MergePortsInternal(const PortRef& port0_ref, const PortRef& port1_ref,
+ bool allow_close_on_bad_state);
+ void ConvertToProxy(Port* port, const NodeName& to_node_name,
+ PortName* port_name,
+ Event::PortDescriptor* port_descriptor,
+ PendingUpdatePreviousPeer* pending_update)
+ MOZ_REQUIRES(ports_lock_);
+ int AcceptPort(const PortName& port_name,
+ const Event::PortDescriptor& port_descriptor);
+
+ int PrepareToForwardUserMessage(const PortRef& forwarding_port_ref,
+ Port::State expected_port_state,
+ bool ignore_closed_peer,
+ UserMessageEvent* message,
+ NodeName* forward_to_node);
+ int BeginProxying(const PortRef& port_ref);
+ int ForwardUserMessagesFromProxy(const PortRef& port_ref);
+ void InitiateProxyRemoval(const PortRef& port_ref);
+ void TryRemoveProxy(const PortRef& port_ref);
+ void DestroyAllPortsWithPeer(const NodeName& node_name,
+ const PortName& port_name);
+
+ // Changes the peer node and port name referenced by |port|. Note that both
+ // |ports_lock_| MUST be held through the extent of this method.
+ // |local_port|'s lock must be held if and only if a reference to |local_port|
+ // exist in |ports_|.
+ void UpdatePortPeerAddress(const PortName& local_port_name, Port* local_port,
+ const NodeName& new_peer_node,
+ const PortName& new_peer_port)
+ MOZ_REQUIRES(ports_lock_);
+
+ // Removes an entry from |peer_port_map_| corresponding to |local_port|'s peer
+ // address, if valid.
+ void RemoveFromPeerPortMap(const PortName& local_port_name, Port* local_port)
+ MOZ_REQUIRES(ports_lock_);
+
+ // Swaps the peer information for two local ports. Used during port merges.
+ // Note that |ports_lock_| must be held along with each of the two port's own
+ // locks, through the extent of this method.
+ void SwapPortPeers(const PortName& port0_name, Port* port0,
+ const PortName& port1_name, Port* port1)
+ MOZ_REQUIRES(ports_lock_);
+
+ // Sends an acknowledge request to the peer if the port has a non-zero
+ // |sequence_num_acknowledge_interval|. This needs to be done when the port's
+ // peer changes, as the previous peer proxy may not have forwarded any prior
+ // acknowledge request before deleting itself.
+ void MaybeResendAckRequest(const PortRef& port_ref);
+
+ // Forwards a stored acknowledge request to the peer if the proxy has a
+ // non-zero |sequence_num_acknowledge_interval|.
+ void MaybeForwardAckRequest(const PortRef& port_ref);
+
+ // Sends an acknowledge of the most recently read sequence number to the peer
+ // if any messages have been read, and the port has a non-zero
+ // |sequence_num_to_acknowledge|.
+ void MaybeResendAck(const PortRef& port_ref);
+
+ const NodeName name_;
+ const DelegateHolder delegate_;
+
+ // Just to clarify readability of the types below.
+ using LocalPortName = PortName;
+ using PeerPortName = PortName;
+
+ // Guards access to |ports_| and |peer_port_maps_| below.
+ //
+ // This must never be acquired while an individual port's lock is held on the
+ // same thread. Conversely, individual port locks may be acquired while this
+ // one is held.
+ //
+ // Because UserMessage events may execute arbitrary user code during
+ // destruction, it is also important to ensure that such events are never
+ // destroyed while this (or any individual Port) lock is held.
+ mozilla::Mutex ports_lock_{"Ports Lock"};
+ std::unordered_map<LocalPortName, RefPtr<Port>> ports_
+ MOZ_GUARDED_BY(ports_lock_);
+
+ // Maps a peer port name to a list of PortRefs for all local ports which have
+ // the port name key designated as their peer port. The set of local ports
+ // which have the same peer port is expected to always be relatively small and
+ // usually 1. Hence we just use a flat_map of local PortRefs keyed on each
+ // local port's name.
+ //
+ // FIXME(nika): We don't have `base::flat_map` or a super equivalent type with
+ // the same API, so just use a nested `std::unordered_map` for now. We should
+ // probably change all of this to instead use our types eventually.
+ using PeerPortMap =
+ std::unordered_map<PeerPortName,
+ std::unordered_map<LocalPortName, PortRef>>;
+
+ // A reverse mapping which can be used to find all local ports that reference
+ // a given peer node or a local port that references a specific given peer
+ // port on a peer node. The key to this map is the corresponding peer node
+ // name.
+ std::unordered_map<NodeName, PeerPortMap> peer_port_maps_
+ MOZ_GUARDED_BY(ports_lock_);
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_NODE_H_
diff --git a/ipc/chromium/src/mojo/core/ports/node_delegate.h b/ipc/chromium/src/mojo/core/ports/node_delegate.h
new file mode 100644
index 0000000000..3172779c06
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/node_delegate.h
@@ -0,0 +1,38 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_NODE_DELEGATE_H_
+#define MOJO_CORE_PORTS_NODE_DELEGATE_H_
+
+#include <stddef.h>
+
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/port_ref.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class NodeDelegate {
+ public:
+ virtual ~NodeDelegate() = default;
+
+ // Forward an event (possibly asynchronously) to the specified node.
+ virtual void ForwardEvent(const NodeName& node, ScopedEvent event) = 0;
+
+ // Broadcast an event to all nodes.
+ virtual void BroadcastEvent(ScopedEvent event) = 0;
+
+ // Indicates that the port's status has changed recently. Use Node::GetStatus
+ // to query the latest status of the port. Note, this event could be spurious
+ // if another thread is simultaneously modifying the status of the port.
+ virtual void PortStatusChanged(const PortRef& port_ref) = 0;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_NODE_DELEGATE_H_
diff --git a/ipc/chromium/src/mojo/core/ports/port.cc b/ipc/chromium/src/mojo/core/ports/port.cc
new file mode 100644
index 0000000000..871ec8fca6
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port.cc
@@ -0,0 +1,95 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/port.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+// Used by std::{push,pop}_heap functions
+inline bool operator<(const mozilla::UniquePtr<Event>& a,
+ const mozilla::UniquePtr<Event>& b) {
+ return a->control_sequence_num() > b->control_sequence_num();
+}
+
+Port::Port(uint64_t next_sequence_num_to_send,
+ uint64_t next_sequence_num_to_receive)
+ : state(kUninitialized),
+ pending_merge_peer(false),
+ next_control_sequence_num_to_send(kInitialSequenceNum),
+ next_control_sequence_num_to_receive(kInitialSequenceNum),
+ next_sequence_num_to_send(next_sequence_num_to_send),
+ last_sequence_num_acknowledged(next_sequence_num_to_send - 1),
+ sequence_num_acknowledge_interval(0),
+ last_sequence_num_to_receive(0),
+ sequence_num_to_acknowledge(0),
+ message_queue(next_sequence_num_to_receive),
+ remove_proxy_on_last_message(false),
+ peer_closed(false),
+ peer_lost_unexpectedly(false) {}
+
+Port::~Port() = default;
+
+bool Port::IsNextEvent(const NodeName& from_node, const Event& event) {
+ if (from_node != prev_node_name) {
+ return false;
+ }
+
+ if (event.from_port() != prev_port_name) {
+ return false;
+ }
+
+ DCHECK_GE(event.control_sequence_num(), next_control_sequence_num_to_receive);
+ return event.control_sequence_num() == next_control_sequence_num_to_receive;
+}
+
+void Port::NextEvent(NodeName* from_node, ScopedEvent* event) {
+ auto it = control_event_queues_.find({prev_node_name, prev_port_name});
+ if (it == control_event_queues_.end()) {
+ return;
+ }
+
+ auto& msg_queue = it->second;
+ // There must always be one entry since we delete the queue after processing
+ // the last element.
+ DCHECK_GE(msg_queue.size(), 1lu);
+
+ if (msg_queue[0]->control_sequence_num() !=
+ next_control_sequence_num_to_receive) {
+ return;
+ }
+
+ std::pop_heap(msg_queue.begin(), msg_queue.end());
+ *from_node = prev_node_name;
+ *event = std::move(msg_queue.back());
+ msg_queue.pop_back();
+ if (msg_queue.size() == 0) {
+ control_event_queues_.erase(it);
+ }
+}
+
+void Port::BufferEvent(const NodeName& from_node, ScopedEvent event) {
+ DCHECK(!IsNextEvent(from_node, *event));
+
+ auto& event_heap = control_event_queues_[{from_node, event->from_port()}];
+ event_heap.emplace_back(std::move(event));
+ std::push_heap(event_heap.begin(), event_heap.end());
+}
+
+void Port::TakePendingMessages(
+ std::vector<mozilla::UniquePtr<UserMessageEvent>>& messages) {
+ for (auto& node_queue_pair : control_event_queues_) {
+ auto& events = node_queue_pair.second;
+ for (auto& event : events) {
+ if (event->type() != Event::Type::kUserMessage) continue;
+ messages.emplace_back(Event::Cast<UserMessageEvent>(&event));
+ }
+ }
+ control_event_queues_.clear();
+}
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/port.h b/ipc/chromium/src/mojo/core/ports/port.h
new file mode 100644
index 0000000000..44529ddb6f
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port.h
@@ -0,0 +1,277 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_PORT_H_
+#define MOJO_CORE_PORTS_PORT_H_
+
+#include <map>
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/message_queue.h"
+#include "mojo/core/ports/user_data.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/PlatformMutex.h"
+#include "mozilla/RefPtr.h"
+#include "nsISupportsImpl.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class PortLocker;
+
+namespace detail {
+
+// Ports cannot use mozilla::Mutex, as the acquires-before relationships handled
+// by PortLocker can overload the debug-only deadlock detector.
+class MOZ_CAPABILITY("mutex") PortMutex : private ::mozilla::detail::MutexImpl {
+ public:
+ void AssertCurrentThreadOwns() const MOZ_ASSERT_CAPABILITY(this) {
+#ifdef DEBUG
+ MOZ_ASSERT(mOwningThread == PR_GetCurrentThread());
+#endif
+ }
+
+ private:
+ // PortMutex should only be locked/unlocked via PortLocker
+ friend class ::mojo::core::ports::PortLocker;
+
+ void Lock() MOZ_CAPABILITY_ACQUIRE() {
+ ::mozilla::detail::MutexImpl::lock();
+#ifdef DEBUG
+ mOwningThread = PR_GetCurrentThread();
+#endif
+ }
+ void Unlock() MOZ_CAPABILITY_RELEASE() {
+#ifdef DEBUG
+ MOZ_ASSERT(mOwningThread == PR_GetCurrentThread());
+ mOwningThread = nullptr;
+#endif
+ ::mozilla::detail::MutexImpl::unlock();
+ }
+
+#ifdef DEBUG
+ mozilla::Atomic<PRThread*, mozilla::Relaxed> mOwningThread;
+#endif
+};
+
+} // namespace detail
+
+// A Port is essentially a node in a circular list of addresses. For the sake of
+// this documentation such a list will henceforth be referred to as a "route."
+// Routes are the fundamental medium upon which all Node event circulation takes
+// place and are thus the backbone of all Mojo message passing.
+//
+// Each Port is identified by a 128-bit address within a Node (see node.h). A
+// Port doesn't really *do* anything per se: it's a named collection of state,
+// and its owning Node manages all event production, transmission, routing, and
+// processing logic. See Node for more details on how Ports may be used to
+// transmit arbitrary user messages as well as other Ports.
+//
+// Ports may be in any of a handful of states (see State below) which dictate
+// how they react to system events targeting them. In the simplest and most
+// common case, Ports are initially created as an entangled pair (i.e. a simple
+// cycle consisting of two Ports) both in the |kReceiving| State. Consider Ports
+// we'll label |A| and |B| here, which may be created using
+// Node::CreatePortPair():
+//
+// +-----+ +-----+
+// | |--------->| |
+// | A | | B |
+// | |<---------| |
+// +-----+ +-----+
+//
+// |A| references |B| via |peer_node_name| and |peer_port_name|, while |B| in
+// turn references |A|. Note that a Node is NEVER aware of who is sending events
+// to a given Port; it is only aware of where it must route events FROM a given
+// Port.
+//
+// For the sake of documentation, we refer to one receiving port in a route as
+// the "conjugate" of the other. A receiving port's conjugate is also its peer
+// upon initial creation, but because of proxying this may not be the case at a
+// later time.
+//
+// ALL access to this data structure must be guarded by |lock_| acquisition,
+// which is only possible using a PortLocker. PortLocker ensures that
+// overlapping Port lock acquisitions on a single thread are always acquired in
+// a globally consistent order.
+class Port {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(Port)
+
+ public:
+ // The state of a given Port. A Port may only exist in one of these states at
+ // any given time.
+ enum State {
+ // The Port is not yet paired with a peer and is therefore unusable. See
+ // Node::CreateUninitializedPort and Node::InitializePort for motivation.
+ kUninitialized,
+
+ // The Port is publicly visible outside of its Node and may be used to send
+ // and receive user messages. There are always AT MOST two |kReceiving|
+ // Ports along any given route. A user message event sent from a receiving
+ // port is always circulated along the Port's route until it reaches either
+ // a dead-end -- in which case the route is broken -- or it reaches the
+ // other receiving Port in the route -- in which case it lands in that
+ // Port's incoming message queue which can by read by user code.
+ kReceiving,
+
+ // The Port has been taken out of the |kReceiving| state in preparation for
+ // proxying to a new destination. A Port enters this state immediately when
+ // it's attached to a user message and may only leave this state when
+ // transitioning to |kProxying|. See Node for more details.
+ kBuffering,
+
+ // The Port is forwarding all user messages (and most other events) to its
+ // peer without discretion. Ports in the |kProxying| state may never leave
+ // this state and only exist temporarily until their owning Node has
+ // established that no more events will target them. See Node for more
+ // details.
+ kProxying,
+
+ // The Port has been closed and is now permanently unusable. Only
+ // |kReceiving| ports can be closed.
+ kClosed
+ };
+
+ // The current State of the Port.
+ State state;
+
+ // The Node and Port address to which events should be routed FROM this Port.
+ // Note that this is NOT necessarily the address of the Port currently sending
+ // events TO this Port.
+ NodeName peer_node_name;
+ PortName peer_port_name;
+
+ // We keep track of the port that is currently sending messages to this port.
+ // This allows us to verify that the sender node is allowed to send messages
+ // to this port as a mitigation against info leak vulnerabilities.
+ // Tracking the previous port has the nice side effect of keeping received
+ // messages in order.
+ NodeName prev_node_name;
+ PortName prev_port_name;
+
+ // Mark this port as to be merged.
+ bool pending_merge_peer;
+
+ // Next sequence number to send for all event messages.
+ uint64_t next_control_sequence_num_to_send;
+ uint64_t next_control_sequence_num_to_receive;
+
+ // The next available sequence number to use for outgoing user message events
+ // originating from this port.
+ uint64_t next_sequence_num_to_send;
+
+ // The largest acknowledged user message event sequence number.
+ uint64_t last_sequence_num_acknowledged;
+
+ // The interval for which acknowledge requests will be sent. A value of N will
+ // cause an acknowledge request for |last_sequence_num_acknowledged| + N when
+ // initially set and on received acknowledge. This means that the lower bound
+ // for unread or in-transit messages is |next_sequence_num_to_send| -
+ // |last_sequence_num_acknowledged| + |sequence_number_acknowledge_interval|.
+ // If zero, no acknowledge requests are sent.
+ uint64_t sequence_num_acknowledge_interval;
+
+ // The sequence number of the last message this Port should ever expect to
+ // receive in its lifetime. May be used to determine that a proxying port is
+ // ready to be destroyed or that a receiving port's conjugate has been closed
+ // and we know the sequence number of the last message it sent.
+ uint64_t last_sequence_num_to_receive;
+
+ // The sequence number of the message for which this Port should send an
+ // acknowledge message. In the buffering state, holds the acknowledge request
+ // value that is forwarded to the peer on transition to proxying.
+ // This is zero in any port that's never received an acknowledge request, and
+ // in proxies that have forwarded a stored acknowledge.
+ uint64_t sequence_num_to_acknowledge;
+
+ // The queue of incoming user messages received by this Port. Only non-empty
+ // for buffering or receiving Ports. When a buffering port enters the proxying
+ // state, it flushes its queue and the proxy then bypasses the queue
+ // indefinitely.
+ //
+ // A receiving port's queue only has elements removed by user code reading
+ // messages from the port.
+ //
+ // Note that this is a priority queue which only exposes messages to consumers
+ // in strict sequential order.
+ MessageQueue message_queue;
+
+ // Buffer outgoing control messages while this port is in kBuffering state.
+ std::vector<std::pair<NodeName, ScopedEvent>> control_message_queue;
+
+ // In some edge cases, a Node may need to remember to route a single special
+ // event upon destruction of this (proxying) Port. That event is stashed here
+ // in the interim.
+ mozilla::UniquePtr<std::pair<NodeName, ScopedEvent>> send_on_proxy_removal;
+
+ // Arbitrary user data attached to the Port. In practice, Mojo uses this to
+ // stash an observer interface which can be notified about various Port state
+ // changes.
+ RefPtr<UserData> user_data;
+
+ // Indicates that this (proxying) Port has received acknowledgement that no
+ // new user messages will be routed to it. If |true|, the proxy will be
+ // removed once it has received and forwarded all sequenced messages up to and
+ // including the one numbered |last_sequence_num_to_receive|.
+ bool remove_proxy_on_last_message;
+
+ // Indicates that this Port is aware that its nearest (in terms of forward,
+ // non-zero cyclic routing distance) receiving Port has been closed.
+ bool peer_closed;
+
+ // Indicates that this Port lost its peer unexpectedly (e.g. via process death
+ // rather than receiving an ObserveClosure event). In this case
+ // |peer_closed| will be true but |last_sequence_num_to_receive| cannot be
+ // known. Such ports will continue to make message available until their
+ // message queue is empty.
+ bool peer_lost_unexpectedly;
+
+ Port(uint64_t next_sequence_num_to_send,
+ uint64_t next_sequence_num_to_receive);
+
+ Port(const Port&) = delete;
+ void operator=(const Port&) = delete;
+
+ void AssertLockAcquired() { lock_.AssertCurrentThreadOwns(); }
+
+ // Check if the given event should be handled next based on the sequence
+ // number and sender peer.
+ bool IsNextEvent(const NodeName& from_node, const Event& event);
+
+ // Get the next buffered event to be processed. If none is available, |event|
+ // will not be modified.
+ void NextEvent(NodeName* from_node, ScopedEvent* event);
+
+ // Buffer the event for later processing.
+ void BufferEvent(const NodeName& from_node, ScopedEvent event);
+
+ // Flushes the queue of events pending peer verification and returns all user
+ // events
+ void TakePendingMessages(
+ std::vector<mozilla::UniquePtr<UserMessageEvent>>& messages);
+
+ private:
+ using NodePortPair = std::pair<NodeName, PortName>;
+ using EventQueue = std::vector<mozilla::UniquePtr<Event>>;
+ std::map<NodePortPair, EventQueue> control_event_queues_;
+
+ friend class PortLocker;
+
+ ~Port();
+
+ // This lock guards all fields in Port, but is locked in a unique way which is
+ // unfortunately somewhat difficult to get to work with the thread-safety
+ // analysis.
+ detail::PortMutex lock_ MOZ_ANNOTATED;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_PORT_H_
diff --git a/ipc/chromium/src/mojo/core/ports/port_locker.cc b/ipc/chromium/src/mojo/core/ports/port_locker.cc
new file mode 100644
index 0000000000..044a26f143
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port_locker.cc
@@ -0,0 +1,75 @@
+// Copyright 2017 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.
+
+#include "mojo/core/ports/port_locker.h"
+
+#include <algorithm>
+
+#include "mojo/core/ports/port.h"
+
+#ifdef DEBUG
+# include "base/thread_local.h"
+#endif
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+namespace {
+
+#ifdef DEBUG
+void UpdateTLS(PortLocker* old_locker, PortLocker* new_locker) {
+ // Sanity check when DCHECK is on to make sure there is only ever one
+ // PortLocker extant on the current thread.
+ static auto* tls = new base::ThreadLocalPointer<PortLocker>();
+ DCHECK_EQ(old_locker, tls->Get());
+ tls->Set(new_locker);
+}
+#endif
+
+} // namespace
+
+PortLocker::PortLocker(const PortRef** port_refs, size_t num_ports)
+ : port_refs_(port_refs), num_ports_(num_ports) {
+#ifdef DEBUG
+ UpdateTLS(nullptr, this);
+#endif
+
+ // Sort the ports by address to lock them in a globally consistent order.
+ std::sort(
+ port_refs_, port_refs_ + num_ports_,
+ [](const PortRef* a, const PortRef* b) { return a->port() < b->port(); });
+ for (size_t i = 0; i < num_ports_; ++i) {
+ // TODO(crbug.com/725605): Remove this CHECK.
+ CHECK(port_refs_[i]->port());
+ port_refs_[i]->port()->lock_.Lock();
+ }
+}
+
+PortLocker::~PortLocker() {
+ for (size_t i = 0; i < num_ports_; ++i) {
+ port_refs_[i]->port()->lock_.Unlock();
+ }
+
+#ifdef DEBUG
+ UpdateTLS(this, nullptr);
+#endif
+}
+
+#ifdef DEBUG
+// static
+void PortLocker::AssertNoPortsLockedOnCurrentThread() {
+ // Forces a DCHECK if the TLS PortLocker is anything other than null.
+ UpdateTLS(nullptr, nullptr);
+}
+#endif
+
+SinglePortLocker::SinglePortLocker(const PortRef* port_ref)
+ : port_ref_(port_ref), locker_(&port_ref_, 1) {}
+
+SinglePortLocker::~SinglePortLocker() = default;
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/port_locker.h b/ipc/chromium/src/mojo/core/ports/port_locker.h
new file mode 100644
index 0000000000..6a88d14912
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port_locker.h
@@ -0,0 +1,90 @@
+// Copyright 2017 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.
+
+#ifndef MOJO_CORE_PORTS_PORT_LOCKER_H_
+#define MOJO_CORE_PORTS_PORT_LOCKER_H_
+
+#include <stdint.h>
+
+#include "base/logging.h"
+#include "mojo/core/ports/port_ref.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class Port;
+class PortRef;
+
+// A helper which must be used to acquire individual Port locks. Any given
+// thread may have at most one of these alive at any time. This ensures that
+// when multiple ports are locked, they're locked in globally consistent order.
+//
+// Port locks are acquired upon construction of this object and released upon
+// destruction.
+class PortLocker {
+ public:
+ // Constructs a PortLocker over a sequence of |num_ports| contiguous
+ // |PortRef*|s. The sequence may be reordered by this constructor, and upon
+ // return, all referenced ports' locks are held.
+ PortLocker(const PortRef** port_refs, size_t num_ports);
+ ~PortLocker();
+
+ PortLocker(const PortLocker&) = delete;
+ void operator=(const PortLocker&) = delete;
+
+ // Provides safe access to a PortRef's Port. Note that in release builds this
+ // doesn't do anything other than pass through to the private accessor on
+ // |port_ref|, but it does force callers to go through a PortLocker to get to
+ // the state, thus minimizing the likelihood that they'll go and do something
+ // stupid.
+ Port* GetPort(const PortRef& port_ref) const {
+#ifdef DEBUG
+ // Sanity check when DEBUG is on to ensure this is actually a port whose
+ // lock is held by this PortLocker.
+ bool is_port_locked = false;
+ for (size_t i = 0; i < num_ports_ && !is_port_locked; ++i) {
+ if (port_refs_[i]->port() == port_ref.port()) {
+ is_port_locked = true;
+ }
+ }
+ DCHECK(is_port_locked);
+#endif
+ return port_ref.port();
+ }
+
+// A helper which can be used to verify that no Port locks are held on the
+// current thread. In non-DCHECK builds this is a no-op.
+#ifdef DEBUG
+ static void AssertNoPortsLockedOnCurrentThread();
+#else
+ static void AssertNoPortsLockedOnCurrentThread() {}
+#endif
+
+ private:
+ const PortRef** const port_refs_;
+ const size_t num_ports_;
+};
+
+// Convenience wrapper for a PortLocker that locks a single port.
+class SinglePortLocker {
+ public:
+ explicit SinglePortLocker(const PortRef* port_ref);
+ ~SinglePortLocker();
+
+ SinglePortLocker(const SinglePortLocker&) = delete;
+ void operator=(const SinglePortLocker&) = delete;
+
+ Port* port() const { return locker_.GetPort(*port_ref_); }
+
+ private:
+ const PortRef* port_ref_;
+ PortLocker locker_;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_PORT_LOCKER_H_
diff --git a/ipc/chromium/src/mojo/core/ports/port_ref.cc b/ipc/chromium/src/mojo/core/ports/port_ref.cc
new file mode 100644
index 0000000000..b9267f8a6a
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port_ref.cc
@@ -0,0 +1,30 @@
+// Copyright 2016 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.
+
+#include "mojo/core/ports/port_ref.h"
+
+#include "mojo/core/ports/port.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+PortRef::~PortRef() = default;
+
+PortRef::PortRef() = default;
+
+PortRef::PortRef(const PortName& name, RefPtr<Port> port)
+ : name_(name), port_(std::move(port)) {}
+
+PortRef::PortRef(const PortRef& other) = default;
+
+PortRef::PortRef(PortRef&& other) = default;
+
+PortRef& PortRef::operator=(const PortRef& other) = default;
+
+PortRef& PortRef::operator=(PortRef&& other) = default;
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/port_ref.h b/ipc/chromium/src/mojo/core/ports/port_ref.h
new file mode 100644
index 0000000000..0ff0d32fc7
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/port_ref.h
@@ -0,0 +1,47 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_PORT_REF_H_
+#define MOJO_CORE_PORTS_PORT_REF_H_
+
+#include "mojo/core/ports/name.h"
+#include "mozilla/RefPtr.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class Port;
+class PortLocker;
+
+class PortRef {
+ public:
+ ~PortRef();
+ PortRef();
+ PortRef(const PortName& name, RefPtr<Port> port);
+
+ PortRef(const PortRef& other);
+ PortRef(PortRef&& other);
+
+ PortRef& operator=(const PortRef& other);
+ PortRef& operator=(PortRef&& other);
+
+ const PortName& name() const { return name_; }
+
+ bool is_valid() const { return !!port_; }
+
+ private:
+ friend class PortLocker;
+
+ Port* port() const { return port_.get(); }
+
+ PortName name_;
+ RefPtr<Port> port_;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_PORT_REF_H_
diff --git a/ipc/chromium/src/mojo/core/ports/user_data.h b/ipc/chromium/src/mojo/core/ports/user_data.h
new file mode 100644
index 0000000000..f3d568c259
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/user_data.h
@@ -0,0 +1,25 @@
+// Copyright 2016 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.
+
+#ifndef MOJO_CORE_PORTS_USER_DATA_H_
+#define MOJO_CORE_PORTS_USER_DATA_H_
+
+#include "nsISupportsImpl.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class UserData {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UserData);
+
+ protected:
+ virtual ~UserData() = default;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_USER_DATA_H_
diff --git a/ipc/chromium/src/mojo/core/ports/user_message.cc b/ipc/chromium/src/mojo/core/ports/user_message.cc
new file mode 100644
index 0000000000..1aadb21425
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/user_message.cc
@@ -0,0 +1,21 @@
+// Copyright 2017 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.
+
+#include "mojo/core/ports/user_message.h"
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+UserMessage::UserMessage(const TypeInfo* type_info) : type_info_(type_info) {}
+
+UserMessage::~UserMessage() = default;
+
+bool UserMessage::WillBeRoutedExternally(UserMessageEvent&) { return true; }
+
+size_t UserMessage::GetSizeIfSerialized() const { return 0; }
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
diff --git a/ipc/chromium/src/mojo/core/ports/user_message.h b/ipc/chromium/src/mojo/core/ports/user_message.h
new file mode 100644
index 0000000000..85c03a9557
--- /dev/null
+++ b/ipc/chromium/src/mojo/core/ports/user_message.h
@@ -0,0 +1,62 @@
+// Copyright 2017 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.
+
+#ifndef MOJO_CORE_PORTS_USER_MESSAGE_H_
+#define MOJO_CORE_PORTS_USER_MESSAGE_H_
+
+#include <stddef.h>
+
+namespace mojo {
+namespace core {
+namespace ports {
+
+class UserMessageEvent;
+
+// Base type to use for any embedder-defined user message implementation. This
+// class is intentionally empty.
+//
+// Provides a bit of type-safety help to subclasses since by design downcasting
+// from this type is a common operation in embedders.
+//
+// Each subclass should define a static const instance of TypeInfo named
+// |kUserMessageTypeInfo| and pass its address down to the UserMessage
+// constructor. The type of a UserMessage can then be dynamically inspected by
+// comparing |type_info()| to any subclass's |&kUserMessageTypeInfo|.
+class UserMessage {
+ public:
+ struct TypeInfo {};
+
+ explicit UserMessage(const TypeInfo* type_info);
+ virtual ~UserMessage();
+
+ UserMessage(const UserMessage&) = delete;
+ void operator=(const UserMessage&) = delete;
+
+ const TypeInfo* type_info() const { return type_info_; }
+
+ // Invoked immediately before the system asks the embedder to forward this
+ // message to an external node.
+ //
+ // The UserMessageEvent is passed in to allow ports and other such values to
+ // be attached to the message before it is sent externally, in case late
+ // serialization is performed.
+ //
+ // Returns |true| if the message is OK to route externally, or |false|
+ // otherwise. Returning |false| implies an unrecoverable condition, and the
+ // message event will be destroyed without further routing.
+ virtual bool WillBeRoutedExternally(UserMessageEvent& event);
+
+ // Returns the size in bytes of this message iff it's serialized. Zero
+ // otherwise.
+ virtual size_t GetSizeIfSerialized() const;
+
+ private:
+ const TypeInfo* const type_info_;
+};
+
+} // namespace ports
+} // namespace core
+} // namespace mojo
+
+#endif // MOJO_CORE_PORTS_USER_MESSAGE_H_
diff --git a/ipc/chromium/src/third_party/libevent/CMakeLists.txt b/ipc/chromium/src/third_party/libevent/CMakeLists.txt
new file mode 100644
index 0000000000..676727f165
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/CMakeLists.txt
@@ -0,0 +1,1575 @@
+#
+# Libevent CMake project
+#
+# Based on initial work by:
+# Alexey Ozeritsky
+#
+# Additional changes:
+# Brodie Thiesfield
+# Joakim Soderberg
+# Trond Norbye
+# Sergei Nikulov
+#
+# Build example:
+#
+# cd libevent
+# md build
+# cd build
+# cmake -G "Visual Studio 10" ..
+# start libevent.sln
+#
+
+cmake_minimum_required(VERSION 3.1 FATAL_ERROR)
+
+if (POLICY CMP0054)
+ cmake_policy(SET CMP0054 NEW)
+endif()
+if (POLICY CMP0074)
+ cmake_policy(SET CMP0074 NEW)
+endif()
+if (POLICY CMP0075)
+ cmake_policy(SET CMP0075 NEW)
+endif()
+
+if(NOT CMAKE_BUILD_TYPE)
+ set(CMAKE_BUILD_TYPE Release
+ CACHE STRING "Set build type to Debug o Release (default Release)" FORCE)
+endif()
+string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER)
+
+# get rid of the extra default configurations
+# what? why would you get id of other useful build types? - Ellzey
+set(CMAKE_CONFIGURATION_TYPES "Debug;Release" CACHE STRING "Limited configurations" FORCE)
+
+set(EVENT__LIBRARY_TYPE DEFAULT CACHE STRING
+ "Set library type to SHARED/STATIC/BOTH (default SHARED for MSVC, otherwise BOTH)")
+
+project(libevent C)
+
+list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/")
+string(REGEX MATCH "SunOS" SOLARIS "${CMAKE_SYSTEM_NAME}")
+
+
+include(CheckTypeSize)
+include(CheckFileOffsetBits)
+include(Macros)
+include(CheckVariableExists)
+include(CheckSymbolExists)
+include(CheckStructHasMember)
+include(CheckCSourceCompiles)
+include(CheckPrototypeDefinition)
+include(CheckFunctionKeywords)
+include(CheckConstExists)
+include(AddCompilerFlags)
+include(VersionViaGit)
+
+event_fuzzy_version_from_git()
+
+set(EVENT_VERSION_MAJOR ${EVENT_GIT___VERSION_MAJOR})
+set(EVENT_VERSION_MINOR ${EVENT_GIT___VERSION_MINOR})
+set(EVENT_VERSION_PATCH ${EVENT_GIT___VERSION_PATCH})
+set(EVENT_VERSION_STAGE ${EVENT_GIT___VERSION_STAGE})
+
+
+set(EVENT_ABI_MAJOR ${EVENT_VERSION_MAJOR})
+set(EVENT_ABI_MINOR ${EVENT_VERSION_MINOR})
+set(EVENT_ABI_PATCH ${EVENT_VERSION_PATCH})
+
+set(EVENT_ABI_LIBVERSION
+ "${EVENT_ABI_MAJOR}.${EVENT_ABI_MINOR}.${EVENT_ABI_PATCH}")
+
+set(EVENT_PACKAGE_VERSION
+ "${EVENT_VERSION_MAJOR}.${EVENT_VERSION_MINOR}.${EVENT_VERSION_PATCH}")
+
+set(EVENT_NUMERIC_VERSION 0x02010c00)
+# equals to VERSION_INFO in Makefile.am
+set(EVENT_ABI_LIBVERSION_CURRENT 7)
+set(EVENT_ABI_LIBVERSION_REVISION 1)
+set(EVENT_ABI_LIBVERSION_AGE 0)
+
+# equals to RELEASE in Makefile.am
+set(EVENT_PACKAGE_RELEASE 2.1)
+
+# only a subset of names can be used, defaults to "beta"
+set(EVENT_STAGE_NAME ${EVENT_VERSION_STAGE})
+
+# a list that defines what can set for EVENT_STAGE_VERSION
+set(EVENT__ALLOWED_STAGE_NAMES
+ rc
+ beta
+ alpha
+ alpha-dev
+ release
+ stable
+)
+list(
+ FIND EVENT__ALLOWED_STAGE_NAMES
+ "${EVENT_STAGE_NAME}"
+ EVENT__STAGE_RET
+)
+if (EVENT__STAGE_RET EQUAL -1)
+ message(WARNING
+ "stage ${EVENT_STAGE_NAME} is not allowed, reset to beta")
+ set(EVENT_STAGE_NAME beta)
+endif()
+
+set(EVENT_VERSION
+ "${EVENT_VERSION_MAJOR}.${EVENT_VERSION_MINOR}.${EVENT_VERSION_PATCH}-${EVENT_STAGE_NAME}")
+
+option(EVENT__DISABLE_DEBUG_MODE
+ "Define if libevent should build without support for a debug mode" OFF)
+
+option(EVENT__ENABLE_VERBOSE_DEBUG
+ "Enables verbose debugging" OFF)
+
+option(EVENT__DISABLE_MM_REPLACEMENT
+ "Define if libevent should not allow replacing the mm functions" OFF)
+
+option(EVENT__DISABLE_THREAD_SUPPORT
+ "Define if libevent should not be compiled with thread support" OFF)
+
+option(EVENT__DISABLE_OPENSSL
+ "Define if libevent should build without support for OpenSSL encryption" OFF)
+
+option(EVENT__DISABLE_BENCHMARK
+ "Defines if libevent should build without the benchmark executables" OFF)
+
+option(EVENT__DISABLE_TESTS
+ "If tests should be compiled or not" OFF)
+
+option(EVENT__DISABLE_REGRESS
+ "Disable the regress tests" OFF)
+
+option(EVENT__DISABLE_SAMPLES
+ "Disable sample files" OFF)
+
+option(EVENT__DISABLE_CLOCK_GETTIME
+ "Do not use clock_gettime even if it is available" OFF)
+
+option(EVENT__FORCE_KQUEUE_CHECK
+ "When crosscompiling forces running a test program that verifies that Kqueue works with pipes. Note that this requires you to manually run the test program on the cross compilation target to verify that it works. See cmake documentation for try_run for more details" OFF)
+
+# TODO: Add --disable-largefile omit support for large files
+option(EVENT__COVERAGE
+"Enable running gcov to get a test coverage report (only works with GCC/CLang). Make sure to enable -DCMAKE_BUILD_TYPE=Debug as well." OFF)
+
+# Put the libaries and binaries that get built into directories at the
+# top of the build tree rather than in hard-to-find leaf directories.
+#
+# But only if this variables are not defined yet
+# (i.e. libevent is used via add_subdirectory())
+if (NOT DEFINED CMAKE_RUNTIME_OUTPUT_DIRECTORY)
+ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
+endif()
+if (NOT DEFINED CMAKE_LIBRARY_OUTPUT_DIRECTORY)
+ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
+endif()
+if (NOT DEFINED CMAKE_ARCHIVE_OUTPUT_DIRECTORY)
+ set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
+endif()
+
+if (EVENT__ENABLE_VERBOSE_DEBUG)
+ add_definitions(-DUSE_DEBUG=1)
+endif()
+
+# make it colorful under ninja-build
+if ("${CMAKE_GENERATOR}" STREQUAL "Ninja")
+ add_compiler_flags(-fdiagnostics-color=always)
+endif()
+
+# Setup compiler flags for coverage.
+if (EVENT__COVERAGE)
+ if (NOT "${CMAKE_BUILD_TYPE_LOWER}" STREQUAL "debug")
+ message(FATAL_ERROR "Coverage requires -DCMAKE_BUILD_TYPE=Debug")
+ endif()
+
+ message(STATUS "Setting coverage compiler flags")
+
+ set(CMAKE_REQUIRED_LIBRARIES "--coverage")
+ add_compiler_flags(-g -O0 --coverage)
+ set(CMAKE_REQUIRED_LIBRARIES "")
+endif()
+
+set(GNUC 0)
+set(CLANG 0)
+set(MSVC 0)
+if (("${CMAKE_C_COMPILER_ID}" STREQUAL "Clang") OR
+ ("${CMAKE_C_COMPILER_ID}" STREQUAL "AppleClang"))
+ set(CLANG 1)
+endif()
+if (("${CMAKE_C_COMPILER_ID}" STREQUAL "GNU") OR (${CLANG}))
+ set(GNUC 1)
+endif()
+if (("${CMAKE_C_COMPILER_ID}" STREQUAL "MSVC") OR (${CLANG}))
+ set(MSVC 1)
+endif()
+
+# Detect library type
+set(EVENT_LIBRARY_TYPE)
+if ("${EVENT__LIBRARY_TYPE}" STREQUAL "DEFAULT")
+ if (${MSVC})
+ set(EVENT_LIBRARY_TYPE SHARED)
+ else()
+ set(EVENT_LIBRARY_TYPE BOTH)
+ endif()
+else()
+ string(TOUPPER "${EVENT__LIBRARY_TYPE}" EVENT_LIBRARY_TYPE)
+endif()
+if ((${MSVC}) AND ("${EVENT_LIBRARY_TYPE}" STREQUAL "BOTH"))
+ message(WARNING
+ "Building SHARED and STATIC is not supported for MSVC "
+ "(due to conflicts in library name"
+ " between STATIC library and IMPORTED library for SHARED libraries)")
+endif()
+set(EVENT_LIBRARY_STATIC OFF)
+set(EVENT_LIBRARY_SHARED OFF)
+if ("${EVENT_LIBRARY_TYPE}" STREQUAL "BOTH")
+ set(EVENT_LIBRARY_STATIC ON)
+ set(EVENT_LIBRARY_SHARED ON)
+elseif ("${EVENT_LIBRARY_TYPE}" STREQUAL "STATIC")
+ set(EVENT_LIBRARY_STATIC ON)
+elseif ("${EVENT_LIBRARY_TYPE}" STREQUAL "SHARED")
+ set(EVENT_LIBRARY_SHARED ON)
+else()
+ message(FATAL_ERROR "${EVENT_LIBRARY_TYPE} is not supported")
+endif()
+
+if (${MSVC})
+ set(msvc_static_runtime OFF)
+ if ("${EVENT_LIBRARY_TYPE}" STREQUAL "STATIC")
+ set(msvc_static_runtime ON)
+ endif()
+
+ # For more info:
+ # - https://docs.microsoft.com/en-us/cpp/build/reference/md-mt-ld-use-run-time-library?view=vs-2017
+ # - https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-can-i-build-my-msvc-application-with-a-static-runtime
+ option(EVENT__MSVC_STATIC_RUNTIME
+ "Link static runtime libraries"
+ ${msvc_static_runtime})
+
+ if (EVENT__MSVC_STATIC_RUNTIME)
+ foreach (flag_var
+ CMAKE_C_FLAGS_DEBUG
+ CMAKE_C_FLAGS_RELEASE
+ CMAKE_C_FLAGS_MINSIZEREL
+ CMAKE_C_FLAGS_RELWITHDEBINFO
+ )
+ if (${flag_var} MATCHES "/MD")
+ string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
+ endif()
+ endforeach()
+ endif()
+endif()
+
+# GNUC specific options.
+if (${GNUC})
+ option(EVENT__DISABLE_GCC_WARNINGS "Disable verbose warnings with GCC" OFF)
+ option(EVENT__ENABLE_GCC_HARDENING "Enable compiler security checks" OFF)
+ option(EVENT__ENABLE_GCC_FUNCTION_SECTIONS "Enable gcc function sections" OFF)
+ option(EVENT__ENABLE_GCC_WARNINGS "Make all GCC warnings into errors" OFF)
+
+ set(GCC_V ${CMAKE_C_COMPILER_VERSION})
+
+ list(APPEND __FLAGS
+ -Wall -Wextra -Wno-unused-parameter -Wstrict-aliasing -Wstrict-prototypes
+
+ -fno-strict-aliasing # gcc 2.9.5+
+ -Wmissing-prototypes
+
+ # gcc 4
+ -Winit-self
+ -Wmissing-field-initializers
+ -Wdeclaration-after-statement
+
+ # gcc 4.2
+ -Waddress
+ -Wnormalized=id
+ -Woverride-init
+
+ # gcc 4.5
+ -Wlogical-op
+
+ -Wwrite-strings
+ )
+
+ if (${CLANG})
+ list(APPEND __FLAGS -Wno-unused-function)
+ endif()
+
+ if (EVENT__DISABLE_GCC_WARNINGS)
+ list(APPEND __FLAGS -w)
+ endif()
+
+ if (EVENT__ENABLE_GCC_HARDENING)
+ list(APPEND __FLAGS
+ -fstack-protector-all
+ -fwrapv
+ -fPIE
+ -Wstack-protector
+ "--param ssp-buffer-size=1")
+
+ add_definitions(-D_FORTIFY_SOURCE=2)
+ endif()
+
+ if (EVENT__ENABLE_GCC_FUNCTION_SECTIONS)
+ list(APPEND __FLAGS -ffunction-sections)
+ # TODO: Add --gc-sections support. We need some checks for NetBSD to ensure this works.
+ endif()
+
+ if (EVENT__ENABLE_GCC_WARNINGS)
+ list(APPEND __FLAGS -Werror)
+ endif()
+
+ add_compiler_flags(${__FLAGS})
+endif()
+
+if (APPLE)
+ # Get rid of deprecated warnings for OpenSSL on OSX 10.7 and greater.
+ add_compiler_flags(
+ -Wno-error=deprecated-declarations
+ -Qunused-arguments
+ )
+endif()
+
+if (MINGW OR CYGWIN)
+ set(WIN32 TRUE)
+endif()
+
+# Winsock.
+if(WIN32)
+ set(CMAKE_REQUIRED_LIBRARIES ws2_32 shell32 advapi32)
+ set(CMAKE_REQUIRED_DEFINITIONS -FIwinsock2.h -FIws2tcpip.h -D_WIN32_WINNT=0x0600)
+endif()
+if (SOLARIS)
+ set(CMAKE_REQUIRED_LIBRARIES socket nsl)
+endif()
+
+# Check if _GNU_SOURCE is available.
+if (NOT DEFINED _GNU_SOURCE)
+ CHECK_SYMBOL_EXISTS(__GNU_LIBRARY__ "features.h" _GNU_SOURCE)
+
+ if (NOT _GNU_SOURCE)
+ unset(_GNU_SOURCE CACHE)
+ CHECK_SYMBOL_EXISTS(_GNU_SOURCE "features.h" _GNU_SOURCE)
+ endif()
+
+ if (ANDROID)
+ set(_GNU_SOURCE TRUE)
+ endif()
+endif()
+
+if (_GNU_SOURCE)
+ add_definitions(-D_GNU_SOURCE=1)
+ set(CMAKE_REQUIRED_DEFINITIONS -D_GNU_SOURCE)
+endif()
+
+# Check if header files exist
+list(APPEND FILES_TO_CHECK
+ fcntl.h
+ inttypes.h
+ memory.h
+ signal.h
+ stdarg.h
+ stddef.h
+ stdint.h
+ stdlib.h
+ string.h
+ errno.h
+ unistd.h
+ time.h
+ sys/types.h
+ sys/stat.h
+ sys/time.h
+ sys/param.h
+)
+if (WIN32)
+ list(APPEND FILES_TO_CHECK
+ io.h
+ winsock2.h
+ ws2tcpip.h
+ afunix.h
+ )
+else()
+ list(APPEND FILES_TO_CHECK
+ netdb.h
+ dlfcn.h
+ arpa/inet.h
+ poll.h
+ port.h
+ sys/socket.h
+ sys/random.h
+ sys/un.h
+ sys/devpoll.h
+ sys/epoll.h
+ sys/eventfd.h
+ sys/event.h
+ sys/ioctl.h
+ sys/mman.h
+ sys/queue.h
+ sys/select.h
+ sys/sendfile.h
+ sys/uio.h
+ sys/wait.h
+ sys/resource.h
+ sys/timerfd.h
+ netinet/in.h
+ netinet/in6.h
+ netinet/tcp.h
+ ifaddrs.h
+ )
+endif()
+
+if (NOT "${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Linux")
+ list(APPEND FILES_TO_CHECK sys/sysctl.h)
+endif()
+
+if (APPLE)
+ list(APPEND FILES_TO_CHECK
+ mach/mach_time.h
+ mach/mach.h
+ )
+endif()
+
+foreach(FILE ${FILES_TO_CHECK})
+ CHECK_INCLUDE_FILE_CONCAT(${FILE} "EVENT")
+endforeach()
+unset(FILES_TO_CHECK)
+
+# Check if functions exist
+list(APPEND SYMBOLS_TO_CHECK
+ getaddrinfo
+ getnameinfo
+ getprotobynumber
+ getservbyname
+ gethostbyname
+ inet_ntop
+ inet_pton
+ gettimeofday
+ signal
+ strtoll
+ splice
+ strlcpy
+ strsep
+ strtok_r
+ vasprintf
+ timerclear
+ timercmp
+ timerisset
+ timeradd
+ nanosleep
+ putenv
+ umask
+)
+if (NOT EVENT__DISABLE_CLOCK_GETTIME)
+ list(APPEND SYMBOLS_TO_CHECK clock_gettime)
+endif()
+
+if (WIN32)
+ list(APPEND SYMBOLS_TO_CHECK
+ _gmtime64_s
+ _gmtime64
+ )
+else()
+ list(APPEND SYMBOLS_TO_CHECK
+ getifaddrs
+ select
+ epoll_create
+ epoll_create1
+ epoll_ctl
+ eventfd
+ poll
+ port_create
+ kqueue
+ fcntl
+ mmap
+ pipe
+ pipe2
+ sendfile
+ sigaction
+ strsignal
+ sysctl
+ accept4
+ arc4random
+ arc4random_buf
+ arc4random_addrandom
+ getrandom
+ getegid
+ geteuid
+ issetugid
+ usleep
+ timerfd_create
+ setenv
+ unsetenv
+ setrlimit
+ gethostbyname_r
+ )
+ if (APPLE)
+ list(APPEND SYMBOLS_TO_CHECK mach_absolute_time)
+ endif()
+endif()
+
+# Add stdio.h for vasprintf
+set(EVENT_INCLUDES ${EVENT_INCLUDES} stdio.h)
+CHECK_SYMBOLS_EXIST("${SYMBOLS_TO_CHECK}" "${EVENT_INCLUDES}" "EVENT")
+unset(SYMBOLS_TO_CHECK)
+set(EVENT__HAVE_EPOLL ${EVENT__HAVE_EPOLL_CREATE})
+
+# Get the gethostbyname_r prototype.
+if(EVENT__HAVE_GETHOSTBYNAME_R)
+ CHECK_PROTOTYPE_DEFINITION(gethostbyname_r
+ "int gethostbyname_r(const char *name, struct hostent *hp, struct hostent_data *hdata)"
+ "0"
+ "netdb.h"
+ EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
+
+ CHECK_PROTOTYPE_DEFINITION(gethostbyname_r
+ "struct hostent *gethostbyname_r(const char *name, struct hostent *hp, char *buf, size_t buflen, int *herr)"
+ "NULL"
+ "netdb.h"
+ EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
+
+ CHECK_PROTOTYPE_DEFINITION(gethostbyname_r
+ "int gethostbyname_r(const char *name, struct hostent *hp, char *buf, size_t buflen, struct hostent **result, int *herr)"
+ "0"
+ "netdb.h"
+ EVENT__HAVE_GETHOSTBYNAME_R_6_ARG)
+endif()
+
+if(HAVE_PORT_H AND HAVE_PORT_CREATE)
+ set(EVENT__HAVE_EVENT_PORTS 1)
+endif()
+
+# Only `CHECK_TYPE_SIZE()' will use `CMAKE_EXTRA_INCLUDE_FILES'
+set(CMAKE_EXTRA_INCLUDE_FILES ${EVENT_INCLUDES})
+
+CHECK_TYPE_SIZE("struct sockaddr_un" EVENT__HAVE_STRUCT_SOCKADDR_UN)
+CHECK_TYPE_SIZE("uint8_t" EVENT__HAVE_UINT8_T)
+CHECK_TYPE_SIZE("uint16_t" EVENT__HAVE_UINT16_T)
+CHECK_TYPE_SIZE("uint32_t" EVENT__HAVE_UINT32_T)
+CHECK_TYPE_SIZE("uint64_t" EVENT__HAVE_UINT64_T)
+CHECK_TYPE_SIZE("short" EVENT__SIZEOF_SHORT BUILTIN_TYPES_ONLY)
+CHECK_TYPE_SIZE("int" EVENT__SIZEOF_INT BUILTIN_TYPES_ONLY)
+CHECK_TYPE_SIZE("unsigned" EVENT__SIZEOF_UNSIGNED BUILTIN_TYPES_ONLY)
+CHECK_TYPE_SIZE("unsigned int" EVENT__SIZEOF_UNSIGNED_INT BUILTIN_TYPES_ONLY)
+CHECK_TYPE_SIZE("long" EVENT__SIZEOF_LONG BUILTIN_TYPES_ONLY)
+CHECK_TYPE_SIZE("long long" EVENT__SIZEOF_LONG_LONG BUILTIN_TYPES_ONLY)
+
+if(WIN32)
+ # These aren't available until Windows Vista.
+ # But you can still link them. They just won't be found when running the exe.
+ set(EVENT__HAVE_INET_NTOP 0)
+ set(EVENT__HAVE_INET_PTON 0)
+endif()
+
+# Check for different inline keyword versions.
+check_function_keywords("inline" "__inline" "__inline__")
+
+if (HAVE_INLINE)
+ set(EVENT__inline inline)
+elseif (HAVE___INLINE)
+ set(EVENT__inline __inline)
+elseif(HAVE___INLINE__)
+ set(EVENT__inline __inline__)
+else()
+ set(EVENT__inline)
+endif()
+
+# __func__/__FUNCTION__ is not a macros in general
+CHECK_SYMBOL_EXISTS("__func__" "" EVENT__HAVE___func__)
+CHECK_SYMBOL_EXISTS("__FUNCTION__" "" EVENT__HAVE___FUNCTION__)
+
+CHECK_SYMBOL_EXISTS(TAILQ_FOREACH sys/queue.h EVENT__HAVE_TAILQFOREACH)
+CHECK_CONST_EXISTS(CTL_KERN sys/sysctl.h EVENT__HAVE_DECL_CTL_KERN)
+CHECK_CONST_EXISTS(KERN_ARND sys/sysctl.h EVENT__HAVE_DECL_KERN_ARND)
+CHECK_SYMBOL_EXISTS(F_SETFD fcntl.h EVENT__HAVE_SETFD)
+
+CHECK_TYPE_SIZE(fd_mask EVENT__HAVE_FD_MASK)
+
+CHECK_TYPE_SIZE(size_t EVENT__SIZEOF_SIZE_T)
+if(NOT EVENT__SIZEOF_SIZE_T)
+ set(EVENT__size_t "unsigned")
+ set(EVENT__SIZEOF_SIZE_T ${EVENT__SIZEOF_UNSIGNED})
+else()
+ set(EVENT__size_t size_t)
+endif()
+
+CHECK_TYPE_SIZE("off_t" EVENT__SIZEOF_OFF_T LANGUAGE C)
+
+
+# XXX we should functionalize these size and type sets. --elley
+
+# Winssck.
+if (_MSC_VER)
+ list(APPEND CMAKE_EXTRA_INCLUDE_FILES BaseTsd.h)
+endif()
+CHECK_TYPE_SIZE("ssize_t" EVENT__SIZEOF_SSIZE_T_LOWER LANGUAGE C)
+CHECK_TYPE_SIZE("SSIZE_T" EVENT__SIZEOF_SSIZE_T_UPPER LANGUAGE C)
+
+if (EVENT__SIZEOF_SSIZE_T_LOWER)
+ set(EVENT__ssize_t "ssize_t")
+ set(EVENT__SIZEOF_SSIZE_T ${EVENT__SIZEOF_SSIZE_T_LOWER})
+elseif (EVENT__SIZEOF_SSIZE_T_UPPER)
+ set(EVENT__ssize_t "SSIZE_T")
+ set(EVENT__SIZEOF_SSIZE_T ${EVENT__SIZEOF_SSIZE_T_UPPER})
+else()
+ set(EVENT__ssize_t "int")
+ set(EVENT__SIZEOF_SSIZE_T ${EVENT__SIZEOF_INT})
+endif()
+
+CHECK_TYPE_SIZE(socklen_t EVENT__SIZEOF_SOCKLEN_T)
+if(NOT EVENT__SIZEOF_SOCKLEN_T)
+ set(EVENT__socklen_t "unsigned int")
+ set(EVENT__SIZEOF_SOCKLEN_T ${EVENT__SIZEOF_UNSIGNED_INT})
+else()
+ set(EVENT__socklen_t "socklen_t")
+endif()
+
+CHECK_TYPE_SIZE(pid_t EVENT__SIZEOF_PID_T)
+if(NOT EVENT__SIZEOF_PID_T)
+ set(EVENT__SIZEOF_PID_T ${EVENT__SIZEOF_INT})
+else()
+ set(EVENT__SIZEOF_PID_T EVENT__SIZEOF_PID_T)
+endif()
+
+if (NOT EVENT__DISABLE_THREAD_SUPPORT)
+ if (NOT WIN32)
+ list(APPEND CMAKE_EXTRA_INCLUDE_FILES pthread.h)
+ endif()
+ CHECK_TYPE_SIZE(pthread_t EVENT__SIZEOF_PTHREAD_T)
+endif()
+
+if(EVENT__HAVE_CLOCK_GETTIME)
+ set(EVENT__DNS_USE_CPU_CLOCK_FOR_ID 1)
+endif()
+
+# we're just getting lazy now.
+CHECK_TYPE_SIZE("uintptr_t" EVENT__HAVE_UINTPTR_T)
+CHECK_TYPE_SIZE("void *" EVENT__SIZEOF_VOID_P)
+CHECK_TYPE_SIZE("time_t" EVENT__SIZEOF_TIME_T)
+
+# Tests file offset bits.
+# TODO: Add AIX test for if -D_LARGE_FILES is needed.
+
+# XXX: Why is this here? we don't even use it. Well, we don't even use it
+# on top of that, why is it set in the config.h?! IT_MAKES_NO_SENSE
+# I'm commenting it out for now.
+# - ellzey
+
+#CHECK_FILE_OFFSET_BITS()
+
+# Verify kqueue works with pipes.
+if (EVENT__HAVE_KQUEUE)
+ if ((CMAKE_CROSSCOMPILING OR APPLE) AND NOT EVENT__FORCE_KQUEUE_CHECK)
+ message(WARNING "Cannot check if kqueue works with pipes when crosscompiling, use EVENT__FORCE_KQUEUE_CHECK to be sure (this requires manually running a test program on the cross compilation target)")
+ set(EVENT__HAVE_WORKING_KQUEUE 1)
+ else()
+ message(STATUS "Checking if kqueue works with pipes...")
+ include(CheckWorkingKqueue)
+ endif()
+endif()
+
+if(EVENT__HAVE_NETDB_H)
+ list(APPEND CMAKE_EXTRA_INCLUDE_FILES netdb.h)
+ CHECK_TYPE_SIZE("struct addrinfo" EVENT__HAVE_STRUCT_ADDRINFO)
+elseif(WIN32)
+ list(APPEND CMAKE_EXTRA_INCLUDE_FILES ws2tcpip.h)
+ CHECK_TYPE_SIZE("struct addrinfo" EVENT__HAVE_STRUCT_ADDRINFO)
+endif()
+
+# Check for sockaddr structure sizes.
+set(SOCKADDR_HEADERS)
+if (WIN32)
+ set(CMAKE_REQUIRED_DEFINITIONS "-DWIN32_LEAN_AND_MEAN")
+ if (_MSC_VER LESS 1300)
+ set(SOCKADDR_HEADERS winsock.h)
+ else()
+ set(SOCKADDR_HEADERS winsock2.h ws2tcpip.h)
+ endif()
+else()
+ if (EVENT__HAVE_NETINET_IN_H)
+ set(SOCKADDR_HEADERS ${SOCKADDR_HEADERS} netinet/in.h)
+ endif()
+
+ if (EVENT__HAVE_NETINET_IN6_H)
+ set(SOCKADDR_HEADERS ${SOCKADDR_HEADERS} netinet/in6.h)
+ endif()
+
+ if (EVENT__HAVE_SYS_SOCKET_H)
+ set(SOCKADDR_HEADERS ${SOCKADDR_HEADERS} sys/socket.h)
+ endif()
+
+ if (EVENT__HAVE_NETDB_H)
+ set(SOCKADDR_HEADERS ${SOCKADDR_HEADERS} netdb.h)
+ endif()
+endif()
+
+CHECK_TYPE_SIZE("struct in6_addr" EVENT__HAVE_STRUCT_IN6_ADDR)
+if(EVENT__HAVE_STRUCT_IN6_ADDR)
+ CHECK_STRUCT_HAS_MEMBER("struct in6_addr"
+ s6_addr16 "${SOCKADDR_HEADERS}"
+ EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16)
+
+ CHECK_STRUCT_HAS_MEMBER("struct in6_addr"
+ s6_addr32 "${SOCKADDR_HEADERS}"
+ EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32)
+endif()
+
+CHECK_TYPE_SIZE("sa_family_t" EVENT__HAVE_SA_FAMILY_T)
+CHECK_TYPE_SIZE("struct sockaddr_in6" EVENT__HAVE_STRUCT_SOCKADDR_IN6)
+
+if(EVENT__HAVE_STRUCT_SOCKADDR_IN6)
+ CHECK_STRUCT_HAS_MEMBER("struct sockaddr_in6"
+ sin6_len "${SOCKADDR_HEADERS}"
+ EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN)
+
+ CHECK_STRUCT_HAS_MEMBER("struct sockaddr_in6"
+ sin_len "${SOCKADDR_HEADERS}"
+ EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN)
+endif()
+
+CHECK_TYPE_SIZE("struct sockaddr_storage" EVENT__HAVE_STRUCT_SOCKADDR_STORAGE)
+if(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE)
+ CHECK_STRUCT_HAS_MEMBER("struct sockaddr_storage"
+ ss_family "${SOCKADDR_HEADERS}"
+ EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY)
+
+ CHECK_STRUCT_HAS_MEMBER("struct sockaddr_storage"
+ __ss_family "${SOCKADDR_HEADERS}" EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY)
+endif()
+
+CHECK_TYPE_SIZE("struct linger" EVENT__HAVE_STRUCT_LINGER)
+
+# Group the source files.
+set(HDR_PRIVATE
+ bufferevent-internal.h
+ changelist-internal.h
+ defer-internal.h
+ epolltable-internal.h
+ evbuffer-internal.h
+ event-internal.h
+ evmap-internal.h
+ evrpc-internal.h
+ evsignal-internal.h
+ evthread-internal.h
+ ht-internal.h
+ http-internal.h
+ iocp-internal.h
+ ipv6-internal.h
+ log-internal.h
+ minheap-internal.h
+ mm-internal.h
+ ratelim-internal.h
+ strlcpy-internal.h
+ util-internal.h
+ evconfig-private.h
+ compat/sys/queue.h)
+
+set(HDR_COMPAT
+ include/evdns.h
+ include/evrpc.h
+ include/event.h
+ include/evhttp.h
+ include/evutil.h)
+
+set(HDR_PUBLIC
+ include/event2/buffer.h
+ include/event2/bufferevent.h
+ include/event2/bufferevent_compat.h
+ include/event2/bufferevent_struct.h
+ include/event2/buffer_compat.h
+ include/event2/dns.h
+ include/event2/dns_compat.h
+ include/event2/dns_struct.h
+ include/event2/event.h
+ include/event2/event_compat.h
+ include/event2/event_struct.h
+ include/event2/http.h
+ include/event2/http_compat.h
+ include/event2/http_struct.h
+ include/event2/keyvalq_struct.h
+ include/event2/listener.h
+ include/event2/rpc.h
+ include/event2/rpc_compat.h
+ include/event2/rpc_struct.h
+ include/event2/tag.h
+ include/event2/tag_compat.h
+ include/event2/thread.h
+ include/event2/util.h
+ include/event2/visibility.h
+ ${PROJECT_BINARY_DIR}/include/event2/event-config.h)
+
+set(SRC_CORE
+ buffer.c
+ bufferevent.c
+ bufferevent_filter.c
+ bufferevent_pair.c
+ bufferevent_ratelim.c
+ bufferevent_sock.c
+ event.c
+ evmap.c
+ evthread.c
+ evutil.c
+ evutil_rand.c
+ evutil_time.c
+ listener.c
+ log.c
+ signal.c
+ strlcpy.c)
+
+if(EVENT__HAVE_SELECT)
+ list(APPEND SRC_CORE select.c)
+endif()
+
+if(EVENT__HAVE_POLL)
+ list(APPEND SRC_CORE poll.c)
+endif()
+
+if(EVENT__HAVE_KQUEUE)
+ list(APPEND SRC_CORE kqueue.c)
+endif()
+
+if(EVENT__HAVE_DEVPOLL)
+ list(APPEND SRC_CORE devpoll.c)
+endif()
+
+if(EVENT__HAVE_EPOLL)
+ list(APPEND SRC_CORE epoll.c)
+endif()
+
+if(EVENT__HAVE_EVENT_PORTS)
+ list(APPEND SRC_CORE evport.c)
+endif()
+
+if (NOT EVENT__DISABLE_OPENSSL)
+ find_package(OpenSSL REQUIRED)
+
+ set(EVENT__HAVE_OPENSSL 1)
+
+ message(STATUS "OpenSSL include: ${OPENSSL_INCLUDE_DIR}")
+ message(STATUS "OpenSSL lib: ${OPENSSL_LIBRARIES}")
+
+ include_directories(${OPENSSL_INCLUDE_DIR})
+
+ list(APPEND SRC_OPENSSL bufferevent_openssl.c)
+ list(APPEND HDR_PUBLIC include/event2/bufferevent_ssl.h)
+ list(APPEND LIB_APPS ${OPENSSL_LIBRARIES})
+endif()
+
+if (NOT EVENT__DISABLE_THREAD_SUPPORT)
+ if (WIN32)
+ list(APPEND SRC_CORE evthread_win32.c)
+ else()
+ find_package(Threads REQUIRED)
+ if (NOT CMAKE_USE_PTHREADS_INIT)
+ message(FATAL_ERROR
+ "Failed to find Pthreads, set EVENT__DISABLE_THREAD_SUPPORT to disable")
+ endif()
+
+ set(EVENT__HAVE_PTHREADS 1)
+ list(APPEND LIB_APPS ${CMAKE_THREAD_LIBS_INIT})
+ endif()
+endif()
+
+if (NOT EVENT__DISABLE_TESTS)
+ # Zlib is only used for testing.
+ find_package(ZLIB)
+
+ if (ZLIB_LIBRARY AND ZLIB_INCLUDE_DIR)
+ include_directories(${ZLIB_INCLUDE_DIRS})
+
+ set(EVENT__HAVE_LIBZ 1)
+ list(APPEND LIB_APPS ${ZLIB_LIBRARIES})
+ endif()
+endif()
+
+set(SRC_EXTRA
+ event_tagging.c
+ http.c
+ evdns.c
+ evrpc.c)
+
+add_definitions(-DHAVE_CONFIG_H)
+
+# We use BEFORE here so we don't accidentally look in system directories
+# first for some previous versions of the headers that are installed.
+include_directories(BEFORE ${PROJECT_SOURCE_DIR}
+ ${PROJECT_SOURCE_DIR}/compat
+ ${PROJECT_SOURCE_DIR}/include)
+
+if(WIN32)
+ list(APPEND SRC_CORE
+ buffer_iocp.c
+ bufferevent_async.c
+ event_iocp.c
+ win32select.c)
+
+ list(APPEND HDR_PRIVATE WIN32-Code/getopt.h)
+
+ set(EVENT__DNS_USE_FTIME_FOR_ID 1)
+ set(LIB_PLATFORM ws2_32 shell32 advapi32)
+ add_definitions(
+ -D_CRT_SECURE_NO_WARNINGS
+ -D_CRT_NONSTDC_NO_DEPRECATE)
+
+ include_directories(./WIN32-Code)
+endif()
+
+if (SOLARIS)
+ list(APPEND LIB_PLATFORM socket nsl)
+endif()
+
+source_group("Headers Private" FILES ${HDR_PRIVATE})
+source_group("Header Compat" FILES ${HDR_COMPAT})
+source_group("Headers Public" FILES ${HDR_PUBLIC})
+source_group("Source Core" FILES ${SRC_CORE})
+source_group("Source Extra" FILES ${SRC_EXTRA})
+
+# Generate the configure headers.
+# (Place them in the build dir so we don't polute the source tree with generated files).
+include_directories(BEFORE ${CMAKE_CURRENT_BINARY_DIR}/include)
+
+if (${GNUC})
+ set(EVENT_SHARED_FLAGS -fvisibility=hidden)
+elseif ("${CMAKE_C_COMPILER_ID}" STREQUAL "SunPro")
+ set(EVENT_SHARED_FLAGS -xldscope=hidden)
+endif()
+
+configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/event-config.h.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/include/event2/event-config.h
+ NEWLINE_STYLE UNIX)
+
+configure_file(
+ ${CMAKE_CURRENT_SOURCE_DIR}/evconfig-private.h.cmake
+ ${CMAKE_CURRENT_BINARY_DIR}/include/evconfig-private.h)
+
+#
+# Create the libraries.
+#
+include(AddEventLibrary)
+add_event_library(event_core SOURCES ${SRC_CORE})
+add_event_library(event_extra
+ INNER_LIBRARIES event_core
+ SOURCES ${SRC_EXTRA})
+
+if (NOT EVENT__DISABLE_OPENSSL)
+ add_event_library(event_openssl
+ INNER_LIBRARIES event_core
+ OUTER_INCLUDES ${OPENSSL_INCLUDE_DIR}
+ LIBRARIES ${OPENSSL_LIBRARIES}
+ SOURCES ${SRC_OPENSSL})
+endif()
+
+if (EVENT__HAVE_PTHREADS)
+ set(SRC_PTHREADS evthread_pthread.c)
+ add_event_library(event_pthreads
+ INNER_LIBRARIES event_core
+ SOURCES ${SRC_PTHREADS})
+endif()
+
+# library exists for historical reasons; it contains the contents of
+# both libevent_core and libevent_extra. You shouldn’t use it; it may
+# go away in a future version of Libevent.
+add_event_library(event SOURCES ${SRC_CORE} ${SRC_EXTRA})
+
+set(WIN32_GETOPT)
+if (WIN32)
+ set(_TMPLIBS)
+ if (${EVENT_LIBRARY_STATIC})
+ list(APPEND _TMPLIBS event_core_static event_static)
+ endif()
+ if (${EVENT_LIBRARY_SHARED})
+ list(APPEND _TMPLIBS event_core_shared event_shared)
+ endif()
+ foreach(lib ${_TMPLIBS})
+ target_link_libraries(${lib} iphlpapi)
+ endforeach()
+ unset(_TMPLIBS)
+
+ list(APPEND WIN32_GETOPT
+ WIN32-Code/getopt.c
+ WIN32-Code/getopt_long.c)
+endif()
+
+#
+# Samples.
+#
+macro(add_sample_prog ssl name)
+ add_executable(${name} ${ARGN})
+
+ target_link_libraries(${name}
+ event_extra
+ event_core
+ ${LIB_APPS}
+ ${LIB_PLATFORM})
+
+ if (${ssl})
+ target_link_libraries(${name} event_openssl)
+ if(WIN32)
+ target_link_libraries(${name} crypt32)
+ endif()
+ endif()
+endmacro()
+if (NOT EVENT__DISABLE_SAMPLES)
+ set(SAMPLES
+ event-read-fifo
+ hello-world
+ signal-test
+ http-connect
+ time-test)
+
+ foreach(SAMPLE ${SAMPLES})
+ add_sample_prog(OFF ${SAMPLE} sample/${SAMPLE}.c)
+ endforeach()
+
+ if (NOT EVENT__DISABLE_OPENSSL)
+ add_sample_prog(ON https-client
+ sample/https-client.c
+ sample/openssl_hostname_validation.c
+ sample/hostcheck.c)
+ add_sample_prog(ON le-proxy
+ sample/le-proxy.c)
+ endif()
+
+ set(SAMPLES_WOPT
+ dns-example
+ http-server
+ )
+ foreach (SAMPLE ${SAMPLES_WOPT})
+ add_sample_prog(OFF ${SAMPLE} sample/${SAMPLE}.c ${WIN32_GETOPT})
+ endforeach()
+endif()
+
+#
+# Benchmarks
+#
+macro(add_bench_prog prog)
+ add_executable(${prog} ${ARGN})
+ target_link_libraries(${prog}
+ event_extra
+ event_core
+ ${LIB_APPS}
+ ${LIB_PLATFORM})
+endmacro()
+if (NOT EVENT__DISABLE_BENCHMARK)
+ foreach (BENCHMARK bench_http bench_httpclient)
+ add_bench_prog(${BENCHMARK} test/${BENCHMARK}.c)
+ endforeach()
+
+ add_bench_prog(bench test/bench.c ${WIN32_GETOPT})
+ add_bench_prog(bench_cascade test/bench_cascade.c ${WIN32_GETOPT})
+endif()
+
+#
+# Tests
+#
+macro(add_test_prog prog)
+ add_executable(${prog} test/${prog}.c)
+ target_link_libraries(${prog}
+ ${LIB_APPS}
+ ${LIB_PLATFORM}
+ event_core
+ event_extra
+ ${ARGN})
+endmacro()
+if (NOT EVENT__DISABLE_TESTS)
+ #
+ # Generate Regress tests.
+ #
+ if (NOT EVENT__DISABLE_REGRESS)
+ # (We require python to generate the regress tests)
+ find_package(PythonInterp 3)
+
+ if (PYTHONINTERP_FOUND)
+ set(__FOUND_USABLE_PYTHON 1)
+ else()
+ find_package(PythonInterp 2)
+ if (PYTHONINTERP_FOUND)
+ set(__FOUND_USABLE_PYTHON 1)
+ else()
+ message(ERROR "No suitable Python version found, bailing...")
+ endif()
+ endif()
+
+ if (__FOUND_USABLE_PYTHON)
+ message(STATUS "Generating regress tests...")
+
+ add_definitions(-DTINYTEST_LOCAL)
+
+ add_custom_command(
+ OUTPUT
+ ${CMAKE_CURRENT_SOURCE_DIR}/test/regress.gen.c
+ ${CMAKE_CURRENT_SOURCE_DIR}/test/regress.gen.h
+ DEPENDS
+ event_rpcgen.py
+ test/regress.rpc
+ COMMAND ${PYTHON_EXECUTABLE} ../event_rpcgen.py --quiet regress.rpc
+ WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/test)
+
+ list(APPEND SRC_REGRESS
+ test/regress.c
+ test/regress.gen.c
+ test/regress.gen.h
+ test/regress_buffer.c
+ test/regress_bufferevent.c
+ test/regress_dns.c
+ test/regress_et.c
+ test/regress_finalize.c
+ test/regress_http.c
+ test/regress_listener.c
+ test/regress_main.c
+ test/regress_minheap.c
+ test/regress_rpc.c
+ test/regress_testutils.c
+ test/regress_testutils.h
+ test/regress_util.c
+ test/tinytest.c)
+
+ if (WIN32)
+ list(APPEND SRC_REGRESS test/regress_iocp.c)
+ if (NOT EVENT__DISABLE_THREAD_SUPPORT)
+ list(APPEND SRC_REGRESS test/regress_thread.c)
+ endif()
+ elseif (EVENT__HAVE_PTHREADS)
+ list(APPEND SRC_REGRESS test/regress_thread.c)
+ endif()
+
+ if (ZLIB_LIBRARY AND ZLIB_INCLUDE_DIR)
+ list(APPEND SRC_REGRESS test/regress_zlib.c)
+ endif()
+
+ if (NOT EVENT__DISABLE_OPENSSL)
+ list(APPEND SRC_REGRESS test/regress_ssl.c)
+ endif()
+
+ add_executable(regress ${SRC_REGRESS})
+
+ target_link_libraries(regress
+ ${LIB_APPS}
+ ${LIB_PLATFORM}
+ event_core
+ event_extra)
+ if (NOT EVENT__DISABLE_OPENSSL)
+ target_link_libraries(regress event_openssl)
+ endif()
+ if (CMAKE_USE_PTHREADS_INIT)
+ target_link_libraries(regress event_pthreads)
+ endif()
+ else()
+ message(WARNING "No suitable Python interpreter found, cannot generate regress tests!")
+ endif()
+ endif()
+
+ #
+ # Test programs.
+ #
+ # all of these, including the cmakelists.txt should be moved
+ # into the dirctory 'tests' first.
+ #
+ # doing this, we can remove all the DISABLE_TESTS stuff, and simply
+ # do something like:
+ #
+ # add_custom_targets(tests)
+ # add_executable(... EXCLUDE_FROM_ALL ...c)
+ # add_dependencis(tests testa testb testc)
+ # add_test(....)
+ #
+ # then you can just run 'make tests' instead of them all
+ # auto-compile|running
+ # - ellzey
+ set(TESTPROGS test-changelist
+ test-eof
+ test-closed
+ test-fdleak
+ test-init
+ test-time
+ test-weof)
+
+ foreach (TESTPROG ${TESTPROGS} test-dumpevents)
+ add_test_prog(${TESTPROG})
+ endforeach()
+ if (UNIX)
+ add_test_prog(test-ratelim m)
+ else()
+ add_test_prog(test-ratelim)
+ endif()
+
+ set(ALL_TESTPROGS
+ ${TESTPROGS}
+ test-dumpevents
+ test-ratelim
+ )
+
+ #
+ # We run all tests with the different backends turned on one at a time.
+ #
+
+ # Add event backends based on system introspection result.
+ set(BACKENDS "")
+
+ if (EVENT__HAVE_EPOLL)
+ list(APPEND BACKENDS EPOLL)
+ endif()
+
+ if (EVENT__HAVE_SELECT)
+ list(APPEND BACKENDS SELECT)
+ endif()
+
+ if (EVENT__HAVE_POLL)
+ list(APPEND BACKENDS POLL)
+ endif()
+
+ if (EVENT__HAVE_KQUEUE)
+ list(APPEND BACKENDS KQUEUE)
+ endif()
+
+ if (EVENT__HAVE_EVENT_PORTS)
+ list(APPEND BACKENDS EVPORT)
+ endif()
+
+ if (EVENT__HAVE_DEVPOLL)
+ list(APPEND BACKENDS DEVPOLL)
+ endif()
+
+ if (WIN32)
+ list(APPEND BACKENDS WIN32)
+ endif()
+
+
+ # Default environment variables turns off all event systems,
+ # then we enable each one, one at a time when creating the tests.
+ set(DEFAULT_TEST_ENV_VARS)
+ foreach(BACKEND ${BACKENDS})
+ set(BACKEND_ENV_VAR "EVENT_NO${BACKEND}=1")
+ list(APPEND DEFAULT_TEST_ENV_VARS "${BACKEND_ENV_VAR}")
+ endforeach()
+
+ # Macro that creates the ctest test for a backend.
+ macro(add_backend_test BACKEND_TEST_NAME ENV_VARS)
+ set(TEST_NAMES "")
+
+ foreach (TESTPROG ${TESTPROGS})
+ set(TEST_NAME ${TESTPROG}__${BACKEND_TEST_NAME})
+
+ add_test(${TEST_NAME}
+ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${TESTPROG})
+
+ list(APPEND TEST_NAMES ${TEST_NAME})
+
+ set_tests_properties(${TEST_NAME}
+ PROPERTIES ENVIRONMENT "${ENV_VARS}")
+ endforeach()
+
+ # Dump events test.
+ if (__FOUND_USABLE_PYTHON)
+ set(TEST_NAME test-dumpevents__${BACKEND_TEST_NAME})
+
+ add_test(${TEST_NAME}
+ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test-dumpevents |
+ ${PYTHON_EXECUTABLE}
+ ${CMAKE_CURRENT_SOURCE_DIR}/test/check-dumpevents.py)
+
+ set_tests_properties(${TEST_NAME}
+ PROPERTIES ENVIRONMENT "${ENV_VARS}")
+ else()
+ message(WARNING "test-dumpevents will be run without output check since python was not found!")
+ set(TEST_NAME test-dumpevents__${BACKEND_TEST_NAME}_no_check)
+
+ add_test(${TEST_NAME}
+ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test-dumpevents)
+
+ set_tests_properties(${TEST_NAME}
+ PROPERTIES ENVIRONMENT "${ENV_VARS}")
+ endif()
+
+ # Regress tests.
+ if (NOT EVENT__DISABLE_REGRESS AND __FOUND_USABLE_PYTHON)
+ set(TEST_NAME regress__${BACKEND_TEST_NAME})
+
+ add_test(${TEST_NAME}
+ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/regress --quiet)
+
+ set_tests_properties(${TEST_NAME}
+ PROPERTIES ENVIRONMENT "${ENV_VARS}")
+
+ add_test(${TEST_NAME}_debug
+ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/regress --quiet)
+
+ set_tests_properties(${TEST_NAME}_debug
+ PROPERTIES ENVIRONMENT "${ENV_VARS};EVENT_DEBUG_MODE=1")
+ endif()
+ endmacro()
+
+ # Add the tests for each backend.
+ foreach(BACKEND ${BACKENDS})
+ # Enable this backend only.
+ set(BACKEND_ENV_VARS ${DEFAULT_TEST_ENV_VARS})
+ list(REMOVE_ITEM BACKEND_ENV_VARS EVENT_NO${BACKEND}=1)
+
+ # Epoll has some extra settings.
+ if (${BACKEND} STREQUAL "EPOLL")
+ add_backend_test(timerfd_${BACKEND}
+ "${BACKEND_ENV_VARS};EVENT_PRECISE_TIMER=1")
+
+ add_backend_test(changelist_${BACKEND}
+ "${BACKEND_ENV_VARS};EVENT_EPOLL_USE_CHANGELIST=yes")
+
+ add_backend_test(timerfd_changelist_${BACKEND}
+ "${BACKEND_ENV_VARS};EVENT_EPOLL_USE_CHANGELIST=yes;EVENT_PRECISE_TIMER=1")
+ else()
+ add_backend_test(${BACKEND} "${BACKEND_ENV_VARS}")
+ endif()
+ endforeach()
+
+ #
+ # Rate limiter tests.
+ #
+
+ # Group limits, no connection limit.
+ set(RL_BIN ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test-ratelim)
+
+ add_test(test-ratelim__group_lim
+ ${RL_BIN}
+ -g 30000
+ -n 30
+ -t 100
+ --check-grouplimit 1000
+ --check-stddev 100)
+
+ # Connection limit, no group limit.
+ add_test(test-ratelim__con_lim
+ ${RL_BIN}
+ -c 1000
+ -n 30
+ -t 100
+ --check-connlimit 50
+ --check-stddev 50)
+
+ # Connection limit and group limit.
+ add_test(test-ratelim__group_con_lim
+ ${RL_BIN}
+ -c 1000
+ -g 30000
+ -n 30
+ -t 100
+ --check-grouplimit 1000
+ --check-connlimit 50
+ --check-stddev 50)
+
+ # Connection limit and group limit with independent drain.
+ add_test(test-ratelim__group_con_lim_drain
+ ${RL_BIN}
+ -c 1000
+ -g 35000
+ -n 30
+ -t 100
+ -G 500
+ --check-grouplimit 1000
+ --check-connlimit 50
+ --check-stddev 50)
+
+ # Add a "make verify" target, same as for autoconf.
+ # (Important! This will unset all EVENT_NO* environment variables.
+ # If they are set in the shell the tests are running using simply "ctest" or "make test" will fail)
+ if (WIN32)
+ # Windows doesn't have "unset". But you can use "set VAR=" instead.
+ # We need to guard against the possibility taht EVENT_NOWIN32 is set, and all test failing
+ # since no event backend being available.
+ file(TO_NATIVE_PATH ${CMAKE_CTEST_COMMAND} WINDOWS_CTEST_COMMAND)
+
+ file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/verify_tests.bat
+ "
+ set EVENT_NOWIN32=
+ \"${WINDOWS_CTEST_COMMAND}\"
+ ")
+
+ message(STATUS "${WINDOWS_CTEST_COMMAND}")
+
+ file(COPY ${CMAKE_CURRENT_BINARY_DIR}/tmp/verify_tests.bat
+ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
+ FILE_PERMISSIONS
+ OWNER_READ
+ OWNER_WRITE
+ OWNER_EXECUTE
+ GROUP_READ
+ GROUP_EXECUTE
+ WORLD_READ WORLD_EXECUTE)
+
+ file(TO_NATIVE_PATH
+ "${CMAKE_CURRENT_BINARY_DIR}/verify_tests.bat" VERIFY_PATH)
+
+ add_custom_target(verify COMMAND "${VERIFY_PATH}"
+ DEPENDS event ${ALL_TESTPROGS})
+ else()
+ # On some platforms doing exec(unset) as CMake does won't work, so make sure
+ # we run the unset command in a shell instead.
+ # First we write the script contents.
+ file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/tmp/verify_tests.sh
+ "
+ #!/bin/bash
+ unset EVENT_NOEPOLL; unset EVENT_NOPOLL; unset EVENT_NOSELECT; unset EVENT_NOWIN32; unset EVENT_NOEVPORT; unset EVENT_NOKQUEUE; unset EVENT_NODEVPOLL
+ ${CMAKE_CTEST_COMMAND}
+ ")
+
+ # Then we copy the file (this allows us to set execute permission on it)
+ file(COPY ${CMAKE_CURRENT_BINARY_DIR}/tmp/verify_tests.sh
+ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
+ FILE_PERMISSIONS
+ OWNER_READ
+ OWNER_WRITE
+ OWNER_EXECUTE
+ GROUP_READ
+ GROUP_EXECUTE
+ WORLD_READ
+ WORLD_EXECUTE)
+
+ # Create the target that runs the script.
+ add_custom_target(verify
+ COMMAND ${CMAKE_CURRENT_BINARY_DIR}/verify_tests.sh
+ DEPENDS event ${ALL_TESTPROGS})
+ endif()
+
+ if (NOT EVENT__DISABLE_REGRESS AND __FOUND_USABLE_PYTHON)
+ add_dependencies(verify regress)
+ endif()
+
+ if (EVENT__COVERAGE)
+ include(CodeCoverage)
+
+ setup_target_for_coverage(
+ verify_coverage # Coverage target name "make verify_coverage"
+ make # Test runner.
+ coverage # Output directory.
+ verify) # Arguments passed to test runner. "make verify"
+ endif()
+
+ enable_testing()
+
+ include(CTest)
+endif()
+
+#
+# Installation preparation.
+#
+
+set(EVENT_INSTALL_CMAKE_DIR
+ "${CMAKE_INSTALL_PREFIX}/lib/cmake/libevent")
+
+export(PACKAGE libevent)
+
+function(gen_package_config forinstall)
+ if(${forinstall})
+ set(CONFIG_FOR_INSTALL_TREE 1)
+ set(dir "${PROJECT_BINARY_DIR}${CMAKE_FILES_DIRECTORY}")
+ else()
+ set(CONFIG_FOR_INSTALL_TREE 0)
+ set(dir "${PROJECT_BINARY_DIR}")
+ endif()
+ configure_file(${PROJECT_SOURCE_DIR}/cmake/LibeventConfig.cmake.in
+ "${dir}/LibeventConfig.cmake"
+ @ONLY)
+endfunction()
+
+# Generate the config file for the build-tree.
+set(EVENT__INCLUDE_DIRS
+ "${PROJECT_SOURCE_DIR}/include"
+ "${PROJECT_BINARY_DIR}/include")
+
+set(LIBEVENT_INCLUDE_DIRS
+ ${EVENT__INCLUDE_DIRS}
+ CACHE PATH "Libevent include directories")
+
+gen_package_config(0)
+
+# Generate the config file for the installation tree.
+gen_package_config(1)
+
+# Generate version info for both build-tree and install-tree.
+configure_file(${PROJECT_SOURCE_DIR}/cmake/LibeventConfigVersion.cmake.in
+ ${PROJECT_BINARY_DIR}/LibeventConfigVersion.cmake
+ @ONLY)
+
+# Install compat headers
+install(FILES ${HDR_COMPAT}
+ DESTINATION "include"
+ COMPONENT dev)
+
+# Install public headers
+install(FILES ${HDR_PUBLIC}
+ DESTINATION "include/event2"
+ COMPONENT dev)
+
+# Install the configs.
+install(FILES
+ ${PROJECT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/LibeventConfig.cmake
+ ${PROJECT_BINARY_DIR}/LibeventConfigVersion.cmake
+ DESTINATION "${EVENT_INSTALL_CMAKE_DIR}"
+ COMPONENT dev)
+
+# Install exports for the install-tree.
+macro(install_export type)
+ install(EXPORT LibeventTargets-${type}
+ NAMESPACE ${PROJECT_NAME}::
+ DESTINATION "${EVENT_INSTALL_CMAKE_DIR}"
+ COMPONENT dev)
+endmacro()
+
+if (${EVENT_LIBRARY_STATIC})
+ install_export(static)
+endif()
+if (${EVENT_LIBRARY_SHARED})
+ install_export(shared)
+endif()
+
+# Install the scripts.
+install(PROGRAMS
+ ${CMAKE_CURRENT_SOURCE_DIR}/event_rpcgen.py
+ DESTINATION "bin"
+ COMPONENT runtime)
+
+# Create documents with doxygen.
+option(EVENT__DOXYGEN
+ "Enables doxygen documentation" OFF)
+if (EVENT__DOXYGEN)
+ include(UseDoxygen)
+ UseDoxygen()
+endif()
+
+
+if (NOT TARGET uninstall)
+ # Create the uninstall target.
+ # https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake
+ configure_file(${PROJECT_SOURCE_DIR}/cmake/Uninstall.cmake.in
+ ${PROJECT_BINARY_DIR}/Uninstall.cmake
+ @ONLY)
+
+ add_custom_target(uninstall
+ COMMAND ${CMAKE_COMMAND} -P ${PROJECT_BINARY_DIR}/Uninstall.cmake)
+endif()
+
+message(STATUS "")
+message(STATUS " ---( Libevent " ${EVENT_VERSION} " )---")
+message(STATUS "")
+message(STATUS "Available event backends: ${BACKENDS}")
+message(STATUS "CMAKE_BINARY_DIR: ${CMAKE_BINARY_DIR}")
+message(STATUS "CMAKE_CURRENT_BINARY_DIR: ${CMAKE_CURRENT_BINARY_DIR}")
+message(STATUS "CMAKE_SOURCE_DIR: ${CMAKE_SOURCE_DIR}")
+message(STATUS "CMAKE_CURRENT_SOURCE_DIR: ${CMAKE_CURRENT_SOURCE_DIR}")
+message(STATUS "PROJECT_BINARY_DIR: ${PROJECT_BINARY_DIR}")
+message(STATUS "PROJECT_SOURCE_DIR: ${PROJECT_SOURCE_DIR}")
+message(STATUS "CMAKE_MODULE_PATH: ${CMAKE_MODULE_PATH}")
+message(STATUS "CMAKE_COMMAND: ${CMAKE_COMMAND}")
+message(STATUS "CMAKE_ROOT: ${CMAKE_ROOT}")
+message(STATUS "CMAKE_SYSTEM: ${CMAKE_SYSTEM}")
+message(STATUS "CMAKE_SYSTEM_NAME: ${CMAKE_SYSTEM_NAME}")
+message(STATUS "CMAKE_SYSTEM_VERSION: ${CMAKE_SYSTEM_VERSION}")
+message(STATUS "CMAKE_SYSTEM_PROCESSOR: ${CMAKE_SYSTEM_PROCESSOR}")
+message(STATUS "CMAKE_SKIP_RPATH: ${CMAKE_SKIP_RPATH}")
+message(STATUS "CMAKE_VERBOSE_MAKEFILE: ${CMAKE_VERBOSE_MAKEFILE}")
+message(STATUS "CMAKE_C_FLAGS: ${CMAKE_C_FLAGS}")
+message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}")
+message(STATUS "CMAKE_C_COMPILER: ${CMAKE_C_COMPILER} (id ${CMAKE_C_COMPILER_ID}, clang ${CLANG}, GNUC ${GNUC})")
+message(STATUS "CMAKE_AR: ${CMAKE_AR}")
+message(STATUS "CMAKE_RANLIB: ${CMAKE_RANLIB}")
+message(STATUS "")
+
diff --git a/ipc/chromium/src/third_party/libevent/CONTRIBUTING.md b/ipc/chromium/src/third_party/libevent/CONTRIBUTING.md
new file mode 100644
index 0000000000..3875693978
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/CONTRIBUTING.md
@@ -0,0 +1,35 @@
+# Contributing to the libevent
+
+## Coding style
+
+First and most generic rule: **just look around**.
+
+But, we have a script for checking patches/files/git-refs:
+```shell
+# Chech HEAD git ref
+./checkpatch.sh -r
+./checkpatch.sh -r HEAD
+
+# Check patch
+git format-patch --stdout -1 | ./checkpatch.sh -p
+git show -1 | ./checkpatch.sh -p
+
+# Or via regular files
+git format-patch --stdout -2
+./checkpatch.sh *.patch
+
+# Over a file
+./checkpatch.sh -d event.c
+./checkpatch.sh -d < event.c
+
+# And print the whole file not only summary
+./checkpatch.sh -f event.c
+./checkpatch.sh -f < event.c
+
+# See
+./checkpatch.sh -h
+```
+
+## Testing
+- Write new unit test in `test/regress_{MORE_SUITABLE_FOR_YOU}.c`
+- `make verify`
diff --git a/ipc/chromium/src/third_party/libevent/ChangeLog b/ipc/chromium/src/third_party/libevent/ChangeLog
new file mode 100644
index 0000000000..17874b14b9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ChangeLog
@@ -0,0 +1,2162 @@
+Changes in version 2.1.12-stable (05 Jul 2020)
+
+ This release contains mostly bug fixes (I decided not to port some features
+ that can be ported even without ABI breakage, if you cannot find feature that
+ you are interested in, please give us a note!)
+
+ Since 2.1.12 libevent will use github actions as main CI, since
+ it recommends itself better then travis/appveyor (and had been removed from
+ upstream).
+
+ Look carefully at "slightly touches the behaviour" section.
+
+ Below you will find some of changes (this list has been cleaned up from the
+ patches that touches only tests and similar):
+
+ CI:
+ o Backport github actions to 2.1 (be3acd7c Azat Khuzhin)
+ o Merge branch 'event_rpcgen.py-cleanup' (f0ded5f3, 48e04887 Enji Cooper)
+ o Add API/ABI checker (using LVC) (709210d4, 2af1f6cc yuangongji)
+
+ test:
+ o tinytest: support timeout on Windows (794e8f75 yuangongji)
+ o Merge branch 'osx-clock' (e85afbe3 Azat Khuzhin)
+ o test-ratelim: calculate timers bias (for slow CPUs) to avoid false-positive (8ad26d0b Azat Khuzhin)
+
+ fixes:
+ o buffer: do not pass NULL to memcpy() from evbuffer_pullup() (5b063049 Azat Khuzhin)
+ o http: fix undefined-shift in EVUTIL_IS*_ helpers (6b8d02a7 Azat Khuzhin)
+ o Check error code of evhttp_add_header_internal() in evhttp_parse_query_impl() (97e28f09 Azat Khuzhin)
+ o http: fix EVHTTP_CON_AUTOFREE in case of timeout (and some else) (1be25938 Azat Khuzhin)
+ o evdns: Add additional validation for values of dns options (c2972453 ayuseleznev)
+ o There is typo in GetAdaptersAddresses windows library. It should be iphlpapi.dll (891adda9 Aleksandr-Melnikov)
+ o Merge branch 'EV_CLOSED-and-EV_ET-fixes' (db2efdf5 Azat Khuzhin)
+ o Fix memory corruption in EV_CLOSURE_EVENT_FINALIZE with debug enabled (8ccd8f56 Jan Kasiak)
+ o increase segment refcnt only if evbuffer_add_file_segment() succeeds (30662a3c yuangongji)
+ o evdns: fix a crash when evdns_base with waiting requests is freed (6f8e0e97 ayuseleznev)
+ o event_base_once: fix potential null pointer threat (2e9ceb16 chenguolong)
+ o http: do not assume body for CONNECT (1b42270b Azat Khuzhin)
+ o evbuffer_add_file: fix freeing of segment in the error path (5f017bde Azat Khuzhin)
+ o Fix checking return value of the evdns_base_resolv_conf_parse() (fc51bf2c Azat Khuzhin)
+ o Merge branch 'fix-signal-leak' (poll/select now needs reinit) (1c9cc07b Azat Khuzhin)
+
+ improvements:
+ o evutil_time: improve evutil_gettimeofday on Windows (a8219143 Nick Grifka)
+ o Support EV_CLOSED on linux for poll(2) (2530e7c6 Azat Khuzhin)
+ o Parse IPv6 scope IDs. (f602211f Philip Homburg)
+ o evutil_time: Implements usleep() using wait funtion on Windows (d42240d1 yuangongji)
+ o evutil_time: detect and use _gmtime64_s()/_gmtime64() (f4a6152c yuangongji)
+
+ slightly touches the behaviour:
+ o bufferevent: allow setting priority on socket and openssl type (4dd3acdd Nicolas J. Bouliane)
+ o Fix EV_CLOSED detection/reporting (epoll only) (1df324d4 Azat Khuzhin) (XXX)
+ o Revert "Warn if forked from the event loop during event_reinit()" (71f5c0d3 Azat Khuzhin)
+
+ samples:
+ o https-client: load certificates from the system cert store on Windows (e9478640 yuangongji)
+
+ build fixes:
+ o Do not use sysctl.h on linux (it had been deprecated) (d2871a37 Azat Khuzhin)
+ o cmake: avoid problems from use of CMAKE_USE_PTHREADS_INIT (a62ec765 Paul Osborne)
+ o Update list of cmake files for autotools dist archive (2016f017 Azat Khuzhin)
+ o LibeventConfig.cmake: restore CMAKE_FIND_LIBRARY_SUFFIXES and LIBEVENT_STATIC_LINK default (640f9cf6 Mario Emmenlauer)
+ o cmake: fix getaddrinfo checking error (dea51c2e yuangongji)
+ o autoconf: fix getaddrinfo checking errors on mingw (b9bf7fa7 yuangongji)
+ o Do not use shared global structures on CYGWIN (8a9b5655 Azat Khuzhin)
+ o Added uninstall target check to cmakelists (3f1fb1f9 Dimo Markov)
+ o Fix compilation without OPENSSL_API_COMPAT (921bdcdd Azat Khuzhin)
+ o cmake: improve package config file (1c047618, baec84f2 yuangongji)
+ o Link with iphlpapi only on windows (976f7d34 Azat Khuzhin)
+ o autotools: fails build when need but can not find openssl (93174bb5 yuangongji)
+ o Merge branch 'http-connect' (e2424229 Azat Khuzhin)
+ o Fix compat with NetBSD >= 10 (5febb4e1 Kamil Rytarowski)
+ o cmake: fix getrandom() detection (e0e5f3bd Azat Khuzhin)
+ o arc4random: replace sysctl() with getrandom (on linux) (66ec78fd Azat Khuzhin)
+ o Upgrade autoconf (after upgrading minimum required to 2.67) (45da7d9d yuangongji)
+ o eliminate some C4267 warnings in Windows (9e468c77 yuangongji)
+ o autotools: attach doxygen target into all target (5d1e8570 yuangongji)
+ o cmake: attach doxygen target into all target (7a85300a yuangongji)
+ o Change the minimum version of automake to 1.13 and autoconf to 2.67 (fdb8fb66 ygj6)
+ o Add Uninstall.cmake.in into dist archive (877f2355 Azat Khuzhin)
+
+Changes in version 2.1.11-stable (01 Aug 2019)
+
+ This release contains one ABI breakage fix (that had been introduced in
+ 2.1.10, and strictly speaking this release breaks ABI again to make it
+ compatible with 2.1.9 and less, please take a look at 18104973 for more
+ details). Apart from that it contains some bug fixes, that grouped below.
+
+ And even though the return value for evbuffer_setcb() had been changed it
+ should ABI compatible (anyway that function is in -compat.h header).
+
+ There is also one patch that introduce new functionality, this is 546a366c,
+ to tune SO_RCVBUF/SO_SNDBUF in evdns, but one can count it as a bug-fix on
+ the application level, since before you cannot tune this settings and hence
+ you could stumble on problems.
+
+ ABI breakage:
+ o Protect min_heap_push_ against integer overflow. (8c899768 Tobias Stoeckmann)
+ o Revert "Protect min_heap_push_ against integer overflow." (18104973 Azat Khuzhin)
+
+ functionality:
+ o evdns: add new options -- so-rcvbuf/so-sndbuf (546a366c Azat Khuzhin)
+
+ build:
+ o Change autoconf version to 2.62 and automake version to 1.11.2 (2a333008 yuangongji)
+ o cmake: install shared library only if it was requested (596855f7 Azat Khuzhin)
+ o Missing <winerror.h> on win7/MinGW(MINGW32_NT-6.1)/MSYS (9559349c yuangongji)
+ o cmake: set library names to be the same as with autotools (305251b9 yuangongji)
+ o Enable _GNU_SOURCE for Android (f013fc7d Keith Smiley)
+ o Enable kqueue for APPLE targets (3aa68a82 Keith Smiley)
+ o autotools: do not install bufferevent_ssl.h under --disable-openssl (5349a07e Azat Khuzhin)
+ o cmake: link against shell32.lib/advapi32.lib (c9ce638c Azat Khuzhin)
+ o Add README.md into dist archive (3660a4cc Azat Khuzhin)
+ o cmake: add missing autotools targets (doxygen, uninstall, event_rpcgen.py) (2d65071c yuangongji)
+ o m4/libevent_openssl.m4: fix detection of openssl (d4056e59 Fabrice Fontaine)
+ o Fix detection of the __has_attribute() for apple clang [ci skip] (7fd7c5ef Azat Khuzhin)
+
+ lib:
+ o buffer: fix possible NULL dereference in evbuffer_setcb() on ENOMEM (598f247d Azat Khuzhin)
+ o Warn if forked from the event loop during event_reinit() (b75922ae Azat Khuzhin)
+ o evutil: set the have_checked_interfaces in evutil_check_interfaces()
+ (ef498aa2, a09265ac jeremyerb)
+
+ samples:
+ o https-client: correction error checking (a8a04565 wenyg)
+
+
+Changes in version 2.1.10-stable (26 May 2019)
+
+ This release contains mostly fixes (some evbuffer oddity, AF_UNIX handling in
+ http server, some UB fixes and others) but also some new functionality
+ (without ABI breakage as usual) and now dist archive can be used for building
+ on windows (getopt had been added into it).
+
+ Above you will find changelog for this particular release (but with some
+ trivial fixes pruned out from it - to make it a little bit more informative).
+
+ To view full changelog please use git:
+ git log --format=' o %s (%h %aN)' release-2.1.9-beta...release-2.1.10-stable
+
+ dist:
+ o Add getopt into dist archive (7042ff24 Azat Khuzhin)
+
+ functionality:
+ o evdns: add DNS_OPTION_NAMESERVERS_NO_DEFAULT/EVDNS_BASE_NAMESERVERS_NO_DEFAULT
+ (58e81106 Azat Khuzhin)
+ o Add support for EV_TIMEOUT to event_base_active_by_fd (3f893f0a John Ohl)
+
+ fixes:
+ o Merge branch 'evbuffer-fixes-806-v2' (2fea04b3 Azat Khuzhin)
+ o Merge branch 'issue-807-accept4-getnameinfo-AF_UNIX' (7c4da937, e2790a7f
+ Azat Khuzhin)
+ o kqueue: Avoid undefined behaviour. (e70e18e9 Tobias Stoeckmann)
+ o Prevent integer overflow in kq_build_changes_list. (43a55a23 Tobias Stoeckmann)
+ o evdns: fix lock/unlock mismatch in evdns_close_server_port() (54103883 zhuizhuhaomeng)
+ o Merge remote-tracking branch 'official/pr/804' -- Enforce limit of NSIG
+ signals (87fa93a8 Tobias Stoeckmann)
+ o Protect min_heap_push_ against integer overflow. (0b46bb8c Tobias Stoeckmann)
+ o le-proxy: initiate use of the Winsock DLL (2a1e1530 linxiaohui)
+ o Fix leaks in error path of the bufferevent_init_common_() (bb0f8fe7 Azat Khuzhin)
+ o buffer: make evbuffer_prepend() of zero-length array no-op (61fa7b7d Azat Khuzhin)
+ o Merge branch 'evbuffer-empty-chain-handling' (6a3dd717 Azat Khuzhin)
+ o Don't loose top error in SSL (3d1a7a1d Yury Korzhetsky)
+ o Remove needless check for arc4_seeded_ok (6602a97d Seong-Joong Kim)
+ o Merge pull request #769 from sungjungk/fix-return-handling (91084140 Nathan French)
+
+ build:
+ o Define `_GNU_SOURCE` properly/consistently per autoconf (00ba9fa2 Enji Cooper)
+ o signal: guard __cdecl definition with #ifdef (d89045a6 Azat Khuzhin)
+ o Link test/regress with event_core/event_extra over event (22380996 Azat Khuzhin)
+
+ tests:
+ o Use kill() over raise() for raising the signal (fixes osx 10.14 with
+ kqueue) (3db5296b, a45f6733 Azat Khuzhin)
+ o tinytest: implement per-test timeout (via alarm() under !win32 only)
+ (b64dbfb6, 75d7e1ff Azat Khuzhin)
+
+Changes in version 2.1.9-beta (10 February 2019)
+
+ This changelog will differs from other releases in the next few clauses:
+ - contains only highlighted changes (so now it will not contains a lot of
+ patches that fixes some stuff in regression tests, typos, leaks fixes in
+ samples and so forth)
+ - no authors (since merge commits breaks them anyway, but AUTHORS sections in
+ README will be kept up to date)
+ - group name trimmed from commit subjects trimmed
+ - it's been 2 years since the previoius release, so it is pretty huge
+
+ And I think that this is more useful, so from now on it will always has the
+ same look (until there will too many objections of course).
+
+ To view full changelog please use git:
+ git log --format=' o %s (%h %aN)' release-2.1.8-stable...release-2.1.9-beta
+
+
+ dist archive:
+ o Add cmake rules into dist archive (bf3a67cf)
+ o Add missing print-winsock-errors.c into dist archive (822d6462)
+ o Include openssl-compat.h into dist archive (08658136)
+
+ core:
+ o Merge branch 'check-O_NONBLOCK-in-debug' (a39898f3, a8155c62)
+ o Merge branch 'event-ET-#636-v2' (ca4b6404)
+ o Fix visibility issues under (mostly on win32)
+ (349081e1g, 802be13ag, a1f28e2f)
+ o Define __EXT_POSIX2 for QNX (a2176f2c)
+ o Cleanup __func__ detection (b3af7bdd)
+ o Add convenience macros for user-triggered events (06ec5de6)
+ o Notify event base if there are no more events, so it can exit without delay (d9d1c09e)
+ o Fix base unlocking in event_del() if event_base_set() runned in another thread (4f0f40e3)
+ o If precise_time is false, we should not set EVENT_BASE_FLAG_PRECISE_TIMER (27dee54d)
+ o Fix race in access to ev_res from event loop with event_active() (43d92a6d)
+ o Return from event_del() after the last event callback termination (876c7ac7)
+
+ http:
+ o Merge branch 'http-EVHTTP_CON_READ_ON_WRITE_ERROR-fixes-v2' (eb7b472b)
+ o Preserve socket error from listen across closesocket cleanup (2ccd00a6)
+ o fix connection retries when there more then one request for connection (d30e7bba)
+ o improve error path for bufferevent_{setfd,enable,disable}() (a8cc449e)
+ o Fix conceivable UAF of the bufferevent in evhttp_connection_free() (6ac2ec25)
+ o Merge branch 'http-request-line-parsing' (cdcfbafe)
+ o Fix evhttp_connection_get_addr() fox incomming http connections (4215c003)
+ o fix leaks in evhttp_uriencode() (123362e9)
+ o CONNECT method only takes an authority (7d1ffe64)
+ o Allow bodies for GET/DELETE/OPTIONS/CONNECT (23eb38b9)
+ o Do not crash when evhttp_send_reply_start() is called after a timeout. (826f1134)
+ o Fix crashing http server when callback do not reply in place (5b40744d, b2581380)
+ o fix handling of close_notify (ssl) in http with openssl bufferevents (7e91622b)
+
+ evrpc:
+ o use *_new_with_arg() to match function prototype (a95cc9e3)
+ o avoid NULL dereference on request is not EVHTTP_REQ_POST (e05136c7)
+
+ regression tests:
+ o Merge branch 'TT_RETRIABLE' (6ea1ec68, f9b592aa)
+
+ bufferevent:
+ o Merge branch 'iocp-fixes' (6bfac964)
+ o Merge branch 'be-wm-overrun-v2' (3f692fff)
+ o bufferevent_socket_connect{,_hostname}() missing event callback and use ret code (1dde74ef)
+ o don't fail be_null_filter if bytes are copied (b92b0792)
+ o Call underlying bev ctrl GET_FD on filtered bufferevents (ebfac517)
+
+ bufferevent_openssl/openssl:
+ o Merge branch 'ssl_bufferevent_wm_filter-fix' (30020a35)
+ o be_openssl: avoid leaking of SSL structure (e86ccfe5)
+ o Fix build with LibreSSL 2.7 (894ca48a)
+ o Add missing includes into openssl-compat.h (01bc36c1)
+ o Explicitly call SSL_clear when reseting the fd. (29b7a516)
+ o Unbreak build with LibreSSL after openssl 1.1 support added (230af9f0)
+
+ samples:
+ o Merge branch 'sample-http-server' (b6309bcc)
+ o sample/https-client: use host SSL certificate store by default (5c0132f3)
+
+ listener:
+ o ipv6only socket bind support (ba148796)
+ o Merge branch 'listener-immediate-close' (df2ed13f)
+ o Merge branch 'evconnlistener-do-not-close-client-fd' (42e851bb)
+
+ evdns:
+ o evdns: handle NULL filename explicitly (0033f5cc)
+ o Merge branch 'evdns_getaddrinfo-race-fix' (3237d697)
+ o Generating evdns_base_config_windows_nameservers docs on all platforms (3bd2ce43)
+
+ utils:
+ o Merge branch 'evutil_found_ifaddr-dev' (b07e43e6)
+ o Avoid possible SEGVs in select() (in unit tests) (8818c86c)
+ o Port `event_rpcgen.py` and `test/check-dumpevents.py` to Python 3. (532a8cc3)
+
+ buffer:
+ o Fix assert() condition in evbuffer_drain() for IOCP (d6326104)
+ o fix incorrect unlock of the buffer mutex (for deferred callbacks) (2b4d127d)
+ o Fix wrong assert in evbuffer_drain() (9f4d0dce)
+
+ cmake:
+ o fix checking of devpoll backend (like in autotools, by devpoll.h existence) (7f161902)
+ o support static runtime (MSVC) (c8b3ec17, 61fb055a)
+ o do not build both (SHARED and STATIC) for MSVC/win32 (bc7f2fd9)
+ o introduce EVENT__LIBRARY_TYPE option (eb10a738)
+ o ensure windows dll's are installed as well as lib files (29590718)
+ o Fix generation of LibeventConfig.cmake for the installation tree (7fa08c4b)
+ o fix pkgconfig generation (copy-paste typo) (cc554d87)
+ o Merge branch 'cmake-missing-bits' (9806b126)
+ o Fix detection of timerfd_create() in CMake. (e50af331)
+ o Merge branch 'cmake-configure-fixes-v2' (a0bfe2c4)
+ o Do not add epoll_sub (syscall wrappers) for epoll in cmake (cea61de6)
+ o Fix RPATH for APPLE (45b1f379)
+
+ autotools:
+ o include win32 specific headers for socklen_t detection on win32/mingw (d7579fb9)
+ o Ignore evconfig-private.h for autotools (37423849)
+ o config.h can't be prefixed unconditionally (63a054f8)
+ o Merge branch 'pull-628' (7e56c8b2)
+ o Provide Makefile variables LIBEVENT_{CFLAGS,CPPFLAGS,LDFLAGS} (2f060c5f)
+ o confirm openssl is working before using (b39ccf8e)
+ o pass $(OPENSSL_INCS) for samples (FTBFS macOS) (c2495265)
+ o Add configure check for midipix (d433201e)
+ o Fix tests with detached builds (c46ff439)
+
+ build:
+ o Fix arc4random_addrandom() detecting and fallback (regression) (303d6d77)
+ o Merge branch 'win32-fixes' (ebd12e6d)
+ o Merge branch 'fix-openssl-linking' (e7bd9e03)
+ o Merge branch 'fix-struct-linger' (8567f2f5)
+
+ CI:
+ o travis-ci/appveyor now uses fast_finish+allow_failures
+ (5e97b6e6, dd472e7d, dfb5fc167)
+ o Merge branch 'travis-ci-osx-fixes' (9f02b39c)
+ o Merge branch 'win64-fixes' (aee0fcd5)
+
+
+Changes in version 2.1.8-stable (22 January 2017)
+
+ Libevent 2.1.8-stable, it contains openssl fixes for resetting fd and using
+ bufferevent_openssl_filter_new(). vagrant fixes, some build fixes, increased
+ timeout for some tests (to reduce number of failures due to timing issues),
+ date in RFC1123 format and running tests in parallel.
+
+ There are highlighted changes above.
+
+ Build fixes:
+ o Fix _FILE_OFFSET_BITS redinition (solaris/autotools) (336f3b11 Azat Khuzhin)
+ o util-internal: fix __func__ redefinition (netbsd) (253e7fa9 Azat Khuzhin)
+ o Fix signedness differ for iov_base (solaris) (2c62062e Azat Khuzhin)
+ o evutil_time: include <unistd.h> when there is only sleep()/usleep() (3e75194c Azat Khuzhin)
+ o http: fix formatter for pritnf for req->ntoread (osx) (1cbf26f6 Azat Khuzhin)
+ Testing environment:
+ o Merge branch 'automake-tests-parallel-v4' (*includes ci bits also*) (59e217df Azat Khuzhin)
+ Vagrant env fixes:
+ o vagrant/netbsd: missing libtool (9c9be399 Azat Khuzhin)
+ o vagrant/netbsd: more reliable way of installing packages (36da6877 Azat Khuzhin)
+ o vagrant/osx: use make instead of gmake (there is no gmake) (f7c70aef Azat Khuzhin)
+ o vagrant: add centos box (ca591c5b Azat Khuzhin)
+ Tests:
+ o test/dns: replace servname since solaris does not have "http" (d6bafbbe Azat Khuzhin)
+ o test/thread: netbsd is too slow, increase timeout for conditions_simple (3c7422fc Azat Khuzhin)
+ o test/dns: run async resolving after sync one (to avoid timeouts) (07862531 Azat Khuzhin)
+ o test/http: turn off some tests that based on backlog filling (falky) (26f416c1 Azat Khuzhin)
+ Bugfixes:
+ o Merge branch 'openssl-filter-fixes-v4' (83e0f43b Azat Khuzhin)
+ o Merge branch 'date-rfc1123' (68def435,4798de6c,4545807d Azat Khuzhin)
+ o Merge branch 'be-openssl-fd-reset-fix-v2' (86fa0070,32adf434 Azat Khuzhin)
+ o Merge branch 'openssl-1.1-init-fixes-v2' (18a161f0 Azat Khuzhin)
+ o Fix incorrect MIME type (23f9a20e johnsonlee)
+ Trivial fixes:
+ Documentation updates:
+ o Update README.md (3821cca1 Breaker)
+
+
+Changes in version 2.1.7-rc (2 Novemer 2016)
+
+ Libevent 2.1.7-rc contains openssl 1.1 support, build fixes, CI improvements
+ and plus Vagrantfile for testing under multiple OS'es.
+
+
+ Continious Integration:
+ o Use coveralls.io via travis (9ac000c Azat Khuzhin)
+ o travis-ci: use container-based infrastructure (7e12e96 Azat Khuzhin)
+ o travis-ci/osx: fix compiling/linking openssl libraries (9d2f8d4 Azat Khuzhin)
+ o travis-ci: use gcc-5 (fixes osx|gcc failures) (d7ceae5 Azat Khuzhin)
+ o Testing with vagrant for 6 OS and cmake+autoconf (9585338 Azat Khuzhin)
+ o travis-ci/osx: install lcov (e4e099b Azat Khuzhin)
+
+ Build Improvements/Fixes:
+ o Fix cmake -DEVENT__COVERAGE=ON (40fbffc Azat Khuzhin)
+ o autogen.sh: learn about gmake (9376ac4 Azat Khuzhin)
+ o autogen.sh: remove all autoconf/automake caches, if any (69cce25 Azat Khuzhin)
+ o cmake: fix finding python2, and check that it is really 2 (3453c08 Azat Khuzhin)
+ o cmake: fix CheckFunctionExistsEx/CheckPrototypeDefinition (CMP0054) (43b69b2 Azat Khuzhin)
+ o cmake: cleanup (dc624ad Zonr Chang)
+ o cmake/win32: fix running regress, but fixing finding python2 interpreter (bcb990a Azat Khuzhin)
+ o cmake: use PYTHON_EXECUTABLE to find python2 (a4d044c Azat Khuzhin)
+ o Merge branch 'force-disable-clockgettime' (83c7cdf Azat Khuzhin)
+
+ Code Improvements (core)
+ o use ev_uint16_t instead of unsigned short for port (e983712 Thomas Bernard)
+ o Merge branch 'contrib-guide-v2' (b9c5077 Azat Khuzhin)
+ o poll: Prevent libevent from spinning if POLLNVAL occurs (675974c Tim Hentenaar)
+
+ Testing:
+ o test/regress: cover a polling of invalid fd (cb0df5c Tim Hentenaar)
+
+ Code Improvements (bufferevent_openssl)
+ o Make it build using OpenSSL 1.1.0 (3e9e0a0 Kurt Roeckx)
+ o Don't call BIO_number_{read|written} on NULL BIOs. (6702da1 Adam Langley)
+ o Switch from a 512 to 2048-bit RSA key. (f9803a6 Adam Langley)
+
+ Trivial fixes:
+ o Ignore temporary configure files (8fb08ae Azat Khuzhin)
+ o README.md: fix typo: ar -> are (2361616 Simone Basso)
+ o be: just a simple mistake, reinclude the <errno.h> (7521664 Seven)
+
+Changes in version 2.1.6-beta (4 July 2016)
+
+ Libevent 2.1.6-beta contains mostly bug fixes (evbuffers, evthread, evdns,
+ bufferevents, core, http, samples), improvements but mostly to fix some
+ possible issues (EVHTTP_CON_LINGERING_CLOSE), a lot of new unit tests and new
+ appveyor integration.
+
+ Security Fixes (utils)
+ o evutil_parse_sockaddr_port(): fix buffer overflow (329acc1 Azat Khuzhin)
+
+ Security Fixes (evdns)
+ o evdns: name_parse(): fix remote stack overread (96f64a0 Azat Khuzhin)
+ o evdns: fix searching empty hostnames (ec65c42 Azat Khuzhin)
+
+ New APIs (evdns)
+ o New function to get address for nameserver. (537177d Nick Mathewson)
+
+ New APIs (bufferevents)
+ o expose bufferevent_incref/decref (with fewer modifications) (1ed6718 Mark Ellzey)
+
+ New APIs (internal)
+ o evdns: export cancel via callbacks in util (like async lib core/extra issues) (8cbe65d Azat Khuzhin)
+
+ New APIs/Improvements (http)
+ o http: take EVHTTP_CON_LINGERING_CLOSE into account for "Expect: 100-Continue" (ac448a7 Azat Khuzhin)
+ o http: lingering close (like nginx have) for entity-too-large (9fde518 Azat Khuzhin)
+ o http: read server response even after server closed the connection (680742e Azat Khuzhin)
+ o http: export evhttp_connection_set_family() (714fc70 Azat Khuzhin)
+ o http: reuse connected address only with EVHTTP_CON_REUSE_CONNECTED_ADDR (a50f5f0 Azat Khuzhin)
+ o http: use IP address that we got before (if any) during retrying (54c887d Azat Khuzhin)
+
+ Bugfixes (core)
+ o Fix getaddrinfo under solaris (for multiprotocol case) (40730ae Azat Khuzhin)
+ o Check for Mac OS X 10.4 kqueue bug properly (df6f99e Mark Mentovai)
+ o event_reinit: make signals works after fork() without evsig_add() (88640aa Nicholas Marriott)
+ o event_reinit: always re-init signal's socketpair (ad0c237 Nicholas Marriott)
+ o Free event queues even for recursive finalizers (7c8d015 Azat Khuzhin)
+ o Fix checking for make_base_notifiable() (f337296 Azat Khuzhin)
+ o Set correct socklen for PF_INET6 sockaddr len (3499ad9 Mark Ellzey)
+ o Fix garbage value in socketpair util function, stdint? (043ae74 Mark Ellzey)
+ o fix the return value of event_deferred_cb_schedule_ (38cef64 Greg Hazel)
+ o event_free_debug_globals_locks(): disable lock debugging (e5c87d1 Azat Khuzhin)
+ o event: call event_disable_debug_mode() in libevent_global_shutdown() (941faae Azat Khuzhin)
+ o ht-internal: don't reset hth_table_length explicitly in name_##HT_CLEAR (597c7b2 Azat Khuzhin)
+
+ Bugfixes (evthread)
+ o evthread: fix evthread_setup_global_lock_() for debug-lock with a real-lock case (e4556fc Azat Khuzhin)
+ o evthread: evthreadimpl_disable_lock_debugging_() for libevent_global_shutdown() (ccc5593 Azat Khuzhin)
+
+ Bugfixes (evdns)
+ o evdns: avoid double-free in evdns_base_free() for probing requests (4db15e0 Azat Khuzhin)
+ o evdns: evdns_base_free(): fix UAF of evdns_base with @fail_requests (00313c5 Azat Khuzhin)
+ o evdns: evdns_base_free(): free requests before namservers (14f84bb Azat Khuzhin)
+ o evdns: fix randomize-case by make case-insensitive as required (9c238de Azat Khuzhin)
+
+ Bugfixes (bufferevents)
+ o be_sock: handle readv() returns ECONNREFUSED (freebsd 9.2) (3189eb0 Azat Khuzhin)
+ o be_filter: avoid data stuck under active watermarks (b627ad8 Eduardo Panisset)
+ o Fix bufferevent_pair to properly set BEV_EVENT_{READING,WRITING} on flush. (2851889 David Paschich)
+ o be_openssl: clear all pending errors before SSL_*() calls (38e0f4a Azat Khuzhin)
+ o be_sock: cancel in-progress dns requests (86dfd2c Azat Khuzhin)
+ o be_sock: unfreeze buffers on fd changing (255525d Azat Khuzhin)
+ o be_sock: bufferevent_socket_connect_hostname(): make it thread-safe (809bb39 Azat Khuzhin)
+ o be_openssl: don't call do_write() directly from outbuf_cb (da52933 Azat Khuzhin)
+ o be_openssl: use bufferevent_enable() instead of bufferevent_add_event_() (0c66d32 Azat Khuzhin)
+ o be_openssl: don't add events during bev creation (like be_sock) (f4b6284 Azat Khuzhin)
+ o Fix lock leak in be_pair_flush() if flush type is BEV_NORMAL (f45d39d Bill Vaughan)
+ o be_openssl: don't use *_auto() in do_handshake() we can't have fd == -1 there (877280d Azat Khuzhin)
+ o be_openssl: don't call set_open_callbacks() if fd == -1 (e8a2da9 Azat Khuzhin)
+ o be_openssl: get rid off hackish "fd_is_set", to fix some corner cases (40b0379 Azat Khuzhin)
+ o be: we don't need to use getpeername() we we have conn_address (2c271e2 Azat Khuzhin)
+ o Call underlying bev ctrl SET_FD on filtered bufferevents (c2aa7dc Mark Ellzey)
+ o be_pair: release shared lock with the latest of bufferevent_pair (92a359e Azat Khuzhin)
+
+ Bugfixes (http)
+ o [Issue #313] set method to ASCII "NULL" if evhttp_method() returns NULL (17cc636 Mark Ellzey)
+ o evhttp_have_expect(): fix -Wlogical-not-parentheses (24b5214 Azat Khuzhin)
+ o http: set fd to -1 unconditioally, to avoid leaking of DNS requests (7a4b472 Azat Khuzhin)
+ o http: avoid leaking of fd in evhttp_connection_free() (f0e1341 Azat Khuzhin)
+ o http: get fd from be layer during connection reset (4a53c54 Azat Khuzhin)
+ o http: fix EVHTTP_CON_READ_ON_WRITE_ERROR when it doesn't supported by OS (2ff164a Azat Khuzhin)
+ o http: do not do function calls under EVUTIL_ASSERT() to fix NDEBUG builds (7c89999 Azat Khuzhin)
+ o http: fix leaking of response_code_line (8f18a62 Azat Khuzhin)
+ o http: fix "Expect: 100-continue" client side (0b46b39 Azat Khuzhin)
+ o http: fix conflicts EVHTTP_CON_AUTOFREE and EVHTTP_CON_REUSE_CONNECTED_ADDR (4dc0979 Azat Khuzhin)
+ o http: avoid epoll_ctl() on already closed fd (triggers by http/chunk_out) (ab3bc69 Azat Khuzhin)
+ o http: install timeout for read too during connect for ssl (040000d Azat Khuzhin)
+ o http: fix evhttp_request_own() by checking EVHTTP_USER_OWNED in more cases (b0d3964 Azat Khuzhin)
+ o http: fix detecting EOF without write (7ed02ac Azat Khuzhin)
+ o evhttp: Fix failure to send all output data for POST/PUT requests (24eea0d John Ohl)
+ o Fix evhttp_uriencode() regression. (c6b1ec1 Mark Ellzey)
+ o removed unused vars (e94250c Mark Ellzey)
+ o pointer overflow checks for evhttp_uriencode (72afe4c Zonr Chang)
+
+ Bugfixes (evbuffers)
+ o buffer: fix overflow check in evbuffer_expand_singlechain() (a3f4ccd Azat Khuzhin)
+ o buffer: evbuffer_add_buffer(): clean empty chains from destination buffer (26fd932 Azat Khuzhin)
+ o Fix n_add_for_cb in evbuffer_prepend() in case of new buffer required (0abd039 Azat Khuzhin)
+ o be_filter: actually disable output_filter during processing output (c031215 Simon Perreault)
+ o evbuffer_add: Use last_with_datap if set, not last. (a8769ef Marcus Sundberg)
+ o EVBUFFER_PTR_SET -> EVBUFFER_PTR_ADD (8674e4f jer-gentoo)
+
+ Bugfixes (evconnlistener)
+ o listener: unlock lev on error in listener_read_cb() (2a71b33 Azat Khuzhin)
+ o Fix potential fd leak in listener_read_cb() (a695a72 Mark Ellzey)
+
+ Testing
+ o tests: use waitpid(..., WNOWAIT) to fix failing of main/fork under solaris (43eb56c Azat Khuzhin)
+ o test: replace sleeping with syncing pair in main/fork (16d220c Azat Khuzhin)
+ o test/http: do not run tests that based on backlog filling (freebsd) (500b6b7 Azat Khuzhin)
+ o test/bufferevent/iocp: fix test name for "bufferevent_connect_fail_eventcb" (4410e9d Azat Khuzhin)
+ o test/ssl: use send()/recv()/EVUTIL_ERR_RW_RETRIABLE()/EVUTIL_SOCKET_ERROR() to fix win32 (a9e8cd6 Azat Khuzhin)
+ o test/https_basic: increase timeout for complete write (fixes win32) (d5a2f2f Azat Khuzhin)
+ o test: fix building with --disable-thread-support under win32 (a487706 Azat Khuzhin)
+ o test/buffer: evbuffer_add_buffer() with empty chains (a272bc4 Azat Khuzhin)
+ o test/buffer: evbuffer_remove_buffer() with empty chains (prepend) (f0cfa14 Azat Khuzhin)
+ o test/buffer: evbuffer_remove_buffer() with empty chains (evbuffer_add_buffer()) (2880ce6 Azat Khuzhin)
+ o test/buffer: cover evbuffer_expand() for overflow (48dab7a Azat Khuzhin)
+ o test/be_filter: creating test case for data stuck with active watermarks (766194b Eduardo Panisset)
+ o test/http: avoid using conditionals with omitted operands (fixes VS2015) (2a4bf29 Azat Khuzhin)
+ o test/http: don't mix declarations and code (fixes -Wdeclaration-after-statement) (aabf1c2 Azat Khuzhin)
+ o test/buffer: fix leak in test_evbuffer_prepend() (c08d90b Azat Khuzhin)
+ o test/buffer: avoid errors with --no-fork (reinitialize static vars) (e7d1e39 Azat Khuzhin)
+ o test/buffer: cover n_add_for_cb when evbuffer_prepend() need to allocate buffer (e77ff41 Azat Khuzhin)
+ o test/tinytest_macros: add new one tt_nstr_op() (bd19a28 Azat Khuzhin)
+ o test/bufferevent: check that output_filter disabled during processing output (ae28812 Azat Khuzhin)
+ o test/listener: regression for missing unlock in listener_read_cb() (7d85651 Azat Khuzhin)
+ o test/regress: add tests for evbuffer_add() breakage on empty last chain (d5ee739 Marcus Sundberg)
+ o test/http: fix running some tests sequential (with --no-fork) (bddad71 Azat Khuzhin)
+ o test/http: localize evhttp server structure (cbc3209 Azat Khuzhin)
+ o test/dns: regression for empty hostname (d7348ba Azat Khuzhin)
+ o test/http: fix SERVER_TIMEOUT tests under win32 (d49a658 Azat Khuzhin)
+ o test/http: add a helper for creating timedout/failed request (376f107 Azat Khuzhin)
+ o test/http: adopt for C90 (mixed code and declarations) (d02a285 Azat Khuzhin)
+ o test/http: cover NS timed out during request cancellations separatelly (0c343af Azat Khuzhin)
+ o test/http: request cancellation with resolving/{conn,write}-timeouts in progress (334340d Azat Khuzhin)
+ o test/http: exit from the loop in the errorcb to wait cancellation (927ab33 Azat Khuzhin)
+ o regress_clean_dnsserver(): reset global port vars (351207f Azat Khuzhin)
+ o test/http: read_on_write_error: fix it for win32 (3b58169 Azat Khuzhin)
+ o test/http: separate coverage for EVHTTP_CON_READ_ON_WRITE_ERROR (5c2b4c1 Azat Khuzhin)
+ o test/http: cover "Expect: 100-continue" client-server interaction (31d8116 Azat Khuzhin)
+ o test/http: *lingering tests shouldn't have "Expect: 100-continue" (ed469ab Azat Khuzhin)
+ o test: use EVUTIL_SHUT_WR (04fc82f Azat Khuzhin)
+ o test/http: avoid huge stack allocations to fix win32 builds (3166765 Azat Khuzhin)
+ o test: http/lingering_close: cover EVHTTP_SERVER_LINGERING_CLOSE (e122ca1 Azat Khuzhin)
+ o test: http/non_lingering_close: cover ~EVHTTP_SERVER_LINGERING_CLOSE (f41e1b0 Azat Khuzhin)
+ o test: http/*: update expected HTTP codes for body exceeds `max_body_size` (addf2b9 Azat Khuzhin)
+ o test: http/data_length_constrains: set EVHTTP_CON_READ_ON_WRITE_ERROR (d38a723 Azat Khuzhin)
+ o test: increase buffer size for http/data_length_constraints to trigger EPIPE (0792e1e Azat Khuzhin)
+ o test/tinytest_demo: include <windows.h> for win32 to fix tdm-gcc (f062bbe Azat Khuzhin)
+ o test/regress: cover event_del() waiting mechanism (5b58b70 Azat Khuzhin)
+ o test/regress: cover existing signal callbacks and fork() + event_reinit() (ceddc60 Azat Khuzhin)
+ o test/regress: cover signals after fork() + event_reinit() (b075b81 Azat Khuzhin)
+ o test/regress: main/fork: rewrite assertions by just removing event in callback (088d8b3 Azat Khuzhin)
+ o test/dns: check exit code of evdns_getaddrinfo() (0b9d432 Azat Khuzhin)
+ o test/dns: cover evdns_getaddrinfo() and evdns_base_free() with @fail_requests (4ad3483 Azat Khuzhin)
+ o test/dns: cover @fail_requests for evdns_base_free() (d6c6fb4 Azat Khuzhin)
+ o test/dns: more graceful coverage of @fail_requests (123d372 Azat Khuzhin)
+ o test/ssl: cover busy-loop (i.e. {read,write}-blocked-on-{write,read} stuff) (da0ea7a Azat Khuzhin)
+ o test/http: write_during_read for https (23c77b6 Azat Khuzhin)
+ o test/http: connection_fail for https (7ea26f7 Azat Khuzhin)
+ o test/http: stream_out for https (ac04968 Azat Khuzhin)
+ o test/http: chunk_out for https (a71ffb9 Azat Khuzhin)
+ o test/regress: fix ssl-less builds (need to make this prettier) (3160716 Azat Khuzhin)
+ o test/http: allow dirty shutdown for ssl to fix https_incomplete (1ede326 Azat Khuzhin)
+ o test/http: https basic (59714b4 Azat Khuzhin)
+ o test/http: incomplete{,_timeout} for https (615490d Azat Khuzhin)
+ o test/http: add simplest test for http/https/https_dirty_shutdown (93b19dc Azat Khuzhin)
+ o test/http: https: retry coverage (7c2d24a Azat Khuzhin)
+ o test/http: https server support (plus some helpers) (a7088ad Azat Khuzhin)
+ o test/http: more sanity checks (a27c53c Azat Khuzhin)
+ o test/ssl: export getkey()/getcert()/get_ssl_ctx()/init_ssl() for https (0c4c387 Azat Khuzhin)
+ o test/regress_be: basic coverage bufferevent_flush() for pair/sock layers (ad52602 Azat Khuzhin)
+ o test/regress_be: socket_filter_inactive: check bufferevent after creation (f8081af Azat Khuzhin)
+ o test/regress_be: cover finalizers from inactive to active queue (337684b Azat Khuzhin)
+ o test/regress_buffer: fix clang compilation warnings (d8fd4c0 Azat Khuzhin)
+ o test/regress_http: fix compilation warnings (-Wmissing-field-initializers) (cd422e0 Azat Khuzhin)
+ o test/regress_dns: fix compilation warnings (-Wmissing-field-initializers/for) (f55db98 Azat Khuzhin)
+ o tests/regress_dns: cover that randomize-case works case-insensitive (1e8bfbc Azat Khuzhin)
+ o test: fix bufferevent/bufferevent_pair_release_lock in debug mode (3f749e9 Azat Khuzhin)
+ o test: fix bufferevent/bufferevent_pair_release_lock for freebsd (79f9ace Azat Khuzhin)
+ o test/regress_be: bufferevent_enable() shouldn't call eventcb by it's own (a0f308d Azat Khuzhin)
+ o test/regress_be: introduce fake_listener_create() (37dc9e0 Azat Khuzhin)
+ o test/regress_http: cover evhttp_request_own() (6f6fa0d Azat Khuzhin)
+ o test/regress_http: cover write during read (3d15aeb Azat Khuzhin)
+ o test/regress_http: verify that closecb will be called without multiple write (4be6c70 Azat Khuzhin)
+ o test/regress: fix bufferevent_pair_release_lock with EVENT_DEBUG_MODE (6ea6655 Azat Khuzhin)
+ o test/regress_ssl: check events fd/pending after timeout triggered (cdafdf0 Azat Khuzhin)
+ o test/regress_ssl: cover case when server didn't up (failed with timeout) (74845f1 Azat Khuzhin)
+ o test/regress_ssl: covert that we can't change fd with underlying (df507af Azat Khuzhin)
+ o test/regress_ssl: cover that events (read/write) at finish not pending (762edb4 Azat Khuzhin)
+ o test/regress_ssl: cover fd manipulations (b78a829 Azat Khuzhin)
+ o test/regress_ssl: convert open_ssl_bufevs() to mask (46bba73 Azat Khuzhin)
+ o test/regress_ssl: convert client/server to mask too (3455991 Azat Khuzhin)
+ o test/regress_ssl: cover "allow_dirty_shutdown" (0430327 Azat Khuzhin)
+ o test/regress_ssl: convert regress_bufferevent_openssl() to bitmask (342e116 Azat Khuzhin)
+ o tests/regress_ssl: drop duplicated assert (25e56fd Azat Khuzhin)
+ o test/regress_http: initialize "dns_base" to avoid reading trash (9f0bff3 Azat Khuzhin)
+ o test/http: cover retrying with saved conn_address by shutting down dns server (f4874d8 Azat Khuzhin)
+ o be_pair/regress: cover use of shared lock (lock/unlock/free) (a558fcd Azat Khuzhin)
+ o regress_dns: drop hack for event_debug_map_HT_GROW in leak tests (3540a19 Azat Khuzhin)
+
+ Sample code
+ o Fix memory leak in signal-test.c (666db91 basavesh.as)
+ o sample/hello-world: exAmple, not eXMple (2d3cd35 kirillDanshin)
+ o dns-example: allow to set ns from args (df19a97 Azat Khuzhin)
+ o dns-example: convert to getopt() (32f8592 Azat Khuzhin)
+ o http-connect: make it win32 compilable (1bf7595 Azat Khuzhin)
+ o sample/https-client: allow to change path to ca-certificates (fdf713a Azat Khuzhin)
+ o sample/https-client: check for ERR_remove_thread_state() existence (c4e9d9b Azat Khuzhin)
+ o sample/https-client: replace ERR_remove_state() by ERR_remove_thread_state() (77ad68a Azat Khuzhin)
+ o sample/https-client: add -timeout option (4637aa8 Azat Khuzhin)
+ o sample/https-client: don't try to free uninitialized SSL (f3d7ff5 Azat Khuzhin)
+ o sample/https-client: graceful exit with freeing memory (to make valgrind happy) (24a1f25 Azat Khuzhin)
+ o https-client: correctly handle URLs with no path (like "https://host:port") (29a0482 Andrey Skriabin)
+ o sample/http-connect: don't use assert() to make it work with NDEBUG (6dc71e7 Azat Khuzhin)
+ o sample/http-connect: made it compatible with C90 (f976d43 Azat Khuzhin)
+ o sample: add HTTP CONNECT tunnelling example using libevent http layer (1d34498 Azat Khuzhin)
+ o Update dns-example. (620ff24 Mark Ellzey)
+
+ Documentation
+ o Update README.md (b8ec70c Mark Ellzey)
+ o Update README.md (80faee9 Mark Ellzey)
+ o Update README.md (ad4a897 Mark Ellzey)
+ o Update README.md (a2b2e1e Mark Ellzey)
+ o Update README.md (0dfa5dc Mark Ellzey)
+
+ Code Improvements (evthread)
+ o evthread: add evthread_get_{lock,condition}_callbacks() helpers (c0b34f6 Azat Khuzhin)
+
+ Code Improvements (core)
+ o util: make @sa const for evutil_socket_connect_() (a8d32c2 Azat Khuzhin)
+
+ Code Improvements (http)
+ o http: assert's that evbuffer_drain() success on connection reset (2185e63 Azat Khuzhin)
+ o http: introduce evhttp_request_free_() helper (22061ac Azat Khuzhin)
+ o http: introduce evhttp_is_request_connection_close() helper (6540da3 Azat Khuzhin)
+
+ Code Improvements (bufferevents)
+ o be_sock: bufferevent_socket_set_conn_address(): assert instead of silent no-op (0ab88c2 Azat Khuzhin)
+ o be_sock: sanity check in bufferevent_socket_set_conn_address() (eedbeff Azat Khuzhin)
+ o be: replace sockaddr_storage with sockaddr_in6 for conn_address (3889612 Azat Khuzhin)
+ o be: replace conn_address by full struct instead of pointer (e5615aa Azat Khuzhin)
+ o bufferevent: move conn_address out from http into bufferevent (8bb3842 Azat Khuzhin)
+ o be: make @sa const for bufferevent_socket_connect() (dc33c78 Azat Khuzhin)
+
+ Cleanups (core)
+ o Refactoring conditional directives that break parts of statements. (4b41eeb lzmths)
+ o epoll: introduce PRINT_CHANGES() macro to avoid copy-pasting (a1b142b Azat Khuzhin)
+ o tab (6e7a580 Greg Hazel)
+
+ Cleanups (evbuffers)
+ o buffer_compat: fix comment -- we have EVBUFFER_EOL_ANY not EOL_STYLE_ANY (575ff67 Azat Khuzhin)
+
+ Cleanups (bufferevents)
+ o be_sock: evutil_getaddrinfo_async_() always return 0 (dbff101 Azat Khuzhin)
+ o be_sock: drop be_sock_add() macro (useless and debug unfriendly) (fad5fe2 Azat Khuzhin)
+ o be: introduce bufferevent_generic_adj_existing_timeouts_() (3c1f58f Azat Khuzhin)
+ o be: add_event: use evutil_timerisset() (a96b73b Azat Khuzhin)
+ o be_openssl: introduce be_openssl_auto_fd() helper (2a8a711 Azat Khuzhin)
+ o be_openssl: introduce set_open_callbacks_auto() (510da71 Azat Khuzhin)
+
+ Cleanups (http)
+ o http: make fallback for EVHTTP_CON_READ_ON_WRITE_ERROR more cleaner (d405492 Azat Khuzhin)
+ o http: coding style issue (365f181 Azat Khuzhin)
+
+ Cleanups (evdns)
+ o evnds: inline TEST_NAME macro to make debuggin easier (0c615f4 Azat Khuzhin)
+
+ Portability Fixes
+ o [#372] check for errno.h (3031617 Mark Ellzey)
+ o Fixed Unicode issue in error messages. (e8b7895 Mattes D)
+ o Assume that ke_udata is an integer type on CloudABI. (5602e45 Ed Schouten)
+ o Add missing include of <netinet/in.h>. (b2c68bc Ed Schouten)
+ o Include <sys/ioctl.h>, <sys/resource.h> and <sys/wait.h> optionally. (c1404b5 Ed Schouten)
+ o Test against SO_REUSEADDR (along with _WIN32). (ce1776c Ed Schouten)
+ o Always define missing TAILQ functions from sys/queue.h (2828bdb Christopher Wiley)
+ o Don't use BSD u_* types. (fd36647 Ed Schouten)
+ o Remove BSD-ism: TIMEVAL_TO_TIMESPEC(). (193c7de Ed Schouten)
+ o be: include all variations of headers for sockaddr_in6 struct (c212291 Azat Khuzhin)
+ o be: fix sockaddr_in6 type definition for win32 (c42bc6b Azat Khuzhin)
+
+ Continious Integration:
+ o travis: split long lines, and make it cleaner (685a6a1 Azat Khuzhin)
+ o travis: fix autotools on osx by reinstalling libtool (088ea5e Azat Khuzhin)
+ o appveyor/autotools: link with openssl by passing LDFLAGS/CFLAGS (6fcfa25 Azat Khuzhin)
+ o appveyor: image already had openssl installed (4634b85 Azat Khuzhin)
+ o appveyor: check -DUNICODE -D_UNICODE according to ReleaseChecklist (cmake only) (e9acc44 Azat Khuzhin)
+ o appveyor: ignore failure of mingw-get (1810857 Azat Khuzhin)
+ o appveyor: drop shallow_clone, since we use tags for detecting version in cmake (ac90133 Azat Khuzhin)
+ o appveyor: support cmake & autotools using build matrix (like travis-ci has) (8f95015 Azat Khuzhin)
+ o travis-ci/osx: relink gcc/g++ instead of clang (481481d Azat Khuzhin)
+ o travis-ci: enable multi-os mode (osx, linux) (79917e4 Azat Khuzhin)
+ o travis-ci: increase matrix (--disable-foo) (59649f7 Azat Khuzhin)
+ o travis-ci: adjust alignment (c8be339 Azat Khuzhin)
+ o travis: add builds without debug mode into matrix (3e56da2 Azat Khuzhin)
+ o test: run regress with EVENT_DEBUG_MODE=1 and without (cf2cf2a Azat Khuzhin)
+ o Update travis config for status updates (37453ab Mark Ellzey)
+ o Use autotools for appveyor until cmake is fixed. (1cc2e29 Mark Ellzey)
+ o Fix the link for appveyor OpenSSL installer (WIN32) (107d565 Mark Ellzey)
+ o Forgot to install OpenSSL for appveyor (26164a5 Joakim Söderberg)
+ o Add support for appveyor.com windows CI (5f89c37 Joakim Söderberg)
+
+ Build Improvements/Fixes:
+ o evutil: mark ai_find_protocol() static (prototype-less) (5a157c8 Azat Khuzhin)
+ o cmake/solaris: set CMAKE_REQUIRED_LIBRARIES to fix functions detections (dc95823 Azat Khuzhin)
+ o cmake/solaris: fix building (link with socket,nsl) (050bfc7 Azat Khuzhin)
+ o cmake: check for ZLIB_INCLUDE_DIR, since we can have only library without headers (c4dfb93 Azat Khuzhin)
+ o autotools/win32: fix searching ssl library (671a24f Azat Khuzhin)
+ o cmake/win32: do not compile regress_thread on -DEVENT__DISABLE_THREAD_SUPPORT=ON (de0c196 Azat Khuzhin)
+ o cmake/win32: do not compile evthread_win32 on -DEVENT__DISABLE_THREAD_SUPPORT=ON (ecb0ec8 Azat Khuzhin)
+ o cmake: fix -DEVENT__ENABLE_VERBOSE_DEBUG (typo on -DUSE_DEBUG) (e35f224 Azat Khuzhin)
+ o cmake: do not use stderr for notifications/version-info (38716c6 Azat Khuzhin)
+ o autoconf: fix --disable-thread-support build under win32 (bb09535 Azat Khuzhin)
+ o buffer: don't mix code and declarations (8892f4c Azat Khuzhin)
+ o Update gitignore file to ignore cscope gen'ed files (0aaa4fb Neeraj Badlani)
+ o For non GCC/clang on OSX the -Wno-deprecated-declarations may not be valid (b5ca365 Rainer Keller)
+ o automake: define serial-tests only if automake have this option (61179de Azat Khuzhin)
+ o test/automake: don't use paralell test harness (since automake 1.12) (44d755e Azat Khuzhin)
+ o Ignore all pkgconfig generated stuff (ce38993 Azat Khuzhin)
+ o libevent_core and libevent_extra also deserve a pkgconfig file (b8d7c62 Jan Heylen)
+ o Ignore verify_tests.bat (win32 version) (0f2de10 Azat Khuzhin)
+ o cmake: require 3.1 only for win32 to make it work under ubunty precise (87f7238 Azat Khuzhin)
+ o cmake: require at least 3.1 for target_sources() (c46ead5 Azat Khuzhin)
+ o cmake: fix adding of compiler flags, and now it will (36588e1 Azat Khuzhin)
+ o Replace -Wswitch-enum with -Wswitch, and add it into cmake rules too (f29f59e Azat Khuzhin)
+ o test/regress_ssl: Fix compile problems for win32 (73d0360 Trond Norbye)
+ o util: fix "%zu" format on TDM-gcc/MinGW-w64 (79b69d8 Azat Khuzhin)
+ o cmake: don't define EVENT__NEED_DLLIMPORT always (fixes VS2013 static build) (49bd790 Azat Khuzhin)
+ o Add missing return statement to del_wait_thread so libevent can build. (4f778ab Nick Mathewson)
+ o cmake: fix building dns-example under win32 (missing getopt) (a1609a8 Azat Khuzhin)
+ o visibility: align it to make it more readable (bb6b53d Azat Khuzhin)
+ o cmake: Fix detection of ssize_t/SSIZE_T (7707f6b Azat Khuzhin)
+ o Ignore more configure stuff (configure.lineno) (8d34302 Azat Khuzhin)
+ o Fixed issue with cmake version generation (d56efd9 Mark Ellzey)
+ o Cmake is now officially working. (7f9646d Mark Ellzey)
+ o More cmake updates, lot's of missing definitions (49a5381 Mark Ellzey)
+ o CMake syntax fixes fo .in files (6aad23d Mark Ellzey)
+ o Revert "The Windows socket type is defined as SOCKET." (a264da8 Mark Ellzey)
+ o CMAKE CMAKE CMAKE CLEANUPS (a9db46a Mark Ellzey)
+ o Lot's of cmake updates (8b228e2 Mark Ellzey)
+ o Provide a mechanism for building the library on Windows with different compiler flags. Add a batch file that builds it for the M[DT][d] options and performs a hunt and gather of the different output libraries. (ded8086 billsegall)
+ o The Windows socket type is defined as SOCKET. (c9e6c3d billsegall)
+ o autotools: fix getservbyname() detection (959a4c2 Azat Khuzhin)
+ o Add missing <string.h> for openssl_hostname_validation module (3316a21 Azat Khuzhin)
+ o make test/regress_ssl.c compile without warnings (9f02a44 Thomas Bernard)
+ o test/regress_be: drop debug __asm__(int3) to fix arm build (8240379 Azat Khuzhin)
+ o event_debug_created_threadable_ctx_: fix compilation without debug mode (a068f2e Azat Khuzhin)
+ o Add a prototype for event_disable_debug_mode() (bfcedee Sebastian Hahn)
+ o http: eliminate warning about "socklen" in evhttp_connection_connect_() (dfad1a4 Azat Khuzhin)
+ o Updated gitignore (1dbb55d Mark Ellzey)
+ o Update bench_httpclient.c (cb96931 Seungmo Koo)
+ o *fix: bench_httpclient to support win32 (4e9325e zeliard)
+ o Commented out a WIN32 threading / timing test for now (e84e269 Mark Ellzey)
+ o Fix mixed declarations and code (forbidden by ISO C90) (0c7f217 Thomas Bernard)
+ o Fix "function declaration isn’t a prototype" (746d2c5 Thomas Bernard)
+ o This fixes a bug introduced in 27bd9faf498b91923296cc91643e03ec4055c230 (19ba454 Joakim Söderberg)
+ o changed strtotimeval signature as per #211 (bdbc823 Xiao Bao Clark)
+ o Added cmake-generated files to ignore list. (6c12bfe Matyas Dolak)
+ o Ignore `make dist` generated files (8a2c6c7 Azat Khuzhin)
+
+ Debugging
+ o Debug mode option to error on evthread init AFTER other event calls. (dcfb19a Mark Ellzey)
+
+
+
+Changes in version 2.1.5-beta (5 January 2015)
+
+ Security Fixes (evbuffers)
+ o Avoid integer overflow bugs in evbuffer_add() and related functions. See CVE-2014-6272 advisory for more information. (d49bc0e88b81a5812116074dc007f1db0ca1eecd)
+
+ New APIs (evconnlistener)
+ o Provide support for SO_REUSEPORT through LEV_OPT_REUSABLE_PORT (b625361 Maciej Soltysiak)
+
+ Bugfixes (core)
+ o Fix use-after-free error in EV_CLOSURE_EVENT callback (3cc0eac John Ohl)
+ o Fix race caused by event_active (3c7d6fc vjpai)
+
+ Bugfixes (evbuffer)
+ o Fix evbuffer_peek() with len==-1 and start_at non-NULL. (ba59923)
+ o Consistently check for failure from evbuffer_pullup() (60f8f72)
+ o Fix evbuffer_peek() with len==-1 and start_at non-NULL. (fb7e76a)
+
+ Bugfixes (windows, IOCP)
+ o be async: avoid double close() (f133b86 Azat Khuzhin)
+
+ Bugfixes (bufferevents)
+ o Fix issue #127, double free for filterevents that use BEV_OPT_CLOSE_ON_FREE (2c82aa0 John Ohl)
+ o make bufferevent_getwatermark api more robust (a21e510 ufo2243)
+ o [Bugfix] fix bufferevent setwatermark suspend_read (b34e4ac ufo2243)
+ o bufferevent_openssl: reset fd_is_set when setfd with -1 is called (3da84c2 Azat Khuzhin)
+ o Fix compilation for older OpenSSL versions. (5c7282f Joakim Soderberg)
+
+ New APIs (evhttp)
+ o Add evhttp_connection_set_family() to set addrinfo->family for DNS requests (12c29b0 Azat Khuzhin)
+ o Implement interface that provides the ability to have an outbound evhttp_connection free itself once all requests have completed (2b9ec4c,10fe4f John Ohl)
+
+ New APIs (core)
+ o Implement new/free for struct evutil_monotonic_timer and export monotonic time functions (f2645f8 Andrea Shepard)
+
+ Bugfixes (evdns)
+ o Load hosts file on Windows. (a0b247c Vilmos Nebehaj)
+ o Don't truncate hosts file path on Windows. (d0dc861 Vilmos Nebehaj)
+ o Fix a crash in evdns related to shutting down evdns (9f39c88,e8fe749)
+ o evdns: avoid read-after-free in evdns_request_timeout_callback() (61262a0 Azat Khuzhin)
+ o Correctly handle allocation failures in evdns_getaddrinfo (6a53d15)
+ o evdns: fix EVDNS_BASE_DISABLE_WHEN_INACTIVE in case retransmit/retry (74d0eee Azat Khuzhin)
+ o evdns: add retry/reissue tests for EVDNS_BASE_DISABLE_WHEN_INACTIVE (3ca9d43 Azat Khuzhin)
+ o evdns: fail ns after we are failing/retrasmitting request (97c750d Azat Khuzhin)
+
+ Bugfixes (evhttp)
+ o http: reset connection before installing retry timer (fix http retries handling) (bc79cc5 Azat Khuzhin)
+
+
+ Testing
+ o regress_dns: fix leaks in getaddrinfo_async{,_cancel_stress} tests (2fdc5f2 Azat Khuzhin)
+ o test: add family argument for http_connection_test_() (177b8a7 Azat Khuzhin)
+ o test: add regress for evhttp_connection_set_family() with AF_INET and AF_UNSPEC (42aefeb Azat Khuzhin)
+ o test/http: add regress test for set family to AF_INET6 (3fbf3cc Azat Khuzhin)
+ o Update to a more recent tinytest_macros. (8da5a18)
+ o test/regress: add simplestsignal: to track reorder bugs separately (b897bef Azat Khuzhin)
+ o test/evbuffer_peek: add regress in case we have first buffer greater (e2d139d Azat Khuzhin)
+ o More evbuffer_peek() test cases (154006a)
+ o use correct tt macro for pointer compare (08c88ea)
+ o regress_buffer: fix 'memcmp' compare size (79800df Maks Naumov)
+ o Fix a use-after-free in unit tests. CID 752027 (3739057)
+ o Fix a dead-code warning in unit tests. CID 1193548 (c119f24)
+ o Use evutil_weakrand() in unit tests. (a677b72, 364c110)
+ o Use a more precise calculation for max in time-ratelim.c (ca5b5c7)
+ o Make a buffer larger in the tests to avoid a scary evbuffer_copyout_from() (fb57b8b)
+ o Fix several memory leaks in the unit tests. (89c1a3b)
+ o Add test for evhttp_connection_free_on_completion (b0e9924 John Ohl)
+ o Fix annoying heisenbug in test-time.c (cb73704)
+
+ Sample code
+ o Make http-server.c output into good html5 (6d72bdc)
+ o Use FindClose for handle from FindFirstFile in http-server.c (6466e88)
+ o https-client: add -retries argument, for connection retries (d9da844 Azat Khuzhin)
+
+ Bugfixes (build)
+ o Add missing headerfile for cmake (15d90cc Trond Norbye)
+ o ignore one more test binary (b6593aa Michael Richardson)
+ o ignore config.cache/test-driver files (c83f333 Mike Frysinger)
+ o add a --disable-samples configure flag (0c492b3 Mike Frysinger)
+ o Add a few files created by "make verify" to .gitignore. (1a8295a Pierre Phaneuf)
+ o updates in cmake build (27bd9fa Sergey Nikulov)
+ o Fix cmake error when the Module path has more than one entry. (befbd13 Acer Yang)
+ o Fix CMake shared library build (e69d910 Nobuaki Sukegawa)
+ o Fix warnings when compiling with clang 3.5 (f5b4765 John Ohl)
+ o Fix mixed declarations and code (forbidden by ISO C90) (8afbdbc Thomas Bernard)
+
+ Bugfixes (miscellaneous)
+ o tree.h: drop duplicated content of tree.h (6193187 Azat Khuzhin)
+ o evdns: disable probing with EVDNS_BASE_DISABLE_WHEN_INACTIVE (610410b,ad0493e,fea86a6,d83b337,5ca9e97 Azat Khuzhin)
+ o [Bugfix] fix grammer error (3a4d249 ufo2243)
+ o Change return type of evutil_load_windows_system_library_ to HMODULE (f691389)
+ o Fix a c90 warning (76643dd)
+ o Fix a typo in a doxygen comment. Reported by 亦得. (be1aeff)
+ o remove trailing comma from enum (b361b8a Jean-Philippe Ouellet)
+
+ Bugfixes (FreeBSD)
+ o Handle ENOTCAPABLE from FreeBSD - this is returned if an event in the changelist is for an FD that has been closed. (6fd7394 Adrian Chadd)
+
+
+
+Changes in version 2.1.4-alpha (21 Mar 2014)
+
+ Libevent 2.1.4-alpha adds a number of new miscellaneous APIs to make
+ Libevent more useful, including support for early close detection with
+ epoll via EPOLLRDHUP, triggering bufferevent callbacks, adding more
+ evhttp callbacks, and more. There are also numerous bugfixes, including
+ a number for finalize-related issues from 2.1.3-alpha; and an
+ alternative (non-primary!) cmake-based build mechanism.
+
+ New APIs (core)
+ o Added event_base_get_num_events() (0fa107d Mobai Zhang)
+ o New event_base_active_by_fd API (865a142 Greg Hazel, 5c9da9a, 87fa2b0)
+ o Add event_base_active_by_signal by analogy (4865943)
+ o Add access to max event count stats (5173bef, efbd3dc, 26230a2
+ Andrew Sweeney)
+ o Implemented EV_CLOSED event for epoll backend
+ (EPOLLRDHUP). (b1b69ac Diego Giagio, 53d2793, 43ffcf6, dfe1e52
+ Marcin Juszkiewicz, ff26633 Joakim Soderberg, 3908a5e)
+
+ New APIs (evutil_secure_rng)
+ o Add evutil_secure_rng_set_urandom_device_file (2bbb5d7)
+
+ New APIs (bufferevents)
+ o Add function to fetch underlying ratelimit cfg (4b3d5af Mark Ellzey)
+ o Pass and return const for bufferevent_get_token_bucket_cfg (1c77fbb
+ Mark Ellzey)
+ o Add watermark introspection (4ce242b Ondřej Kuzník)
+ o Add an option to trigger bufferevent I/O callbacks (61ee18b Ondřej Kuzník)
+ o Add an option to trigger bufferevent event callbacks (a7384c7
+ Ondřej Kuzník)
+ o Clarifications in response to merge req. comments (bd41947 Ondřej
+ Kuzník)
+ o Minor optimizations on bufferevent_trigger options (a3172a4)
+
+ New APIs (evhttp)
+ o Add evhttp_connection_get_server(). (a7f82a3 Maxime Henrion)
+ o add a http default content type option (5a5acd9 Nicolas Martyanoff)
+ o http: implement new evhttp_connection_get_addr() api. (0c7f040 Azat
+ Khuzhin)
+ o Add a variant of evhttp_send_reply_chunk() with a callback on
+ evhttp_write_buffer() (8d8decf Julien BLACHE)
+ o Allow registering callback for parsing HTTP headers (b0bd7fe Balint Reczey)
+ o Provide on request complete callback facility (b083ca0 Andrew Sweeney)
+ o evhttp_request_set_on_complete_cb to be more specific about what
+ the function actually does and usage (da86dda Andrew Sweeney)
+ o Update unit test to make sure that the callback happens after the
+ output data is written (b85f398 Andrew Sweeney)
+
+ Features (evdns)
+ o bug fix for issues #293 evdns_base_load_hosts doesn't remove
+ outdated addresses (954d2f9, f03d353, 45eba6f Kuldeep Gupta)
+
+ Features: (cmake build support)
+ o Initial CMake commit. (e415196 Joakim Soderberg)
+ o Add all tests and benchmarks to CMake project. (e9fc014 Joakim Soderberg)
+ o More work on adding tests to CMake project (99c1dc3 Joakim Soderberg)
+ o Generate a dummy evconfig-private.h so things build
+ properly. (ce14def Joakim Soderberg)
+ o Link libm on unix platforms. (58fcd42 Joakim Soderberg)
+ o Added some GCC specific options. (19222e5 Joakim Soderberg)
+ o Use evutil_closesocket instead. (dbf2b51 Joakim Soderberg)
+ o Add copyright and licensing files for CMake modules. (c259d53
+ Joakim Soderberg)
+ o Only include WIN32 getopt where it is used. (9bbce0b Joakim Soderberg)
+ o Fix bench_cascade program on Windows. (78da644 Joakim Soderberg)
+ o Don't segfault on no found event backend. (8f2af50 Joakim Soderberg)
+ o Only test the event backends available on the system. (7ea4159
+ Joakim Soderberg)
+ o Added a "make verify" target. (e053c4f Joakim Soderberg)
+ o Fix the make "verify" target on Windows. (67e5d74 Joakim Soderberg)
+ o Get rid of deprecation warnings for OpenSSL on OSX 10.7+ (69c3516
+ Joakim Söderberg)
+ o Fix kqueue support. (a831f2f Joakim Söderberg)
+ o Added a test for testing if kqueue works with pipes. (2799b35
+ Joakim Söderberg)
+ o Change the BSD license from 4 to 3-clause. (86df3ed Joakim Soderberg)
+ o Minimum required python version is 2.4. (968e97b Joakim Soderberg)
+ o Get rid of unknown pragma warnings. (0ef1d04 Joakim Soderberg)
+ o Add a "make verify_coverage" target generation coverage
+ info. (f2483f8 Joakim Soderberg)
+ o Fix the "make verify" target on NetBSD (4ac086a Joakim Soderberg)
+ o Only look for ZLib when it is used (if tests are
+ included). (f780593 Joakim Soderberg)
+ o Added EVENT__ENABLE_GCC_WARNINGS, turns all warnings into
+ errors. (dd413bd Joakim Soderberg)
+ o Add CMake config and install targets. (f3446ed Joakim Soderberg)
+ o Fix typo (4b754df Joakim Soderberg)
+ o Some work on making it possible to simply do add_subdirectory() on
+ the project. (49ab363 Joakim Soderberg)
+ o Set USE_DEBUG=1 on EVENT__ENABLE_VERBOSE_DEBUG (fd42e70 Joakim Soderberg)
+ o Fix so that old nmake project still builds. (24d6466 Joakim
+ Soderberg)
+ o Rename README to README.md and use markdown to format. (d2bc39a
+ Joakim Soderberg)
+ o Update README with CMake build instructions. (604b8cc Joakim Soderberg)
+ o Clean up the README some. (8d4cb35 JoakimSoderberg)
+ o Forgotten headers for old nmake project compatability. (8697b99
+ Joakim Soderberg)
+ o Change all uses of WIN32 to _WIN32 (4e14395 Joakim Söderberg)
+ o Fix include bug. (2024467 Joakim Söderberg)
+ o Check if we're on OSX before disabling deprecation in le-proxy
+ (8b40a5b Joakim Söderberg)
+ o Fix broken autotools build. (ae1bd82 Joakim Söderberg)
+ o Disclaimerize cmake a little in the README (d03b5bf)
+ o Fix CMake compile when OpenSSL is disabled. (e423d42 Joakim
+ Söderberg)
+ o CMake: Get rid of python not found warning when regress tests
+ turned off. (d38d798 Joakim Söderberg)
+ o Fix https-client compilation on Windows. (d7be788 Joakim Soderberg)
+ o Guard against EVENT_NOWIN32 being set during testing. (f1715b4
+ Joakim Soderberg)
+ o Check for OSX when checking for clang. (e212c54 Joakim Soderberg)
+ o Added a Travis-CI configuration file. (8c0f0a9 Joakim Soderberg)
+ o Added -Qunused-arguments for clang on macosx (ed99d92 Trond Norbye)
+ o Rename event_extras to event_extra (a0dd5df Trond Norbye)
+ o Add option to build shared library (4545fa9 Trond Norbye)
+ o Add -Qunused-arguments for clang on macos (b56611d Trond Norbye)
+ o Add cmake-related files to .gitignore (e061321 Trond Norbye)
+ o Export event_extra not event_extras. (2b41bcf Joakim Söderberg)
+
+ Bugfixes (core)
+ o If evsel->del() fails, don't leave the evmap in an inconsistent
+ state (9b5a527 Maxime Henrion)
+ o Move event_debug_note_teardown_ before mm_free. (69b5c64)
+ o Check CLOCK_MONOTONIC_* at runtime if needed. (911abf3)
+ o Fix reinit of fds with EV_WRITE but not EV_READ. (ebfd8a8 maksqwe)
+ o Tweaked callbacks to prevent race condition
+ (https://github.com/libevent/libevent/issues/104) (40830f1, 2ea15ed
+ John Ohl)
+ o Move assert(ev) to before we use ev in EV_CLOSURE_EVENT_FINALIZE
+ case (9805972)
+
+ Bugfixes (evhttp)
+ o Fix a double close() bug in evhttp when the underlying bufferevent uses
+ BEV_OPT_CLOSE_ON_FREE. (31db8a0 Maxime Henrion)
+ o Fix an unlikely but possible error case for http connections (f22049e)
+ o Avoid racy bufferevent activation (5eb1788 Nate Rosenblum)
+
+ Bugfixes on 2.0 (Windows)
+ o Use windows vsnprintf fixup logic on all windows environments (e826f19)
+ o libevent/win32_dealloc() : fix sizeof(pointer) vs sizeof(*pointer)
+ (b8f5980 Frank Denis)
+
+ Bugfixes (evutil_secure_rng)
+ o When we seed from /proc/sys/kernel/random/uuid, count it as success
+ (e35b540)
+ o We should return after arc4random_buf() (1ea1f26 Makoto Kato)
+ o Avoid other RNG initialization FS reads when urandom file is
+ specified (9695e9c)
+ o Really remove RNG seeds from the stack (f5ced88)
+ o Fix another arc4random_buf-related warning (e64a2b0)
+
+ Bugfixes (bufferevents)
+ o Initialize async bufferevent timeout CBs unconditionally (af9b2a7)
+
+ Bugfixes (evdns)
+ o Checking request nameserver for NULL, before using it. (5c710c0
+ Belobrov Andrey)
+ o Fix SEGFAULT after evdns_base_resume if no nameservers
+ installed. (14971a8 Azat Khuzhin)
+ o Actually use the log facility for reporting evdns problems. (e1766a1)
+ o Fix SEGFAULT after evdns_base_resume if no nameservers
+ installed. (f8d7df8 Azat Khuzhin)
+ o fix for ServFail from RIPE Atlas release (62f596b Antony Antony)
+
+ Bugfixes (compilation)
+ o Fix test compilation with nmake: add the gdi.lib dependency (5ba8ab7)
+ o Whoops. It is gdi.lib, not gdi32.lib. (github issue #61) (8ab612e)
+ o Don't use return since return type is void and build error occurs
+ using clang (838161d Makoto Kato)
+ o Use void casts to suppress some "unchecked return value" warns (7080d55)
+ o rpcgen: Generate regress.gen.[c,h] in build rather than src dir
+ (243386c Ross Lagerwall)
+ o Fix a compiler warning when checking for arc4random_buf linker
+ breakage. (5cb3865)
+ o Fix 'make distcheck' by adding regress.gen.[ch] to DISTCLEANFILES
+ (239d834)
+
+ o Fix a c90 warning (c207682)
+ o Fix consts in WIN32-Code/getopt*.[ch] (57abb35)
+
+ Bugfixes (locks, synchronization)
+ o Missed lock acquire/release in event_base_cancel_single_callback_()
+ (d3d999a Azat Khuzhin)
+ o Fix locking in bufferevent_get_options_(). (dbc9cd4 Maxime Henrion)
+
+ Bugfixes (leaks)
+ o Avoid leaking segment mappings when offset is not a page multiple (d409514)
+
+ Testing
+ o Add tests for evdns_base_resume(). (1cd9ff5 Azat Khuzhin)
+ o Fix dns/leak_resume_send_err test. (7e876df Azat Khuzhin)
+ o Add checks for evhttp_connection_get_server() in unit
+ tests. (fbc323b Maxime Henrion)
+ o Fix a (failure-only) null dereference in the unit tests (1104d0b)
+ o Fix a logic error in test_evbuffer_freeze (7765884)
+ o Add missing check to test_evbuffer_file_segment_add_cleanup_cb (eba4506)
+ o Fix some crash-on-fail cases in DNS regression tests (87cd6f0)
+ o DNS tests: add a missing check (f314900)
+ o Finalize tests: add a missing check (82b6956)
+ o test_evutil_rtrim: add another missing check. (e193c95)
+ o regress_main: logging all if env EVENT_DEBUG_LOGGING_ALL isset
+ (611e28b Azat Khuzhin)
+ o regress_http: add tests for evhttp_connection_get_addr() (4dd500c
+ Azat Khuzhin)
+ o Update to the latest version of tinytest (7a80476)
+ o Heap-allocate zlib data structure in regress_zlib tests (4947c18)
+
+ Performance tweaks (core)
+ o Avoid redundant syscall to make a nonblocking socket nonblocking
+ (42c03da Maxime Henrion)
+ o Avoid redundant syscall if making a socket cloexec twice (1f29b18)
+ o Avoid redundant invocations of init_extension_functions for IOCP (3b77d62)
+
+ Documentation
+ o Document that arc4random is not a great cryptographic PRNG. (6e49696)
+ o Small doxygen tweaks (6e67b51)
+ o Try another doxygen tweak (ccf432b)
+ o Clarify event_base_loop exit conditions (031a803)
+ o Fix a typo (be7bf2c Ondřej Kuzník)
+ o Document deferred eventcb behaviour (13a9a02 Ondřej Kuzník)
+ o Typo fixes from Linus Nordberg (cec62cb, 8cd695b)
+ o Fix duplicate paragraph in evbuffer_ptr documentation (58408ee)
+
+ Code Improvements (coverity)
+ o Fix a pile of coverity warnings in the unit tests (867f401)
+ o Fix coverity warnings in benchmark tools. (ff7f739)
+ o Whoops; fix compilation in bench.c (544cf88)
+ o Remove spurious checks in evrpc.c error cases (coverity) (991b362)
+ o Fix a couple of compilation warnings in regress_http.c (860767e)
+ o Fix even more coverity warnings. (d240328)
+ o Stop checking for inet_aton; we don't use it. (f665d5c)
+ o Add an include to evrpc-internal to fix openbsd compilation warning
+ (5e161c6)
+
+ Cleanups
+ o Remove an unreachable return statement in minheap-internal.h (e639a9e)
+ o Refactor evmap_{io,signal}_active_() to tolerate bad inputs (974c60e)
+ o Fix needless bufferevent includes in evdns.c (254c04e)
+ o Fix a couple of "#ifdef WIN32" instances (88ecda3)
+ o Remove unneeded declaration in bufferevent-internal.h (4c8ebcd)
+
+ Sample code
+ o le-proxy: Fail more gracefully if opening listener fails (44b2491)
+ o http-server: drop uri_root from base_url in http-server. (6171e1c Azat Khuzhin)
+ o https-client: POST supported, args supported (c5887f7 Alexey Ozeritsky)
+ o https-client: code cleanup (29af65e Alexey Ozeritsky)
+ o https-client: Small tweaks to https-client.c (90786eb)
+ o https-client: Set hostname for SNI extension (by f69m) (d1976f8)
+ o https-client: add a cast to https-client.c (462e6b6)
+
+
+
+Changes in version 2.1.3-alpha (1 May 2013)
+
+ Libevent 2.1.3-alpha fixes various bugs, adds new unit tests, and cleans
+ up the code in a couple of places. It has a new callback in evhttp for
+ reporting errors during a request, a new feature for allowing evdns to
+ not keep the event_base looping when there are no requests inflight, and
+ example code for writing an https client.
+
+ Libevent 2.1.3-alpha also has an important new (experimental) event
+ finalization feature to allow safe event teardown in multithreaded
+ programs. This ought to fix the longstanding bug with deadlocks in
+ multithreaded use of SSL-based bufferevents that some people have been
+ experiencing since Libevent 2.0.
+
+
+ Core (event finalization)
+ o Implement event_finalize() and related functions to avoid certain
+ deadlocks (8eedeab)
+ o Use finalization feature so bufferevents can avoid deadlocks (02fbf68)
+ o Always run pending finalizers when event_base_free() is called (e9ebef8)
+ o Remove bufferevent_del_generic_timeout_cbs as now unused (4ea4c6a)
+ o More documentation for finalization feature (a800b91)
+ o Make the event_finalize* functions return an error code (5d11f4f)
+ o Mark the finalize stuff as experiemental in case it needs to
+ change (23e2e29)
+
+ Evdns
+ o evdns: New flag to make evdns not prevent the event loop from
+ exiting (6b7fa62 Azat Khuzhin)
+
+ Bugfixes (Core)
+ o Make event_remove_timer behave correctly with persistent timers (5623e80)
+ o Unit test for event_remove_timer with EV_PERSIST. (96150dd)
+ o Double-check next timeout when adding events (9443868 Nate Rosenblum)
+ o event_base_update_cache_time should be a no-op if the loop isn't
+ running (5e6fa2a)
+
+ Bugfixes (evhttp, crash fix, from 2.0)
+ o fix #73 and fix http_connection_fail_test to catch it (b618204 Greg Hazel)
+
+ Bugfixes (compilation and portability, from 2.0)
+ o Fix compilation with WIN32_HAVE_CONDITION_VARIABLES enabled (7e45739)
+ o Fix missing AC_PROG_SED on older Autoconfs (9ab2b3f Tay Ray Chuan)
+ o Backport libevent to vanilla Autoconf 2.59 (as used in RHEL5)
+ (74d4c44 Kevin Bowling)
+ o Use AC_CONFIG_HEADERS in place of AM_CONFIG_HEADERS for autmake
+ 1.13 compat (817ea36)
+ o Rename configure.in to configure.ac to appease newer autoconfs (0c79787)
+ o Avoid using top_srcdir in TESTS: new automakes do not like this (a55514e)
+
+ Bugfixes (resource leaks/lock errors on error, from 2.0)
+ o Avoid leaking fds on evconnlistener with no callback set (69db261)
+ o Avoid double-close on getsockname error in evutil_ersatz_socketpair
+ (0a822a6)
+ o Fix a locking error in bufferevent_socket_get_dns_error. (0a5eb2e)
+
+ Documentation Fixes (from 2.0)
+ o Fix a mistake in evbuffer_remove() arguments in example http server code
+ (c322c20 Gyepi Sam)
+ o Fix a typo in a comment in buffer.h. Spotted by Alt_F4 (773b0a5)
+
+ Documentation Fixes
+ o minor documentation typos (809586a Patrick Pelletier)
+ o Fix cut-and-paste err in whatsnew-2.1 (49905ac)
+ o Fix comment to refer to sample/include.am correctly (9e8cdf3 Sebastian
+ Hahn)
+ o Fix typo : Dispatching instead of Dispaching (0c2bacc Volker Lendecke)
+ o fix some hinky indentation in evhttp_make_request (80e220e Patrick
+ Pelletier)
+ o "buffer" spelling (a452811 Patrick Pelletier)
+ o Specify return behavior in header for evbuffer_pullup() in corner case
+ (cf8d1cd Dan Petro)
+ o Clarify an important point about event_base_foreach_event() (920a5e6)
+
+ Compilation Fixes/Tool Support
+ o avoid valgrind false positive by zeroing epoll_event (1258614 Patrick
+ Pelletier)
+ o Fix harmless clang enum warning (b452a43 Sebastian Hahn)
+ o remove all exes on "make clean", not just regress.exe (974bfa0 Patrick
+ Pelletier)
+ o Make --disable-libevent-regress work again (787fd74)
+ o Do not build strlcpy.c when it will have no code. (4914620)
+
+ Portability Fixes
+ o When EWOULDBLOCK is not EAGAIN, treat it as equivalent to it (bf7a0ff)
+ o Preliminary changes for Minix3. (0dda56a Nicholas Heath)
+ o Use AC_CONFIG_HEADERS in place of AM_CONFIG_HEADERS for autmake 1.13
+ compat (bf278b)
+ o Avoid using $(top_srcdir) in TESTS. (2863c83)
+ o build test/test-script.sh on systems with a less-featureful $< (f935e21)
+ o Implement EVUTIL_ERR_IS_EAGAIN on windows. (42aaf4d)
+
+ Evhttp changes:
+ o Fix ipv6 support for http. When URL contain domain, not IP
+ address. (71e709c Azat Khuzhin)
+ o uri decode: fix for warning "use of uninitialised value" (64b6ece Azat
+ Khuzhin)
+ o uri decode: changed the test for the existence of the next character
+ (e1903e3 Azat Khuzhin)
+ o Move prototype of evhttp_decode_uri_internal() to http-internal.h
+ (de8101a Azat Khuzhin)
+ o Test: decoding just part of string with evhttp_decode_uri_internal()
+ (1367653 Azat Khuzhin)
+ o Add new error_cb for actual reporting of HTTP request errors. (7b07719
+ Azat Khuzhin)
+ o Add test for EVREQ_HTTP_REQUEST_CANCEL into http_cancel_test() (862c217
+ Azat Khuzhin)
+ o Drop extra header http_struct.h from regress_http.c (54cc800 Azat Khuzhin)
+
+ Testing
+ o Add regress test ipv6_for_domain. (9ec88bd Azat Khuzhin)
+ o Add an environment variable (EVENT_DEBUG_MODE) to run unit tests in debug
+ mode (2fad0f3)
+ o Add a test with an active_later event at event_base_free time. (1c3147f)
+ o Make all tests pass under EVENT_DEBUG_MODE=1 (b1b054f)
+ o Add some verbose notes to bufferevent unit tests (9d893c9)
+ o New test for active_later->active transition on event_active (a153874)
+ o New tests for event_base_foreach_event() (0b096ef)
+ o Unit tests for event_base_gettimeofday_cached() and
+ event_base_update_cache_time() (30ea291)
+ o A test for event_get_assignment() (f09629e)
+ o More unit tests for initializing common timeouts. (d596739)
+ o Fix a bug in the new main/event_foreach test (702c9aa)
+
+ Windows:
+ o use FormatMessage for winsock errors (0c6ec5d, 2078e9b, 4ccdd53, c9ad3af
+ Patrick Pelletier)
+ o a program to print out the error strings for winsock errors (7296512
+ Patrick Pelletier)
+ o Fix a warning introduced in 0c6ec5d8 (eeb700c)
+ o Fix another warning introduced in 0c6ec5d8 (ed26561)
+
+ Examples (http)
+ o Add sample/https-client.c, an example of stacking evhttp as a client on
+ top of bufferevent_ssl. (be46c99 Catalin Patulea)
+ o use ${OPENSSL_LIBS} instead of -lssl -lcrypto (bf31fa5 Patrick Pelletier)
+ o https-client was putting newlines at 256-byte boundaries (42d7441 Patrick
+ Pelletier)
+ o better handling of OpenSSL errors (5754d96 Patrick Pelletier)
+ o use Debian's default root certificate location (aacd674 Patrick Pelletier)
+ o use iSECPartners code to validate hostname in certificate (64d9f16
+ Patrick Pelletier)
+ o avoid sign mismatch warning in openssl_hostname_validation.c (6021cb5
+ Patrick Pelletier)
+ o pull in wildcard matching code from cURL (4db9da6 Patrick Pelletier)
+ o Another tweak to https-client.c (95acdaa)
+ o Remove http_struct.h usage in sample/https-client.c (8a90a85)
+
+
+
+Changes in version 2.1.2-alpha (18 Nov 2012)
+
+ Libevent 2.1.2-alpha includes more portable for monotonic timers,
+ refactors much of Libevent's internal and external infrastructure,
+ closes some longstanding gaps in the interface, makde other
+ improvements. Ths log below tries to organize features by rough area of
+ effect. It omits a few commits which were pure bugfixes on other commits
+ listed below. For more detail, see the git changelogs. For more
+ insight, see the "whatsnew-2.1.txt" document included in the Libevent
+ 2.1.2-alpha distribution.
+
+ Libevent 2.1.2-alpha also includes all changes made in 2.0.19-stable
+ through 2.0.21-stable inclusive.
+
+ Performance (core):
+ o Replace pipe-based notification with EVFILT_USER where possible. This
+ should make multithreaded programs on OSX and *BSD alert the main thread a
+ little faster. (53a07fe)
+ o Make th_base_lock nonrecursive. (9cd5acb)
+
+ New/Changed API Functions:
+ o New event_get_priority() function to return an event's priority (f90e255)
+ o Add a bufferevent_get_priority() function (bd39554)
+ o Add an event_base_loopcontinue() to tell Libevent to rescan for more
+ events right away (7d6aa5e)
+ o Add a new callback to get called on evbuffer_file_segment free
+ (e9f8feb yangacer, 64051b9)
+ o Expose event_base_foreach_event() as a public API. (84fd6d7 Roman
+ Puls, 232055e, ffe1643)
+ o Add an event_remove_timer() to remove timer on an event without
+ deleting it (e3b2e08)
+ o Make bufferevent_set_timeouts(bev, NULL, NULL) have plausible
+ semantics (9dee36b)
+ o Rename event_enable_lock_debuging() to ..._debugging(). (The old name
+ should still work.) (07e132e)
+ o Add missing implementation for event_enable_debug_logging (3b3e21d)
+
+ PORTABLE MONOTONIC TIMERS:
+
+ Libevent 2.1.2 includes internal support for monotonic timers on
+ (nearly) all supported platforms, including Windows, and OSX. Libevent
+ applications should now be more resilient to jumps forwards or backwards
+ in the system clock. Also, on Linux systems with epoll, we now
+ optionally support microsecond-level timeouts (whereas epoll only
+ supports millisecond-precision timeouts).
+
+ o Use mach_absolute_time() for monotonic clock support on OSX. (b8fd6f9)
+ o Do not track use_monotonic field when is no monotonic clock (cb653a0)
+ o EVENT_BASE_FLAG_PRECISE_TIMER indicates we want fine timer precision
+ (ddd69d3)
+ o On Linux, use CLOCK_MONOTONIC_COARSE by default (55780a7)
+ o Implement a GetTickCount-based monotonic timer for Windows (d5e1d5a)
+ o Refactor monotonic timer handling into a new type and set of
+ functions; add a gettimeofday-based ratcheting implementation (f5e4eb0)
+ o Add EVENT_PRECISE_TIMER environment var for selecting precise-but-slow
+ timer (a2598ec)
+ o Implement fast/precise monotonic clocks on Windows (2c47045)
+ o Simple unit tests for monotonic timers (630f077)
+ o Improve the monotonic-time unit test: make it check the step size (7428c78)
+ o When PRECISE_TIMERS is set with epoll, use timerfd for microsecond
+ precision (26c7582)
+ o Split out time-related evutil functions into a new evutil_time.c (c419485)
+ o Split out time-related prototypes into time-internal.h (71bca50)
+ o Add evutil_time.obj to Makefile.nmake (0ba0683)
+ o Avoid giving a spurious warning when timerfd support is unavailable
+ (1aaf9f0 Dave Hart)
+ o Make test_evutil_monotonic a little more tolerant (def3b83)
+ o Avoid unused-var warning on systems with clock_gettime but without
+ CLOCK_MONOTONIC_COARSE (9be5468)
+
+EVENT_BASE_ONCE LEAKS:
+ If a callback added by event_base_once() is never invoked, Libevent no
+ longer leaks internal memory.
+
+ o Free dangling event_once objects on event_base_free() (c17dd59)
+ o Add a unit test in which an event is created with event_base_once()
+ but never fires (4343edf)
+
+TESTING SUPPORT, FIXES AND IMPROVEMENTS:
+
+ Libevent now disables by default its unit tests that would touch the
+ network, or that tend to fail on heavily-loaded systems. To re-enable
+ them, invoke the ./test/regress program with the @all alias.
+
+ o Simplify test.sh code significantly. (9b856fd Ross Lagerwall)
+ o Make all tests that hit the network disabled by default (f2cea87)
+ o Avoid a resource leak on error in http client benchmark (ea92fba)
+ o Update to latest tinytest (911b4f0349377) (ef7c4f7)
+ o Avoid (unlikely) overflow in bench_httpclient.c (5671033)
+ o Shave 700 msec off the persistent_timeout_jump test (21205b8)
+ o Check return value of write() in regress.c (c8009d2)
+ o Make load-dependent monotonic timer tests off-by-default (2b6fe8b)
+ o Add deferred_cb_skew to list of timing-dependent tests (34c8f31)
+ o Avoid test -e; older shs don't have one. (f1bd938)
+ o Fix renegotiation test to work around openssl 1.0.1 bug (c2f3086)
+ o Fix a couple of compile warnings in the unit tests (5a9a014)
+
+MISC:
+ o Change evutil_weakrand_() to avoid platform random() (e86af4b Nicholas
+ Marriott, 3aa4415)
+
+INFRASTRUCTURE (Active-later events):
+ As a simplification and optimization to Libevent's "deferred callback"
+ logic (introduced in 2.0 to avoid callback recursion), Libevent now
+ treats all of its deferrable callback types using the same logic it uses
+ for active events. Now deferred events no longer cause priority
+ inversion, no longer require special code to cancel them, and so on.
+
+ o Refactor the callback part of an event into its own event_callback
+ type (cba59e5)
+ o Add "active later" event_callbacks to supersede deferred (745a63d)
+ o event_base_assert_ok: check value of event_active_count for
+ correctness (fec8bae)
+ o Replace deferred_cbs with event_callback-based implementation. (ae2b84b)
+ o Replace more deferred_cb names with event_callback (a4079aa)
+ o Give event_base_process_active a single exit path (581b5be)
+ o Restore our priority-inversion-prevention code with deferreds (c0e425a)
+ o Refactor event_persist_closure: raise and extract some common logic
+ (bec22b4)
+ o Remove the unused bits from EVLIST_ALL (9889a3d)
+||||||| merged common ancestors
+Changes in version 2.0.22-stable (?? Dec 2013)
+
+ (As of 3b77d62829c4393bda6f9105a5d3b73b48a64b71.)
+
+BUGFIXES (evhttp)
+ o fix #73 and fix http_connection_fail_test to catch it (crash fix) (b618204 Greg Hazel)
+ o Avoid racy bufferevent activation (5eb1788 Nate Rosenblum)
+
+BUGFIXES (compilation and portability)
+ o Fix compilation with WIN32_HAVE_CONDITION_VARIABLES enabled (7e45739)
+ o Fix missing AC_PROG_SED on older Autoconfs (9ab2b3f Tay Ray Chuan)
+ o Backport libevent to vanilla Autoconf 2.59 (as used in RHEL5) (74d4c44 Kevin Bowling)
+ o Use AC_CONFIG_HEADERS in place of AM_CONFIG_HEADERS for autmake 1.13 compat (817ea36)
+ o Rename configure.in to configure.ac to appease newer autoconfs (0c79787)
+ o Avoid using top_srcdir in TESTS: new automakes do not like this (a55514e)
+ o Use windows vsnprintf fixup logic on all windows environments (e826f19)
+ o Fix a compiler warning when checking for arc4random_buf linker breakage. (5cb3865)
+ o Fix another arc4random_buf-related warning (e64a2b0)
+
+BUGFIXES (resource leaks/lock errors on error)
+ o Avoid leaking fds on evconnlistener with no callback set (69db261)
+ o Avoid double-close on getsockname error in evutil_ersatz_socketpair (0a822a6)
+ o Fix a locking error in bufferevent_socket_get_dns_error. (0a5eb2e)
+ o libevent/win32_dealloc() : fix sizeof(pointer) vs sizeof(*pointer) (b8f5980 Frank Denis)
+
+BUGFIXES (miscellaneous)
+ o Avoid other RNG initialization FS reads when urandom file is specified (9695e9c, bb52471)
+ o Avoid redundant invocations of init_extension_functions for IOCP (3b77d62)
+
+BUFGIXES (evdns)
+ o Checking request nameserver for NULL, before using it. (5c710c0 Belobrov Andrey)
+ o Fix SEGFAULT after evdns_base_resume if no nameservers installed. (f8d7df8 Azat Khuzhin)
+
+BUGFIXES (evutil_secure_random)
+ o When we seed from /proc/sys/kernel/random/uuid, count it as success (e35b540)
+ o Document that arc4random is not a great cryptographic PRNG. (6e49696)
+ o Add evutil_secure_rng_set_urandom_device_file (2bbb5d7)
+ o Really remove RNG seeds from the stack (f5ced88)
+
+
+DOCUMENTATION FIXES
+ o Fix a mistake in evbuffer_remove() arguments in example http server code (c322c20 Gyepi Sam)
+ o Fix a typo in a comment in buffer.h. Spotted by Alt_F4 (773b0a5)
+
+
+
+Changes in version 2.0.21-stable (18 Nov 2012)
+BUGFIXES:
+ o ssl: Don't discard SSL read event when timeout and read come close together (576b29f)
+ o ssl: Stop looping in "consider_reading" if reading is suspended. (f719b8a Joachim Bauch)
+ o ssl: No need to reserve space if reading is suspended. (1acf2eb Joachim Bauch)
+ o dns: Avoid a memory-leak on OOM in evdns. (73e85dd, f2bff75 George Danchev)
+ o build: Use python2 rather than python (0eb0109 Ross Lagerwall)
+ o build: Compile without warnings on mingw64 (94866c2)
+ o build: Fix compilation on mingw64 with -DUSE_DEBUG (62bd2c4)
+ o build: Make rpcgen_wrapper.sh work on systems without a "python2" binary (f3009e4)
+ o iocp: Close IOCP listener socket on free when LEV_OPT_CLOSE_ON_FREE is set (cb853ea Juan Pablo Fernandez)
+ o core: Avoid crash when event_pending() called with no event_base set on event (e3cccf3)
+ o misc: remove stray 'x' so print_err will compile when uncommented (ac35650 Patrick Pelletier)
+ o tests: Fix renegotiation test to work around openssl 1.0.1 bug (c2f3086)
+ o tests: Warn when openssl version in unit test mismatches compiled version. (ac009f9)
+
+
+Changes in version 2.0.20-stable (23 Aug 2012)
+BUGFIXES:
+ o core: Make event_pending() threadsafe. (be7a95c Simon Liu)
+ o win32: avoid crash when waiting forever on zero fds. (160e58b)
+ o evhttp: Fix a memory leak on error in evhttp_uriencode (11c8b31)
+ o evbuffer: Avoid possible needless call to writev. Found by coverity. (6a4ec5c)
+ o evdns: memset sockaddr_in before using it. Found by coverity. (a1a0e67)
+ o evhttp: Check more setsockopt return values when binding sockets. Found by coverity (a0912e3)
+ o evdns: Avoid segfault on weird timeout during name lookup. (dc32077 Greg Hazel)
+ o bufferevent_ssl: Correctly invoke callbacks when a SSL bufferevent reads some and then blocks. (606ac43)
+
+
+PORTABILITY FIXES:
+ o check for arc4random_buf at runtime, on OS X (bff5f94 Greg Hazel)
+ o Correctly check for arc4random_buf (fcec3e8 Sebastian Hahn)
+ o Add explicit AC_PROG_SED to configure.in so all autoconfs will expose $(SED) (ca80ea6)
+
+BUILD FIXES:
+ o Add GCC annotations so that the vsprintf functions get checked properly (117e327)
+ o Fix an unused variable warning on *BSD. (c0720c1)
+
+UNIT TEST FIXES:
+ o Fix a couple of memory leaks (found with Valgrind). (3b2529a Ross Lagerwall)
+ o Remove deadcode in http regression tests. Found by coverity. (5553346)
+ o Fix possible uninitialized read in dns regression tests. Found by coverity. (2259777)
+ o Set umask before calling mkstemp in unit tests. Found by coverity (f1ce15d)
+ o Fix various check-after-dereference issues in unit tests: found by coverity (4f3732d)
+ o Fix resource leaks in the unit tests; found by coverity (270f279)
+ o Add some missing null checks to unit tests; found by coverity (f021c3d)
+ o Avoid more crashes/bad calls in unit tests; found by coverity (3cde5bf)
+ o Remove unused variable; spotted by coverity (6355b2a)
+ o Add checks to various return values in unit tests. Found by coverity (b9e7329)
+ o Move assignment outside tt_assert in ssl unit tests. Appeases coverity. (a2006c0)
+
+
+
+Changes in version 2.0.19-stable (3 May 2012)
+BUGFIXES (CORE):
+ o Refactor event_persist_closure: raise and extract some common logic (bec22b4)
+ o If time has jumped so we'd reschedule a periodic event in the past, schedule it for the future instead (dfd808c)
+ o If a higher-priority event becomes active, don't continue running events of the current priority. (2bfda40)
+
+BUGFIXES (SSL):
+ o Fixed potential double-readcb execution with openssl bufferevents. (4e62cd1 Mark Ellzey)
+
+BUGFIXES (DNS):
+ o Cancel a probe request when the server is freed, and ignore cancelled probe callbacks (94d2336 Greg Hazel)
+ o Remove redundant DNS_ERR_CANCEL check, move comment (46b8060 Greg Hazel)
+ o When retransmitting a timed-out DNS request, pick a fresh nameserver. (3d9e52a)
+
+DOCUMENTATION FIXES:
+ o Fix a typo in the bufferevent documentation (98e9119)
+ o Add missing ) to changelog; spotted by rransom (4c7ee6b)
+ o Fix the website URL in the readme (f775521)
+
+COMPILATION FIXES:
+ o Fix a compilation error with MSVC 2005 due to use of mode_t (336dcae)
+ o Configure with gcc older than 2.95 (4a6fd43 Sebastian Hahn)
+ o Generate event-config.h with a single sed script (30b6f88 Zack Weinberg)
+
+FORWARD-COMPATIBILITY:
+ o Backport: provide EVENT_LOG_* names, and deprecate _EVENT_LOG_* (d1a03b2)
+
+TESTING/DEBUGGING SUPPORT:
+ o dns-example.c can now take a resolv.conf file on the commandline (6610fa5)
+ o Make some evdns.c debug logs more verbose (d873d67)
+ o Work-around a stupid gcov-breaking bug in OSX 10.6 (b3887cd)
+
+
+
+Changes in version 2.0.18-stable (22 Mar 2012)
+BUGFIXES (core):
+ o Make uses of open() close-on-exec safe by introducing an internal evutil_open_closeonexec. (d2b5f72 Ross Lagerwall, 03dce42)
+
+BUGFIXES (kqueue):
+ o Properly zero the kevent in kq_setup_kevent() (c2c7b39 Sebastian Hahn)
+
+BUILD FIXES:
+ o Added OPENSSL_LDFLAGS env variable which is appended to SSL checks. (9278196 Mark Ellzey)
+ o Changed OPENSSL_LDFLAGS to OPENSSL_LIBADD (2d67b63 Mark Ellzey)
+ o Don't do clang version detection when disabling some flags (083296b Sebastian Hahn)
+
+BUGFIXES (dns):
+ o Stop crashing in evdns when nameserver probes give a weird error (bec5068)
+
+
+Changes in version 2.0.17-stable (10 Feb 2012)
+
+BUGFIXES (core):
+ o Be absolutely sure to clear pncalls before leaving event_signal_closure (11f36a5)
+ o check for sysctl before we use it (358c745 Mike Frysinger)
+ o Remove bogus casts of socket to int before calling ev_callback (f032516)
+ o Make evconnlistener work around bug in older Linux when getting nmapped (ecfc720)
+ o Fix a list corruption bug when using event_reinit() with signals present (6e41cdc)
+ o Fix a fd leak in event_reinit() (3f18ad1)
+ o Do a memberwise comparison of threading function tables (c94a5f2 Nate R)
+ o Use C-style comments in C source files (for compatibility with compilers such as xlc on AIX). (d84d917 Greg Hewgill)
+ o Avoid crash when freeing event_iocp and using event_set_mem_functions (19715a6)
+ o In the kqueue backend, do not report EBADF as an EV_READ (5d7bfa1 Nicholas Marriott)
+
+BUGFIXES (evbuffer and bufferevents):
+ o Fix behavior of evbuffer_peek(buf,-1,NULL,NULL,0) (c986f23 Zack Weinberg)
+ o Loop on filtering SSL reads until we are blocked or exhausted. (5b4b812)
+
+BUGFIXES (evhttp):
+ o Force strict validation of HTTP version in response. (790f6b3 Catalin Patulea)
+
+BUGFIXES (evdns):
+ o evdns: fix a bug in circular-queue implementation (d6094b1)
+
+BUILD FIXES:
+ o Fix a silly compilation error with the sun compiler (1927776 Colin Watt)
+ o Suppress a gcc warning from ignoring fwrite return in http-sample.c (7206e8c)
+
+DOCUMENTATION FIXES:
+ o Slightly clarify evbuffer_peek documentation (7bbf6ca)
+ o Update copyright notices to 2012 (e49e289)
+
+NEW APIS:
+ o Backport evhttp_connection_get_bufferevent to Libevent 2.0 (da70fa7 Arno Bakker)
+
+TESTS AND TEST FIXES:
+ o Fix a race condition in the dns/bufferevent_connect_hostname test. (cba48c7)
+ o Add function to check referential integrity of an event_base (27737d5)
+ o Check event_base correctness at end of each unit test (3312b02)
+ o Workaround in the unit tests for an apparent epoll bug in Linux 3.2 (dab9187)
+ o Better workaround for Linux 3.2 edge-triggered epoll bug (9f9e259)
+
+Changes in version 2.0.16-stable (18 Nov 2011)
+BUGFIXES (core):
+ o More detailed message in case of libevent self-debugging failure. (9e6a4ef Leonid Evdokimov)
+ o epoll: close fd on alloc fail at initialization (1aee718 Jamie Iles)
+ o Fix compile warning from saying event2/*.h inside a comment (447b0ba)
+ o Warn when unable to construct base because of failing make_base_notifiable (4e797f3)
+ o Don't try to make notifiable event_base when no threading fns are configured (e787413)
+
+BUGFIXES (evbuffer):
+ o unit test for remove_buffer bug (90bd620 Greg Hazel)
+ o Fix an evbuffer crash in evbuffer_remove_buffer() (c37069c)
+
+BUGFIXES (bufferevent_openssl):
+ o Refactor amount-to-read calculations in buffervent_ssl consider_reading() (a186e73 Mark Ellzey)
+ o Move SSL rate-limit enforcement into bytes_to_read() (96c562f)
+ o Avoid spinning on OpenSSL reads (2aa036f Mark Ellzey)
+
+BUGFIXES (dns)
+ o Empty DNS reply with OK status is another way to say NODATA. (21a08d6 Leonid Evdokimov)
+
+TESTING:
+ o Tests for 94fba5b and f72e8f6 (d58c15e Leonid Evdokimov)
+ o Test for commit aff6ba1 (f7841bf Leonid Evdokimov)
+ o Style and comment tweaks for dns/leak* tests (5e42202)
+ o improve test to remove at least one buffer from src (7eb52eb Greg Hazel)
+
+DOCUMENTATION:
+ o Add note about evhttp_send_reply_end to its doxygen (724bfb5)
+ o Update copyright dates to 2011. (3c824bd)
+ o Fix typo in whatsnew-2.0.txt (674bc6a Mansour Moufid)
+ o Improve win32 behavior of dns-sample.c code (a3f320e Gisle Vanem)
+
+
+
+Changes in version 2.0.15-stable (12 Oct 2011)
+BUGFIXES (DNS):
+ o DNS: add ttl for negative answers using RFC 2308 idea. (f72e8f6 Leonid Evdokimov)
+ o Add DNS_ERR_NODATA error code to handle empty replies. (94fba5b Leonid Evdokimov)
+
+BUFGIXES (bufferevents and evbuffers):
+ o Make evbuffer callbacks get the right n_added value after evbuffer_add (1ef1f68 Alex)
+ o Prefer mmap to sendfile unless a DRAINS_TO_FD flag is set. Allows add_file to work with SSL. (0ba0af9)
+
+BUGFIXES (event loop):
+ o When a signal callback is activated to run multiple times, allow event_base_loopbreak to work even before they all have run. (4e8eb6a)
+
+DOCUMENTATION FIXES:
+ o Fix docstring in dns.h (2b6eae5 Leonid Evdokimov)
+ o refer to non-deprecated evdns functions in comments (ba5c27d Greg Hazel)
+
+BUILD AND TESTING FIXES:
+ o le-proxy and regress depend on openssl directly (9ae061a Sergey Avseyev)
+ o Use _SOURCES, not _sources, in sample/Makefile.am (7f82382)
+ o Fixed compiler warnings for unchecked read/write calls. (c3b62fd Mark Ellzey)
+ o Make write-checking fixes use tt_fail_perror (2b76847)
+ o Fix some "value never used" warnings with gcc 4.6.1 (39c0cf7)
+
+
+
+Changes in version 2.0.14-stable (31 Aug 2011)
+BUGFIXES (bufferevents and evbuffers):
+ o Propagate errors on the underlying bufferevent to the user. (4a34394 Joachim Bauch)
+ o Ignore OpenSSL deprecation warnings on OS X (5d1b255 Sebastian Hahn)
+ o Fix handling of group rate limits under 64 bytes of burst (6d5440e)
+ o Solaris sendfile: correctly detect amount of data sent (643922e Michael Herf)
+ o Make rate limiting work with common_timeout logic (5b18f13)
+ o clear read watermark on underlying bufferevent when creating filtering bev to fix potentially failing fragmented ssl handshakes (54f7e61 Joachim Bauch)
+
+BUGFIXES (IOCP):
+ o IOCP: don't launch reads or writes on an unconnected socket (495c227)
+ o Make IOCP rate-limiting group support stricter and less surprising. (a98da7b)
+ o Have test-ratelim.c support IOCP (0ff2c5a)
+ o Make overlapped reads result in evbuffer callbacks getting invoked (6acfbdd)
+ o Correctly terminate IO on an async bufferevent on bufferevent_free (e6af35d)
+
+BUGFIXES (other):
+ o Fix evsig_dealloc memory leak with debugging turned on. (9b724b2 Leonid Evdokimov)
+ o Fix request_finished memory leak with debugging turned on. (aff6ba1 Leonid Evdokimov)
+
+BUILD AND TESTING FIXES:
+ o Allow OS-neutral builds for platforms where some versions have arc4random_buf (b442302 Mitchell Livingston)
+ o Try to fix 'make distcheck' errors when building out-of-tree (04656ea Dave Hart)
+ o Clean up some problems identified by Coverity. (7c11e51 Harlan Stenn)
+
+
+Changes in version 2.0.13-stable (18 Jul 2011)
+BUGFIXES
+ o Avoid race-condition when initializing global locks (b683cae)
+ o Fix bug in SSL bufferevents backed by a bev with a write high-watermarks (e050703 Joachim Bauch)
+ o Speed up invoke_callbacks on evbuffers when there are no callbacks (f87f568 Mark Ellzey)
+ o Avoid a segfault when all methods are disabled or broken (27ce38b)
+ o Fix incorrect results from evbuffer_search_eol(EOL_LF) (4461f1a)
+ o Add some missing checks for mm_calloc failures (89d5e09)
+ o Replace an assertion for event_base_free(NULL) with a check-and-warn (09fe97d)
+ o Report kqueue ebadf, epipe, and eperm as EV_READ events (1fd34ab)
+ o Check if the `evhttp_new_object' function in `http.c' returns NULL. (446cc7a Mansour Moufid)
+ o Use the correct printf args when formatting size_t (3203f88)
+ o Complain if the caller tries to change threading cbs after setting them (cb6ecee)
+
+DOCUMENTATION FIXES AND IMPROVEMENTS
+ o Revise the event/evbuffer/bufferevent doxygen for clarity and accuracy (2888fac)
+ o Update Doxyfile to produce more useful output (aea0555)
+
+TEST FIXES
+ o Fix up test_evutil_snprintf (caf695a)
+ o Fix tinytest invocation from windows shell (57def34 Ed Day)
+
+BUILD FIXES
+ o Use AM_CPPFLAGS in sample/Makefile.am, not AM_CFLAGS (4a5c82d)
+ o Fix select.c compilation on systems with no NFDBITS (49d1136)
+ o Fix a few warnings on OpenBSD (8ee9f9c Nicholas Marriott)
+ o Don't break when building tests from git without python installed (b031adf)
+ o Don't install event_rpcgen.py when --disable-libevent-install is used (e23cda3 Harlan Stenn)
+ o Fix AIX build issue with TAILQ_FOREACH definition (e934096)
+
+
+Changes in version 2.0.12-stable (4 Jun 2011)
+BUGFIXES
+ o Fix a warn-and-fail bug in kqueue by providing kevent() room to report errors (28317a0)
+ o Fix an assert-inducing fencepost bug in the select backend (d90149d)
+ o Fix failing http assertion introducd in commit 0d6622e (0848814 Kevin Ko)
+ o Fix a bug that prevented us from configuring IPv6 nameservers. (74760f1)
+ o Prevent size_t overflow in evhttp_htmlescape. (06c51cd Mansour Moufid)
+ o Added several checks for under/overflow conditions in evhttp_handle_chunked_read (a279272 Mark Ellzey)
+ o Added overflow checks in evhttp_read_body and evhttp_get_body (84560fc Mark Ellzey)
+
+DOCUMENTATION:
+ o Add missing words to EVLOOP_NONBLOCK documentation (9556a7d)
+
+BUILD FIXES
+ o libssl depends on libcrypto, not the other way around. (274dd03 Peter Rosin)
+ o Libtool brings in the dependencies of libevent_openssl.la automatically (7b819f2 Peter Rosin)
+ o Use OPENSSL_LIBS in Makefile.am (292092e Sebastian Hahn)
+ o Move the win32 detection in configure.in (ceb03b9 Sebastian Hahn)
+ o Correctly detect openssl on windows (6619385 Sebastian Hahn)
+ o Fix a compile warning with zlib 1.2.4 and 1.2.5 (5786b91 Sebastian Hahn)
+ o Fix compilation with GCC 2, which had no __builtin_expect (09d39a1 Dave Hart)
+ o Fix new warnings from GCC 4.6 (06a714f)
+ o Link with -lshell32 and -ladvapi32 on Win32. (86090ee Peter Rosin)
+ o Make the tests build when OpenSSL is not available. (07c41be Peter Rosin)
+ o Bring in the compile script from automake, if needed. (f3c7a4c Peter Rosin)
+ o MSVC does not provide S_ISDIR, so provide it manually. (70be7d1 Peter Rosin)
+ o unistd.h and sys/time.h might not exist. (fe93022 Peter Rosin)
+ o Make sure TINYTEST_LOCAL is defined when building tinytest.c (8fa030c Peter Rosin)
+ o Fix winsock2.h #include issues with MSVC (3d768dc Peter Rosin)
+ o Use evutil_gettimeofday instead of relying on the system gettimeofday. (0de87fe Peter Rosin)
+ o Always use evutil_snprintf, even if OS provides it (d1b2d11 Sebastian Hahn)
+ o InitializeCriticalSectionAndSpinCount requires _WIN32_WINNT >= 0x0403. (816115a Peter Rosin)
+ o cygwin: make it possible to build DLLs (d54d3fc)
+
+
+
+Changes in version 2.0.11-stable (27 Apr 2011)
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES:
+ o Fix evport handling of POLLHUP and POLLERR (b42ce4b)
+ o Fix compilation on Windows with NDEBUG (cb8059d)
+ o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (0144886 Trond Norbye)
+ o Detect and handle more allocation failures. (666b096 Jardel Weyrich)
+ o Use event_err() only if the failure is truly unrecoverable. (3f8d22a Jardel Weyrich)
+ o Handle resize failures in the select backend better. (83e805a)
+ o Correctly free selectop fields when select_resize fails in select_init (0c0ec0b)
+ o Make --enable-gcc-warnings a no-op if not using gcc (3267703)
+ o Fix a type error in our (unused) arc4random_stir() (f736198)
+ o Correctly detect and stop non-chunked http requests when the body is too long (63a715e)
+ o Have event_base_gettimeofday_cached() always return wall-clock time (a459ef7)
+ o Workaround for http crash bug 3078187 (5dc5662 Tomash Brechko)
+ o Fix incorrect assertions and possible use-after-free in evrpc_free() (4b8f02f Christophe Fillot)
+ o Reset outgoing http connection when read data in idle state. (272823f Tomash Brechko)
+ o Fix subtle recursion in evhttp_connection_cb_cleanup(). (218cf19 Tomash Brechko)
+ o Fix the case when failed evhttp_make_request() leaved request in the queue. (0d6622e Tomash Brechko)
+ o Fix a crash bug in evdns server circular list code (00e91b3)
+ o Handle calloc failure in evdns. (Found by Dave Hart) (364291e)
+ o Fix a memory leak on win32 socket->event map. (b4f89f0)
+ o Add a forgotten NULL check to evhttp_parse_headers (12311ff Sebastian Hahn)
+ o Fix possible NULL-deref in evdns_cancel_request (5208544 Sebastian Hahn)
+
+PORTABILITY:
+ o Fall back to sscanf if we have no other way to implement strtoll (453317b)
+ o Build correctly on platforms without sockaddr_storage (9184563)
+ o Try to build correctly on platforms with no IPv6 support (713c254)
+ o Build on systems without AI_PASSIVE (cb92113)
+ o Fix http unit test on non-windows platforms without getaddrinfo (6092f12)
+ o Do not check for gethostbyname_r versions if we have getaddrinfo (c1260b0)
+ o Include arpa/inet.h as needed on HPUX (10c834c Harlan Stenn)
+ o Include util-internal.h as needed to build on platforms with no sockaddr_storage (bbf5515 Harlan Stenn)
+ o Check for getservbyname even if not on win32. (af08a94 Harlan Stenn)
+ o Add -D_OSF_SOURCE to fix hpux builds (0b33479 Harlan Stenn)
+ o Check for allocation failures in apply_socktype_protocol_hack (637d17a)
+ o Fix the check for multicast or broadcast addresses in evutil_check_interfaces (1a21d7b)
+ o Avoid a free(NULL) if out-of-memory in evdns_getaddrinfo. Found by Dave Hart (3417f68)
+
+DEFENSIVE PROGRAMMING:
+ o Add compile-time check for AF_UNSPEC==PF_UNSPEC (3c8f4e7)
+
+BUGS IN TESTS:
+ o Fix test.sh output on solaris (b4f89b6 Dave Hart)
+ o Make test-eof fail with a timeout if we never get an eof. (05a2c22 Harlan Stenn)
+ o Use %s with printf in test.sh (039b9bd)
+ o Add an assert to appease clang's static analyzer (b0ff7eb Sebastian Hahn)
+ o Add a forgotten return value check in the unit tests (3819b62 Sebastian Hahn)
+ o Actually send NULL request in http_bad_request_test (b693c32 Sebastian Hahn)
+ o add some (void) casts for unused variables (65707d7 Sebastian Hahn)
+ o Refactor test_getaddrinfo_async_cancel_stress() (48c44a6 Sebastian Hahn)
+ o Be nice and "handle" error return values in sample code (4bac793 Sebastian Hahn)
+ o Check return value of evbuffer_add_cb in tests (93a1abb Sebastian Hahn)
+ o Remote some dead code from dns-example.c (744c745 Sebastian Hahn)
+ o Zero a struct sockaddr_in before using it (646f9fe Sebastian Hahn)
+
+BUILD FIXES:
+ o Fix warnings about AC_LANG_PROGRAM usage (f663112 Sebastian Hahn)
+ o Skip check for zlib if we have no zlib.h (a317c06 Harlan Stenn)
+ o Fix autoconf bracket issues; make check for getaddrinfo include netdb.h (833e5e9 Harlan Stenn)
+ o Correct an AM_CFLAGS to an AM_CPPFLAGS in test/Makefile.am (9c469db Dave Hart)
+ o Fix make distcheck & installation of libevent 1 headers (b5a1f9f Dave Hart)
+ o Fix compilation under LLVM/clang with --enable-gcc-warnings (ad9ff58 Sebastian Hahn)
+
+FEATURES:
+ o Make URI parser able to tolerate nonconformant URIs. (95060b5)
+
+DOCUMENTATION:
+ o Clarify event_set_mem_functions doc (926f816)
+ o Correct evhttp_del_accept_socket documentation on whether socket is closed (f665924)
+ o fix spelling mistake in whatsnew-2.0.txt (deb2f73)
+ o Fix sample/http-server ipv6 fixes (eb692be)
+ o Comment internal headers used in sample code. (4eb281c)
+ o Be explicit about how long event loops run in event.h documentation (f95bafb)
+ o Add comment to configure.in to explain gc-sections test logic (c621359)
+ o Fix a couple of memory leaks in samples/http-server.c. Found by Dave Hart. (2e9f665)
+
+
+
+BUILD IMPROVEMENTS:
+ Libevent 2.1.2-alpha modernizes Libevent's use of autotools, and makes
+ numerous other build system. Parallel builds should be faster, and all
+ builds should be quieter.
+
+ o Split long lists in Makefile.am into one-item-per-line (2711cda)
+ o Remove unnecessary code in configure.in. (e65914f Ross Lagerwall)
+ o attempt to support OpenSSL in Makefile.nmake (eba0eb2 Patrick Pelletier)
+ o Use newer syntax for autoconf/automake init (7d60ba8)
+ o Enable silent build rules by default. Override with V=1 (7b18e5c)
+ o Switch to non-recursive makefiles (7092f3b)
+ o Rename subordinate Makefile.ams to include.am (6cdfeeb)
+ o Make quiet build even quieter (371a123)
+ o New --quiet option for event_rpcgen.py (aa59c1e)
+ o Be quiet when making regress.gen.[ch] (607a8ff)
+ o Fix handling of no-python case for nonrecursive make (1e3123d)
+ o We now require automake 1.9 or later. Modernize! (b7f6e89)
+ o Rename configure.in to configure.ac. (b3fea67 Ross Lagerwall)
+ o Use correct openssl libs and includes in pkgconfig file (d70af27)
+ o Use the same CFLAGS for openssl when building unit tests as with
+ libevent (1d9d511)
+
+DOCUMENTATION
+ o Note that make_base_notifiable should not be necessary (26ee5f9)
+ o Be more clear that LEV_OPT_DEFERRED_ACCEPT has tricky prereqs (371efeb)
+ o Add caveat to docs about bufferevent_free() with data in outbuf (6fab9ee)
+ o Make it more clear that NOLOCK means "I promise, no multithreading"
+ (9444524)
+ o Fix a comment in test-fdleak after 077c7e949. (3881d8f Ross Lagerwall)
+ o Make the Makefile.nmake warning slightly less dire (e7bf4c8)
+ o Fix typo : events instead of evets (05f1aca Azat Khuzhin)
+ o Additional comments about OPENSSL_DIR variable, prompted by Dave Hart
+ (6bde2ef Patrick Pelletier)
+
+EVHTTP:
+ o ignore LWS after field-content in headers (370a2c0 Artem Germanov)
+ o Clean up rtrim implementation (aa59d80)
+ o Remove trailing tabs in HTTP headers as well. (ac42519)
+ o Remove internal ws from multiline http headers correctly (c6ff381)
+ o Move evutil_rtrim_lws_ to evutil.c where it belongs (61b93af)
+ o add evhttp_request_get_response_code_line (4f4d0c9 Jay R. Wren)
+ o Use EVUTIL_SOCKET_ERROR() wrapper to save/restore errno in
+ evhttp_connection_fail_ (7afbd60)
+ o preserve errno in evhttp_connection_fail_ for inspection by the
+ callback (36d0ee5 Patrick Pelletier)
+
+BUGFIXES:
+ o Correctly handle running on a system where accept4 doesn't work. (9fbfe9b)
+ o Avoid double-free on error in evbuffer_add_file. Found by
+ coverity. (6a81b1f)
+ o Fix another possible uninitialized read in dns regression tests. Found
+ by coverity. (13525c5)
+ o Add checks for functions in test-ratelim.c; found by Coverity (aa501e1)
+ o Avoid memory leak in test_event_calloc unit test; found by coverity
+ (92817a1)
+ o Fix a shadowed variable in addfile_test_readcb; found by coverity
+ (225344c)
+ o Check return value when using LEV_OPT_DEFERRED_ACCEPT. Found by
+ coverity (6487f63)
+ o Prevent reference leak of bufferevent if getaddrinfo fails. (b757786
+ Joachim Bauch)
+ o Make event_base_getnpriorities work with old "implicit base" code
+ (c46cb9c)
+ o Simplify and correct evutil_open_closeonexec_ (0de587f)
+ o Fix event_dlist definition when sys/queue not included (81b6209
+ Derrick Pallas)
+
+
+
+Changes in version 2.1.1-alpha (4 Apr 2012)
+
+ Libevent 2.1.1-alpha includes a number of new features and performance
+ improvements. The log below tries to organize them by rough area of
+ effect. It omits some commits which were pure bugfixes on other commits
+ listed below. For more detail, see the git changelogs. For more
+ insight, see the "whatsnew-2.1.txt" document included in the Libevent
+ 2.1.1-alpha distribution.
+
+ Performance: Core
+ o Replace several TAILQ users with LIST. LIST can be a little faster than
+ TAILQ for cases where we don't need queue-like behavior. (f9db33d,
+ 6494772, d313c29, 974d004)
+ o Disabled code to optimize the case where we reinsert an existing
+ timeout (e47042f, 09cbc3d)
+ o Remove a needless base-notify when rescheduling the first timeout (77a96fd)
+ o Save a needless comparison when removing/adjusting timeouts (dd5189b)
+ o Possible optimization: split event_queue_insert/remove into
+ separate functions. needs testing (efc4dc5)
+ o Make event_count maintenance branchless at the expense of an
+ extra shift. Needs benchmarking (d1cee3b)
+ o In the 2.1 branch, let's try out lazy gettimeofday/clock_gettime
+ comparison (2a83ecc)
+ o Optimization in event_process_active(): ignore maxcb & endtime
+ for highest priority events. (a9866aa Alexander Drozdov)
+ o Bypass event_add when using event_base_once() for a 0-sec timeout (35c5c95)
+ o Remove the eventqueue list and the ev_next pointers. (604569b 066775e)
+
+ Performance: Evbuffers
+ o Roughly 20% speed increase when line-draining a buffer using
+ EVBUFFER_EOL_CRLF (5dde0f0 Mina Naguib)
+ o Try to squeeze a little more speed out of EVBUFFER_EOL_CRLF (7b9d139)
+ o Fix a bug in the improved EOL_CRLF code (d927965)
+ o Remove a needless branch in evbuffer_drain() (d19a326)
+
+ Performance: Linux
+ o Infrastructure for using faster/fewer syscalls when creating
+ sockets (a1c042b)
+ o Minimize syscalls during socket creation in listener.c (7e9e289)
+ o Use a wrapper function to create the notification
+ pipe/socketpair/eventfd (ca76cd9)
+ o Use pipes for telling signals to main thread when possible (a35f396)
+ o Save syscalls when constructing listener sockets for evhttp (af6c9d8)
+ o Save some syscalls when creating evdns sockets (713e570)
+ o Save some syscalls when constructing a socket for a bufferevent (33fca62)
+ o Prefer epoll_create1 on Linuxen that have it (bac906c)
+
+ Performance: Epoll backend
+ o Use current event set rather than current pending change when
+ deciding whether to no-op a del (04ba27e Mike Smellie)
+ o Replace big chain of if/thens in epoll.c with a table lookup (8c83eb6)
+ o Clean up error handling in epoll_apply_one_change() a little (2d55a19)
+
+ Performance: Evport backend
+ o evport: use evmap_io to track fdinfo status. Should save time and
+ RAM. (4687ce4)
+ o evport: Remove a linear search over recent events when
+ reactivating them (0f77efe)
+ o evport: Use portev_user to remember fdinfo struct (276ec0e)
+ o evport: don't scan more events in ed_pending than needed (849a5cf)
+ o evport: Remove artificial low limit on max events per getn call (c04d927)
+ o Reenable main/many_events_slow_add for evport in 2.1 (e903db3)
+
+ Performance: Windows
+ o Use GetSystemTimeAsFileTime to implement gettimeofday on
+ win32. It's faster and more accurate than our old
+ approach. (b8b8aa5)
+
+ New functions and features: debugging
+ o Add event_enable_debug_logging() to control use of debug logs (e30a82f)
+
+ New functions and features: core
+ o Add event_config function to limit time/callbacks between calls
+ to dispatch (fd4de1e, 9fa56bd, a37a0c0, 3c63edd)
+ o New EVLOOP_NO_EXIT_ON_EMPTY option to keep looping even when no
+ events are pending (084e68f)
+ o Add event_base_get_npriorities() function. (ee3a4ee Alexander Drozdov)
+ o Make evbase_priority_init() and evbase_get_npriorities()
+ threadsafe (3c55b5e)
+ o New event_base_update_cache_time() to set cached_tv to current
+ time (212533e Abel Mathew)
+ o Add event_self_cbarg() to be used in conjunction with
+ event_new(). (ed36e6a Ross Lagerwall, fa931bb, 09a1906, 1338e6c,
+ 33e43ef)
+ o Add a new libevent_global_shutdown() to free all globals before
+ exiting. (041ca00 Mark Ellzey, f98c158, 15296d0, 55e991b)
+ o Use getifaddrs to detect our interfaces if possible (7085a45)
+ o Add event_base_get_running_event() to get the event* whose cb we
+ are in (c5732fd, 13dad99)
+
+ New functions and features: building
+ o Implement --enable-gcc-hardening configure option (7550267 Sebastian Hahn)
+
+ New functions and features: evbuffers
+ o Add evbuffer_add_file_segment() so one fd can be used efficiently
+ in more than one evbuffer_add_file at a time (e72afae, c2d9884,
+ 3f405d2, 0aad014)
+ o Fix windows file segment mappings (8254de7)
+ o Allow evbuffer_ptr_set to yield a point just after the end of the
+ buffer. (e6fe1da)
+ o Allow evbuffer_ptr to point to position 0 in an empty evbuffer
+ (7aeb2fd Nir Soffer)
+ o Set the special "not found" evbuffer_ptr consistently. (e3e97ae Nir Soffer)
+ o support adding buffers to other buffers non-destructively
+ (9d7368a Joachim Bauch)
+ o prevent nested multicast references, reworked locking (26041a8
+ Joachim Bauch)
+ o New EVBUFFER_EOL_NUL to read NUL-terminated strings from an
+ evbuffer (d7a8b36 Andrea Montefusco, 54142c9)
+ o Make evbuffer_file_segment_types adaptable (c6bbbf1)
+ o Added evbuffer_add_iovec and unit tests. (aaec5ac Mark Ellzey, 27b5398)
+ o Add evbuffer_copyout_from to copy data from the middle of a
+ buffer (27e2225)
+
+ New functions and features: bufferevents
+ o Allow users to set allow_dirty_shutdown (099d27d Catalin Patulea)
+ o Tweak allow_dirty_shutdown documentation (a44cd2b)
+ o Fix two issues in the allow_dirty_shutdown code. (f3b89de)
+ o Add a bufferevent_getcb() to find a bufferevent's current
+ callbacks (a650394)
+ o bufferevent: Add functions to set/get max_single_read/write
+ values. (998c813 Alexander Drozdov)
+ o bev_ssl: Be more specific in event callbacks. evhttp in particular gets
+ confused without at least one of BEV_EVENT_{READING|WRITING}. (f7eb69a
+ Catalin Patulea)
+
+ New functions and features: evconnlisteners
+ o Support TCP_DEFER_ACCEPT sockopts for listeners (5880e4a Mark Ellzey,
+ a270728)
+ o Add another caveat to the TCP_DEFER_ACCEPT documentation (a270728)
+ o Allow evconnlistener to be created in disabled state. (9593a33
+ Alexander Drozdov)
+ o The LEV_OPT_CLOSE_ON_EXEC flag now applies to accepted listener
+ sockets too (4970329)
+
+ Evhttp:
+ o Add new evhttp_{connection_}set_timeout_tv() functions to set
+ finger-grained http timeouts (6350e6c Constantine Verutin)
+ o Performance tweak to evhttp_parse_request_line. (aee1a97 Mark Ellzey)
+ o Add missing break to evhttp_parse_request_line (0fcc536)
+ o Add evhttp callback for bufferevent creation; this lets evhttp
+ support SSL. (8d3a850)
+ o Remove calls to deprecated bufferevent functions from evhttp.c (4d63758)
+ o evhttp: Add evhttp_foreach_bound_socket. (a2c48e3 Samy Al Bahra)
+
+ Build improvements:
+ o Add AC_USE_SYSTEM_EXTENSIONS to configure.in. Requires follow on
+ patches for correctness and robustness. (1fa7dbe Kevin Bowling)
+ o Filter '# define' statements from autoconf and generate
+ event-private.h (321b558 Kevin Bowling)
+ o Remove internal usage of _GNU_SOURCE (3b26541 Kevin Bowling)
+ o Eliminate a couple more manual internal _GNU_SOURCE defines (c51ef93
+ Kevin Bowling)
+ o Add AC_GNU_SOURCE to the fallback case. (ea8fa4c Kevin Bowling)
+ o Use a Configuration Header Template for evconfig-private.h (868f888
+ Kevin Bowling)
+ o Fix a comment warning and add evconfig-private.h to .gitignore
+ (f6d66bc Kevin Bowling)
+ o Include evconfig-private.h in internal files for great good. (0915ca0
+ Kevin Bowling)
+ o Backport libevent to vanilla Autoconf 2.59 (as used in RHEL5)
+ (ad03952 Kevin Bowling)
+ o Prefer the ./configure evconfig-private.h in MinGW, just in
+ case. (f964b72 Kevin Bowling)
+ o Shell hack for weird mkdir -p commands (fd7b5a8 Kevin Bowling)
+ o Add evconfig-private to remaining files (ded0a09 Kevin Bowling)
+ o Allow use of --enable-silent-rules for quieter compilation with
+ automake 1.11 (f1f8514 Dave Hart)
+ o Use "_WIN32", not WIN32: it's standard and we don't need to fake it
+ (9f560b)
+ o In configure, test for _WIN32 not WIN32. (85078b1 Peter Rosin)
+ o Do not define WIN32 in Makefile.nmake (d41f3ea Peter Rosin)
+ o Provide the autoconf m4 macros for the new OpenSSL via pkg-config
+ stuff. (674dc3d Harlan Stenn)
+ o Use pkg-config (if available) to handle OpenSSL. (1c63860 Harlan Stenn)
+ o We need AM_CPPFLAGS when compiling bufferevent_openssl.c (6d2613b
+ Harlan Stenn)
+ o Fix OSX build: $(OPENSSL_INCS) needs to be after
+ $(AM_CPPFLAGS). (46f1769 Zack Weinberg)
+ o Make gcc warnings on by default, and --enable-gcc-warnings only add
+ -Werror (d46517e Sebastian Hahn)
+ o Split up extra-long AC_CHECK_FUNCS/HEADERS lines in configure.in (88a30ad)
+ o Move libevent 1.x headers to include/, to put all public headers in
+ one place. (bbea8d6)
+ o Put #ifdef around some files to support alternate build
+ systems. (76d4c92 Ross Lagerwall)
+ o Also make win32select.c conditional for IDE users (bf2c5a7)
+
+ Debugging:
+ o Add a magic number to debug_locks to better catch lock-coding
+ errors. (b4a29c0 Dave Hart)
+ o munge the debug_lock signature before freeing it: it might help us
+ catch use-after-free (f28084d)
+ o Added --enable-event-debugging in configure (bc7b4e4, a9c2c9a Mark Ellzey)
+ o Debug addition for printing usec on TIMEOUT debugging. (ac43ce0 Mark Ellzey)
+ o Added usec debug in another area for debug (3baab0d Mark Ellzey)
+ o added timeout debug logs to include event ptr. (4b7d298 Mark Ellzey)
+ o more event dbg updates (6727543 Mark Ellzey)
+ o Clarify event_enable_debug_logging a little (6207826)
+ o Make --enable-verbose-debug option match its help text (10c3450)
+ o Add argument checks to some memory functions in `event.c'. (c8953d1
+ Mansour Moufid)
+
+ Testing:
+ o More abstraction in test.sh (cd74c4e)
+ o Add failing test for evbuffer_search_range. (8e26154 Nir Soffer)
+ o Tweaks to return types with end-of-buf ptrs (9ab8ab8)
+ o Add an (internal) usleep function for use by unit tests (f25d9d3)
+ o Synchronize with upstream tinytest (6c81be7)
+ o Make test-changelist faster (7622d26)
+ o Reduce the timeout in the main/fork test. (ab14f7c)
+ o New evhttp function to adjust initial retry timeout (350a3c4)
+ o Make regression tests run over 3x faster. (67a1763)
+ o Use test_timeval_diff_eq more consistently (b77b43f)
+ o Allow more slop in deferred_cb_skew test; freebsd needs it (b9f7e5f)
+ o When including an -internal.h header outside the main tree, do so
+ early (95e2455)
+ o Add a new test: test-fdleak which tests for fd leaks by creating many
+ sockets. (2ef9278 Ross Lagerwall, f7af194, 1c4288f, etc)
+ o Add a unit test for event_base_dump_events() (7afe48a, 8d08cce)
+ o Test more bufferevent_ratelim features (c24f91a)
+
+ Documentation:
+ o Improve evbuffer_ptr documentation (261ba63)
+ o added comments to describe refcounting of multicast chains (ba24f61
+ Joachim Bauch)
+ o Add doxygen for event_base_dump_events (cad5753)
+
+ OSX:
+ o Use "unlimited select" on OSX so that we can have more than
+ FD_SETSIZE fds (1fb5cc6)
+
+ KQueue:
+ o Use SIG_IGN instead of a do-nothing handler for signal events with
+ kqueue (148458e Zack Weinberg)
+
+ evprc:
+ o event_rpcgen.py now prints status information to stdout and errors to
+ stderr. (ffb0ba0 Ross Lagerwall)
+
+ Code improvement and refactoring:
+ o Make event_reinit() more robust and maintainable (272033e)
+ o Restore fast-path event_reinit() for slower backends (2c4b5de)
+ o Check changelist as part of checking representational integrity (39b3f38)
+ o Fix a compile warning in event_reinit (e4a56ed Sebastian Hahn)
+ o Refactor the functions that run over every event. (c89b4e6)
+ o Remove the last vestiges of _EVENT_USE_EVENTLIST (a3cec90)
+ o Make event-config.h depend on Makefile.am (2958a5c)
+
+ Build fixes:
+ o Don't do clang version detection when disabling some flags (083296b
+ Sebastian Hahn)
+
+ C standards conformance:
+ o Check for NULL return on win32 mm_calloc, and set ENOMEM. (af7ba69)
+ o Convert event-config.h macros to avoid reserved identifiers (68120d9)
+ o Generate event-config.h using the correct macros. (f82c57e)
+ o Convert include-guard macro convention to avoid reserved identifiers
+ (3f8c7cd)
+ o Make event_rpcgen.py output conform to identifier conventions (372bff1)
+ o Stop referring to an obsolete include guard in bench_http.h (5c0f7e0)
+ o Make the generated event-config.h use correct include guards (639383a)
+ o Fix all identifiers with names beginning with underscore. (cb9da0b)
+ o Make event_rpcgen.py output conform to identifier conventions, more
+ (bcefd24)
+ o Fix some problems introduced by automated identifier cleanup script
+ (c963534)
+ o Have all visible internal function names end with an underscore. (8ac3c4c)
+ o Apply the naming convention to our EVUTIL_IS* functions (c7848fa)
+ o Clean up lingering _identifiers. (946b584)
+ o Fix doxygen to use new macro conventions (da455e9)
+
+ Bugfixes:
+ o Do not use system EAI/AI values if we are not using the system
+ getaddrinfo. (7bcac07)
+
+ Sample Code:
+ o Fix up sample/event-test.c to use newer interfaces and make it
+ actually work. (19bab4f Ross Lagerwall)
+ o On Unix, remove event.fifo left by sample/event-test.c. (c0dacd2 Ross
+ Lagerwall)
+ o Rename event-test.c to event-read-fifo.c. (a5b370a Ross Lagerwall)
+ o event-read-fifo: Use EV_PERSIST appropriately (24dab0b)
+
+
+
+
diff --git a/ipc/chromium/src/third_party/libevent/ChangeLog-1.4 b/ipc/chromium/src/third_party/libevent/ChangeLog-1.4
new file mode 100644
index 0000000000..d7f6517b2b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ChangeLog-1.4
@@ -0,0 +1,231 @@
+Changes in 1.4.14b-stable
+ o Set the VERSION_INFO correctly for 1.4.14
+
+Changes in 1.4.14-stable
+ o Add a .gitignore file for the 1.4 branch. (d014edb)
+ o Backport evbuffer_readln(). (b04cc60 Nicholas Marriott)
+ o Make the evbuffer_readln backport follow the current API (c545485)
+ o Valgrind fix: Clear struct kevent before checking for OSX bug. (5713d5d William Ahern)
+ o Fix a crash when reading badly formatted resolve.conf (5b10d00 Yasuoka Masahiko)
+ o Fix memory-leak of signal handler array with kqueue. [backport] (01f3775)
+ o Update sample/signal-test.c to use newer APIs and not leak. (891765c Evan Jones)
+ o Correct all versions in 1.4 branch (ac0d213)
+ o Make evutil_make_socket_nonblocking() leave any other flags alone. (81c26ba Jardel Weyrich)
+ o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (5f2e250 Jardel Weyrich)
+ o Correct a debug message in evhttp_parse_request_line (35df59e)
+ o Merge branch 'readln-backport' into patches-1.4 (8771d5b)
+ o Do not send an HTTP error when we've already closed or responded. (4fd2dd9 Pavel Plesov)
+ o Re-add event_siglcb; some old code _was_ still using it. :( (bd03d06)
+ o Make Libevent 1.4 build on win32 with Unicode enabled. (bce58d6 Brodie Thiesfield)
+ o Distribute nmake makefile for 1.4 (20d706d)
+ o do not fail while sending on http connections the client closed. (5c8b446)
+ o make evhttp_send() safe against terminated connections, too (01ea0c5)
+ o Fix a free(NULL) in min_heap.h (2458934)
+ o Fix memory leak when setting up priorities; reported by Alexander Drozdov (cb1a722)
+ o Clean up properly when adding a signal handler fails. (ae6ece0 Gilad Benjamini)
+ o Do not abort HTTP requests missing a reason string. (29d7b32 Pierre Phaneuf)
+ o Fix compile warning in http.c (906d573)
+ o Define _REENTRANT as needed on Solaris, elsewhere (6cbea13)
+
+
+Changes in 1.4.13-stable:
+ o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it. Fixes bug 2841177; found by Alexander Pronchenkov.
+ o Do not allocate the maximum event queue and fd array for the epoll backend at startup. Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them. Saves up to 512K per epoll-based event_base. Resolves bug 2839240.
+ o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
+ o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
+ o Rename our replacement compat/sys/_time.h header to avoid build a conflict on HPUX; reported by Kathryn Hogg.
+ o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
+ o Fix a problem with excessive memory allocation when using multiple event priorities.
+ o When running set[ug]id, don't check the environment. Based on a patch from OpenBSD.
+
+
+Changes in 1.4.12-stable:
+ o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
+ o Fix an obscure timing-dependent, allocator-dependent crash in the evdns code.
+ o Use __VA_ARGS__ syntax for varargs macros in event_rpcgen when compiler is not GCC.
+ o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
+ o Fix another pair of fencepost bugs in epoll.c. [Patch from Adam Langley.]
+ o Do not break evdns connections to nameservers when our IP changes.
+ o Set truncated flag correctly in evdns server replies.
+ o Disable strict aliasing with GCC: our code is not compliant with it.
+
+Changes in 1.4.11-stable:
+ o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
+ o Remove the limit on size of HTTP headers by removing static buffers.
+ o Fix a nasty dangling pointer bug in epoll.c that could occur after epoll_recalc(). [Patch from Kevin Springborn]
+ o Distribute Win32-Code/event-config.h, not ./event-config.h
+
+Changes in 1.4.10-stable:
+ o clean up buffered http connection data on reset; reported by Brian O'Kelley
+ o bug fix and potential race condition in signal handling; from Alexander Drozdov
+ o rename the Solaris event ports backend to evport
+ o support compilation on Haiku
+ o fix signal processing when a signal callback delivers a signal; from Alexander Drozdov
+ o const-ify some arguments to evdns functions.
+ o off-by-one error in epoll_recalc; reported by Victor Goya
+ o include Doxyfile in tar ball; from Jeff Garzik
+ o correctly parse queries with encoded \r, \n or + characters
+
+Changes in 1.4.9-stable:
+ o event_add would not return error for some backends; from Dean McNamee
+ o Clear the timer cache on entering the event loop; reported by Victor Chang
+ o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
+ o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
+ o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
+ o Fix a typo in setting the global event base; reported by lance.
+ o Fix a memory leak when reading multi-line headers
+ o Fix a memory leak by not running explicit close detection for server connections
+
+Changes in 1.4.8-stable:
+ o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
+ o Fix a merge problem in which name_from_addr returned pointers to the stack; found by Jiang Hong.
+ o Do not remove Accept-Encoding header
+
+Changes in 1.4.7-stable:
+ o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
+
+Changes in 1.4.6-stable:
+ o evutil.h now includes <stdarg.h> directly
+ o switch all uses of [v]snprintf over to evutil
+ o Correct handling of trailing headers in chunked replies; from Scott Lamb.
+ o Support multi-line HTTP headers; based on a patch from Moshe Litvin
+ o Reject negative Content-Length headers; anonymous bug report
+ o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report
+ o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
+ o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
+ o Deal with evbuffer_read() returning -1 on EINTR|EAGAIN; from Adam Langley.
+ o Fix a bug in which the DNS server would incorrectly set the type of a cname reply to a.
+ o Fix a bug where setting the timeout on a bufferevent would take not effect if the event was already pending.
+ o Fix a memory leak when using signals for some event bases; reported by Alexander Drozdov.
+ o Add libevent.vcproj file to distribution to help with Windows build.
+ o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov.
+ o Fix off-by-one errors in devpoll; from Ian Bell
+ o Make event_add not change any state if it fails; reported by Ian Bell.
+ o Do not warn on accept when errno is either EAGAIN or EINTR
+
+Changes in 1.4.5-stable:
+ o Fix connection keep-alive behavior for HTTP/1.0
+ o Fix use of freed memory in event_reinit; pointed out by Peter Postma
+ o Constify struct timeval * where possible; pointed out by Forest Wilkinson
+ o allow min_heap_erase to be called on removed members; from liusifan.
+ o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT. Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
+ o Do not use SO_REUSEADDR when connecting
+ o Fix Windows build
+ o Fix a bug in event_rpcgen when generated fixed-sized entries
+
+Changes in 1.4.4-stable:
+ o Correct the documentation on buffer printf functions.
+ o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
+ o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c. This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
+ o Fix a potential stack corruption bug in tagging on 64-bit CPUs.
+ o expose bufferevent_setwatermark via header files and fix high watermark on read
+ o fix a bug in bufferevent read water marks and add a test for them
+ o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
+ o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
+ o reduce system calls for getting current time by caching it.
+ o fix evhttp_bind_socket() so that multiple sockets can be bound by the same http server.
+ o Build test directory correctly with CPPFLAGS set.
+ o Fix build under Visual C++ 2005.
+ o Expose evhttp_accept_socket() API.
+ o Merge windows gettimeofday() replacement into a new evutil_gettimeofday() function.
+ o Fix autoconf script behavior on IRIX.
+ o Make sure winsock2.h include always comes before windows.h include.
+
+Changes in 1.4.3-stable:
+ o include Content-Length in reply for HTTP/1.0 requests with keep-alive
+ o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
+ o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
+ o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
+ o make event methods static so that they are not exported; from Andrei Nigmatulin
+ o make RPC replies use application/octet-stream as mime type
+ o do not delete uninitialized timeout event in evdns
+
+Changes in 1.4.2-rc:
+ o remove pending timeouts on event_base_free()
+ o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
+ o devpoll and evport need reinit; tested by W.C.A Wijngaards
+ o event_base_get_method; from Springande Ulv
+ o Send CRLF after each chunk in HTTP output, for compliance with RFC2626. Patch from "propanbutan". Fixes bug 1894184.
+ o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
+ o Use a 64-bit field to hold HTTP content-lengths. Patch from Scott Lamb.
+ o Allow regression code to build even without Python installed
+ o remove NDEBUG ifdefs from evdns.c
+ o update documentation of event_loop and event_base_loop; from Tani Hosokawa.
+ o detect integer types properly on platforms without stdint.h
+ o Remove "AM_MAINTAINER_MODE" declaration in configure.in: now makefiles and configure should get re-generated automatically when Makefile.am or configure.in chanes.
+ o do not insert event into list when evsel->add fails
+
+Changes in 1.4.1-beta:
+ o free minheap on event_base_free(); from Christopher Layne
+ o debug cleanups in signal.c; from Christopher Layne
+ o provide event_base_new() that does not set the current_base global
+ o bufferevent_write now uses a const source argument; report from Charles Kerr
+ o better documentation for event_base_loopexit; from Scott Lamb.
+ o Make kqueue have the same behavior as other backends when a signal is caught between event_add() and event_loop(). Previously, it would catch and ignore such signals.
+ o Make kqueue restore signal handlers correctly when event_del() is called.
+ o provide event_reinit() to reintialize an event_base after fork
+ o small improvements to evhttp documentation
+ o always generate Date and Content-Length headers for HTTP/1.1 replies
+ o set the correct event base for HTTP close events
+ o New function, event_{base_}loopbreak. Like event_loopexit, it makes an event loop stop executing and return. Unlike event_loopexit, it keeps subsequent pending events from getting executed. Patch from Scott Lamb
+ o Removed obsoleted recalc code
+ o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
+ o fix a bug with event_rpcgen for integers
+ o move EV_PERSIST handling out of the event backends
+ o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
+ o prefix {encode,decode}_tag functions with evtag to avoid collisions
+ o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
+ o The configure script now takes an --enable-gcc-warnings option that turns on many optional gcc warnings. (Nick has been building with these for a while, but they might be useful to other developers.)
+ o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
+ o removed linger from http server socket; reported by Ilya Martynov
+ o allow \r or \n individually to separate HTTP headers instead of the standard "\r\n"; from Charles Kerr.
+ o demote most http warnings to debug messages
+ o Fix Solaris compilation; from Magne Mahre
+ o Add a "Date" header to HTTP responses, as required by HTTP 1.1.
+ o Support specifying the local address of an evhttp_connection using set_local_address
+ o Fix a memory leak in which failed HTTP connections would not free the request object
+ o Make adding of array members in event_rpcgen more efficient, but doubling memory allocation
+ o Fix a memory leak in the DNS server
+ o Fix compilation when DNS_USE_OPENSSL_FOR_ID is enabled
+ o Fix buffer size and string generation in evdns_resolve_reverse_ipv6().
+ o Respond to nonstandard DNS queries with "NOTIMPL" rather than by ignoring them.
+ o In DNS responses, the CD flag should be preserved, not the TC flag.
+ o Fix http.c to compile properly with USE_DEBUG; from Christopher Layne
+ o Handle NULL timeouts correctly on Solaris; from Trond Norbye
+ o Recalculate pending events properly when reallocating event array on Solaris; from Trond Norbye
+ o Add Doxygen documentation to header files; from Mark Heily
+ o Add a evdns_set_transaction_id_fn() function to override the default
+ transaction ID generation code.
+ o Add an evutil module (with header evutil.h) to implement our standard cross-platform hacks, on the theory that somebody else would like to use them too.
+ o Fix signals implementation on windows.
+ o Fix http module on windows to close sockets properly.
+ o Make autogen.sh script run correctly on systems where /bin/sh isn't bash. (Patch from Trond Norbye, rewritten by Hagne Mahre and then Hannah Schroeter.)
+ o Skip calling gettime() in timeout_process if we are not in fact waiting for any events. (Patch from Trond Norbye)
+ o Make test subdirectory compile under mingw.
+ o Fix win32 buffer.c behavior so that it is correct for sockets (which do not like ReadFile and WriteFile).
+ o Make the test.sh script run unit tests for the evpoll method.
+ o Make the entire evdns.h header enclosed in "extern C" as appropriate.
+ o Fix implementation of strsep on platforms that lack it
+ o Fix implementation of getaddrinfo on platforms that lack it; mainly, this will make Windows http.c work better. Original patch by Lubomir Marinov.
+ o Fix evport implementation: port_disassociate called on unassociated events resulting in bogus errors; more efficient memory management; from Trond Norbye and Prakash Sangappa
+ o support for hooks on rpc input and output; can be used to implement rpc independent processing such as compression or authentication.
+ o use a min heap instead of a red-black tree for timeouts; as a result finding the min is a O(1) operation now; from Maxim Yegorushkin
+ o associate an event base with an rpc pool
+ o added two additional libraries: libevent_core and libevent_extra in addition to the regular libevent. libevent_core contains only the event core whereas libevent_extra contains dns, http and rpc support
+ o Begin using libtool's library versioning support correctly. If we don't mess up, this will more or less guarantee binaries linked against old versions of libevent continue working when we make changes to libevent that do not break backward compatibility.
+ o Fix evhttp.h compilation when TAILQ_ENTRY is not defined.
+ o Small code cleanups in epoll_dispatch().
+ o Increase the maximum number of addresses read from a packet in evdns to 32.
+ o Remove support for the rtsig method: it hasn't compiled for a while, and nobody seems to miss it very much. Let us know if there's a good reason to put it back in.
+ o Rename the "class" field in evdns_server_request to dns_question_class, so that it won't break compilation under C++. Use a macro so that old code won't break. Mark the macro as deprecated.
+ o Fix DNS unit tests so that having a DNS server with broken IPv6 support is no longer cause for aborting the unit tests.
+ o Make event_base_free() succeed even if there are pending non-internal events on a base. This may still leak memory and fds, but at least it no longer crashes.
+ o Post-process the config.h file into a new, installed event-config.h file that we can install, and whose macros will be safe to include in header files.
+ o Remove the long-deprecated acconfig.h file.
+ o Do not require #include <sys/types.h> before #include <event.h>.
+ o Add new evutil_timer* functions to wrap (or replace) the regular timeval manipulation functions.
+ o Fix many build issues when using the Microsoft C compiler.
+ o Remove a bash-ism in autogen.sh
+ o When calling event_del on a signal, restore the signal handler's previous value rather than setting it to SIG_DFL. Patch from Christopher Layne.
+ o Make the logic for active events work better with internal events; patch from Christopher Layne.
+ o We do not need to specially remove a timeout before calling event_del; patch from Christopher Layne.
diff --git a/ipc/chromium/src/third_party/libevent/ChangeLog-2.0 b/ipc/chromium/src/third_party/libevent/ChangeLog-2.0
new file mode 100644
index 0000000000..16f36008cd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ChangeLog-2.0
@@ -0,0 +1,1280 @@
+Changes in version 2.0.21-stable (18 Nov 2012)
+BUGFIXES:
+ o ssl: Don't discard SSL read event when timeout and read come close together (576b29f)
+ o ssl: Stop looping in "consider_reading" if reading is suspended. (f719b8a Joachim Bauch)
+ o ssl: No need to reserve space if reading is suspended. (1acf2eb Joachim Bauch)
+ o dns: Avoid a memory-leak on OOM in evdns. (73e85dd, f2bff75 George Danchev)
+ o build: Use python2 rather than python (0eb0109 Ross Lagerwall)
+ o build: Compile without warnings on mingw64 (94866c2)
+ o build: Fix compilation on mingw64 with -DUSE_DEBUG (62bd2c4)
+ o build: Make rpcgen_wrapper.sh work on systems without a "python2" binary (f3009e4)
+ o iocp: Close IOCP listener socket on free when LEV_OPT_CLOSE_ON_FREE is set (cb853ea Juan Pablo Fernandez)
+ o core: Avoid crash when event_pending() called with no event_base set on event (e3cccf3)
+ o misc: remove stray 'x' so print_err will compile when uncommented (ac35650 Patrick Pelletier)
+ o tests: Fix renegotiation test to work around openssl 1.0.1 bug (c2f3086)
+ o tests: Warn when openssl version in unit test mismatches compiled version. (ac009f9)
+
+
+Changes in version 2.0.20-stable (23 Aug 2012)
+BUGFIXES:
+ o core: Make event_pending() threadsafe. (be7a95c Simon Liu)
+ o win32: avoid crash when waiting forever on zero fds. (160e58b)
+ o evhttp: Fix a memory leak on error in evhttp_uriencode (11c8b31)
+ o evbuffer: Avoid possible needless call to writev. Found by coverity. (6a4ec5c)
+ o evdns: memset sockaddr_in before using it. Found by coverity. (a1a0e67)
+ o evhttp: Check more setsockopt return values when binding sockets. Found by coverity (a0912e3)
+ o evdns: Avoid segfault on weird timeout during name lookup. (dc32077 Greg Hazel)
+ o bufferevent_ssl: Correctly invoke callbacks when a SSL bufferevent reads some and then blocks. (606ac43)
+
+
+PORTABILITY FIXES:
+ o check for arc4random_buf at runtime, on OS X (bff5f94 Greg Hazel)
+ o Correctly check for arc4random_buf (fcec3e8 Sebastian Hahn)
+ o Add explicit AC_PROG_SED to configure.in so all autoconfs will expose $(SED) (ca80ea6)
+
+BUILD FIXES:
+ o Add GCC annotations so that the vsprintf functions get checked properly (117e327)
+ o Fix an unused variable warning on *BSD. (c0720c1)
+
+UNIT TEST FIXES:
+ o Fix a couple of memory leaks (found with Valgrind). (3b2529a Ross Lagerwall)
+ o Remove deadcode in http regression tests. Found by coverity. (5553346)
+ o Fix possible uninitialized read in dns regression tests. Found by coverity. (2259777)
+ o Set umask before calling mkstemp in unit tests. Found by coverity (f1ce15d)
+ o Fix various check-after-dereference issues in unit tests: found by coverity (4f3732d)
+ o Fix resource leaks in the unit tests; found by coverity (270f279)
+ o Add some missing null checks to unit tests; found by coverity (f021c3d)
+ o Avoid more crashes/bad calls in unit tests; found by coverity (3cde5bf)
+ o Remove unused variable; spotted by coverity (6355b2a)
+ o Add checks to various return values in unit tests. Found by coverity (b9e7329)
+ o Move assignment outside tt_assert in ssl unit tests. Appeases coverity. (a2006c0)
+
+
+
+Changes in version 2.0.19-stable (3 May 2012)
+BUGFIXES (CORE):
+ o Refactor event_persist_closure: raise and extract some common logic (bec22b4)
+ o If time has jumped so we'd reschedule a periodic event in the past, schedule it for the future instead (dfd808c)
+ o If a higher-priority event becomes active, don't continue running events of the current priority. (2bfda40)
+
+BUGFIXES (SSL):
+ o Fixed potential double-readcb execution with openssl bufferevents. (4e62cd1 Mark Ellzey)
+
+BUGFIXES (DNS):
+ o Cancel a probe request when the server is freed, and ignore cancelled probe callbacks (94d2336 Greg Hazel)
+ o Remove redundant DNS_ERR_CANCEL check, move comment (46b8060 Greg Hazel)
+ o When retransmitting a timed-out DNS request, pick a fresh nameserver. (3d9e52a)
+
+DOCUMENTATION FIXES:
+ o Fix a typo in the bufferevent documentation (98e9119)
+ o Add missing ) to changelog; spotted by rransom (4c7ee6b)
+ o Fix the website URL in the readme (f775521)
+
+COMPILATION FIXES:
+ o Fix a compilation error with MSVC 2005 due to use of mode_t (336dcae)
+ o Configure with gcc older than 2.95 (4a6fd43 Sebastian Hahn)
+ o Generate event-config.h with a single sed script (30b6f88 Zack Weinberg)
+
+FORWARD-COMPATIBILITY:
+ o Backport: provide EVENT_LOG_* names, and deprecate _EVENT_LOG_* (d1a03b2)
+
+TESTING/DEBUGGING SUPPORT:
+ o dns-example.c can now take a resolv.conf file on the commandline (6610fa5)
+ o Make some evdns.c debug logs more verbose (d873d67)
+ o Work-around a stupid gcov-breaking bug in OSX 10.6 (b3887cd)
+
+
+
+Changes in version 2.0.18-stable (22 Mar 2012)
+BUGFIXES (core):
+ o Make uses of open() close-on-exec safe by introducing an internal evutil_open_closeonexec. (d2b5f72 Ross Lagerwall, 03dce42)
+
+BUGFIXES (kqueue):
+ o Properly zero the kevent in kq_setup_kevent() (c2c7b39 Sebastian Hahn)
+
+BUILD FIXES:
+ o Added OPENSSL_LDFLAGS env variable which is appended to SSL checks. (9278196 Mark Ellzey)
+ o Changed OPENSSL_LDFLAGS to OPENSSL_LIBADD (2d67b63 Mark Ellzey)
+ o Don't do clang version detection when disabling some flags (083296b Sebastian Hahn)
+
+BUGFIXES (dns):
+ o Stop crashing in evdns when nameserver probes give a weird error (bec5068)
+
+
+Changes in version 2.0.17-stable (10 Feb 2012)
+
+BUGFIXES (core):
+ o Be absolutely sure to clear pncalls before leaving event_signal_closure (11f36a5)
+ o check for sysctl before we use it (358c745 Mike Frysinger)
+ o Remove bogus casts of socket to int before calling ev_callback (f032516)
+ o Make evconnlistener work around bug in older Linux when getting nmapped (ecfc720)
+ o Fix a list corruption bug when using event_reinit() with signals present (6e41cdc)
+ o Fix a fd leak in event_reinit() (3f18ad1)
+ o Do a memberwise comparison of threading function tables (c94a5f2 Nate R)
+ o Use C-style comments in C source files (for compatibility with compilers such as xlc on AIX). (d84d917 Greg Hewgill)
+ o Avoid crash when freeing event_iocp and using event_set_mem_functions (19715a6)
+ o In the kqueue backend, do not report EBADF as an EV_READ (5d7bfa1 Nicholas Marriott)
+
+BUGFIXES (evbuffer and bufferevents):
+ o Fix behavior of evbuffer_peek(buf,-1,NULL,NULL,0) (c986f23 Zack Weinberg)
+ o Loop on filtering SSL reads until we are blocked or exhausted. (5b4b812)
+
+BUGFIXES (evhttp):
+ o Force strict validation of HTTP version in response. (790f6b3 Catalin Patulea)
+
+BUGFIXES (evdns):
+ o evdns: fix a bug in circular-queue implementation (d6094b1)
+
+BUILD FIXES:
+ o Fix a silly compilation error with the sun compiler (1927776 Colin Watt)
+ o Suppress a gcc warning from ignoring fwrite return in http-sample.c (7206e8c)
+
+DOCUMENTATION FIXES:
+ o Slightly clarify evbuffer_peek documentation (7bbf6ca)
+ o Update copyright notices to 2012 (e49e289)
+
+NEW APIS:
+ o Backport evhttp_connection_get_bufferevent to Libevent 2.0 (da70fa7 Arno Bakker)
+
+TESTS AND TEST FIXES:
+ o Fix a race condition in the dns/bufferevent_connect_hostname test. (cba48c7)
+ o Add function to check referential integrity of an event_base (27737d5)
+ o Check event_base correctness at end of each unit test (3312b02)
+ o Workaround in the unit tests for an apparent epoll bug in Linux 3.2 (dab9187)
+ o Better workaround for Linux 3.2 edge-triggered epoll bug (9f9e259)
+
+Changes in version 2.0.16-stable (18 Nov 2011)
+BUGFIXES (core):
+ o More detailed message in case of libevent self-debugging failure. (9e6a4ef Leonid Evdokimov)
+ o epoll: close fd on alloc fail at initialization (1aee718 Jamie Iles)
+ o Fix compile warning from saying event2/*.h inside a comment (447b0ba)
+ o Warn when unable to construct base because of failing make_base_notifiable (4e797f3)
+ o Don't try to make notifiable event_base when no threading fns are configured (e787413)
+
+BUGFIXES (evbuffer):
+ o unit test for remove_buffer bug (90bd620 Greg Hazel)
+ o Fix an evbuffer crash in evbuffer_remove_buffer() (c37069c)
+
+BUGFIXES (bufferevent_openssl):
+ o Refactor amount-to-read calculations in buffervent_ssl consider_reading() (a186e73 Mark Ellzey)
+ o Move SSL rate-limit enforcement into bytes_to_read() (96c562f)
+ o Avoid spinning on OpenSSL reads (2aa036f Mark Ellzey)
+
+BUGFIXES (dns)
+ o Empty DNS reply with OK status is another way to say NODATA. (21a08d6 Leonid Evdokimov)
+
+TESTING:
+ o Tests for 94fba5b and f72e8f6 (d58c15e Leonid Evdokimov)
+ o Test for commit aff6ba1 (f7841bf Leonid Evdokimov)
+ o Style and comment tweaks for dns/leak* tests (5e42202)
+ o improve test to remove at least one buffer from src (7eb52eb Greg Hazel)
+
+DOCUMENTATION:
+ o Add note about evhttp_send_reply_end to its doxygen (724bfb5)
+ o Update copyright dates to 2011. (3c824bd)
+ o Fix typo in whatsnew-2.0.txt (674bc6a Mansour Moufid)
+ o Improve win32 behavior of dns-sample.c code (a3f320e Gisle Vanem)
+
+
+
+Changes in version 2.0.15-stable (12 Oct 2011)
+BUGFIXES (DNS):
+ o DNS: add ttl for negative answers using RFC 2308 idea. (f72e8f6 Leonid Evdokimov)
+ o Add DNS_ERR_NODATA error code to handle empty replies. (94fba5b Leonid Evdokimov)
+
+BUFGIXES (bufferevents and evbuffers):
+ o Make evbuffer callbacks get the right n_added value after evbuffer_add (1ef1f68 Alex)
+ o Prefer mmap to sendfile unless a DRAINS_TO_FD flag is set. Allows add_file to work with SSL. (0ba0af9)
+
+BUGFIXES (event loop):
+ o When a signal callback is activated to run multiple times, allow event_base_loopbreak to work even before they all have run. (4e8eb6a)
+
+DOCUMENTATION FIXES:
+ o Fix docstring in dns.h (2b6eae5 Leonid Evdokimov)
+ o refer to non-deprecated evdns functions in comments (ba5c27d Greg Hazel)
+
+BUILD AND TESTING FIXES:
+ o le-proxy and regress depend on openssl directly (9ae061a Sergey Avseyev)
+ o Use _SOURCES, not _sources, in sample/Makefile.am (7f82382)
+ o Fixed compiler warnings for unchecked read/write calls. (c3b62fd Mark Ellzey)
+ o Make write-checking fixes use tt_fail_perror (2b76847)
+ o Fix some "value never used" warnings with gcc 4.6.1 (39c0cf7)
+
+
+
+Changes in version 2.0.14-stable (31 Aug 2011)
+BUGFIXES (bufferevents and evbuffers):
+ o Propagate errors on the underlying bufferevent to the user. (4a34394 Joachim Bauch)
+ o Ignore OpenSSL deprecation warnings on OS X (5d1b255 Sebastian Hahn)
+ o Fix handling of group rate limits under 64 bytes of burst (6d5440e)
+ o Solaris sendfile: correctly detect amount of data sent (643922e Michael Herf)
+ o Make rate limiting work with common_timeout logic (5b18f13)
+ o clear read watermark on underlying bufferevent when creating filtering bev to fix potentially failing fragmented ssl handshakes (54f7e61 Joachim Bauch)
+
+BUGFIXES (IOCP):
+ o IOCP: don't launch reads or writes on an unconnected socket (495c227)
+ o Make IOCP rate-limiting group support stricter and less surprising. (a98da7b)
+ o Have test-ratelim.c support IOCP (0ff2c5a)
+ o Make overlapped reads result in evbuffer callbacks getting invoked (6acfbdd)
+ o Correctly terminate IO on an async bufferevent on bufferevent_free (e6af35d)
+
+BUGFIXES (other):
+ o Fix evsig_dealloc memory leak with debugging turned on. (9b724b2 Leonid Evdokimov)
+ o Fix request_finished memory leak with debugging turned on. (aff6ba1 Leonid Evdokimov)
+
+BUILD AND TESTING FIXES:
+ o Allow OS-neutral builds for platforms where some versions have arc4random_buf (b442302 Mitchell Livingston)
+ o Try to fix 'make distcheck' errors when building out-of-tree (04656ea Dave Hart)
+ o Clean up some problems identified by Coverity. (7c11e51 Harlan Stenn)
+
+
+Changes in version 2.0.13-stable (18 Jul 2011)
+BUGFIXES
+ o Avoid race-condition when initializing global locks (b683cae)
+ o Fix bug in SSL bufferevents backed by a bev with a write high-watermarks (e050703 Joachim Bauch)
+ o Speed up invoke_callbacks on evbuffers when there are no callbacks (f87f568 Mark Ellzey)
+ o Avoid a segfault when all methods are disabled or broken (27ce38b)
+ o Fix incorrect results from evbuffer_search_eol(EOL_LF) (4461f1a)
+ o Add some missing checks for mm_calloc failures (89d5e09)
+ o Replace an assertion for event_base_free(NULL) with a check-and-warn (09fe97d)
+ o Report kqueue ebadf, epipe, and eperm as EV_READ events (1fd34ab)
+ o Check if the `evhttp_new_object' function in `http.c' returns NULL. (446cc7a Mansour Moufid)
+ o Use the correct printf args when formatting size_t (3203f88)
+ o Complain if the caller tries to change threading cbs after setting them (cb6ecee)
+
+DOCUMENTATION FIXES AND IMPROVEMENTS
+ o Revise the event/evbuffer/bufferevent doxygen for clarity and accuracy (2888fac)
+ o Update Doxyfile to produce more useful output (aea0555)
+
+TEST FIXES
+ o Fix up test_evutil_snprintf (caf695a)
+ o Fix tinytest invocation from windows shell (57def34 Ed Day)
+
+BUILD FIXES
+ o Use AM_CPPFLAGS in sample/Makefile.am, not AM_CFLAGS (4a5c82d)
+ o Fix select.c compilation on systems with no NFDBITS (49d1136)
+ o Fix a few warnings on OpenBSD (8ee9f9c Nicholas Marriott)
+ o Don't break when building tests from git without python installed (b031adf)
+ o Don't install event_rpcgen.py when --disable-libevent-install is used (e23cda3 Harlan Stenn)
+ o Fix AIX build issue with TAILQ_FOREACH definition (e934096)
+
+
+Changes in version 2.0.12-stable (4 Jun 2011)
+BUGFIXES
+ o Fix a warn-and-fail bug in kqueue by providing kevent() room to report errors (28317a0)
+ o Fix an assert-inducing fencepost bug in the select backend (d90149d)
+ o Fix failing http assertion introducd in commit 0d6622e (0848814 Kevin Ko)
+ o Fix a bug that prevented us from configuring IPv6 nameservers. (74760f1)
+ o Prevent size_t overflow in evhttp_htmlescape. (06c51cd Mansour Moufid)
+ o Added several checks for under/overflow conditions in evhttp_handle_chunked_read (a279272 Mark Ellzey)
+ o Added overflow checks in evhttp_read_body and evhttp_get_body (84560fc Mark Ellzey)
+
+DOCUMENTATION:
+ o Add missing words to EVLOOP_NONBLOCK documentation (9556a7d)
+
+BUILD FIXES
+ o libssl depends on libcrypto, not the other way around. (274dd03 Peter Rosin)
+ o Libtool brings in the dependencies of libevent_openssl.la automatically (7b819f2 Peter Rosin)
+ o Use OPENSSL_LIBS in Makefile.am (292092e Sebastian Hahn)
+ o Move the win32 detection in configure.in (ceb03b9 Sebastian Hahn)
+ o Correctly detect openssl on windows (6619385 Sebastian Hahn)
+ o Fix a compile warning with zlib 1.2.4 and 1.2.5 (5786b91 Sebastian Hahn)
+ o Fix compilation with GCC 2, which had no __builtin_expect (09d39a1 Dave Hart)
+ o Fix new warnings from GCC 4.6 (06a714f)
+ o Link with -lshell32 and -ladvapi32 on Win32. (86090ee Peter Rosin)
+ o Make the tests build when OpenSSL is not available. (07c41be Peter Rosin)
+ o Bring in the compile script from automake, if needed. (f3c7a4c Peter Rosin)
+ o MSVC does not provide S_ISDIR, so provide it manually. (70be7d1 Peter Rosin)
+ o unistd.h and sys/time.h might not exist. (fe93022 Peter Rosin)
+ o Make sure TINYTEST_LOCAL is defined when building tinytest.c (8fa030c Peter Rosin)
+ o Fix winsock2.h #include issues with MSVC (3d768dc Peter Rosin)
+ o Use evutil_gettimeofday instead of relying on the system gettimeofday. (0de87fe Peter Rosin)
+ o Always use evutil_snprintf, even if OS provides it (d1b2d11 Sebastian Hahn)
+ o InitializeCriticalSectionAndSpinCount requires _WIN32_WINNT >= 0x0403. (816115a Peter Rosin)
+ o cygwin: make it possible to build DLLs (d54d3fc)
+
+
+
+Changes in version 2.0.11-stable (27 Apr 2011)
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES:
+ o Fix evport handling of POLLHUP and POLLERR (b42ce4b)
+ o Fix compilation on Windows with NDEBUG (cb8059d)
+ o Check for POLLERR, POLLHUP and POLLNVAL for Solaris event ports (0144886 Trond Norbye)
+ o Detect and handle more allocation failures. (666b096 Jardel Weyrich)
+ o Use event_err() only if the failure is truly unrecoverable. (3f8d22a Jardel Weyrich)
+ o Handle resize failures in the select backend better. (83e805a)
+ o Correctly free selectop fields when select_resize fails in select_init (0c0ec0b)
+ o Make --enable-gcc-warnings a no-op if not using gcc (3267703)
+ o Fix a type error in our (unused) arc4random_stir() (f736198)
+ o Correctly detect and stop non-chunked http requests when the body is too long (63a715e)
+ o Have event_base_gettimeofday_cached() always return wall-clock time (a459ef7)
+ o Workaround for http crash bug 3078187 (5dc5662 Tomash Brechko)
+ o Fix incorrect assertions and possible use-after-free in evrpc_free() (4b8f02f Christophe Fillot)
+ o Reset outgoing http connection when read data in idle state. (272823f Tomash Brechko)
+ o Fix subtle recursion in evhttp_connection_cb_cleanup(). (218cf19 Tomash Brechko)
+ o Fix the case when failed evhttp_make_request() leaved request in the queue. (0d6622e Tomash Brechko)
+ o Fix a crash bug in evdns server circular list code (00e91b3)
+ o Handle calloc failure in evdns. (Found by Dave Hart) (364291e)
+ o Fix a memory leak on win32 socket->event map. (b4f89f0)
+ o Add a forgotten NULL check to evhttp_parse_headers (12311ff Sebastian Hahn)
+ o Fix possible NULL-deref in evdns_cancel_request (5208544 Sebastian Hahn)
+
+PORTABILITY:
+ o Fall back to sscanf if we have no other way to implement strtoll (453317b)
+ o Build correctly on platforms without sockaddr_storage (9184563)
+ o Try to build correctly on platforms with no IPv6 support (713c254)
+ o Build on systems without AI_PASSIVE (cb92113)
+ o Fix http unit test on non-windows platforms without getaddrinfo (6092f12)
+ o Do not check for gethostbyname_r versions if we have getaddrinfo (c1260b0)
+ o Include arpa/inet.h as needed on HPUX (10c834c Harlan Stenn)
+ o Include util-internal.h as needed to build on platforms with no sockaddr_storage (bbf5515 Harlan Stenn)
+ o Check for getservbyname even if not on win32. (af08a94 Harlan Stenn)
+ o Add -D_OSF_SOURCE to fix hpux builds (0b33479 Harlan Stenn)
+ o Check for allocation failures in apply_socktype_protocol_hack (637d17a)
+ o Fix the check for multicast or broadcast addresses in evutil_check_interfaces (1a21d7b)
+ o Avoid a free(NULL) if out-of-memory in evdns_getaddrinfo. Found by Dave Hart (3417f68)
+
+DEFENSIVE PROGRAMMING:
+ o Add compile-time check for AF_UNSPEC==PF_UNSPEC (3c8f4e7)
+
+BUGS IN TESTS:
+ o Fix test.sh output on solaris (b4f89b6 Dave Hart)
+ o Make test-eof fail with a timeout if we never get an eof. (05a2c22 Harlan Stenn)
+ o Use %s with printf in test.sh (039b9bd)
+ o Add an assert to appease clang's static analyzer (b0ff7eb Sebastian Hahn)
+ o Add a forgotten return value check in the unit tests (3819b62 Sebastian Hahn)
+ o Actually send NULL request in http_bad_request_test (b693c32 Sebastian Hahn)
+ o add some (void) casts for unused variables (65707d7 Sebastian Hahn)
+ o Refactor test_getaddrinfo_async_cancel_stress() (48c44a6 Sebastian Hahn)
+ o Be nice and "handle" error return values in sample code (4bac793 Sebastian Hahn)
+ o Check return value of evbuffer_add_cb in tests (93a1abb Sebastian Hahn)
+ o Remote some dead code from dns-example.c (744c745 Sebastian Hahn)
+ o Zero a struct sockaddr_in before using it (646f9fe Sebastian Hahn)
+
+BUILD FIXES:
+ o Fix warnings about AC_LANG_PROGRAM usage (f663112 Sebastian Hahn)
+ o Skip check for zlib if we have no zlib.h (a317c06 Harlan Stenn)
+ o Fix autoconf bracket issues; make check for getaddrinfo include netdb.h (833e5e9 Harlan Stenn)
+ o Correct an AM_CFLAGS to an AM_CPPFLAGS in test/Makefile.am (9c469db Dave Hart)
+ o Fix make distcheck & installation of libevent 1 headers (b5a1f9f Dave Hart)
+ o Fix compilation under LLVM/clang with --enable-gcc-warnings (ad9ff58 Sebastian Hahn)
+
+FEATURES:
+ o Make URI parser able to tolerate nonconformant URIs. (95060b5)
+
+DOCUMENTATION:
+ o Clarify event_set_mem_functions doc (926f816)
+ o Correct evhttp_del_accept_socket documentation on whether socket is closed (f665924)
+ o fix spelling mistake in whatsnew-2.0.txt (deb2f73)
+ o Fix sample/http-server ipv6 fixes (eb692be)
+ o Comment internal headers used in sample code. (4eb281c)
+ o Be explicit about how long event loops run in event.h documentation (f95bafb)
+ o Add comment to configure.in to explain gc-sections test logic (c621359)
+ o Fix a couple of memory leaks in samples/http-server.c. Found by Dave Hart. (2e9f665)
+
+BUILD IMPROVEMENTS:
+ o Use the gcc -ffunction-segments feature to allow gc when linking with static libevent (0965c56 Dave Hart)
+ o Add configure options to disable installation, regression tests (49e9bb7 Dave Hart)
+
+
+
+Changes in version 2.0.10-stable (16 Dec 2010)
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+BUGFIXES
+ o Minor fix for IOCP shutdown handling fix (2599b2d Kelly Brock)
+ o Correctly notify the main thread when activating an event from a subthread (5beeec9)
+ o Reject overlong http requests early when Expect:100-continue is set (d23839f Constantine Verutin)
+ o EVUTIL_ASSERT: Use sizeof() to avoid "unused variable" warnings with -DNDEBUG. (b63ab17 Evan Jones)
+
+CODE CLEANUPS
+ o bufferevent-internal.h: Use the new event2/util.h header, not evutil.h (ef5e65a Evan Jones)
+ o Use relative includes instead of system includes consistently. (fbe64f2 Evan Jones)
+ o Make whitespace more consistent
+
+TESTING
+ o tests: Use new event2 headers instead of old compatibility headers. (4f33209 Evan Jones)
+
+DOCUMENTATION
+ o Document that the cpu_hint is only used on Windows with IOCP for now (57689c4)
+ o Add stuff to "whats new in 2.0" based on reading include changes since August. (18adc3f)
+
+
+Changes in 2.0.9-rc (30 Nov 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW AND MODIFIED APIs
+ o Add a function to change a listener's callback. (46ee061)
+ o Make evbuffer_add_file take ev_off_t, not off_t (ac7e52d)
+ o Make rate-limits go up to SIZE_MAX/EV_SSIZE_MAX, not just INT32_MAX (2cbb1a1)
+ o Add a bufferevent_get_base function (aab49b6)
+
+MAJOR BUGFIXES
+ o Disable changelist for epoll by default because of Linux dup() bug; add an option and/or an envvar to reenable it for speed. (9531763)
+ o Fix a 100%-CPU bug where an SSL connection would sometimes never stop trying to write (1213d3d)
+ o Fix a nasty bug related to use of dup() with epoll on Linux (c281aba)
+ o Fix bugs in posix thread-id calculation when sizeof(pthread_t) != sizeof(long) (fbaf077)
+ o Fix some ints to evutil_socket_t; make tests pass on win64. (f817bfa Dimitre Piskyulev)
+ o Set _EVENT_SIZEOF_VOID_P correctly on win32 and win64 (1ae82cd Dimitre Piskyulev)
+ o Avoid double-invocation of user callback with EVUTIL_EAI_CANCEL (abf01ed)
+ o Set SO_UPDATE_ACCEPT_CONTEXT on sockets from AcceptEx so that shutdown() can work (52aa419)
+ o When closing a filtering bufferevent, clear callbacks on the underlying bufferevent (fc7b1b0)
+
+NEW AND MODIFIED HTTP APIs
+ o Add evhttp_parse_query_str to be used with evhttp_uri_parse. (2075fbc)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Define enumerators for all HTTP methods, including PATCH from RFC5789 (75a7341 Felix Nawothnig)
+ o Functions to actually use evhttp_bound_socket with/as evconnlistener. (006efa7)
+ o Add evhttp_request_get_command so code can tell GET from POST without peeking at the struct. (49f4bf7)
+ o Introduce absolute URI parsing helpers. (86dd720 Pavel Plesov)
+ o Revise evhttp_uri_parse implementation to handle more of RFC3986 (eaa5f1d)
+ o Add evhttp_connection_get_base() to get the event_base from an http connection (cd00079)
+ o Let evhttp_parse_query return -1 on failure (b1756d0)
+ o New evhttp_uri(encode|decode) functions to handle + and NUL characters right (a8148ce)
+ o Add evhttp_response_code to remove one more reason to include http_struct.h (22e0a9b)
+ o Tweak interface for allowed methods (f5b391e)
+ o Add evhttp server alias interface, correct flagging of proxy requests. (aab8c38 Christopher Davis)
+
+HTTP BUGFIXES
+ o Add some comments to http.c and make a few functions static. (90b3ed5)
+ o Fix Content-Length when trying send more than 100GB of data (!) on an evhttp. (525da3e)
+ o Fix a bug where we would read too much data in HTTP bodies or requests. (58a1cc6)
+ o Correctly count req->body_size on http usage without Content-Length (8e342e5)
+ o Avoid missed-request bug when entire http request arrives before data is flushed (74c0e86)
+ o reset "chunked" flag when sending non-chunked reply (aa5f55f Joachim Bauch)
+ o evhttp_encode_uri encodes all reserved characters, including !$'()*+,/:=@ (2e63a60)
+ o Replace exact-version checks for HTTP/1.1 with >= or < checks (647e094)
+ o evhttp: Return 501 when we get an unrecognized method, not 400. (536311a)
+ o Don't disable reading from the HTTP connection after sending the request to be notified of connection-close in time (c76640b Felix Nawothnig)
+ o Never call evhttp_readcb while writing. (0512487)
+ o Try to fix an assertion failure related to close detection (0faaa39)
+ o Correctly detect timeouts during http connects (04861d5)
+ o Preliminary support for Continue expectation in evhttp. (fa9305f Christopher Davis)
+
+OTHER BUGFIXES
+ o Correct logic for realigning a chain in evbuffer_add (e4f34e8)
+ o Fix a minor syntax error that most compilers didn't care about (e56ff65)
+ o Fix some uses of int for socket in regress (5d389dc)
+ o Check return value for ioctlsocket on win32 (f5ad31c Trond Norbye)
+ o Fix som event_warns that should have been event_warnx (19c71e7)
+ o Fix signal handler types for win64. (b81217f)
+ o Try to clear up more size_t vs int/long issues. (598d133)
+ o Make sure IOCP evconnlistener uses virtual events. (7b40a00 Christopher Davis)
+ o Don't free evdns_request handles until after the callback is invoked (9ed30de)
+ o Fix some more cancel-related bugs in getaddrinfo_async (c7cfbcf)
+ o Make evdns_getaddrinfo_cancel threadsafe (d51b2fc)
+ o Only clear underlying callbacks when the user hasn't reset them. (1ac5b23)
+ o Fix bug in bufferevent_connect on an openssl bufferevent that already had an fd (4f228a1)
+ o Resolve an evport bug in the thread/forking test (3a67d0b)
+ o Make sure the CLOEXEC flag is set on fds we open for base notification (3ab578f)
+ o Fix IRIX build. sa_family collides with a #define in sys/socket.h on IRIX. (e874982 Kevin Bowling)
+ o If not WIN32, include <sys/socket.h> in event2/util.h. (1cd45e5 Kevin Bowling)
+ o Fix some C99-style comments to work with the xlC compiler. (c2e5e22 Kevin Bowling)
+ o Add some checks since lack of TAILQ_FOREACH doesn't imply lack of FIRST, END, NEXT, or INSERT_BEFORE. Quiet some warnings in XL C. (c4dc335 Kevin Bowling)
+ o Reworked AIX __ss_family workaround to use AC_STRUCT_MEMBER. (2e2a3d7 Kevin Bowling)
+ o Take select from <sys/select.h> when testing in autoconf. AIX build fix. (a3a9f6b Kevin Bowling)
+ o Fix snprintf related failures on IRIX. (3239073 Kevin Bowling)
+ o Remove _event_initialized(); make event_initialized() a function(); make it consistent on windows and non-windows (652024b)
+ o Do not let EVLOOP_ONCE exit the loop until all deferred callbacks have run (2d5e1bd)
+ o Make EVLOOP_ONCE ignore internal events (0617a81)
+ o Possible crash fix when freeing an underlying bufferevent of an openssl bufferevent (29f7623)
+
+HTTP CLEANUPS
+ o Stop using Libevent-1 headers in regress_http (1f507d7)
+ o Modernize header usage in bench_http.c (e587069)
+ o fix signed/unsigned warnings in http.c (74a91e5)
+ o Update the HTTP regression tests to use Libevent2 apis for non-http stuff (d9ffa89)
+ o Start porting http tests to not use legacy interfaces (8505a74)
+ o Convert the rest of the http tests to be non-legacy unit tests. (9bb8239)
+ o Rename the confusing "base" static variable in regress_http.c (353402a)
+ o Stop accessing http request struct directly from in the unit tests. (0b137f4)
+ o Refactor http version parsing into a single function (a38140b)
+
+TESTING
+ o Improvements to tinytest_macros.h (ad923a1)
+ o Add a huge pile of tests for the new URI functions, and make them pass. (a5a76e6)
+ o Unit tests for evhttp_uri_set* (bc98f5e)
+ o Increase the skew tolerance to 2 seconds in thread/deferred_cb_skew (f806476 Christopher Davis)
+ o Reorder backends in test.sh to match preference order in event.c (ece974f)
+ o Add a stress test for getaddrinfo_cancel (da1bf52)
+ o Units test for unexpected evhttp methods. (75e3320)
+
+DOCUMENTATION
+ o Document behavior of URI parsing more thoroughly. (3a33462)
+ o Document that two bufferevent functions only work on socket bufferevents (70e1b60)
+ o add a requested docstring for event_rpcgen.CommandLine.__init__ (f1250eb)
+ o Fix a mistake in http documentation found by Julien Blache (229714d)
+ o Add a basic example of how to write a static HTTP server. (4e794d5)
+ o Document event_get_assignment (88be27d)
+ o Note that reentrant calls to libevent from logging cbs may fail badly (e431bcd)
+ o Clarify EVLOOP_* documentation to be more precise. (057a514)
+
+CLEANUPS
+ o Simplify the logic for choosing EPOLL_CTL_ADD vs EPOLL_CTL_MOD (2c66983)
+ o Rename "size" variables in win32select that were really fd counts. (b6a158c)
+ o Fix even more win64 warnings (7484df6)
+ o Fix even more win64 warnings: buffer, event_tagging, http, evdns, evrpc (545a611)
+ o Fix more wn64 warnings. (34b84b9 Christopher Davis)
+ o Use the label_len local variable in evdns instead of recalculating it over and over (ba01456)
+ o Fix some irix compilation warnings spotted by Kevin Bowling (7bcace2)
+
+
+
+Changes in 2.0.8-rc (14 Oct 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Add error callback to evconnlistener (c4be8d8 Simon Perreault)
+ o Add a LEV_OPT_THREADSAFE option for threadsafe evconnlisteners (127d4f2)
+
+CHANGED BEHAVIOR
+ o Correct logic on disabling underlying bufferevents when disabling a filter (ac27eb8)
+
+BUGFIXES
+ o Obey enabled status when unsuspending (040a019 Simon Perreault)
+ o Warn when using the error-prone EV_SIGNAL interface in an error-prone way. Also, fix a couple of race conditions in signal.c (720bd93)
+ O Make default signal backend fully threadsafe (95a7d41)
+ o Put internal events at highest priority (90651b3)
+ o Fix warnings in the main codebase flagged by -Wsigned-compare (9c8db0, 5e4bafb, 5c214a, 6be589a, e06f514)
+ o Fix compile in kqueue.c (b395392 Sebastian Hahn)
+ o Do not search outside of the system directory for windows DLLs (d49b5e3)
+ o Fix a spurious-call bug on epoll.c (0faaee0)
+ o Send a shutdown(SHUT_WR) before closing an http connection (e0fd870 Christopher Davis)
+ o Fix warnings on mingw with gcc 4.5 (5b7a370)
+ o Fix an EINVAL on evbuffer_write_iovec on OpenSolaris. (fdc640b)
+ o Fix allocation error for IOCP listeners. Probably harmless, since struct event is big (481ef92)
+ o Make iocp/listener/error work; don't accept again if lev is disabled. (62b429a Christopher Davis)
+ o Handle rate-limiting for reading on OpenSSL bufferevents correctly. (819b171)
+ o Fix serious bugs in per-bufferevent rate-limiting code (34d64f8)
+ o Avoid spurious reads from just-created open openssl bufferevents (223ee40)
+ o Fix a case where an ssl bufferevent with CLOSE_ON_FREE didn't close its fd (93bb7d8)
+ o The corrected bufferevent filter semantics let us fix our openssl tests (34331e4)
+
+TESTING
+ o Make SSL tests cover enabling/disabling EV_READ. (a5ce9ad)
+ o Bump to the latest version of tinytest (f0bd83e)
+ o Unit tests for listener error callbacks (045eef4)
+ o New unit test for ssl bufferevents starting with connected SSLs. (02f6259)
+
+DEBUGGABILITY
+ o Make debugging output for epoll backend more comprehensive (ec2b05e)
+ o Make event.c debugging messages report fds (e119899)
+ o Make the --enable-gcc-warnings option include signed comparison warnings (d3b096c)
+
+DEADCODE REMOVAL
+ o Remove the now-useless evsig_caught and evsig_process (4858b79)
+ o Remove event_base.evsigbase; nothing used it. (38d0960)
+
+
+
+Changes in 2.0.7-rc (9 Sep 2010):
+ [Autogenerated from the Git log, sorted and cleaned by hand.]
+NEW APIS
+ o Expose a evdns_base_nameserver_sockaddr_add() function to add a nameserver by sockaddr (1952143)
+ o Add event_config_set_num_cpus_hint() for tuning win32 IOCP thread pools, etc. (2447fe8 Christopher Davis)
+
+BUGFIXES
+ o Fix a nasty dangling-event bug when using rate-limiting groups (0bffe43)
+ o Clean up syntax on TAILQ_ENTRY() usage to build correctly with recent MSVC (60433a0 Gilad Benjamini)
+ o Make definition of WIN32_LEAN_AND_MEAN in event.h conditional (3920172 Gilad Benjamini)
+ o Correctly detect failure to delete bufferevent read-timeout event (da6e7cd)
+ o Set close-on-exec bit for filedescriptors created by dns subsystem (d0b8843)
+ o Fix kqueue correctness test on x84_64 (6123d12)
+ o Detect events with no ev_base; warn instead of crashing (f1074b7)
+ o Fix an issue with forking and signal socketpairs in select/poll backends (d61b2f3)
+ o Stop using global arrays to implement the EVUTIL_ctype functions (1fdec20)
+ o On windows, make lock/thread function tables static (5de2bcb)
+ o Close th_notify_fds and open a new pair on reinit (495ed66)
+ o Declare signal handler function as "__cdecl" on Windows (f0056d0)
+ o Use the _func() replacements for open, fstat, etc in evutil.c on win32 (e50c0fc)
+ o Only process up to MAX_DEFERRED deferred_cbs at a time (17a14f1 Christopher Davis)
+
+THREADING BUGFIXES
+ o Avoid deadlock when activating signals (970e6ad)
+ o Add a condition variable backend, with implementations for pthreads and win32 (d4977b5)
+ o Use conditions instead of current_event_lock to fix a deadlock (e0972c2)
+ o Fix logic error in win32 TRY_LOCK that caused problems with rate-limiting (4c32b9d)
+ o Avoid needlessly calling evthread_notify_base() when the loop is not running (c7a06bf)
+ o Minimize calls to base_notify implementation functions, thereby avoiding needless syscalls (4632b78)
+
+IOCP BUGFIXES
+ o IOCP-related evbuffer fixes (03afa20 Christopher Davis)
+ o Stop IOCP when freeing the event_base (d844242 Christopher Davis)
+ o Some IOCP bufferevent tweaks (76f7e7a Christopher Davis)
+
+TESTS
+ o Make the regress_pthread.c tests work on windows with current test APIs (d74ae38)
+ o Add a unit test for conditions (5fb1095)
+ o Allow more than one copy of regression tests to run at once (a97320a)
+ o Fix event_del(0) instance in bench.c (b0f284c Shuo Chen)
+ o Fix a few memory leaks in the tests (1115366)
+ o IOCP-related unit test tweaks (499452f Christopher Davis)
+ o Improve testing of when thread-notification occurs (ce85280)
+
+BUILD AND DISTRIBUTION
+ o Add pkgconfig files for libevent_{openssl,pthreads} (ebcb1f0)
+ o Change include order in Makefile.nmake (4022b28)
+ o Make include/event2/event-config.h not included in source dist (a4af9be)
+ o Honor NDEBUG; build without warnings with NDEBUG; make NDEBUG always-off in unit test code (743f866)
+ o Declare evkeyvalq and event_list even if event_struct.h comes before sys/queue.h (d3ceca8)
+ o Move evkeyvalq into a separate header for evhttp_parse_query users (ca9048f)
+ o Prefer autoreconf -ivf to manual autogen.sh (7ea8e89)
+
+CLEANUP
+ o Completely remove the (mostly-removed) obsolete thread functions (3808168)
+ o Rename regress_pthread.c to regress_thread.c (041989f)
+ o Make defer-internal.h use lock macros, not direct calls to lock fns (5218d2a)
+
+DOCUMENTATION
+ o Document that DNS_NO_SEARCH is an obsolete alias for DNS_QUERY_NO_SEARCH (33200e7)
+ o Update the whatsnew-2.0.txt document (4991669)
+
+
+
+Changes in 2.0.6-rc (6 Aug 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Document a change in the semantics of event_get_struct_event_size() (e21f5d1)
+ o Add a comment to describe our plan for library versioning (9659ece)
+ o Fix sentence fragment in docs for event_get_struct_event_size() (7b259b6)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove the obsolete evthread interfaces (c5bab56)
+ o Let evhttp_send_error infer the right error reasons (3990669)
+ o Add a function to retrieve the other side of a bufferevent pair (17a8e2d)
+ o Add bufferevent_lock()/bufferevent_unlock() (215e629)
+ o Stop asserting when asked for a (unsupported) TCP dns port. Just return NULL. (7e87a59)
+ o Replace (unused,always 0) is_tcp argument to evdns_add_server_port*() with flags (e1c1167)
+ o Constify a couple of arguments to evdns_server_request_add_*_reply (cc2379d)
+ o Add an interface to expose min_share in ratelimiting groups (6ae53d6)
+
+BUGFIXES
+ o Avoid event_del on uninitialized event in event_base_free (6d19510)
+ o Add some missing includes to fix Linux build again (75701e8)
+ o Avoid close of uninitialized socket in evbuffer unit test (bda21e7)
+ o Correctly recognize .255 addresses as link-local when looking for interfaces (8c3452b)
+ o If no evdns request can be launched, return NULL, not a handle (b14f151)
+ o Use generic win32 interfaces, not ASCII-only ones, where possible. (899b0a3)
+ o Fix the default HTTP error template (06bd056 Felix Nawothnig)
+ o Close the file in evutil_read_file whether there's an error or not. (0798dd1 Pierre Phaneuf)
+ o Fix possible nullptr dereference in evhttp_send_reply_end() (29b2e23 Felix Nawothnig)
+ o never let bufferevent_rlim functions return negative (0859870)
+ o Make sample/hello_world work on windows (d89fdba)
+ o Fix a deadlock related to event-base notification. Diagnosed by Zhou Li, Avi Bab, and Scott Lamb. (17522d2)
+ o Possible fix to 100% cpu usage with epoll and openssl (cf249e7 Mike Smellie)
+ o Don't race when calling event_active/event_add on a running signal event (fc5e0a2)
+ o Suppress a spurious EPERM warning in epoll.c (e73cbde)
+ o Fix wrong size calculation of iovec buffers when exact=1 (65abdc2 niks)
+ o Change bufferevent_openssl::do_write so it doesn't call SSL_write with a 0 length buffer (c991317 Mike Smellie)
+ o Fixed compilation of sample/le-proxy.c on win32 (13b912e Trond Norbye)
+ o Fix rate-limit calculation on openssl bufferevents. (009f300)
+ o Remember to initialize timeout events for bufferevent_async (de1f5d6 Christopher Davis)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Test the unlocked-deferred callback case of bufferevents (dfb75ab)
+ o Remove the now-unusable EVTHREAD_LOCK/UNLOCK constants (fdfc3fc)
+ o Use -Wlogical-op on gcc 4.5 or higher (d14bb92)
+ o Add the libtool-generated /m4/* stuff to .gitignore (c21c663)
+ o Remove some automake-generated files from version control. (9b14911)
+ o Have autogen.sh pass --force-missing to automake (8a44062)
+ o Set library version for libevent_pthreads correctly (b2d7440)
+ o Really only add libevent_core.la to LIBADD on mingw (1425003 Sebastian Hahn)
+ o Build more cleanly with NetBSDs that dislike toupper(char) (42a8c71)
+ o Fix unit tests with -DUSE_DEBUG enabled (28f31a4)
+ o Fix evdns build with -DUNICODE (5fa30d2)
+ o Move event-config.h to include/event2 (ec347b9)
+
+TESTING
+ o Add options to test-ratelim.c to check its results (2b44dcc)
+ o Make test-ratelim clean up after itself better. (b5bfc44)
+ o Remove the now-obsolete setup_test() and cleanup_test() functions (e73f1d7)
+ o Remove all non-error prints from test/regress.c (8bc1e3d)
+ o Make test.sh exit with nonzero status if tests fail (faf2a04)
+ o Have the unit tests report errors from test.sh (3689bd2)
+ o Fix logic in correcting high values from FIONREAD (3467f2f)
+ o Add test for behavior on remote socket close (44d57ee)
+ o Unit test for event_get_struct_event_size() (7510aac)
+ o Make test/test.sh call test-changelist (7c92691)
+ o Fix badly-behaved subtest of dns/bufferevent_connect_hostname (840a72f Joachim Bauch)
+ o Add option to test-ratelim to test min_share (42f6b62)
+ o Fix an assertion bug in test-ratelim (b2c6202)
+ o Make tests quieter on local dns resolver failure (e996b3d)
+ o Increase the tolerance in our unit tests for sloppy clocks. (170ffd2)
+ o Use AF_INET socketpair to test sendfile on Solaris (9b60209)
+ o Make test-changelist count cpu usage right on win32 (ea1ea3d)
+
+INTERNALS, PERFORMANCE, AND CODE CLEANUPS
+ o Mark the event_err() functions as __attribute__((noreturn)) (33bbbed)
+ o Do not check that event_base is set in EVBASE_ACQUIRE_LOCK (218a3c3)
+ o Replace (safe) use of strcpy with memcpy to appease OpenBSD (caca2f4)
+ o Remove some dead assignments (47c5dfb)
+ o Fix a pedantic gcc 4.4 warning in event2/event.h (276e7ee)
+ o Drain th_notify_fd[0] more bytes at a time. (a5bc15b)
+ o Tidy up the code in evthread_make_base_notifiable a little (61e1eee)
+ o Pass flags to fcntl(F_SETFL) and fcntl(F_SETFD) as int, not long (7c2dea1)
+ o Remove unused variables in test/test-changelist.c (b00d4c0)
+ o Fix whitespace. (cb927a5)
+ o Improve error message for failed epoll to make debugging easier. (9e725f7)
+ o Turn our socketpair() replacement into its own function (57b30cd)
+
+
+
+Changes in 2.0.5-beta (10 May 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Update all our copyright notices to say "2010" (17efc1c)
+ o Add Christopher Clark and Maxim Yegorushkin to the LICENSE file (38b7b57)
+ o Clarify Christopher Clark's status as writer of original ht code. (78772c3)
+ o Try to comment some of the event code more (cdd4c49)
+ o Add a few more evmap/changelist comments (c247adc)
+ o Add a comment to explain why evdns_request is now separte from request (ceefbe8)
+ o Document evutil_secure_rng_init() and evutil_secure_rng_add_bytes() (a5bf43a)
+ o Stop distributing and installing manpages: they were too inaccurate (7731ec8)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Remove signal_assign() and signal_new() macros. (2fac0f7)
+ o Make evdns use the regular logging system by default (b2f2be6)
+ o Allow evbuffer_read() to split across more than 2 iovecs (e470ad3)
+ o Functions to manipulate existing rate limiting groups. (ee41aca)
+ o Functions to track the total bytes sent over a rate limit group. (fb366c1)
+ o Detect and refuse reentrant event_base_loop() calls (b557b17)
+ o Limit the maximum number of events on each socket to 65535 (819f949)
+ o Add evbuffer_copyout to copy data from an evbuffer without draining (eb86c8c)
+ o Expose the request and reply members of rpc_req_generic() (07edf78 Shuo Chen)
+ o Add void* arguments to request_new and reply_new evrpc hooks (755fbf1 Shuo Chen)
+ o Seed the RNG using sysctl() as well as /dev/urandom (71fc3eb)
+ o Make evutil_secure_rng_init() work even with builtin arc4random (f980716)
+ o Report DNS error when lookup fails during bufferevent_socket_connect_hostname. (0ef4070 Christopher Davis)
+ o Release locks on bufferevents while executing callbacks (a5208fe Joachim Bauch) o Make debug mode catch mixed ET and non-ET events on an fd (cb67074)
+ o Catch attempts to enable debug_mode too late (9ecf0d4)
+ o Refuse null keys in evhttp_parse_query() (953e229 Frank Denis)
+
+BUGFIXES
+ o Avoid a spurious close(-1) on Linux (70a44b6)
+ o Do not close(-1) when freeing an uninitialized socket bufferevent (b34abf3)
+ o Free evdns_base->req_heads on evdns_base_free (859af67)
+ o Avoid an (untriggerable so far) crash bug in bufferevent_free() (0cf1431)
+ o Set mem_offset for every bufferevent type (657d1b6)
+ o Fix infrequent memory leak in bufferevent_init_common(). (8398641 Jardel Weyrich)
+ o Make evutil_signal_active() match declaration. (e1e703d Patrick Galbraith)
+ o Fix minheap code to use replacement malloc functions (a527618)
+ o Fix a free(NULL) in minheap-internal.h (6f20492)
+ o Fix critical bug in evbuffer_write when writev is not available (cda56ab)
+ o Make the no_iovecs case of write_atmost compile (8e227b0)
+ o Fix a memory leak when appending/prepending to a buffer with unused space. (45068a3)
+ o Clean up a mistake in pointer manipulation in evbuffer_remove (28bfed4 Christopher Davis)
+ o Always round up when there's a fractional number of msecs. (8f9e60c Christopher Davis)
+ o Fix compiler warnings under WIN32 (d469c50 Giuseppe Scrivano)
+ o Clean up properly when adding a signal handler fails. (b84b598 Gilad Benjamini) o Ensure that evdns_request is a persistent handle. (15bb82d Christopher Davis)
+ o Free search state when finished searching to avoid an infinite loop. (a625840 Christopher Davis)
+ o Assert for valid requests as necessary. (67072f3 Christopher Davis)
+ o do not leak the request object on persistent connections (9d8edf2)
+ o Make evdns logging threadsafe (b1c7950)
+ o Fix a couple of bugs in the BSD sysctl arc4seed logic (a47a4b7)
+ o Remove one last bug in last_with_datap logic. Found with valgrind (d49b92a)
+ o fix a leak when unpausing evrpc requests (94ee125)
+ o Fix a memory leak when unmarshalling RPC object arrays (f6ab2a2)
+ o Fix compilation when openssl support is disabled (40c301b)
+ o Allow empty reason line in HTTP status (739e688 Pierre Phaneuf)
+ o Fix a compile warning introduced in 739e688 (bd1ed5f Sebastian Hahn)
+ o Fix nonstandard TAILQ_FOREACH_REVERSE() definition (71afc52 Frank Denis)
+ o Try /proc on Linux as entropy fallback; use sysctl as last resort (20fda29)
+ o Fix symbol conflict between mm_*() macros and libmm (99e50e9)
+ o Fix some crazy macro mistakes in arc4random.c (90d4225)
+ o Make evbuffer_add_file() work on windows (dcdae6b)
+ o Fix unused-variable warning when building with threads disabled (ad811cd)
+ o Numerous opensolaris compilation fixes (c44de06)
+ o Fix getaddrinfo with protocol unset on Solaris 9. Found by Dagobert Michelsen (2cf2a28)
+ o Fix another nasty solaris getaddrinfo() behavior (3557071)
+ o Define _REENTRANT as needed on Solaris, elsewhere (c1cd32a)
+ o Fix some autoconf issues on OpenBSD (7c519df)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Distribute libevent.pc.in, not libevent.pc (22aff04)
+ o Avoid errors in evutil.c when building with _UNICODE defined (b677032 Brodie Thiesfield)
+ o Avoid errors in http.c when building with VC 2003 .NET (13e4f3b Brodie Thiesfield)
+ o Support the standard 'make check' target in place of 'make verify' (426c8fb)
+ o Remove redundant stuff from EXTRA_DIST (b660edf)
+ o Switch to using AM conditionals in place of AC_LIBOBJ (2e898f5)
+ o Remove an orphaned RELEASE flag in Makefile.am (0794b0d)
+ o Give a better warning for bad automake versions. (77c917d)
+ o Use dist_bin_SCRIPTS, not EXTRA_DIST, to distribute scripts (9eb2fd7)
+ o Never test for select() on windows (3eb044d Trond Norbye)
+ o Do not inhibit automake dependencies generation (10c4c90 Giuseppe Scrivano)
+ o Create shared libraries under Windows (3cbca86 Giuseppe Scrivano)
+ o Add ctags/etags files to .gitignore (0861d17)
+ o Only specify -no-undefined on mingw (25433b9)
+ o Only add libevent_core.la to LIBADD on mingw (fdc6297)
+
+TESTING
+ o Get bench_http to work on Windows; add a switch to enable IOCP. (4ac38a5 Christopher Davis)
+ o VC has no getopt(), so do without in bench_http. (1273d2f Christopher Davis)
+ o Fix an obnoxious typo in the bufferevent_timeout_filter test (0d047c3)
+ o Fix a write of uninitialized RAM in regression tests (68dc742)
+ o Fix some memory leaks in the unit tests (274a7bd)
+ o Make 'main/many_events' test 70 fds, not 64. (33874b0)
+ o Unit-test every evbuffer_add_file() implementation. (06a4443)
+ o Add more unit tests for evbuffer_expand (8c83e99)
+ o Test another case of evbuffer_prepend (1234b95)
+ o Fix a possible double-free bug in SSL bufferevents with CLOSE_ON_FREE (7501895) o Add dns/search_cancel unit test. (39b870b Christopher Davis)
+ o Make http_base_test stop leaking an event_base. (96730d3)
+ o Detect broken unsetenv at unit-test runtime (f37cd4c)
+ o Implement regress_make_tempfile on win32 to test evbuffer_add_file (b4f12a1)
+ o add more (currently skipped) add_file tests on win32 (05de45d)
+ o Fix bench_http build on win32. (384d124)
+ o Make unit test for add_file able to tell "error" from "done" (88a543f)
+ o Make test for bufferevent_connect_hostname system-neutral (f89168e)
+ o Make test.sh support mingw/msys on win32 (0ee6f6c)
+ o Fix test.sh on freebsd (3d9e05b)
+
+INTERNALS, PERFORMANCE, AND AND CODE CLEANUPS
+ o Improve the speed of evbuffer_readln() (cc1600a)
+ o more whitespace normalization (2c2618d)
+ o Revise evbuffer to add last_with_data (2a6d2a1)
+ o Use last_with_data in place of previous_to_last (c8ac57f)
+ o Remove previous_to_last from evbuffer (6f47bd1)
+ o Fix last_with_data compilation on windows (1e7b986)
+ o Add some glass-box tests for the last_with_data code. (17da042)
+ o Improve robustness for refcounting (f1bc125)
+ o Remove a needless min_heap_shift_up_() call (7204b91)
+ o Increase MIN_BUFFER_SIZE to 512 (1024 on 64-bit) (2014ae4)
+ o Do not use evbuffer_expand() to add the first chain to a buffer (5c0ebb3)
+ o Make evbuffer_prepend handle empty buffers better (c87272b)
+ o Replace last_with_data with a slightly smarter version (b7442f8)
+ o Turn the increasingly complex *_CHAIN() macros into functions (96865c4)
+ o Rewrite evbuffer_expand and its users (d5ebcf3)
+ o Add evutil_tv_to_msec for safe conversion of timevals to milliseconds. (850c3ff Christopher Davis)
+ o Initialize last_with_datap correctly in evbuffer_overlapped (a0983b6)
+ o Replace EVUTIL_CLOSESOCKET macro with a function (899c1dc Sebastian Sjöberg)
+ o Move domain search state to evdns_request. (beaa14a Christopher Davis)
+ o Remove redundant checks for lock!=NULL before calling EVLOCK_LOCK (50ec59f)
+ o Rename current_base symbol to event_global_current_base_ (c16e684)
+ o Fix whitespace in evutil.c (935e150)
+ o Replace users of "int fd" with "evutil_socket_t fd" in portable code (c7cf6f0)
+
+
+
+Changes in 2.0.4-alpha (28 Feb 2010):
+ [Autogenerated from the Git log, sorted by hand.]
+DOCUMENTATION
+ o Add stub header for 2.0.4-alpha changelog. (94d0065)
+ o Improve the README with more information and links. (0b42726)
+ o Add more people who wrote patches to the acknowledgments (0af10d5)
+ o Add a warning about the use of event_initialized. (f32b575)
+ o Add a LICENSE file so people can find our license easily (7067006)
+ o Add a new "hello world" sample program (becb9f9)
+ o Clarify status of example programs (d60a1bd)
+ o Update time-test.c to use event2 (f4190bf)
+ o Add the arc4random.c license to the LICENSE file. (e15e1e9)
+
+NEW FEATURES AND INTERFACE CHANGES
+ o Improved optional lock debugging. (0cd3bb9)
+ o Rate-limiting for bufferevents; group and individual limits are supported. (737c9cd)
+ o Testing code for bufferevent rate-limiting. (f0c0124)
+ o Make the initial nameserver probe timeout configurable. (1e56a32)
+ o Revise the locking API: deprecate the old locking callbacks and add trylock. (347952f)
+ o Do not make bufferevent_setfd implicitly disable EV_READ and EV_WRITE. (8274379)
+ o Do not ignore bufferevent_enable(EV_READ) before bufferevent_connect(). (4a5b534)
+ o Introduced evutil_make_socket_closeonexec() to preserve fd flags for F_SETFD. (d0939d2 Jardel Weyrich)
+ o evdns_getaddrinfo() now supports the /etc/hosts file. (72dd666)
+ o Look at the proper /etc/hosts file on windows. (66c02c7)
+ o Allow http connections to use evdns for hostname looksups. (c698b77)
+ o Changelist code to defer event changes until just before dispatch (27308aa)
+ o do not use a function to assign the evdns base; instead assign it via evhttp_connection_base_new() which is a new function introduced in 2.0 (5032e52)
+ o Functions to access more fields of struct event. (0683950)
+ o Make kqueue use changelists. (45e5ae3)
+ o Remove kqueue->pend_changes. (3225dfb)
+ o Minimize epoll_ctl calls by using changelist (c8c6a89)
+ o Add support for a "debug mode" to try to catch common errors. (cd17c3a)
+ o Note a missing ratelim function (361da8f)
+ o Add ev_[u]intptr_t to include/event2/util.h (1fa4c81)
+ o const-ify a few more functions in event.h (d38a7a1)
+ o Deprecate EVENT_FD and EVENT_SIGNAL. (f6b2694)
+ o Remove EVUTIL_CHECK_FMT. (6c21c89)
+ o Add EV_*_MAX macros to event2/util.h to expose limits for ev_* types. (aba1fff) o Functions to view and manipulate rate-limiting buckets. (85047a6)
+ o Add the rest of the integer limits, and add a test for them. (60742d5)
+ o Remove the 'flags' argument from evdns_base_set_option() (1dd7e6d)
+ o Add an arc4random implementation for use by evdns (d4de062)
+ o Use off_t for the length parameter of evbuffer_add_file (3fe60fd)
+ o Construct Windows locks using InitializeCriticalSectionAndSpinCount (32c6f1b)
+ o Expose view of current rate limit as constrained by group limit (162ce8a)
+ o Provide consistent, tested semantics for bufferevent timeouts (d328829)
+
+BUGFIXES AND TESTS
+ o Tolerate code that returns from a fatal_cb. (91fe23f)
+ o Parenthesize macro arguments more aggressively (07e9e9b)
+ o Fix memory-leak of signal handler array with kqueue. (e1ffbb8)
+ o Stop passing EVTHREAD_READ and EVTHREAD_WRITE to non-rw locks. (76cd2b7)
+ o Fix two use-after-free bugs in unit tests spoted by lock debugging (d84d838)
+ o Fix a locking bug in event_base_loop() (da1718b)
+ o Fix an evdns lock violation. (2df1f82 Zhuang Yuyao)
+ o Valgrind fix: Clear struct kevent before checking for OSX bug. (56771a3 William Ahern)
+ o Fix up evthread compilation on windows (bd6f1ba Roman Puls)
+ o Fix regress_iocp.c usage of old lock allocation macros. (31687b4 unknown)
+ o Update nmake makefile to build evthread.c (b62d979 unknown)
+ o Fix a crash when reading badly formatted resolve.conf; from Yasuoka Masahiko (6c7c579 Yasuoka Masahiko)
+ o Fix a snow leopard compile warning in the unit tests. (7ae9445)
+ o Fix compile on Snow Leopard with gcc warnings enabled (70cdfe4 Sebastian Hahn)
+ o Only define _GNU_SOURCE if it is not already defined. (ea6b1df Joachim Bauch)
+ o Update sample/signal-test.c to use newer APIs and not leak. (f6430ac Evan Jones)
+ o Fix a segfault when writing a very fragmented evbuffer onto an SSL (a6adeca Joachim Bauch)
+ o Fix a segfault when freeing SSL bufferevents in an unusual order (a773df5 Joachim Bauch)
+ o Drop install-sh from our git repo: a mismatched version could break "make dist" (6799527)
+ o Set all instances of the version number correctly. (5a112d3)
+ o Fix a few locking issues on windows. (c51bb3c unknown)
+ o Use evutil_socket_t, not int, when logging socket errors. (292467c)
+ o Fix up behavior of never-defered callbacks a little (390e056)
+ o Replace some cases of uint32_t with ev_uint32_t. (a47d88d)
+ o Fix compilation of devpoll.c by adding missing thread includes. (fee2c77 Dagobert Michelsen)
+ o Make evutil_make_socket_nonblocking() leave any other flags alone. (4c8b7cd Jardel Weyrich)
+ o Fix an fd leak in evconnlistener_new_bind(). (24fb502 Jardel Weyrich)
+ o Fix a bogus free in evutil_new_addrinfo() (0d64051 Jardel Weyrich)
+ o Adjusted fcntl() retval comparison on evutil_make_socket_nonblocking(). (4df7dbc Jardel Weyrich)
+ o Fix the code that allowed DNS options to not end with : (ee4953f)
+ o Fix crash bugs when a bufferevent's eventcb is not set. (2e8eeea)
+ o Fix test-ratelim compilation on Linux. (885b427)
+ o Fix compilation of rate-limiting code on win32. (165d30e)
+ o Eradicated the last free() call. Let mm_free() take care of deallocation. (0546ce1 Jardel Weyrich)
+ o Fix byte counts when mixing deferred and non-deferred evbuffer callbacks. (29151e6)
+ o Fixed a memory leak on windows threads implementation. The CRITICAL_SECTION was not being free'd in evthread_win32_lock_free(). (2f33e00 Jardel Weyrich)
+ o Fixed a fd leak in start_accepting(), plus cosmetic changes (4367a33 Jardel Weyrich)
+ o Improved error handling in evconnlistener_new_async(). Also keeping the fd open because it is not opened by this function, so the caller is responsible for closing it. Additionally, since evconnlistener_new_bind() creates a socket and passes it to the function above, it required error checking to close the same socket. (fec66f9 Jardel Weyrich)
+ o Don't use a bind address for nameservers on loopback (8d4aaf9)
+ o Fix compilation of rate-limit code when threading support is disabled (97a8c79)
+ o Detect setenv/unsetenv; skip main/base_environ test if we can't fake them. (7296971)
+ o Check more internal event_add() calls for failure (ff3f6cd)
+ o Fix windows and msvc build (5c7a7bc)
+ o Call event_debug_unassign on internal events (a19b4a0)
+ o Try to fix a warning in hash_debug_entry (137f2c6)
+ o Fix a dumb typo in ev_intptr_t definitions. (27c9a40)
+ o do not fail while sending on http connections the client closed. (93d7369)
+ o make evhttp_send() safe against terminated connections, too (3978180)
+ o Make Libevent 1.4.12 build on win32 with Unicode enabled. (000a33e Brodie Thiesfield)
+ o Fix some additional -DUNICODE issues on win32. (a7a9431)
+ o Add a check to make soure our EVUTIL_AI flags do not conflict with the native ones (c18490e)
+ o Always use our own gai_strerror() replacement. (6810bdb)
+ o Make RNG work when we have arc4random() but not arc4random_buf() (4ec8fea)
+ o validate close cb on server when client connection closes (2f782af)
+ o Fix two unlocked reads in evbuffer. (7116bf2)
+ o When working without a current event base, don't try to use IOCP listeners (cb52838)
+ o Fix getpid() usage on Windows (ff2a134)
+ o Add a unit test for secure rng. (48a29b6)
+ o Add some headers to fix freebsd compilation (b72be50)
+ o When connect() succeeds immediately, don't invoke the callback immediately. (7515de9)
+ o Suspend read/write on bufferevents during hostname lookup (db08f64)
+ o Make bufferevent_free() clear all callbacks immediately. (b2fbeb3)
+ o Fix some race conditions in persistent events and event_reinit (e2642f0)
+ o Fix a bug in resetting timeouts on persistent events when IO triggers. (38ec0a7)
+ o Add a test for timeouts on filtering bufferevents. (c02bfe1)
+ o Add test for periodic timers that get activated for other reasons (8fcb7a1)
+ o Use new timeval diff comparison function in bufferevent test (f3dfe46)
+ o Delete stack-alloced event in new unit test before returning. (7ffd387)
+ o Fix mingw compilation (23170a6)
+ o Try to define a sane _EVENT_SIZEOF_SIZE_T for msvc compilation (1e14f82)
+ o Fix arc4random compilation on MSVC. (98edb89)
+ o deal with connect() failing immediately (7bc48bf)
+ o Small cleanups on freebsd-connect-refused patch. (57b7248)
+
+BUILD AND DISTRIBUTION CHANGES
+ o Remove the contents of WIN32-Prj as unmaintained. (c69d5a5)
+ o Allow the user to redirect the verbose output of test/test.sh to a file (c382de6)
+ o Allow test.sh to be run as ./test/test.sh (7dfbe94)
+ o Never believe that we have pthreads on win32, even if gcc thinks we do. (78ed097)
+ o Make it compile under gcc --std=c89. (e2ca403)
+ o Fix a number of warnings from gcc -pedantic (918e9c5)
+ o Add the msvc-generated .lib files to .gitignore. (e244a2e)
+ o Add the "compile" script to gitignore. (1ba6bed)
+
+INTERNALS AND CODE CLEANUPS
+ o Add a .gitignore file. (ba34071)
+ o New EVTHREAD_TRY_LOCK function to try to grab a lock. (689fc09)
+ o Add the abilitity to mark some buffer callbacks as never-deferred. (438f9ed)
+ o Refactor our 'suspend operation' logic on bufferevents. (0d744aa)
+ o Simplify the read high-watermark checking. (5846bf6)
+ o Improve readability of evutil_unparse_protoname() (5a43df8 Jardel Weyrich)
+ o Expose our cached gettimeofday value with a new interface (47854a8)
+ o Whitespace fixes in test.sh (0b151a9)
+ o Enable branch-prediction hints with EVUTIL_UNLIKELY. (eaaf27f)
+ o Refactor code from evdns into a new internal "read a file" function. (0f7144f)
+ o Comestic changes in evconnlistener_new(), new_accepting_socket(), accepted_socket_invoke_user_cb() and iocp_listener_enable(). (510ab6b Jardel Weyrich)
+ o Add unit-test for bad_request bug fixed in 1.4 recently. (6cc79c6 Pavel Plesov) o Add a comment on evthread_enable_lock_debuging. (b9f43b2)
+ o Fix test.sh on shells without echo -n (94131e9)
+ o More unit tests for getaddrinfo_async: v4timeout and cancel. (a334b31)
+ o Make http use evconnlistener. (ec34533)
+ o move dns utility functions into a separate file so that we can use them for http testing (b822639)
+ o add a test for evhttp_connection_base_new with a dns_base (26714ca)
+ o forgot to add void to test function (78a50fe)
+ o Add a forgotten header (changelist-internal.h) (4b9f307)
+ o Remove some commented-out code in evutil (26e1b6f)
+ o Remove a needless include of rpc_compat.h (70a4a3e)
+ o Use less memory for each entry in a hashtable (a66e947)
+ o Try to untangle the logic in server_port_flush(). (439aea0)
+ o Use ev_[u]intptr_t types in place of [u]intptr_t (cef61a2)
+ o Reduce windows header includes in our own headers. (da6135e)
+ o clean up terminate_chunked test (e8a9782)
+ o Increment the submicro version number. (63e868e)
+ o Update event-config.h version number to match configure.in (aae7db5)
+ o Clean up formatting: Disallow space-before-tab. (8fdf09c)
+ o Clean up formatting: use tabs, not 8-spaces, to indent. (e5bbd40)
+ o Clean up formatting: remove trailing spaces (e5cf987)
+ o Clean up formatting: function/keyword spacing consistency. (4faeaea)
+
+
+
+Changes in 2.0.3-alpha (20 Nov 2009):
+ o Add a new code to support SSL/TLS on bufferevents, using the OpenSSL library (where available).
+ o Fix a bug where we didn't allocate enough memory in event_get_supported_methods().
+ o Avoid segfault during failed allocation of locked evdns_base. (Found by Rocco Carbone.)
+ o Export new evutil_ascii_* functions to perform locale-independent character type operations.
+ o Try to compile better with MSVC: patches from Brodie Thiesfield
+ o New evconnlistener_get_fd function to expose a listener's associated socket.
+ o Expose an ev_socklen_t type for consistent use across platforms.
+ o Make bufferevent_socket_connect() work when the original fd was -1.
+ o Fix a bug in bufferevent_socket_connect() when the connection succeeds too quickly.
+ o Export an evutil_sockaddr_cmp() to compare to sockaddr objects for equality.
+ o Add a bufferevent_get_enabled() to tell what a bufferevent has been configured to do.
+ o Add an evbuffer_search_eol() function to locate the end of a line nondestructively.
+ o Add an evbuffer_search_range() function to search a bounded range of a buffer.
+ o Fix a rare crash bug in evdns.
+ o Have bufferevent_socket_connect() with no arguments put a bufferevent into connecting mode.
+ o Support sendfile on Solaris: patch from Caitlin Mercer.
+ o New functions to explicitly reference a socket used by an evhttp object. Patches from David Reiss.
+ o When we send a BEV_EVENT_CONNECTED to indicate connected status, we no longer invoke the write callback as well unless we actually wrote data too.
+ o If the kernel tells us that there are a negative number of bytes to read from a socket, do not believe it. Fixes bug 2841177; found by Alexander Pronchenkov.
+ o Do not detect whether we have monotonic clock support every time a new event base is created: instead do it only once. Patch taken from Chromium.
+ o Do not allocate the maximum event queue for the epoll backend at startup. Instead, start out accepting 32 events at a time, and double the queue's size when it seems that the OS is generating events faster than we're requesting them. Saves up to 374K per epoll-based event_base. Resolves bug 2839240.
+ o Treat an event with a negative fd as valid but untriggerable by Libevent. This is useful for applications that want to manually activate events.
+ o Fix compilation on Android, which forgot to define fd_mask in its sys/select.h
+ o Do not drop data from evbuffer when out of memory; reported by Jacek Masiulaniec
+ o New event_base_got_exit() and event_base_got_break() functions to tell whether an event loop exited because of an event_base_loopexit() or an event_base_loopbreak(). Patch from Ka-Hing Cheung.
+ o When adding or deleting an event from a non-main thread, only wake up the main thread when its behavior actually needs to change.
+ o Fix some bugs when using the old evdns interfaces to initialize the evdns module.
+ o Detect errors during bufferevent_connect(). Patch from Christopher Davis.
+ o Fix compilation for listener.h for C++ - missing extern "C". Patch from Ferenc Szalai.
+ o Make the event_base_loop() family of functions respect thread-safety better. This should clear up a few hard-to-debug race conditions.
+ o Fix a bug when using a specialized memory allocator on win32.
+ o Have the win32 select() backend label TCP-socket-connected events as EV_WRITE, not EV_READ. This should bring it in line with the other backends, and improve portability. Patch from Christopher Davis.
+ o Stop using enums as arguments or return values when what we mean is a bitfield of enum values. C++ doesn't believe that you can OR two enum values together and get another enum, and C++ takes its typing seriously. Patch from Christopher Davis.
+ o Add an API to replace all fatal calls to exit() with a user-provided panic function.
+ o Replace all assert() calls with a variant that is aware of the user-provided logging and panic functions.
+ o Add a return value to event_assign so that it can fail rather than asserting when the user gives it bad input. event_set still dies on bad input.
+ o The event_base_new() and event_base_new_with_config() functions now never call exit() on failure. For backward "compatibility", event_init() still does, but more consistently.
+ o Remove compat/sys/_time.h. It interfered with system headers on HPUX, and its functionality has been subsumed by event2/util.h and util-internal.h.
+ o Add a new bufferevent_socket_connect_hostname() to encapsulate the resolve-then-connect operation.
+ o Build kqueue.c correctly on GNU/kFreeBSD platforms. Patch pulled upstream from Debian.
+ o Alternative queue-based timeout algorithm for programs that use a large number of timeouts with the same value.
+ o New event_base_config option to disable the timeval cache entirely.
+ o Make EV_PERSIST timeouts more accurate: schedule the next event based on the scheduled time of the previous event, not based on the current time.
+ o Allow http.c to handle cases where getaddrinfo returns an IPv6 address. Patch from Ryan Phillips.
+ o Fix a problem with excessive memory allocation when using multiple event priorities.
+ o Default to using arc4random for DNS transaction IDs on systems that have it; from OpenBSD.
+ o Never check the environment when we're running setuid or setgid; from OpenBSD.
+ o Options passed to evdns_set_option() no longer need to end with a colon.
+ o Add an evutil_getaddrinfo() function to clone getaddrinfo on platforms that don't have it.
+ o Add an evdns_getaddrinfo() function to provide a nonblocking getaddrinfo using evdns, so programs can perform useful hostname lookup.
+ o Finally expose the IOCP-based bufferevent backend. It passes its unit tests, but probably still has some bugs remaining. Code by Nick Mathewson and Christopher Davis.
+ o Numerous other bugfixes.
+ o On FreeBSD and other OSes, connect can return ECONREFUSED immediately; instead of failing the function call, pretend with faileld in the callback.
+ o Fix a race condition in the pthreads test case; found by Nick Mathewson
+ o Remove most calls to event_err() in http and deal with memory errors instead
+
+
+
+Changes in 2.0.2-alpha (25 Jul 2009):
+ o Add a new flag to bufferevents to make all callbacks automatically deferred.
+ o Make evdns functionality locked, and automatically defer dns callbacks.
+ o Fix a possible free(NULL) when freeing an event_base with no signals.
+ o Add a flag to disable checking environment varibles when making an event_base
+ o Disallow setting less than 1 priority.
+ o Fix a bug when removing a timeout from the heap. [Patch from Marko Kreen]
+ o Use signal.h, not sys/signal.h. [Patch from mmadia]
+ o Try harder to build with certain older c99 compilers.
+ o Make sure that an event_config's flags field is always initialized to 0. [Bug report from Victor Goya]
+ o Avoid data corruption when reading data entirely into the second-to-last chain of an evbuffer. [Bug report from Victor Goya]
+ o Make sendfile work on FreeBSD
+ o Do not use vararg macros for accessing evrpc structures; this is not backwards compatible, but we did not promise any backwards compatibility for the rpc code.
+ o Actually define the event_config_set_flag() function.
+ o Try harder to compile with Visual C++.
+ o Move event_set() and its allies to event2/event_compat.h where they belong.
+ o Remove the event_gotsig code, which has long been deprecated and unused.
+ o Add an event_get_base() function to return the base assigned to an event.
+ o New function to automate connecting on a socket-based bufferevent.
+ o New functions to automate listening for incoming TCP connections.
+ o Do case-insensitive checks with a locale-independent comparison function.
+ o Rename the evbuffercb and everrorcb callbacks to bufferevent_data_cb and bufferevent_event_cb respectively. The old names are available in bufferevent_compat.h.
+ o Rename the EVBUFFER_* codes used by bufferevent event callbacks to BEV_EVENT_*, to avoid namespace collision with evbuffer flags. The old names are available in bufferevent_compat.h.
+ o Move the EVBUFFER_INPUT and EVBUFFER_OUTPUT macros to bufferevent_compat.h
+ o Add a bufferevent_getfd() function to mirror bufferevent_setfd()
+ o Make bufferevent_setfd() return an error code if the operation is not successful.
+ o Shave 22 bytes off struct event on 32-bit platforms by shrinking and re-ordering fields. The savings on 64-bit platforms is likely higher.
+ o Cap the maximum number of priorities at 256.
+ o Change the semantics of evbuffer_cb_set_flags() to be set-flag only; add a new evbuffer_cb_clear_flags() to remove set flags.
+ o Change the interface of evbuffer_add_reference so that the cleanup callback gets more information
+ o Revise the new evbuffer_reserve_space/evbuffer_commit_space() interfaces so that you can use them without causing extraneous copies or leaving gaps in the evbuffer.
+ o Add a new evbuffer_peek() interface to inspect data in an evbuffer without removing it.
+ o Fix a deadlock when suspending reads in a bufferevent due to a full buffer. (Spotted by Joachim Bauch.)
+ o Fix a memory error when freeing a thread-enabled event base with registered events. (Spotted by Joachim Bauch.)
+ o Try to contain degree of failure when running on a win32 version so heavily firewalled that we can't fake a socketpair.
+ o Activate fd events in a pseudorandom order with O(N) backends, so that we don't systematically favor low fds (select) or earlier-added fds (poll, win32).
+ o Replace some read()/write() instances with send()/recv() to work properly on win32.
+ o Set truncated flag correctly in evdns server replies.
+ o Raise RpcGenError in event_rpcgen.py; from jmanison and Zack Weinberg
+ o Fix preamble of rpcgen-generated files to rely on event2 includes; based on work by jmansion; patch from Zack Weinberg.
+ o Allow specifying the output filename for rpcgen; based on work by jmansion; patch from Zack Weinberg.
+ o Allow C identifiers as struct names; allow multiple comments in .rpc files; from Zack Weinberg
+ o Mitigate a race condition when using socket bufferevents in multiple threads.
+ o Use AC_SEARCH_LIBS, not AC_CHECK_LIB to avoid needless library use.
+ o Do not allow event_del(ev) to return while that event's callback is executing in another thread. This fixes a nasty race condition.
+ o event_get_supported_methods() now lists methods that have been disabled with the EVENT_NO* environment options.
+ o Rename encode_int[64] to evtag_encode_int[64] to avoid polluting the global namespace. The old method names are still available as macros in event2/tag_compat.h.
+
+
+
+Changes in 2.0.1-alpha (17 Apr 2009):
+ o free minheap on event_base_free(); from Christopher Layne
+ o debug cleanups in signal.c; from Christopher Layne
+ o provide event_base_new() that does not set the current_base global
+ o bufferevent_write now uses a const source argument; report from Charles Kerr
+ o improve documentation on event_base_loopexit; patch from Scott Lamb
+ o New function, event_{base_}loopbreak. Like event_loopexit, it makes an event loop stop executing and return. Unlike event_loopexit, it keeps subsequent pending events from getting executed. Patch from Scott Lamb
+ o Check return value of event_add in signal.c
+ o provide event_reinit() to reintialize an event_base after fork
+ o New function event_set_mem_functinons. It allows the user to give libevent replacement functions to use for memory management in place of malloc(), free(), etc. This should be generally useful for memory instrumentation, specialized allocators, and so on.
+ o The kqueue implementation now catches signals that are raised after event_add() is called but before the event_loop() call. This makes it match the other implementations.
+ o The kqueue implementation now restores original signal handlers correctly when its signal events are removed.
+ o Check return value of event_add in signal.c
+ o Add a more powerful evbuffer_readln as a replacement for evbuffer_readline. The new function handles more newline styles, and is more useful with buffers that may contain a nul characters.
+ o Do not mangle socket handles on 64-bit windows.
+ o The configure script now takes an --enable-gcc-warnings option that turns on many optional gcc warnings. (Nick has been building with these for a while, but they might be useful to other developers.)
+ o move EV_PERSIST handling out of the event backends
+ o small improvements to evhttp documentation
+ o always generate Date and Content-Length headers for HTTP/1.1 replies
+ o set the correct event base for HTTP close events
+ o When building with GCC, use the "format" attribute to verify type correctness of calls to printf-like functions.
+ o Rewrite win32.c backend to be O(n lg n) rather than O(n^2).
+ o Removed obsoleted recalc code
+ o support for 32-bit tag numbers in rpc structures; this is wire compatible, but changes the API slightly.
+ o pull setters/getters out of RPC structures into a base class to which we just need to store a pointer; this reduces the memory footprint of these structures.
+ o prefix {encode,decode}_tag functions with evtag to avoid collisions
+ o fix a bug with event_rpcgen for integers
+ o Correctly handle DNS replies with no answers set (Fixes bug 1846282)
+ o add -Wstrict-aliasing to warnings and more cleanup
+ o removed linger from http server socket; reported by Ilya Martynov
+ o event_rpcgen now allows creating integer arrays
+ o support string arrays in event_rpcgen
+ o change evrpc hooking to allow pausing of RPCs; this will make it possible for the hook to do some meaning ful work; this is not backwards compatible.
+ o allow an http request callback to take ownership of a request structure
+ o allow association of meta data with RPC requests for hook processing
+ o associate more context for hooks to query such as the connection object
+ o remove pending timeouts on event_base_free()
+ o also check EAGAIN for Solaris' event ports; from W.C.A. Wijngaards
+ o devpoll and evport need reinit; tested by W.C.A Wijngaards
+ o event_base_get_method; from Springande Ulv
+ o Send CRLF after each chunk in HTTP output, for compliance with RFC2626. Patch from "propanbutan". Fixes bug 1894184.
+ o Add a int64_t parsing function, with unit tests, so we can apply Scott Lamb's fix to allow large HTTP values.
+ o Use a 64-bit field to hold HTTP content-lengths. Patch from Scott Lamb.
+ o Allow regression code to build even without Python installed
+ o remove NDEBUG ifdefs from evdns.c
+ o detect integer types properly on platforms without stdint.h
+ o udpate documentation of event_loop and event_base_loop; from Tani Hosokawa.
+ o simplify evbuffer by removing orig_buffer
+ o do not insert event into list when evsel->add fails
+ o add support for PUT/DELETE requests; from Josh Rotenberg
+ o introduce evhttp_accept_socket() to accept from an already created socket
+ o include Content-Length in reply for HTTP/1.0 requests with keep-alive
+ o increase listen queue for http sockets to 128; if that is not enough the evhttp_accpet_socket() api can be used with a prepared socket.
+ o Patch from Tani Hosokawa: make some functions in http.c threadsafe.
+ o test support for PUT/DELETE requests; from Josh Rotenberg
+ o rewrite of the evbuffer code to reduce memory copies
+ o Some older Solaris versions demand that _REENTRANT be defined to get strtok_r(); do so.
+ o Do not free the kqop file descriptor in other processes, also allow it to be 0; from Andrei Nigmatulin
+ o Provide OpenSSL style support for multiple threads accessing the same event_base
+ o make event_rpcgen.py generate code include event-config.h; reported by Sam Banks.
+ o switch thread support so that locks get allocated as they are needed.
+ o make event methods static so that they are not exported; from Andrei Nigmatulin
+ o make RPC replies use application/octet-stream as mime type
+ o do not delete uninitialized timeout event in evdns
+ o Correct the documentation on buffer printf functions.
+ o Don't warn on unimplemented epoll_create(): this isn't a problem, just a reason to fall back to poll or select.
+ o Correctly handle timeouts larger than 35 minutes on Linux with epoll.c. This is probably a kernel defect, but we'll have to support old kernels anyway even if it gets fixed.
+ o Make name_from_addr() threadsafe in http.c
+ o Add new thread-safe interfaces to evdns functions.
+ o Make all event_tagging interfaces threadsafe.
+ o Rename internal memory management functions.
+ o New functions (event_assign, event_new, event_free) for use by apps that want to be safely threadsafe, or want to remain ignorant of the contents of struct event.
+ o introduce bufferevent_read_buffer; allows reading without memory copy.
+ o expose bufferevent_setwatermark via header files and fix high watermark on read
+ o fix a bug in buffrevent read water marks and add a test for them
+ o fix a bug in which bufferevent_write_buffer would not schedule a write event
+ o provide bufferevent_input and bufferevent_output without requiring knowledge of the structure
+ o introduce bufferevent_setcb and bufferevent_setfd to allow better manipulation of bufferevents
+ o convert evhttp_connection to use bufferevents.
+ o use libevent's internal timercmp on all platforms, to avoid bugs on old platforms where timercmp(a,b,<=) is buggy.
+ o Remove the never-exported, never-used evhttp_hostportfile function.
+ o Support input/output filters for bufferevents; somewhat similar to libio's model. This will allow us to implement SSL, compression, etc, transparently to users of bufferevents such as the http layer.
+ o allow connections to be removed from an rpc pool
+ o add new evtimer_assign, signal_assign, evtimer_new, and signal_new functions to manipulate timer and signal events, analagous to the now-recommended event_assign and event_new
+ o switch internal uses of event_set over to use event_assign.
+ o introduce evbuffer_contiguous_space() api that tells a user how much data is available in the first buffer chain
+ o introduce evbuffer_reserve_space() and evbuffer_commit_space() to make processing in filters more efficient.
+ o reduce system calls for getting current time by caching it.
+ o separate signal events from io events; making the code less complex.
+ o support for periodic timeouts
+ o support for virtual HTTP hosts.
+ o turn event_initialized() into a function, and add function equivalents to EVENT_SIGNAL and EVENT_FD so that people don't need to include event_struct.h
+ o Build test directory correctly with CPPFLAGS set.
+ o Provide an API for retrieving the supported event mechanisms.
+ o event_base_new_with_config() and corresponding config APIs.
+ o migrate the evhttp header to event2/ but accessors are still missing.
+ o deprecate timeout_* event functions by moving them to event_compat.h
+ o Move windows gettimeofday replacement into a new evutil_gettimeofday().
+ o Make configure script work on IRIX.
+ o provide a method for canceling ongoing http requests.
+ o Make vsnprintf() returns consistent on win32.
+ o Fix connection keep-alive behavior for HTTP/1.0
+ o Fix use of freed memory in event_reinit; pointed out by Peter Postma
+ o constify struct timeval * where possible
+ o make event_get_supported_methods obey environment variables
+ o support for edge-triggered events on epoll and kqueue backends: patch from Valery Kholodkov
+ o support for selecting event backends by their features, and for querying the features of a backend.
+ o change failing behavior of event_base_new_with_config: if a config is provided and no backend is selected, return NULL instead of aborting.
+ o deliver partial data to request callbacks when chunked callback is set even if there is no chunking on the http level; allows cancelation of requests from within the chunked callback; from Scott Lamb.
+ o allow min_heap_erase to be called on removed members; from liusifan.
+ o Rename INPUT and OUTPUT to EVRPC_INPUT and EVRPC_OUTPUT. Retain INPUT/OUTPUT aliases on on-win32 platforms for backwards compatibility.
+ o Do not use SO_REUSEADDR when connecting
+ o Support 64-bit integers in RPC structs
+ o Correct handling of trailing headers in chunked replies; from Scott Lamb.
+ o Support multi-line HTTP headers; based on a patch from Moshe Litvin
+ o Reject negative Content-Length headers; anonymous bug report
+ o Detect CLOCK_MONOTONIC at runtime for evdns; anonymous bug report
+ o Various HTTP correctness fixes from Scott Lamb
+ o Fix a bug where deleting signals with the kqueue backend would cause subsequent adds to fail
+ o Support multiple events listening on the same signal; make signals regular events that go on the same event queue; problem report by Alexander Drozdov.
+ o Fix a problem with epoll() and reinit; problem report by Alexander Drozdov.
+ o Fix off-by-one errors in devpoll; from Ian Bell
+ o Make event_add not change any state if it fails; reported by Ian Bell.
+ o Fix a bug where headers arriving in multiple packets were not parsed; fix from Jiang Hong; test by me.
+ o Match the query in DNS replies to the query in the request; from Vsevolod Stakhov.
+ o Add new utility functions to correctly observe and log winsock errors.
+ o Do not remove Accept-Encoding header
+ o Clear the timer cache on entering the event loop; reported by Victor Chang
+ o Only bind the socket on connect when a local address has been provided; reported by Alejo Sanchez
+ o Allow setting of local port for evhttp connections to support millions of connections from a single system; from Richard Jones.
+ o Clear the timer cache when leaving the event loop; reported by Robin Haberkorn
+ o Fix a typo in setting the global event base; reported by lance.
+ o Set the 0x20 bit on outgoing alphabetic characters in DNS requests randomly, and insist on a match in replies. This helps resist DNS poisoning attacks.
+ o Make the http connection close detection work properly with bufferevents and fix a potential memory leak associated with it.
+ o Restructure the event backends so that they do not need to keep track of events themselves, as a side effect multiple events can use the same fd or signal.
+ o Add generic implementations for parsing and emiting IPv6 addresses on platforms that do not have inet_ntop and/or inet_pton.
+ o Allow DNS servers that have IPv6 addresses.
+ o Add an evbuffer_write_atmost() function to write a limited number of bytes to an fd.
+ o Refactor internal notify-main-thread logic to prefer eventfd to pipe, then pipe to socketpair, and only use socketpairs as a last resort.
+ o Try harder to pack all evbuffer reads into as few chains as possible, using readv/WSARecv as appropriate.
+ o New evthread_use_windows_threads() and evthread_use_pthreads() functions to set up the evthread callbacks with reasonable defaults.
+ o Change the semantics of timeouts in conjunction with EV_PERSIST; timeouts in that case will now repeat until deleted.
+ o sendfile, mmap and memory reference support for evbuffers.
+ o New evutil_make_listen_socket_reuseable() to abstract SO_REUSEADDR.
+ o New bind-to option to allow DNS clients to bind to an arbitrary port for outgoing requests.
+ o evbuffers can now be "frozen" to prevent operations at one or both ends.
+ o Bufferevents now notice external attempts to add data to an inbuf or remove it from an outbuf, and stop them.
+ o Fix parsing of queries where the encoded queries contained \r, \n or +
+ o Do not allow internal events to starve lower-priority events.
+
diff --git a/ipc/chromium/src/third_party/libevent/Doxyfile b/ipc/chromium/src/third_party/libevent/Doxyfile
new file mode 100644
index 0000000000..3f094f7213
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/Doxyfile
@@ -0,0 +1,257 @@
+# Doxyfile 1.5.1
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+# TAG = value [value, ...]
+# For lists items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME = $(PROJECT)-$(VERSION)
+
+# Place all output under 'doxygen/'
+
+OUTPUT_DIRECTORY = $(DOCDIR)
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like the Qt-style comments (thus requiring an
+# explicit @brief command for a brief description.
+
+JAVADOC_AUTOBRIEF = YES
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH = include/
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT = \
+ $(SRCDIR)/include/event2/buffer.h \
+ $(SRCDIR)/include/event2/buffer_compat.h \
+ $(SRCDIR)/include/event2/bufferevent.h \
+ $(SRCDIR)/include/event2/bufferevent_compat.h \
+ $(SRCDIR)/include/event2/bufferevent_ssl.h \
+ $(SRCDIR)/include/event2/dns.h \
+ $(SRCDIR)/include/event2/dns_compat.h \
+ $(SRCDIR)/include/event2/event.h \
+ $(SRCDIR)/include/event2/event_compat.h \
+ $(SRCDIR)/include/event2/http.h \
+ $(SRCDIR)/include/event2/http_compat.h \
+ $(SRCDIR)/include/event2/listener.h \
+ $(SRCDIR)/include/event2/rpc.h \
+ $(SRCDIR)/include/event2/rpc_compat.h \
+ $(SRCDIR)/include/event2/tag.h \
+ $(SRCDIR)/include/event2/tag_compat.h \
+ $(SRCDIR)/include/event2/thread.h \
+ $(SRCDIR)/include/event2/util.h
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML = $(GENERATE_HTML)
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX = $(GENERATE_LATEX)
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+
+LATEX_CMD_NAME = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS = NO
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN = $(GENERATE_MAN)
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS = YES
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED = TAILQ_ENTRY RB_ENTRY EVENT_DEFINED_TQENTRY_ EVENT_IN_DOXYGEN_
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS = YES
diff --git a/ipc/chromium/src/third_party/libevent/LICENSE b/ipc/chromium/src/third_party/libevent/LICENSE
new file mode 100644
index 0000000000..402ca50896
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/LICENSE
@@ -0,0 +1,99 @@
+Libevent is available for use under the following license, commonly known
+as the 3-clause (or "modified") BSD license:
+
+==============================
+Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+==============================
+
+Portions of Libevent are based on works by others, also made available by
+them under the three-clause BSD license above. The copyright notices are
+available in the corresponding source files; the license is as above. Here's
+a list:
+
+log.c:
+ Copyright (c) 2000 Dug Song <dugsong@monkey.org>
+ Copyright (c) 1993 The Regents of the University of California.
+
+strlcpy.c:
+ Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+
+win32select.c:
+ Copyright (c) 2003 Michael A. Davis <mike@datanerds.net>
+
+evport.c:
+ Copyright (c) 2007 Sun Microsystems
+
+ht-internal.h:
+ Copyright (c) 2002 Christopher Clark
+
+minheap-internal.h:
+ Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
+
+==============================
+
+The arc4module is available under the following, sometimes called the
+"OpenBSD" license:
+
+ Copyright (c) 1996, David Mazieres <dm@uun.org>
+ Copyright (c) 2008, Damien Miller <djm@openbsd.org>
+
+ Permission to use, copy, modify, and distribute this software for any
+ purpose with or without fee is hereby granted, provided that the above
+ copyright notice and this permission notice appear in all copies.
+
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+==============================
+
+The Windows timer code is based on code from libutp, which is
+distributed under this license, sometimes called the "MIT" license.
+
+
+Copyright (c) 2010 BitTorrent, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/ipc/chromium/src/third_party/libevent/Makefile.am b/ipc/chromium/src/third_party/libevent/Makefile.am
new file mode 100644
index 0000000000..21815008a4
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/Makefile.am
@@ -0,0 +1,344 @@
+# Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+# 'foreign' means that we're not enforcing GNU package rules strictly.
+# '1.13' means that we need automake 1.13 or later (and we do).
+AUTOMAKE_OPTIONS = foreign 1.13 subdir-objects
+
+ACLOCAL_AMFLAGS = -I m4
+
+# This is the "Release" of the Libevent ABI. It takes precedence over
+# the VERSION_INFO, so that two versions of Libevent with the same
+# "Release" are never binary-compatible.
+#
+# This number incremented once for the 2.0 release candidate, and
+# will increment for each series until we revise our interfaces enough
+# that we can seriously expect ABI compatibility between series.
+#
+RELEASE = -release 2.1
+
+# This is the version info for the libevent binary API. It has three
+# numbers:
+# Current -- the number of the binary API that we're implementing
+# Revision -- which iteration of the implementation of the binary
+# API are we supplying?
+# Age -- How many previous binary API versions do we also
+# support?
+#
+# To increment a VERSION_INFO (current:revision:age):
+# If the ABI didn't change:
+# Return (current:revision+1:age)
+# If the ABI changed, but it's backward-compatible:
+# Return (current+1:0:age+1)
+# If the ABI changed and it isn't backward-compatible:
+# Return (current+1:0:0)
+#
+# Once an RC is out, DO NOT MAKE ANY ABI-BREAKING CHANGES IN THAT SERIES
+# UNLESS YOU REALLY REALLY HAVE TO.
+VERSION_INFO = 7:1:0
+
+# History: RELEASE VERSION_INFO
+# 2.0.1-alpha -- 2.0 1:0:0
+# 2.0.2-alpha -- 2:0:0
+# 2.0.3-alpha -- 2:0:0 (should have incremented; didn't.)
+# 2.0.4-alpha -- 3:0:0
+# 2.0.5-beta -- 4:0:0
+# 2.0.6-rc -- 2.0 2:0:0
+# 2.0.7-rc -- 2.0 3:0:1
+# 2.0.8-rc -- 2.0 4:0:2
+# 2.0.9-rc -- 2.0 5:0:0 (ABI changed slightly)
+# 2.0.10-stable-- 2.0 5:1:0 (No ABI change)
+# 2.0.11-stable-- 2.0 6:0:1 (ABI changed, backward-compatible)
+# 2.0.12-stable-- 2.0 6:1:1 (No ABI change)
+# 2.0.13-stable-- 2.0 6:2:1 (No ABI change)
+# 2.0.14-stable-- 2.0 6:3:1 (No ABI change)
+# 2.0.15-stable-- 2.0 6:3:1 (Forgot to update :( )
+# 2.0.16-stable-- 2.0 6:4:1 (No ABI change)
+# 2.0.17-stable-- 2.0 6:5:1 (No ABI change)
+# 2.0.18-stable-- 2.0 6:6:1 (No ABI change)
+# 2.0.19-stable-- 2.0 6:7:1 (No ABI change)
+# 2.0.20-stable-- 2.0 6:8:1 (No ABI change)
+# 2.0.21-stable-- 2.0 6:9:1 (No ABI change)
+#
+# For Libevent 2.1:
+# 2.1.1-alpha -- 2.1 1:0:0
+# 2.1.2-alpha -- 2.1 1:0:0 (should have been 2:0:1)
+# 2.1.3-alpha -- 2.1 3:0:0 (ABI changed slightly)
+# 2.1.4-alpha -- 2.1 4:0:0 (ABI changed slightly)
+# 2.1.5-beta -- 2.1 5:0:0 (ABI changed slightly)
+# 2.1.6-beta -- 2.1 6:0:0 (ABI changed slightly)
+# 2.1.7-beta -- 2.1 6:1:0 (ABI changed slightly)
+# 2.1.8-stable-- 2.1 6:2:0 (No ABI change)
+# 2.1.9-beta-- 2.1 6:3:0 (No ABI change)
+# 2.1.10-stable-- 2.1 6:4:0 (No ABI change, WRONG)
+# 2.1.11-stable-- 2.1 7:0:0 (ABI changed)
+# 2.1.12-stable-- 2.1 7:1:0 (No ABI change)
+
+# ABI version history for this package effectively restarts every time
+# we change RELEASE. Version 1.4.x had RELEASE of 1.4.
+#
+# Ideally, we would not be using RELEASE at all; instead we could just
+# use the VERSION_INFO field to label our backward-incompatible ABI
+# changes, and those would be few and far between. Unfortunately,
+# Libevent still exposes far too many volatile structures in its
+# headers, so we pretty much have to assume that most development
+# series will break ABI compatibility. For now, it's simplest just to
+# keep incrementing the RELEASE between series and resetting VERSION_INFO.
+#
+# Eventually, when we get to the point where the structures in the
+# headers are all non-changing (or not there at all!), we can shift to
+# a more normal worldview where backward-incompatible ABI changes are
+# nice and rare. For the next couple of years, though, 'struct event'
+# is user-visible, and so we can pretty much guarantee that release
+# series won't be binary-compatible.
+
+if INSTALL_LIBEVENT
+dist_bin_SCRIPTS = event_rpcgen.py
+endif
+
+pkgconfigdir=$(libdir)/pkgconfig
+LIBEVENT_PKGCONFIG=libevent.pc libevent_core.pc libevent_extra.pc
+
+# These sources are conditionally added by configure.ac or conditionally
+# included from other files.
+PLATFORM_DEPENDENT_SRC = \
+ arc4random.c \
+ epoll_sub.c
+
+CMAKE_FILES = \
+ cmake/AddCompilerFlags.cmake \
+ cmake/AddEventLibrary.cmake \
+ cmake/CheckConstExists.cmake \
+ cmake/CheckFileOffsetBits.c \
+ cmake/CheckFileOffsetBits.cmake \
+ cmake/CheckFunctionKeywords.cmake \
+ cmake/CheckPrototypeDefinition.c.in \
+ cmake/CheckPrototypeDefinition.cmake \
+ cmake/CheckWorkingKqueue.cmake \
+ cmake/CodeCoverage.cmake \
+ cmake/COPYING-CMAKE-SCRIPTS \
+ cmake/Copyright.txt \
+ cmake/LibeventConfig.cmake.in \
+ cmake/LibeventConfigVersion.cmake.in \
+ cmake/Macros.cmake \
+ cmake/Uninstall.cmake.in \
+ cmake/UseDoxygen.cmake \
+ cmake/VersionViaGit.cmake \
+ event-config.h.cmake \
+ evconfig-private.h.cmake \
+ CMakeLists.txt
+
+EXTRA_DIST = \
+ ChangeLog-1.4 \
+ ChangeLog-2.0 \
+ Doxyfile \
+ LICENSE \
+ Makefile.nmake test/Makefile.nmake \
+ autogen.sh \
+ event_rpcgen.py \
+ libevent.pc.in \
+ make-event-config.sed \
+ whatsnew-2.0.txt \
+ whatsnew-2.1.txt \
+ README.md \
+ $(CMAKE_FILES) \
+ $(PLATFORM_DEPENDENT_SRC)
+
+LIBEVENT_LIBS_LA = libevent.la libevent_core.la libevent_extra.la
+if PTHREADS
+LIBEVENT_LIBS_LA += libevent_pthreads.la
+LIBEVENT_PKGCONFIG += libevent_pthreads.pc
+endif
+if OPENSSL
+LIBEVENT_LIBS_LA += libevent_openssl.la
+LIBEVENT_PKGCONFIG += libevent_openssl.pc
+endif
+
+if INSTALL_LIBEVENT
+lib_LTLIBRARIES = $(LIBEVENT_LIBS_LA)
+pkgconfig_DATA = $(LIBEVENT_PKGCONFIG)
+else
+noinst_LTLIBRARIES = $(LIBEVENT_LIBS_LA)
+endif
+
+EXTRA_SOURCE=
+noinst_HEADERS=
+noinst_PROGRAMS=
+EXTRA_PROGRAMS=
+CLEANFILES=
+DISTCLEANFILES=
+BUILT_SOURCES =
+include include/include.am
+include sample/include.am
+include test/include.am
+
+if BUILD_WIN32
+
+SYS_CORE_LIBS = -liphlpapi
+SYS_LIBS = -lws2_32 -lshell32 -ladvapi32
+SYS_SRC = win32select.c buffer_iocp.c event_iocp.c \
+ bufferevent_async.c
+SYS_INCLUDES = -IWIN32-Code -IWIN32-Code/nmake
+
+if THREADS
+SYS_SRC += evthread_win32.c
+endif
+
+else
+
+SYS_CORE_LIBS =
+SYS_LIBS =
+SYS_SRC =
+SYS_INCLUDES =
+
+endif
+
+if STRLCPY_IMPL
+SYS_SRC += strlcpy.c
+endif
+if SELECT_BACKEND
+SYS_SRC += select.c
+endif
+if POLL_BACKEND
+SYS_SRC += poll.c
+endif
+if DEVPOLL_BACKEND
+SYS_SRC += devpoll.c
+endif
+if KQUEUE_BACKEND
+SYS_SRC += kqueue.c
+endif
+if EPOLL_BACKEND
+SYS_SRC += epoll.c
+endif
+if EVPORT_BACKEND
+SYS_SRC += evport.c
+endif
+if SIGNAL_SUPPORT
+SYS_SRC += signal.c
+endif
+
+BUILT_SOURCES += include/event2/event-config.h
+
+include/event2/event-config.h: config.h make-event-config.sed
+ $(AM_V_GEN)test -d include/event2 || $(MKDIR_P) include/event2
+ $(AM_V_at)$(SED) -f $(srcdir)/make-event-config.sed < config.h > $@T
+ $(AM_V_at)mv -f $@T $@
+
+CORE_SRC = \
+ buffer.c \
+ bufferevent.c \
+ bufferevent_filter.c \
+ bufferevent_pair.c \
+ bufferevent_ratelim.c \
+ bufferevent_sock.c \
+ event.c \
+ evmap.c \
+ evthread.c \
+ evutil.c \
+ evutil_rand.c \
+ evutil_time.c \
+ listener.c \
+ log.c \
+ $(SYS_SRC)
+
+EXTRAS_SRC = \
+ evdns.c \
+ event_tagging.c \
+ evrpc.c \
+ http.c
+
+if BUILD_WITH_NO_UNDEFINED
+NO_UNDEFINED = -no-undefined
+MAYBE_CORE = libevent_core.la
+else
+NO_UNDEFINED =
+MAYBE_CORE =
+endif
+
+AM_CFLAGS = $(LIBEVENT_CFLAGS)
+AM_CPPFLAGS = -I$(srcdir)/compat -I./include -I$(srcdir)/include $(SYS_INCLUDES) $(LIBEVENT_CPPFLAGS)
+AM_LDFLAGS = $(LIBEVENT_LDFLAGS)
+
+GENERIC_LDFLAGS = -version-info $(VERSION_INFO) $(RELEASE) $(NO_UNDEFINED) $(AM_LDFLAGS)
+
+libevent_la_SOURCES = $(CORE_SRC) $(EXTRAS_SRC)
+libevent_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS) $(SYS_CORE_LIBS)
+libevent_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+libevent_core_la_SOURCES = $(CORE_SRC)
+libevent_core_la_LIBADD = @LTLIBOBJS@ $(SYS_LIBS) $(SYS_CORE_LIBS)
+libevent_core_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+if PTHREADS
+libevent_pthreads_la_SOURCES = evthread_pthread.c
+libevent_pthreads_la_LIBADD = $(MAYBE_CORE)
+libevent_pthreads_la_LDFLAGS = $(GENERIC_LDFLAGS)
+endif
+
+libevent_extra_la_SOURCES = $(EXTRAS_SRC)
+libevent_extra_la_LIBADD = $(MAYBE_CORE) $(SYS_LIBS)
+libevent_extra_la_LDFLAGS = $(GENERIC_LDFLAGS)
+
+if OPENSSL
+libevent_openssl_la_SOURCES = bufferevent_openssl.c
+libevent_openssl_la_LIBADD = $(MAYBE_CORE) $(OPENSSL_LIBS)
+libevent_openssl_la_LDFLAGS = $(GENERIC_LDFLAGS)
+libevent_openssl_la_CPPFLAGS = $(AM_CPPFLAGS) $(OPENSSL_INCS)
+endif
+
+noinst_HEADERS += \
+ WIN32-Code/nmake/evconfig-private.h \
+ WIN32-Code/nmake/event2/event-config.h \
+ WIN32-Code/getopt.h \
+ WIN32-Code/getopt.c \
+ WIN32-Code/getopt_long.c \
+ WIN32-Code/tree.h \
+ bufferevent-internal.h \
+ changelist-internal.h \
+ compat/sys/queue.h \
+ defer-internal.h \
+ epolltable-internal.h \
+ evbuffer-internal.h \
+ event-internal.h \
+ evmap-internal.h \
+ evrpc-internal.h \
+ evsignal-internal.h \
+ evthread-internal.h \
+ ht-internal.h \
+ http-internal.h \
+ iocp-internal.h \
+ ipv6-internal.h \
+ kqueue-internal.h \
+ log-internal.h \
+ minheap-internal.h \
+ mm-internal.h \
+ ratelim-internal.h \
+ ratelim-internal.h \
+ strlcpy-internal.h \
+ time-internal.h \
+ util-internal.h \
+ openssl-compat.h
+
+EVENT1_HDRS = \
+ include/evdns.h \
+ include/event.h \
+ include/evhttp.h \
+ include/evrpc.h \
+ include/evutil.h
+
+if INSTALL_LIBEVENT
+include_HEADERS = $(EVENT1_HDRS)
+else
+noinst_HEADERS += $(EVENT1_HDRS)
+endif
+
+verify: check
+
+include doxygen.am
+
+DISTCLEANFILES += *~ libevent.pc libevent_core.pc libevent_extra.pc ./include/event2/event-config.h
+
diff --git a/ipc/chromium/src/third_party/libevent/Makefile.nmake b/ipc/chromium/src/third_party/libevent/Makefile.nmake
new file mode 100644
index 0000000000..f27cd61949
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/Makefile.nmake
@@ -0,0 +1,82 @@
+# WATCH OUT! This makefile is a work in progress. -*- makefile -*-
+#
+# I'm not very knowledgeable about MSVC and nmake beyond their most basic
+# aspects. If anything here looks wrong to you, please let me know.
+
+# If OPENSSL_DIR is not set, builds without OpenSSL support. If you want
+# OpenSSL support, you can set the OPENSSL_DIR variable to where you
+# installed OpenSSL. This can be done in the environment:
+# set OPENSSL_DIR=c:\openssl
+# Or on the nmake command line:
+# nmake OPENSSL_DIR=C:\openssl -f Makefile.nmake
+# Or by uncommenting the following line here in the makefile...
+
+# OPENSSL_DIR=c:\openssl
+
+!IFDEF OPENSSL_DIR
+SSL_CFLAGS=/I$(OPENSSL_DIR)\include /DEVENT__HAVE_OPENSSL
+!ELSE
+SSL_CFLAGS=
+!ENDIF
+
+# Needed for correctness
+CFLAGS=/IWIN32-Code /IWIN32-Code/nmake /Iinclude /Icompat /DHAVE_CONFIG_H /I. $(SSL_CFLAGS)
+
+# For optimization and warnings
+CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
+
+# XXXX have a debug mode
+
+LIBFLAGS=/nologo
+
+CORE_OBJS=event.obj buffer.obj bufferevent.obj bufferevent_sock.obj \
+ bufferevent_pair.obj listener.obj evmap.obj log.obj evutil.obj \
+ strlcpy.obj signal.obj bufferevent_filter.obj evthread.obj \
+ bufferevent_ratelim.obj evutil_rand.obj evutil_time.obj
+WIN_OBJS=win32select.obj evthread_win32.obj buffer_iocp.obj \
+ event_iocp.obj bufferevent_async.obj
+EXTRA_OBJS=event_tagging.obj http.obj evdns.obj evrpc.obj
+
+!IFDEF OPENSSL_DIR
+SSL_OBJS=bufferevent_openssl.obj
+SSL_LIBS=libevent_openssl.lib
+!ELSE
+SSL_OBJS=
+SSL_LIBS=
+!ENDIF
+
+ALL_OBJS=$(CORE_OBJS) $(WIN_OBJS) $(EXTRA_OBJS) $(SSL_OBJS)
+STATIC_LIBS=libevent_core.lib libevent_extras.lib libevent.lib $(SSL_LIBS)
+
+
+all: static_libs tests
+
+static_libs: $(STATIC_LIBS)
+
+libevent_core.lib: $(CORE_OBJS) $(WIN_OBJS)
+ lib $(LIBFLAGS) $(CORE_OBJS) $(WIN_OBJS) /out:libevent_core.lib
+
+libevent_extras.lib: $(EXTRA_OBJS)
+ lib $(LIBFLAGS) $(EXTRA_OBJS) /out:libevent_extras.lib
+
+libevent.lib: $(CORE_OBJS) $(WIN_OBJS) $(EXTRA_OBJS)
+ lib $(LIBFLAGS) $(CORE_OBJS) $(EXTRA_OBJS) $(WIN_OBJS) /out:libevent.lib
+
+libevent_openssl.lib: $(SSL_OBJS)
+ lib $(LIBFLAGS) $(SSL_OBJS) /out:libevent_openssl.lib
+
+clean:
+ del $(ALL_OBJS)
+ del $(STATIC_LIBS)
+ cd test
+ $(MAKE) /F Makefile.nmake clean
+ cd ..
+
+tests:
+ cd test
+!IFDEF OPENSSL_DIR
+ $(MAKE) OPENSSL_DIR=$(OPENSSL_DIR) /F Makefile.nmake
+!ELSE
+ $(MAKE) /F Makefile.nmake
+!ENDIF
+ cd ..
diff --git a/ipc/chromium/src/third_party/libevent/README.md b/ipc/chromium/src/third_party/libevent/README.md
new file mode 100644
index 0000000000..1247e220f5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/README.md
@@ -0,0 +1,487 @@
+<p align="center">
+ <img src="https://strcpy.net/libevent3.png" alt="libevent logo"/>
+</p>
+
+
+
+[![Appveyor Win32 Build Status](https://ci.appveyor.com/api/projects/status/ng3jg0uhy44mp7ik?svg=true)](https://ci.appveyor.com/project/libevent/libevent)
+[![Travis Build Status](https://travis-ci.org/libevent/libevent.svg?branch=master)](https://travis-ci.org/libevent/libevent)
+[![Coverage Status](https://coveralls.io/repos/github/libevent/libevent/badge.svg)](https://coveralls.io/github/libevent/libevent)
+[![Join the chat at https://gitter.im/libevent/libevent](https://badges.gitter.im/libevent/libevent.svg)](https://gitter.im/libevent/libevent?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+
+
+# 0. BUILDING AND INSTALLATION (Briefly)
+
+## Autoconf
+
+ $ ./configure
+ $ make
+ $ make verify # (optional)
+ $ sudo make install
+
+## CMake (General)
+
+
+The following Libevent specific CMake variables are as follows (the values being
+the default).
+
+```
+# Type of the library to build (SHARED or STATIC)
+# Default is: SHARED for MSVC, otherwise BOTH
+EVENT__LIBRARY_TYPE:STRING=DEFAULT
+
+# Installation directory for CMake files
+EVENT_INSTALL_CMAKE_DIR:PATH=lib/cmake/libevent
+
+# Enable running gcov to get a test coverage report (only works with
+# GCC/CLang). Make sure to enable -DCMAKE_BUILD_TYPE=Debug as well.
+EVENT__COVERAGE:BOOL=OFF
+
+# Defines if Libevent should build without the benchmark executables
+EVENT__DISABLE_BENCHMARK:BOOL=OFF
+
+# Define if Libevent should build without support for a debug mode
+EVENT__DISABLE_DEBUG_MODE:BOOL=OFF
+
+# Define if Libevent should not allow replacing the mm functions
+EVENT__DISABLE_MM_REPLACEMENT:BOOL=OFF
+
+# Define if Libevent should build without support for OpenSSL encryption
+EVENT__DISABLE_OPENSSL:BOOL=OFF
+
+# Disable the regress tests
+EVENT__DISABLE_REGRESS:BOOL=OFF
+
+# Disable sample files
+EVENT__DISABLE_SAMPLES:BOOL=OFF
+
+# If tests should be compiled or not
+EVENT__DISABLE_TESTS:BOOL=OFF
+
+# Define if Libevent should not be compiled with thread support
+EVENT__DISABLE_THREAD_SUPPORT:BOOL=OFF
+
+# Enables verbose debugging
+EVENT__ENABLE_VERBOSE_DEBUG:BOOL=OFF
+
+# When cross compiling, forces running a test program that verifies that Kqueue
+# works with pipes. Note that this requires you to manually run the test program
+# on the the cross compilation target to verify that it works. See CMake
+# documentation for try_run for more details
+EVENT__FORCE_KQUEUE_CHECK:BOOL=OFF
+```
+
+__More variables can be found by running `cmake -LAH <sourcedir_path>`__
+
+
+## CMake (Windows)
+
+Install CMake: <https://www.cmake.org>
+
+
+ $ md build && cd build
+ $ cmake -G "Visual Studio 10" .. # Or whatever generator you want to use cmake --help for a list.
+ $ start libevent.sln
+
+## CMake (Unix)
+
+ $ mkdir build && cd build
+ $ cmake .. # Default to Unix Makefiles.
+ $ make
+ $ make verify # (optional)
+
+
+# 1. BUILDING AND INSTALLATION (In Depth)
+
+## Autoconf
+
+To build Libevent, type
+
+ $ ./configure && make
+
+
+ (If you got Libevent from the git repository, you will
+ first need to run the included "autogen.sh" script in order to
+ generate the configure script.)
+
+You can run the regression tests by running
+
+ $ make verify
+
+Install as root via
+
+ $ make install
+
+Before reporting any problems, please run the regression tests.
+
+To enable low-level tracing, build the library as:
+
+ $ CFLAGS=-DUSE_DEBUG ./configure [...]
+
+Standard configure flags should work. In particular, see:
+
+ --disable-shared Only build static libraries.
+ --prefix Install all files relative to this directory.
+
+
+The configure script also supports the following flags:
+
+ --enable-gcc-warnings Enable extra compiler checking with GCC.
+ --disable-malloc-replacement
+ Don't let applications replace our memory
+ management functions.
+ --disable-openssl Disable support for OpenSSL encryption.
+ --disable-thread-support Don't support multithreaded environments.
+
+## CMake (Windows)
+
+(Note that autoconf is currently the most mature and supported build
+environment for Libevent; the CMake instructions here are new and
+experimental, though they _should_ be solid. We hope that CMake will
+still be supported in future versions of Libevent, and will try to
+make sure that happens.)
+
+First of all install <https://www.cmake.org>.
+
+To build Libevent using Microsoft Visual studio open the "Visual Studio Command prompt" and type:
+
+```
+$ cd <libevent source dir>
+$ mkdir build && cd build
+$ cmake -G "Visual Studio 10" .. # Or whatever generator you want to use cmake --help for a list.
+$ start libevent.sln
+```
+
+In the above, the ".." refers to the dir containing the Libevent source code.
+You can build multiple versions (with different compile time settings) from the same source tree
+by creating other build directories.
+
+It is highly recommended to build "out of source" when using
+CMake instead of "in source" like the normal behaviour of autoconf for this reason.
+
+The "NMake Makefiles" CMake generator can be used to build entirely via the command line.
+
+To get a list of settings available for the project you can type:
+
+```
+$ cmake -LH ..
+```
+
+### GUI
+
+CMake also provides a GUI that lets you specify the source directory and output (binary) directory
+that the build should be placed in.
+
+# 2. USEFUL LINKS:
+
+For the latest released version of Libevent, see the official website at
+<http://libevent.org/> .
+
+There's a pretty good work-in-progress manual up at
+ <http://www.wangafu.net/~nickm/libevent-book/> .
+
+For the latest development versions of Libevent, access our Git repository
+via
+
+```
+$ git clone https://github.com/libevent/libevent.git
+```
+
+You can browse the git repository online at:
+
+<https://github.com/libevent/libevent>
+
+To report bugs, issues, or ask for new features:
+
+__Patches__: https://github.com/libevent/libevent/pulls
+> OK, those are not really _patches_. You fork, modify, and hit the "Create Pull Request" button.
+> You can still submit normal git patches via the mailing list.
+
+__Bugs, Features [RFC], and Issues__: https://github.com/libevent/libevent/issues
+> Or you can do it via the mailing list.
+
+There's also a libevent-users mailing list for talking about Libevent
+use and development:
+
+<http://archives.seul.org/libevent/users/>
+
+# 3. ACKNOWLEDGMENTS
+
+The following people have helped with suggestions, ideas, code or
+fixing bugs:
+
+ * Samy Al Bahra
+ * Antony Antony
+ * Jacob Appelbaum
+ * Arno Bakker
+ * Weston Andros Adamson
+ * William Ahern
+ * Ivan Andropov
+ * Sergey Avseyev
+ * Avi Bab
+ * Joachim Bauch
+ * Andrey Belobrov
+ * Gilad Benjamini
+ * Stas Bekman
+ * Denis Bilenko
+ * Julien Blache
+ * Kevin Bowling
+ * Tomash Brechko
+ * Kelly Brock
+ * Ralph Castain
+ * Adrian Chadd
+ * Lawnstein Chan
+ * Shuo Chen
+ * Ka-Hing Cheung
+ * Andrew Cox
+ * Paul Croome
+ * George Danchev
+ * Andrew Danforth
+ * Ed Day
+ * Christopher Davis
+ * Mike Davis
+ * Frank Denis
+ * Antony Dovgal
+ * Mihai Draghicioiu
+ * Alexander Drozdov
+ * Mark Ellzey
+ * Shie Erlich
+ * Leonid Evdokimov
+ * Juan Pablo Fernandez
+ * Christophe Fillot
+ * Mike Frysinger
+ * Remi Gacogne
+ * Artem Germanov
+ * Alexander von Gernler
+ * Diego Giagio
+ * Artur Grabowski
+ * Diwaker Gupta
+ * Kuldeep Gupta
+ * Sebastian Hahn
+ * Dave Hart
+ * Greg Hazel
+ * Nicholas Heath
+ * Michael Herf
+ * Savg He
+ * Mark Heily
+ * Maxime Henrion
+ * Michael Herf
+ * Greg Hewgill
+ * Andrew Hochhaus
+ * Aaron Hopkins
+ * Tani Hosokawa
+ * Jamie Iles
+ * Xiuqiang Jiang
+ * Claudio Jeker
+ * Evan Jones
+ * Marcin Juszkiewicz
+ * George Kadianakis
+ * Makoto Kato
+ * Phua Keat
+ * Azat Khuzhin
+ * Alexander Klauer
+ * Kevin Ko
+ * Brian Koehmstedt
+ * Marko Kreen
+ * Ondřej Kuzník
+ * Valery Kyholodov
+ * Ross Lagerwall
+ * Scott Lamb
+ * Christopher Layne
+ * Adam Langley
+ * Graham Leggett
+ * Volker Lendecke
+ * Philip Lewis
+ * Zhou Li
+ * David Libenzi
+ * Yan Lin
+ * Moshe Litvin
+ * Simon Liu
+ * Mitchell Livingston
+ * Hagne Mahre
+ * Lubomir Marinov
+ * Abilio Marques
+ * Nicolas Martyanoff
+ * Abel Mathew
+ * Nick Mathewson
+ * James Mansion
+ * Nicholas Marriott
+ * Andrey Matveev
+ * Caitlin Mercer
+ * Dagobert Michelsen
+ * Andrea Montefusco
+ * Mansour Moufid
+ * Mina Naguib
+ * Felix Nawothnig
+ * Trond Norbye
+ * Linus Nordberg
+ * Richard Nyberg
+ * Jon Oberheide
+ * John Ohl
+ * Phil Oleson
+ * Alexey Ozeritsky
+ * Dave Pacheco
+ * Derrick Pallas
+ * Tassilo von Parseval
+ * Catalin Patulea
+ * Patrick Pelletier
+ * Simon Perreault
+ * Dan Petro
+ * Pierre Phaneuf
+ * Amarin Phaosawasdi
+ * Ryan Phillips
+ * Dimitre Piskyulev
+ * Pavel Plesov
+ * Jon Poland
+ * Roman Puls
+ * Nate R
+ * Robert Ransom
+ * Balint Reczey
+ * Bert JW Regeer
+ * Nate Rosenblum
+ * Peter Rosin
+ * Maseeb Abdul Qadir
+ * Wang Qin
+ * Alex S
+ * Gyepi Sam
+ * Hanna Schroeter
+ * Ralf Schmitt
+ * Mike Smellie
+ * Steve Snyder
+ * Nir Soffer
+ * Dug Song
+ * Dongsheng Song
+ * Hannes Sowa
+ * Joakim Soderberg
+ * Joseph Spadavecchia
+ * Kevin Springborn
+ * Harlan Stenn
+ * Andrew Sweeney
+ * Ferenc Szalai
+ * Brodie Thiesfield
+ * Jason Toffaletti
+ * Brian Utterback
+ * Gisle Vanem
+ * Bas Verhoeven
+ * Constantine Verutin
+ * Colin Watt
+ * Zack Weinberg
+ * Jardel Weyrich
+ * Jay R. Wren
+ * Zack Weinberg
+ * Mobai Zhang
+ * Alejo
+ * Alex
+ * Taral
+ * propanbutan
+ * masksqwe
+ * mmadia
+ * yangacer
+ * Andrey Skriabin
+ * basavesh.as
+ * billsegall
+ * Bill Vaughan
+ * Christopher Wiley
+ * David Paschich
+ * Ed Schouten
+ * Eduardo Panisset
+ * Jan Heylen
+ * jer-gentoo
+ * Joakim Söderberg
+ * kirillDanshin
+ * lzmths
+ * Marcus Sundberg
+ * Mark Mentovai
+ * Mattes D
+ * Matyas Dolak
+ * Neeraj Badlani
+ * Nick Mathewson
+ * Rainer Keller
+ * Seungmo Koo
+ * Thomas Bernard
+ * Xiao Bao Clark
+ * zeliard
+ * Zonr Chang
+ * Kurt Roeckx
+ * Seven
+ * Simone Basso
+ * Vlad Shcherban
+ * Tim Hentenaar
+ * Breaker
+ * johnsonlee
+ * Philip Prindeville
+ * Vis Virial
+ * Andreas Gustafsson
+ * Andrey Okoshkin
+ * an-tao
+ * baixiangcpp
+ * Bernard Spil
+ * Bogdan Harjoc
+ * Carlo Marcelo Arenas Belón
+ * David Benjamin
+ * David Disseldorp
+ * Dmitry Alimov
+ * Dominic Chen
+ * dpayne
+ * ejurgensen
+ * Fredrik Strupe
+ * Gonçalo Ribeiro
+ * James Synge
+ * Jan Beich
+ * Jesse Fang
+ * Jiri Luznicky
+ * José Luis Millán
+ * Kiyoshi Aman
+ * Leo Zhang
+ * lightningkay
+ * Luke Dashjr
+ * Marcin Szewczyk
+ * Maximilian Brunner
+ * Maya Rashish
+ * Murat Demirten
+ * Nathan French
+ * Nikolay Edigaryev
+ * Philip Herron
+ * Redfoxmoon
+ * stenn
+ * SuckShit
+ * The Gitter Badger
+ * tim-le
+ * Vincent JARDIN
+ * Xiang Zhang
+ * Xiaozhou Liu
+ * yongqing.jiao
+ * Enji Cooper
+ * linxiaohui
+ * Seong-Joong Kim
+ * Tobias Stoeckmann
+ * Yury Korzhetsky
+ * zhuizhuhaomeng
+ * Pierce Lopez
+ * yuangongji
+ * Keith Smiley
+ * jeremyerb
+ * Fabrice Fontaine
+ * wenyg
+ * Aleksandr-Melnikov
+ * ayuseleznev
+ * chenguolong
+ * Dimo Markov
+ * dota17
+ * fanquake
+ * Jan Kasiak
+ * Kamil Rytarowski
+ * Mario Emmenlauer
+ * Michael Davidsaver
+ * mohuang
+ * Nick Grifka
+ * Nicolas J. Bouliane
+ * Paul Osborne
+ * Philip Homburg
+ * Wataru Ashihara
+ * William A Rowe Jr
+ * yangyongsheng
+
+
+If we have forgotten your name, please contact us.
diff --git a/ipc/chromium/src/third_party/libevent/README.mozilla b/ipc/chromium/src/third_party/libevent/README.mozilla
new file mode 100644
index 0000000000..3518aa6ee5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/README.mozilla
@@ -0,0 +1,31 @@
+This is a clean copy of libevent-2.1.12-stable with the following modifications.
+
+1. Add the following files:
+
+- android/event2/event-config.h
+- bsd/event2/event-config.h
+- linux/event2/event-config.h
+- mac/event2/event-config.h
+- solaris/event2/event-config.h
+- evconfig-private.h
+
+These files are taken from libevent-2.1.12-stable built on the development
+environment indicated by the first path component. You have to run
+"./configure" and "make" to get all of the pre-processing done. The
+event-config.h header can then be found in include/event2/ sub-directory and
+evconfig-private.h can be found in the root source directory.
+
+You then need to modify the EVENT__SIZEOF_* constants in the generated Linux,
+Android, and BSD headers to be appropriate for both 32-bit and 64-bit platforms.
+Mac doesn't need this since only 64-bit is supported. Use __LP64__ to
+distinguish the two cases. If you get something wrong, the CHECK_EVENT_SIZEOF
+static assertions in message_pump_libevent.cc will fail. If a new constant is
+added, also add a static assertion for it to message_pump_libevent.cc.
+
+You also need to modify the EVENT__HAVE_ARC4RANDOM and EVENT__HAVE_ARC4RANDOM_BUF
+constants in the generated Linux header to account for the results of the arc4random
+and arc4random_buf configure checks.
+
+2. No additional patches are needed at this time, but be careful to avoid
+clobbering changes to the various event-config.h files which have been customized
+over time to avoid various build bustages.
diff --git a/ipc/chromium/src/third_party/libevent/Vagrantfile b/ipc/chromium/src/third_party/libevent/Vagrantfile
new file mode 100644
index 0000000000..d275089e2e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/Vagrantfile
@@ -0,0 +1,397 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+# DESCRIPTION:
+# ============
+# Vagrant for running libevent tests with:
+# - timeout 30min, to avoid hungs
+# - run tests in parallel under ctest (10 concurency)
+# - if you have uncommited changes, you should commit them first to check
+# - unix only, because of some tar'ing to avoid one vm affect another
+#
+# ENVIRONMENT:
+# ============
+# - NO_PKG -- do not install packages
+# - NO_CMAKE -- do not run with cmake
+# - NO_AUTOTOOLS -- do not run with autoconf/automake
+
+Vagrant.configure("2") do |config|
+ # to allow running boxes provisions in parallel, we can't share the same dirs
+ # via virtualbox, however sometimes it is the only way, so instead let's
+ # create an archive of HEAD (this way we will not have any trash there) and
+ # extract it for every box to the separate folder.
+ #
+ # P.S. we will change this --prefix with tar(1) --trasnform
+ system('git archive --prefix=libevent/ --output=.vagrant/libevent.tar HEAD')
+
+ config.vm.provider "virtualbox" do |vb|
+ vb.memory = "512"
+
+ # otherwise osx fails, anyway we do not need this
+ vb.customize ["modifyvm", :id, "--usb", "off"]
+ vb.customize ["modifyvm", :id, "--usbehci", "off"]
+ end
+
+ # disable /vagrant share, in case we will not use default mount
+ config.vm.synced_folder ".", "/vagrant", disabled: true
+
+ config.vm.define "ubuntu" do |ubuntu|
+ system('tar --overwrite --transform=s/libevent/libevent-linux/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ ubuntu.vm.box = "ubuntu/xenial64"
+ ubuntu.vm.synced_folder ".vagrant/libevent-linux", "/vagrant",
+ type: "rsync"
+
+ if ENV['NO_PKG'] != "true"
+ ubuntu.vm.provision "shell", inline: <<-SHELL
+ apt-get update
+ apt-get install -y zlib1g-dev libssl-dev python2.7
+ apt-get install -y build-essential cmake ninja-build
+ apt-get install -y autoconf automake libtool
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ ubuntu.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ rm -fr .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G Ninja ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ ubuntu.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ ./autogen.sh
+ ./configure
+ make -j20 verify
+ SHELL
+ end
+ end
+
+ config.vm.define "freebsd" do |freebsd|
+ system('tar --overwrite --transform=s/libevent/libevent-freebsd/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ freebsd.vm.box = "freebsd/FreeBSD-11.0-STABLE"
+ freebsd.vm.synced_folder ".vagrant/libevent-freebsd", "/vagrant",
+ type: "rsync", group: "wheel"
+
+ # otherwise reports error
+ freebsd.ssh.shell = "sh"
+
+ if ENV['NO_PKG'] != "true"
+ freebsd.vm.provision "shell", inline: <<-SHELL
+ pkg install --yes openssl cmake ninja automake autotools
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ freebsd.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ rm -fr .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G Ninja ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ freebsd.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ ./autogen.sh
+ ./configure
+ make -j20 verify
+ SHELL
+ end
+ end
+
+ config.vm.define "netbsd" do |netbsd|
+ system('tar --overwrite --transform=s/libevent/libevent-netbsd/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ netbsd.vm.box = "kja/netbsd-7-amd64"
+ netbsd.vm.synced_folder ".vagrant/libevent-netbsd", "/vagrant",
+ type: "rsync", group: "wheel"
+
+ if ENV['NO_PKG'] != "true"
+ netbsd.vm.provision "shell", inline: <<-SHELL
+ export PKG_PATH="ftp://ftp.netbsd.org/pub/pkgsrc/packages/NetBSD/x86_64/7.0_2016Q2/All/"
+ pkg_add ncurses ninja-build automake cmake libtool
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ netbsd.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ rm -fr .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G Ninja ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ netbsd.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ ./autogen.sh
+ ./configure
+ make -j20 verify
+ SHELL
+ end
+ end
+
+ config.vm.define "solaris" do |solaris|
+ system('tar --overwrite --transform=s/libevent/libevent-solaris/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ # XXX:
+ # - solaris do not have '-or' it only has '-o' for find(1), so we can't use
+ # rsync
+ # - and autoconf(1) doesn't work on virtualbox share, ugh
+ solaris.vm.synced_folder ".vagrant/libevent-solaris", "/vagrant-vbox",
+ type: "virtualbox"
+
+ solaris.vm.box = "tnarik/solaris10-minimal"
+ if ENV['NO_PKG'] != "true"
+ # TODO: opencsw does not include ninja(1)
+ solaris.vm.provision "shell", inline: <<-SHELL
+ pkgadd -d http://get.opencsw.org/now
+ pkgutil -U
+ pkgutil -y -i libssl_dev cmake rsync python gmake gcc5core automake autoconf libtool
+ SHELL
+ end
+
+ # copy from virtualbox mount to newly created folder
+ solaris.vm.provision "shell", privileged: false, inline: <<-SHELL
+ rm -fr ~/vagrant
+ cp -r /vagrant-vbox ~/vagrant
+ SHELL
+
+ if ENV['NO_CMAKE'] != "true"
+ # builtin compiler cc(1) is a wrapper, so we should use gcc5 manually,
+ # otherwise it will not work.
+ # Plus we should set some paths so that cmake/compiler can find tham.
+ solaris.vm.provision "shell", privileged: false, inline: <<-SHELL
+ export CMAKE_INCLUDE_PATH=/opt/csw/include
+ export CMAKE_LIBRARY_PATH=/opt/csw/lib
+ export CFLAGS=-I$CMAKE_INCLUDE_PATH
+ export LDFLAGS=-L$CMAKE_LIBRARY_PATH
+
+ cd ~/vagrant
+ rm -rf .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -DCMAKE_C_COMPILER=gcc ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ # and we should set MAKE for `configure` otherwise it will try to use
+ # `make`
+ solaris.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd ~/vagrant
+ ./autogen.sh
+ MAKE=gmake ./configure
+ gmake -j20 verify
+ SHELL
+ end
+ end
+
+ # known failures:
+ # - sometimes vm hangs
+ config.vm.define "osx" do |osx|
+ system('tar --overwrite --transform=s/libevent/libevent-osx/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ osx.vm.synced_folder ".vagrant/libevent-osx", "/vagrant",
+ type: "rsync", group: "wheel"
+
+ osx.vm.box = "jhcook/osx-elcapitan-10.11"
+ if ENV['NO_PKG'] != "true"
+ osx.vm.provision "shell", privileged: false, inline: <<-SHELL
+ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
+
+ brew uninstall libtool
+ brew install libtool openssl ninja cmake autoconf automake
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ # we should set some paths so that cmake/compiler can find tham
+ osx.vm.provision "shell", privileged: false, inline: <<-SHELL
+ export OPENSSL_ROOT=$(echo /usr/local/Cellar/openssl/*)
+ export CMAKE_INCLUDE_PATH=$OPENSSL_ROOT/include
+ export CMAKE_LIBRARY_PATH=$OPENSSL_ROOT/lib
+
+ cd /vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G Ninja ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ osx.vm.provision "shell", privileged: false, inline: <<-SHELL
+ export OPENSSL_ROOT=$(echo /usr/local/Cellar/openssl/*)
+ export CFLAGS=-I$OPENSSL_ROOT/include
+ export LDFLAGS=-L$OPENSSL_ROOT/lib
+
+ cd /vagrant
+ ./autogen.sh
+ ./configure
+ make -j20 verify
+ SHELL
+ end
+ end
+
+ config.vm.define "centos" do |centos|
+ system('tar --overwrite --transform=s/libevent/libevent-centos/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ centos.vm.synced_folder ".vagrant/libevent-centos", "/vagrant",
+ type: "rsync", group: "wheel"
+
+ centos.vm.box = "centos/7"
+ if ENV['NO_PKG'] != "true"
+ centos.vm.provision "shell", inline: <<-SHELL
+ echo "[russianfedora]" > /etc/yum.repos.d/russianfedora.repo
+ echo name=russianfedora >> /etc/yum.repos.d/russianfedora.repo
+ echo baseurl=http://mirror.yandex.ru/fedora/russianfedora/russianfedora/free/el/releases/7/Everything/x86_64/os/ >> /etc/yum.repos.d/russianfedora.repo
+ echo enabled=1 >> /etc/yum.repos.d/russianfedora.repo
+ echo gpgcheck=0 >> /etc/yum.repos.d/russianfedora.repo
+ SHELL
+ centos.vm.provision "shell", inline: <<-SHELL
+ yum -y install zlib-devel openssl-devel python
+ yum -y install gcc cmake ninja-build
+ yum -y install autoconf automake libtool
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ centos.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ rm -fr .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G Ninja ..
+
+ export CTEST_TEST_TIMEOUT=1800
+ export CTEST_OUTPUT_ON_FAILURE=1
+ export CTEST_PARALLEL_LEVEL=20
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ centos.vm.provision "shell", privileged: false, inline: <<-SHELL
+ cd /vagrant
+ ./autogen.sh
+ ./configure
+ make -j20 verify
+ SHELL
+ end
+ end
+
+ # known failures:
+ # - issues with timers (not enough allowed error)
+ config.vm.define "win" do |win|
+ system('tar --overwrite --transform=s/libevent/libevent-win/ -xf .vagrant/libevent.tar -C .vagrant/')
+
+ # 512MB not enough after libtool install, huh
+ win.vm.provider "virtualbox" do |vb|
+ vb.memory = "1024"
+ end
+
+ # windows does not have rsync builtin, let's use virtualbox for now
+ win.vm.synced_folder ".vagrant/libevent-win", "/vagrant",
+ type: "virtualbox"
+
+ win.vm.box = "senglin/win-10-enterprise-vs2015community"
+ if ENV['NO_PKG'] != "true"
+ # box with vs2015 does not have C++ support, so let's install it manually
+ # plus chocolatey that includes in this box, can't handle sha1 checksum for
+ # cmake.install, so let's update it<
+ win.vm.provision "shell", inline: <<-SHELL
+ choco upgrade -y chocolatey -pre -f
+ choco install -y VisualStudioCommunity2013
+ choco install -y openssl.light
+ choco install -y cygwin cyg-get
+ choco install -y cmake
+ choco install -y cmake.install
+ choco install -y python2
+ SHELL
+
+ # chocolatey openssl.light package does not contains headers
+ win.vm.provision "shell", inline: <<-SHELL
+ (new-object System.Net.WebClient).DownloadFile('http://strcpy.net/packages/Win32OpenSSL-1_0_2a.exe', '/openssl.exe')
+ /openssl.exe /silent /verysilent /sp- /suppressmsgboxes
+ SHELL
+
+ # XXX:
+ # - cyg-get depends from cygwinsetup.exe
+ # https://github.com/chocolatey/chocolatey-coreteampackages/issues/200
+ # - cyg-get only downloads, do not installs them, ugh. so let's do not use
+ # it
+ win.vm.provision "shell", privileged: false, inline: <<-SHELL
+ (new-object System.Net.WebClient).DownloadFile('https://cygwin.com/setup-x86_64.exe', '/tools/cygwin/cygwinsetup.exe')
+
+ $env:PATH="/tools/cygwin/bin;$($env:PATH);/tools/cygwin"
+
+ cygwinsetup --root c:/tools/cygwin/ --local-package-dir c:/tools/cygwin/packages/ --no-desktop --no-startmenu --verbose --quiet-mode --download --packages automake,autoconf,gcc-core,libtool,make,python,openssl-devel
+ cygwinsetup --root c:/tools/cygwin/ --local-package-dir c:/tools/cygwin/packages/ --no-desktop --no-startmenu --verbose --quiet-mode --local-install --packages automake,autoconf,gcc-core,libtool,make,python,openssl-devel
+ SHELL
+ end
+
+ if ENV['NO_CMAKE'] != "true"
+ win.vm.provision "shell", privileged: false, inline: <<-SHELL
+ $env:PATH="/Program Files/CMake/bin;/tools/python2;$($env:PATH)"
+
+ cd /vagrant
+ Remove-Item -Recurse -Force .cmake-vagrant
+ mkdir -p .cmake-vagrant
+ cd .cmake-vagrant
+ cmake -G "Visual Studio 12" ..
+
+ $env:CTEST_TEST_TIMEOUT = "1800"
+ $env:CTEST_OUTPUT_ON_FAILURE = "1"
+ $env:CTEST_PARALLEL_LEVEL = "10"
+ cmake --build . --target verify
+ SHELL
+ end
+
+ if ENV['NO_AUTOTOOLS'] != "true"
+ win.vm.provision "shell", privileged: false, inline: <<-SHELL
+ $env:PATH="/tools/cygwin/bin;$($env:PATH)"
+
+ bash -lc "echo 'C:/tools/mingw64 /mingw ntfs binary 0 0' > /etc/fstab"
+ bash -lc "echo 'C:/OpenSSL-Win32 /ssl ntfs binary 0 0' >> /etc/fstab"
+ bash -lc "echo 'C:/vagrant /vagrant ntfs binary 0 0' >> /etc/fstab"
+
+ bash -lc "exec 0</dev/null; exec 2>&1; cd /vagrant; bash -x ./autogen.sh && ./configure LDFLAGS='-L/ssl -L/ssl/lib -L/ssl/lib/MinGW' CFLAGS=-I/ssl/include && make -j20 verify"
+ SHELL
+ end
+ end
+end
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.c b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.c
new file mode 100644
index 0000000000..0fcba5d915
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.c
@@ -0,0 +1,149 @@
+/* $NetBSD: getopt.c,v 1.16 1999/12/02 13:15:56 kleink Exp $ */
+
+/*
+ * Copyright (c) 1987, 1993, 1994, 1995
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the names of the copyright holders nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
+ * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if 0
+static char sccsid[] = "@(#)getopt.c 8.3 (Berkeley) 4/27/95";
+#endif
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <string.h>
+
+#define __P(x) x
+#define _DIAGASSERT(x) assert(x)
+
+#ifdef __weak_alias
+__weak_alias(getopt,_getopt);
+#endif
+
+
+int opterr = 1, /* if error message should be printed */
+ optind = 1, /* index into parent argv vector */
+ optopt, /* character checked for validity */
+ optreset; /* reset getopt */
+char *optarg; /* argument associated with option */
+
+static char * _progname __P((char *));
+int getopt_internal __P((int, char * const *, const char *));
+
+static char *
+_progname(nargv0)
+ char * nargv0;
+{
+ char * tmp;
+
+ _DIAGASSERT(nargv0 != NULL);
+
+ tmp = strrchr(nargv0, '/');
+ if (tmp)
+ tmp++;
+ else
+ tmp = nargv0;
+ return(tmp);
+}
+
+#define BADCH (int)'?'
+#define BADARG (int)':'
+#define EMSG ""
+
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt(nargc, nargv, ostr)
+ int nargc;
+ char * const nargv[];
+ const char *ostr;
+{
+ static char *__progname = 0;
+ static char *place = EMSG; /* option letter processing */
+ char *oli; /* option letter list index */
+ __progname = __progname?__progname:_progname(*nargv);
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(ostr != NULL);
+
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc || *(place = nargv[optind]) != '-') {
+ place = EMSG;
+ return (-1);
+ }
+ if (place[1] && *++place == '-' /* found "--" */
+ && place[1] == '\0') {
+ ++optind;
+ place = EMSG;
+ return (-1);
+ }
+ } /* option letter okay? */
+ if ((optopt = (int)*place++) == (int)':' ||
+ !(oli = strchr(ostr, optopt))) {
+ /*
+ * if the user didn't specify '-' as an option,
+ * assume it means -1.
+ */
+ if (optopt == (int)'-')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (opterr && *ostr != ':')
+ (void)fprintf(stderr,
+ "%s: illegal option -- %c\n", __progname, optopt);
+ return (BADCH);
+ }
+ if (*++oli != ':') { /* don't need argument */
+ optarg = NULL;
+ if (!*place)
+ ++optind;
+ }
+ else { /* need an argument */
+ if (*place) /* no white space */
+ optarg = place;
+ else if (nargc <= ++optind) { /* no arg */
+ place = EMSG;
+ if (*ostr == ':')
+ return (BADARG);
+ if (opterr)
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ __progname, optopt);
+ return (BADCH);
+ }
+ else /* white space */
+ optarg = nargv[optind];
+ place = EMSG;
+ ++optind;
+ }
+ return (optopt); /* dump back option letter */
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.h b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.h
new file mode 100644
index 0000000000..796f455050
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt.h
@@ -0,0 +1,33 @@
+#ifndef __GETOPT_H__
+#define __GETOPT_H__
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern int opterr; /* if error message should be printed */
+extern int optind; /* index into parent argv vector */
+extern int optopt; /* character checked for validity */
+extern int optreset; /* reset getopt */
+extern char *optarg; /* argument associated with option */
+
+struct option
+{
+ const char *name;
+ int has_arg;
+ int *flag;
+ int val;
+};
+
+#define no_argument 0
+#define required_argument 1
+#define optional_argument 2
+
+int getopt(int, char**, const char*);
+int getopt_long(int, char**, const char*, const struct option*, int*);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __GETOPT_H__ */
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt_long.c b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt_long.c
new file mode 100644
index 0000000000..092defbc4b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/getopt_long.c
@@ -0,0 +1,234 @@
+
+/*
+ * Copyright (c) 1987, 1993, 1994, 1996
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the names of the copyright holders nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS
+ * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "getopt.h"
+
+extern int opterr; /* if error message should be printed */
+extern int optind; /* index into parent argv vector */
+extern int optopt; /* character checked for validity */
+extern int optreset; /* reset getopt */
+extern char *optarg; /* argument associated with option */
+
+#define __P(x) x
+#define _DIAGASSERT(x) assert(x)
+
+static char * __progname __P((char *));
+int getopt_internal __P((int, char * const *, const char *));
+
+static char *
+__progname(nargv0)
+ char * nargv0;
+{
+ char * tmp;
+
+ _DIAGASSERT(nargv0 != NULL);
+
+ tmp = strrchr(nargv0, '/');
+ if (tmp)
+ tmp++;
+ else
+ tmp = nargv0;
+ return(tmp);
+}
+
+#define BADCH (int)'?'
+#define BADARG (int)':'
+#define EMSG ""
+
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_internal(nargc, nargv, ostr)
+ int nargc;
+ char * const *nargv;
+ const char *ostr;
+{
+ static char *place = EMSG; /* option letter processing */
+ char *oli; /* option letter list index */
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(ostr != NULL);
+
+ if (optreset || !*place) { /* update scanning pointer */
+ optreset = 0;
+ if (optind >= nargc || *(place = nargv[optind]) != '-') {
+ place = EMSG;
+ return (-1);
+ }
+ if (place[1] && *++place == '-') { /* found "--" */
+ /* ++optind; */
+ place = EMSG;
+ return (-2);
+ }
+ } /* option letter okay? */
+ if ((optopt = (int)*place++) == (int)':' ||
+ !(oli = strchr(ostr, optopt))) {
+ /*
+ * if the user didn't specify '-' as an option,
+ * assume it means -1.
+ */
+ if (optopt == (int)'-')
+ return (-1);
+ if (!*place)
+ ++optind;
+ if (opterr && *ostr != ':')
+ (void)fprintf(stderr,
+ "%s: illegal option -- %c\n", __progname(nargv[0]), optopt);
+ return (BADCH);
+ }
+ if (*++oli != ':') { /* don't need argument */
+ optarg = NULL;
+ if (!*place)
+ ++optind;
+ } else { /* need an argument */
+ if (*place) /* no white space */
+ optarg = place;
+ else if (nargc <= ++optind) { /* no arg */
+ place = EMSG;
+ if ((opterr) && (*ostr != ':'))
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %c\n",
+ __progname(nargv[0]), optopt);
+ return (BADARG);
+ } else /* white space */
+ optarg = nargv[optind];
+ place = EMSG;
+ ++optind;
+ }
+ return (optopt); /* dump back option letter */
+}
+
+#if 0
+/*
+ * getopt --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt2(nargc, nargv, ostr)
+ int nargc;
+ char * const *nargv;
+ const char *ostr;
+{
+ int retval;
+
+ if ((retval = getopt_internal(nargc, nargv, ostr)) == -2) {
+ retval = -1;
+ ++optind;
+ }
+ return(retval);
+}
+#endif
+
+/*
+ * getopt_long --
+ * Parse argc/argv argument vector.
+ */
+int
+getopt_long(nargc, nargv, options, long_options, index)
+ int nargc;
+ char ** nargv;
+ const char * options;
+ const struct option * long_options;
+ int * index;
+{
+ int retval;
+
+ _DIAGASSERT(nargv != NULL);
+ _DIAGASSERT(options != NULL);
+ _DIAGASSERT(long_options != NULL);
+ /* index may be NULL */
+
+ if ((retval = getopt_internal(nargc, nargv, options)) == -2) {
+ char *current_argv = nargv[optind++] + 2, *has_equal;
+ int i, match = -1;
+ size_t current_argv_len;
+
+ if (*current_argv == '\0') {
+ return(-1);
+ }
+ if ((has_equal = strchr(current_argv, '=')) != NULL) {
+ current_argv_len = has_equal - current_argv;
+ has_equal++;
+ } else
+ current_argv_len = strlen(current_argv);
+
+ for (i = 0; long_options[i].name; i++) {
+ if (strncmp(current_argv, long_options[i].name, current_argv_len))
+ continue;
+
+ if (strlen(long_options[i].name) == current_argv_len) {
+ match = i;
+ break;
+ }
+ if (match == -1)
+ match = i;
+ }
+ if (match != -1) {
+ if (long_options[match].has_arg == required_argument ||
+ long_options[match].has_arg == optional_argument) {
+ if (has_equal)
+ optarg = has_equal;
+ else
+ optarg = nargv[optind++];
+ }
+ if ((long_options[match].has_arg == required_argument)
+ && (optarg == NULL)) {
+ /*
+ * Missing argument, leading :
+ * indicates no error should be generated
+ */
+ if ((opterr) && (*options != ':'))
+ (void)fprintf(stderr,
+ "%s: option requires an argument -- %s\n",
+ __progname(nargv[0]), current_argv);
+ return (BADARG);
+ }
+ } else { /* No matching argument */
+ if ((opterr) && (*options != ':'))
+ (void)fprintf(stderr,
+ "%s: illegal option -- %s\n", __progname(nargv[0]), current_argv);
+ return (BADCH);
+ }
+ if (long_options[match].flag) {
+ *long_options[match].flag = long_options[match].val;
+ retval = 0;
+ } else
+ retval = long_options[match].val;
+ if (index)
+ *index = match;
+ }
+ return(retval);
+}
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/evconfig-private.h b/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/evconfig-private.h
new file mode 100644
index 0000000000..88e206272b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/evconfig-private.h
@@ -0,0 +1,6 @@
+#if !defined(EVENT_EVCONFIG__PRIVATE_H_) && !defined(__MINGW32__)
+#define EVENT_EVCONFIG__PRIVATE_H_
+
+/* Nothing to see here. Move along. */
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/event2/event-config.h b/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/event2/event-config.h
new file mode 100644
index 0000000000..3f3a0d2968
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/nmake/event2/event-config.h
@@ -0,0 +1,350 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+#ifndef EVENT_CONFIG_H__
+#define EVENT_CONFIG_H__
+/* config.h. Generated by configure. */
+/* config.h.in. Generated from configure.in by autoheader. */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define if clock_gettime is available in libc */
+/* #undef _EVENT_DNS_USE_CPU_CLOCK_FOR_ID */
+
+/* Define is no secure id variant is available */
+/* #define _EVENT_DNS_USE_GETTIMEOFDAY_FOR_ID 1 */
+#define EVENT_DNS_USE_FTIME_FOR_ID_ 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+/* #undef EVENT__HAVE_ARPA_INET_H */
+
+/* Define to 1 if you have the `clock_gettime' function. */
+/* #undef EVENT__HAVE_CLOCK_GETTIME */
+
+/* Define if /dev/poll is available */
+/* #undef EVENT__HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+/* #undef EVENT__HAVE_DLFCN_H */
+
+/* Define if your system supports the epoll system calls */
+/* #undef EVENT__HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef EVENT__HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the `eventfd' function. */
+/* #undef EVENT__HAVE_EVENTFD */
+
+/* Define if your system supports event ports */
+/* #undef EVENT__HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+/* #undef EVENT__HAVE_FCNTL */
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the `getaddrinfo' function. */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+/* #define EVENT__HAVE_GETTIMEOFDAY 1 */
+
+/* Define to 1 if you have the `inet_ntop' function. */
+/* #undef EVENT__HAVE_INET_NTOP */
+
+/* Define to 1 if you have the `inet_pton' function. */
+/* #undef EVENT__HAVE_INET_PTON */
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+/* #define EVENT__HAVE_INTTYPES_H 1 */
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef EVENT__HAVE_KQUEUE */
+
+/* Define if the system has zlib */
+/* #undef EVENT__HAVE_LIBZ */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+/* #undef EVENT__HAVE_MMAP */
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN_H */
+
+/* Define to 1 if you have the `pipe' function. */
+/* #undef EVENT__HAVE_PIPE */
+
+/* Define to 1 if you have the `poll' function. */
+/* #undef EVENT__HAVE_POLL */
+
+/* Define to 1 if you have the <poll.h> header file. */
+/* #undef EVENT__HAVE_POLL_H */
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef EVENT__HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef EVENT__HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+/* #undef EVENT__HAVE_PTHREADS */
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+/* #undef EVENT__HAVE_SA_FAMILY_T */
+
+/* Define to 1 if you have the `select' function. */
+/* #undef EVENT__HAVE_SELECT */
+
+/* Define to 1 if you have the `sendfile' function. */
+/* #undef EVENT__HAVE_SENDFILE */
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+/* #undef EVENT__HAVE_SETFD */
+
+/* Define to 1 if you have the `sigaction' function. */
+/* #undef EVENT__HAVE_SIGACTION */
+
+/* Define to 1 if you have the `signal' function. */
+#define EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef EVENT__HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+/* #define EVENT__HAVE_STDINT_H 1 */
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef EVENT__HAVE_STRLCPY */
+
+/* Define to 1 if you have the `strsep' function. */
+/* #undef EVENT__HAVE_STRSEP */
+
+/* Define to 1 if you have the `strtok_r' function. */
+/* #undef EVENT__HAVE_STRTOK_R */
+
+/* Define to 1 if you have the `strtoll' function. */
+/* #define EVENT__HAVE_STRTOLL 1 */
+
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+
+/* Define to 1 if `s6_addr32' is member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is member of `struct sockaddr_in6'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is member of `struct sockaddr_in'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENTFD_H */
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+/* #undef EVENT__HAVE_SYS_IOCTL_H */
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+/* #undef EVENT__HAVE_SYS_MMAN_H */
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+/* #define EVENT__HAVE_SYS_PARAM_H 1 */
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+/* #undef EVENT__HAVE_SYS_QUEUE_H */
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+/* #undef EVENT__HAVE_SYS_SELECT_H */
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+/* #undef EVENT__HAVE_SYS_SENDFILE_H */
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+/* #undef EVENT__HAVE_SYS_SOCKET_H */
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+/* #define EVENT__HAVE_SYS_TIME_H 1 */
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+/* #undef EVENT__HAVE_SYS_UIO_H */
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+/* #undef EVENT__HAVE_TAILQFOREACH */
+
+/* Define if timeradd is defined in <sys/time.h> */
+/* #undef EVENT__HAVE_TIMERADD */
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+/* #define EVENT__HAVE_UINT16_T 1 */
+
+/* Define to 1 if the system has the type `uint32_t'. */
+/* #define EVENT__HAVE_UINT32_T 1 */
+
+/* Define to 1 if the system has the type `uint64_t'. */
+/* #define EVENT__HAVE_UINT64_T 1 */
+
+/* Define to 1 if the system has the type `uint8_t'. */
+/* #define EVENT__HAVE_UINT8_T 1 */
+
+/* Define to 1 if you have the <unistd.h> header file. */
+/* #define EVENT__HAVE_UNISTD_H 1 */
+
+/* Define to 1 if you have the `vasprintf' function. */
+/* #undef EVENT__HAVE_VASPRINTF */
+
+/* Define if kqueue works correctly with pipes */
+/* #undef EVENT__HAVE_WORKING_KQUEUE */
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME ""
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING ""
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION ""
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* The size of a `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of a `long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG 4
+
+/* The size of a `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of a `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef _WIN64
+#define EVENT__SIZEOF_SIZE_T 8
+#else
+#define EVENT__SIZEOF_SIZE_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef _WIN64
+#define EVENT__SIZEOF_VOID_P 8
+#else
+#define EVENT__SIZEOF_VOID_P 4
+#endif
+
+/* The size of `time_t`, as computed by sizeof. */
+#ifdef _WIN64
+#define EVENT__SIZEOF_TIME_T 8
+#else
+#define EVENT__SIZEOF_TIME_T 4
+#endif
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#define EVENT__inline __inline
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+/* #undef EVENT__size_t */
+
+/* Define to unsigned int if you dont have it */
+#define EVENT__socklen_t unsigned int
+
+/* Define to `int' if <sys/types.h> does not define. */
+#define EVENT__ssize_t SSIZE_T
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/WIN32-Code/tree.h b/ipc/chromium/src/third_party/libevent/WIN32-Code/tree.h
new file mode 100644
index 0000000000..2ccfbf20ac
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/WIN32-Code/tree.h
@@ -0,0 +1,677 @@
+/* $OpenBSD: tree.h,v 1.7 2002/10/17 21:51:54 art Exp $ */
+/*
+ * Copyright 2002 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef _SYS_TREE_H_
+#define _SYS_TREE_H_
+
+/*
+ * This file defines data structures for different types of trees:
+ * splay trees and red-black trees.
+ *
+ * A splay tree is a self-organizing data structure. Every operation
+ * on the tree causes a splay to happen. The splay moves the requested
+ * node to the root of the tree and partly rebalances it.
+ *
+ * This has the benefit that request locality causes faster lookups as
+ * the requested nodes move to the top of the tree. On the other hand,
+ * every lookup causes memory writes.
+ *
+ * The Balance Theorem bounds the total access time for m operations
+ * and n inserts on an initially empty tree as O((m + n)lg n). The
+ * amortized cost for a sequence of m accesses to a splay tree is O(lg n);
+ *
+ * A red-black tree is a binary search tree with the node color as an
+ * extra attribute. It fulfills a set of conditions:
+ * - every search path from the root to a leaf consists of the
+ * same number of black nodes,
+ * - each red node (except for the root) has a black parent,
+ * - each leaf node is black.
+ *
+ * Every operation on a red-black tree is bounded as O(lg n).
+ * The maximum height of a red-black tree is 2lg (n+1).
+ */
+
+#define SPLAY_HEAD(name, type) \
+struct name { \
+ struct type *sph_root; /* root of the tree */ \
+}
+
+#define SPLAY_INITIALIZER(root) \
+ { NULL }
+
+#define SPLAY_INIT(root) do { \
+ (root)->sph_root = NULL; \
+} while (0)
+
+#define SPLAY_ENTRY(type) \
+struct { \
+ struct type *spe_left; /* left element */ \
+ struct type *spe_right; /* right element */ \
+}
+
+#define SPLAY_LEFT(elm, field) (elm)->field.spe_left
+#define SPLAY_RIGHT(elm, field) (elm)->field.spe_right
+#define SPLAY_ROOT(head) (head)->sph_root
+#define SPLAY_EMPTY(head) (SPLAY_ROOT(head) == NULL)
+
+/* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */
+#define SPLAY_ROTATE_RIGHT(head, tmp, field) do { \
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (0)
+
+#define SPLAY_ROTATE_LEFT(head, tmp, field) do { \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ (head)->sph_root = tmp; \
+} while (0)
+
+#define SPLAY_LINKLEFT(head, tmp, field) do { \
+ SPLAY_LEFT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field); \
+} while (0)
+
+#define SPLAY_LINKRIGHT(head, tmp, field) do { \
+ SPLAY_RIGHT(tmp, field) = (head)->sph_root; \
+ tmp = (head)->sph_root; \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field); \
+} while (0)
+
+#define SPLAY_ASSEMBLE(head, node, left, right, field) do { \
+ SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field); \
+ SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\
+ SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field); \
+ SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field); \
+} while (0)
+
+/* Generates prototypes and inline functions */
+
+#define SPLAY_PROTOTYPE(name, type, field, cmp) \
+void name##_SPLAY(struct name *, struct type *); \
+void name##_SPLAY_MINMAX(struct name *, int); \
+struct type *name##_SPLAY_INSERT(struct name *, struct type *); \
+struct type *name##_SPLAY_REMOVE(struct name *, struct type *); \
+ \
+/* Finds the node with the same key as elm */ \
+static __inline struct type * \
+name##_SPLAY_FIND(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) \
+ return(NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) \
+ return (head->sph_root); \
+ return (NULL); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_NEXT(struct name *head, struct type *elm) \
+{ \
+ name##_SPLAY(head, elm); \
+ if (SPLAY_RIGHT(elm, field) != NULL) { \
+ elm = SPLAY_RIGHT(elm, field); \
+ while (SPLAY_LEFT(elm, field) != NULL) { \
+ elm = SPLAY_LEFT(elm, field); \
+ } \
+ } else \
+ elm = NULL; \
+ return (elm); \
+} \
+ \
+static __inline struct type * \
+name##_SPLAY_MIN_MAX(struct name *head, int val) \
+{ \
+ name##_SPLAY_MINMAX(head, val); \
+ return (SPLAY_ROOT(head)); \
+}
+
+/* Main splay operation.
+ * Moves node close to the key of elm to top
+ */
+#define SPLAY_GENERATE(name, type, field, cmp) \
+struct type * \
+name##_SPLAY_INSERT(struct name *head, struct type *elm) \
+{ \
+ if (SPLAY_EMPTY(head)) { \
+ SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL; \
+ } else { \
+ int __comp; \
+ name##_SPLAY(head, elm); \
+ __comp = (cmp)(elm, (head)->sph_root); \
+ if(__comp < 0) { \
+ SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\
+ SPLAY_RIGHT(elm, field) = (head)->sph_root; \
+ SPLAY_LEFT((head)->sph_root, field) = NULL; \
+ } else if (__comp > 0) { \
+ SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\
+ SPLAY_LEFT(elm, field) = (head)->sph_root; \
+ SPLAY_RIGHT((head)->sph_root, field) = NULL; \
+ } else \
+ return ((head)->sph_root); \
+ } \
+ (head)->sph_root = (elm); \
+ return (NULL); \
+} \
+ \
+struct type * \
+name##_SPLAY_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *__tmp; \
+ if (SPLAY_EMPTY(head)) \
+ return (NULL); \
+ name##_SPLAY(head, elm); \
+ if ((cmp)(elm, (head)->sph_root) == 0) { \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL) { \
+ (head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\
+ } else { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ (head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\
+ name##_SPLAY(head, elm); \
+ SPLAY_RIGHT((head)->sph_root, field) = __tmp; \
+ } \
+ return (elm); \
+ } \
+ return (NULL); \
+} \
+ \
+void \
+name##_SPLAY(struct name *head, struct type *elm) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+ int __comp; \
+\
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+ __left = __right = &__node; \
+\
+ while ((__comp = (cmp)(elm, (head)->sph_root))) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if ((cmp)(elm, __tmp) > 0){ \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+} \
+ \
+/* Splay with either the minimum or the maximum element \
+ * Used to find minimum or maximum element in tree. \
+ */ \
+void name##_SPLAY_MINMAX(struct name *head, int __comp) \
+{ \
+ struct type __node, *__left, *__right, *__tmp; \
+\
+ SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\
+ __left = __right = &__node; \
+\
+ while (1) { \
+ if (__comp < 0) { \
+ __tmp = SPLAY_LEFT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp < 0){ \
+ SPLAY_ROTATE_RIGHT(head, __tmp, field); \
+ if (SPLAY_LEFT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKLEFT(head, __right, field); \
+ } else if (__comp > 0) { \
+ __tmp = SPLAY_RIGHT((head)->sph_root, field); \
+ if (__tmp == NULL) \
+ break; \
+ if (__comp > 0) { \
+ SPLAY_ROTATE_LEFT(head, __tmp, field); \
+ if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\
+ break; \
+ } \
+ SPLAY_LINKRIGHT(head, __left, field); \
+ } \
+ } \
+ SPLAY_ASSEMBLE(head, &__node, __left, __right, field); \
+}
+
+#define SPLAY_NEGINF -1
+#define SPLAY_INF 1
+
+#define SPLAY_INSERT(name, x, y) name##_SPLAY_INSERT(x, y)
+#define SPLAY_REMOVE(name, x, y) name##_SPLAY_REMOVE(x, y)
+#define SPLAY_FIND(name, x, y) name##_SPLAY_FIND(x, y)
+#define SPLAY_NEXT(name, x, y) name##_SPLAY_NEXT(x, y)
+#define SPLAY_MIN(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF))
+#define SPLAY_MAX(name, x) (SPLAY_EMPTY(x) ? NULL \
+ : name##_SPLAY_MIN_MAX(x, SPLAY_INF))
+
+#define SPLAY_FOREACH(x, name, head) \
+ for ((x) = SPLAY_MIN(name, head); \
+ (x) != NULL; \
+ (x) = SPLAY_NEXT(name, head, x))
+
+/* Macros that define a red-back tree */
+#define RB_HEAD(name, type) \
+struct name { \
+ struct type *rbh_root; /* root of the tree */ \
+}
+
+#define RB_INITIALIZER(root) \
+ { NULL }
+
+#define RB_INIT(root) do { \
+ (root)->rbh_root = NULL; \
+} while (0)
+
+#define RB_BLACK 0
+#define RB_RED 1
+#define RB_ENTRY(type) \
+struct { \
+ struct type *rbe_left; /* left element */ \
+ struct type *rbe_right; /* right element */ \
+ struct type *rbe_parent; /* parent element */ \
+ int rbe_color; /* node color */ \
+}
+
+#define RB_LEFT(elm, field) (elm)->field.rbe_left
+#define RB_RIGHT(elm, field) (elm)->field.rbe_right
+#define RB_PARENT(elm, field) (elm)->field.rbe_parent
+#define RB_COLOR(elm, field) (elm)->field.rbe_color
+#define RB_ROOT(head) (head)->rbh_root
+#define RB_EMPTY(head) (RB_ROOT(head) == NULL)
+
+#define RB_SET(elm, parent, field) do { \
+ RB_PARENT(elm, field) = parent; \
+ RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL; \
+ RB_COLOR(elm, field) = RB_RED; \
+} while (0)
+
+#define RB_SET_BLACKRED(black, red, field) do { \
+ RB_COLOR(black, field) = RB_BLACK; \
+ RB_COLOR(red, field) = RB_RED; \
+} while (0)
+
+#ifndef RB_AUGMENT
+#define RB_AUGMENT(x)
+#endif
+
+#define RB_ROTATE_LEFT(head, elm, tmp, field) do { \
+ (tmp) = RB_RIGHT(elm, field); \
+ if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) { \
+ RB_PARENT(RB_LEFT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_LEFT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (0)
+
+#define RB_ROTATE_RIGHT(head, elm, tmp, field) do { \
+ (tmp) = RB_LEFT(elm, field); \
+ if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) { \
+ RB_PARENT(RB_RIGHT(tmp, field), field) = (elm); \
+ } \
+ RB_AUGMENT(elm); \
+ if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) { \
+ if ((elm) == RB_LEFT(RB_PARENT(elm, field), field)) \
+ RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \
+ else \
+ RB_RIGHT(RB_PARENT(elm, field), field) = (tmp); \
+ } else \
+ (head)->rbh_root = (tmp); \
+ RB_RIGHT(tmp, field) = (elm); \
+ RB_PARENT(elm, field) = (tmp); \
+ RB_AUGMENT(tmp); \
+ if ((RB_PARENT(tmp, field))) \
+ RB_AUGMENT(RB_PARENT(tmp, field)); \
+} while (0)
+
+/* Generates prototypes and inline functions */
+#define RB_PROTOTYPE(name, type, field, cmp) \
+void name##_RB_INSERT_COLOR(struct name *, struct type *); \
+void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\
+struct type *name##_RB_REMOVE(struct name *, struct type *); \
+struct type *name##_RB_INSERT(struct name *, struct type *); \
+struct type *name##_RB_FIND(struct name *, struct type *); \
+struct type *name##_RB_NEXT(struct type *); \
+struct type *name##_RB_MINMAX(struct name *, int); \
+ \
+
+/* Main rb operation.
+ * Moves node close to the key of elm to top
+ */
+#define RB_GENERATE(name, type, field, cmp) \
+void \
+name##_RB_INSERT_COLOR(struct name *head, struct type *elm) \
+{ \
+ struct type *parent, *gparent, *tmp; \
+ while ((parent = RB_PARENT(elm, field)) && \
+ RB_COLOR(parent, field) == RB_RED) { \
+ gparent = RB_PARENT(parent, field); \
+ if (parent == RB_LEFT(gparent, field)) { \
+ tmp = RB_RIGHT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field);\
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_RIGHT(parent, field) == elm) { \
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_RIGHT(head, gparent, tmp, field); \
+ } else { \
+ tmp = RB_LEFT(gparent, field); \
+ if (tmp && RB_COLOR(tmp, field) == RB_RED) { \
+ RB_COLOR(tmp, field) = RB_BLACK; \
+ RB_SET_BLACKRED(parent, gparent, field);\
+ elm = gparent; \
+ continue; \
+ } \
+ if (RB_LEFT(parent, field) == elm) { \
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ tmp = parent; \
+ parent = elm; \
+ elm = tmp; \
+ } \
+ RB_SET_BLACKRED(parent, gparent, field); \
+ RB_ROTATE_LEFT(head, gparent, tmp, field); \
+ } \
+ } \
+ RB_COLOR(head->rbh_root, field) = RB_BLACK; \
+} \
+ \
+void \
+name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \
+{ \
+ struct type *tmp; \
+ while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) && \
+ elm != RB_ROOT(head)) { \
+ if (RB_LEFT(parent, field) == elm) { \
+ tmp = RB_RIGHT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\
+ struct type *oleft; \
+ if ((oleft = RB_LEFT(tmp, field)))\
+ RB_COLOR(oleft, field) = RB_BLACK;\
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_RIGHT(head, tmp, oleft, field);\
+ tmp = RB_RIGHT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_RIGHT(tmp, field)) \
+ RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\
+ RB_ROTATE_LEFT(head, parent, tmp, field);\
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } else { \
+ tmp = RB_LEFT(parent, field); \
+ if (RB_COLOR(tmp, field) == RB_RED) { \
+ RB_SET_BLACKRED(tmp, parent, field); \
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ tmp = RB_LEFT(parent, field); \
+ } \
+ if ((RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\
+ (RB_RIGHT(tmp, field) == NULL || \
+ RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\
+ RB_COLOR(tmp, field) = RB_RED; \
+ elm = parent; \
+ parent = RB_PARENT(elm, field); \
+ } else { \
+ if (RB_LEFT(tmp, field) == NULL || \
+ RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\
+ struct type *oright; \
+ if ((oright = RB_RIGHT(tmp, field)))\
+ RB_COLOR(oright, field) = RB_BLACK;\
+ RB_COLOR(tmp, field) = RB_RED; \
+ RB_ROTATE_LEFT(head, tmp, oright, field);\
+ tmp = RB_LEFT(parent, field); \
+ } \
+ RB_COLOR(tmp, field) = RB_COLOR(parent, field);\
+ RB_COLOR(parent, field) = RB_BLACK; \
+ if (RB_LEFT(tmp, field)) \
+ RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\
+ RB_ROTATE_RIGHT(head, parent, tmp, field);\
+ elm = RB_ROOT(head); \
+ break; \
+ } \
+ } \
+ } \
+ if (elm) \
+ RB_COLOR(elm, field) = RB_BLACK; \
+} \
+ \
+struct type * \
+name##_RB_REMOVE(struct name *head, struct type *elm) \
+{ \
+ struct type *child, *parent, *old = elm; \
+ int color; \
+ if (RB_LEFT(elm, field) == NULL) \
+ child = RB_RIGHT(elm, field); \
+ else if (RB_RIGHT(elm, field) == NULL) \
+ child = RB_LEFT(elm, field); \
+ else { \
+ struct type *left; \
+ elm = RB_RIGHT(elm, field); \
+ while ((left = RB_LEFT(elm, field))) \
+ elm = left; \
+ child = RB_RIGHT(elm, field); \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+ if (RB_PARENT(elm, field) == old) \
+ parent = elm; \
+ (elm)->field = (old)->field; \
+ if (RB_PARENT(old, field)) { \
+ if (RB_LEFT(RB_PARENT(old, field), field) == old)\
+ RB_LEFT(RB_PARENT(old, field), field) = elm;\
+ else \
+ RB_RIGHT(RB_PARENT(old, field), field) = elm;\
+ RB_AUGMENT(RB_PARENT(old, field)); \
+ } else \
+ RB_ROOT(head) = elm; \
+ RB_PARENT(RB_LEFT(old, field), field) = elm; \
+ if (RB_RIGHT(old, field)) \
+ RB_PARENT(RB_RIGHT(old, field), field) = elm; \
+ if (parent) { \
+ left = parent; \
+ do { \
+ RB_AUGMENT(left); \
+ } while ((left = RB_PARENT(left, field))); \
+ } \
+ goto color; \
+ } \
+ parent = RB_PARENT(elm, field); \
+ color = RB_COLOR(elm, field); \
+ if (child) \
+ RB_PARENT(child, field) = parent; \
+ if (parent) { \
+ if (RB_LEFT(parent, field) == elm) \
+ RB_LEFT(parent, field) = child; \
+ else \
+ RB_RIGHT(parent, field) = child; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = child; \
+color: \
+ if (color == RB_BLACK) \
+ name##_RB_REMOVE_COLOR(head, parent, child); \
+ return (old); \
+} \
+ \
+/* Inserts a node into the RB tree */ \
+struct type * \
+name##_RB_INSERT(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp; \
+ struct type *parent = NULL; \
+ int comp = 0; \
+ tmp = RB_ROOT(head); \
+ while (tmp) { \
+ parent = tmp; \
+ comp = (cmp)(elm, parent); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ RB_SET(elm, parent, field); \
+ if (parent != NULL) { \
+ if (comp < 0) \
+ RB_LEFT(parent, field) = elm; \
+ else \
+ RB_RIGHT(parent, field) = elm; \
+ RB_AUGMENT(parent); \
+ } else \
+ RB_ROOT(head) = elm; \
+ name##_RB_INSERT_COLOR(head, elm); \
+ return (NULL); \
+} \
+ \
+/* Finds the node with the same key as elm */ \
+struct type * \
+name##_RB_FIND(struct name *head, struct type *elm) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ int comp; \
+ while (tmp) { \
+ comp = cmp(elm, tmp); \
+ if (comp < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else if (comp > 0) \
+ tmp = RB_RIGHT(tmp, field); \
+ else \
+ return (tmp); \
+ } \
+ return (NULL); \
+} \
+ \
+struct type * \
+name##_RB_NEXT(struct type *elm) \
+{ \
+ if (RB_RIGHT(elm, field)) { \
+ elm = RB_RIGHT(elm, field); \
+ while (RB_LEFT(elm, field)) \
+ elm = RB_LEFT(elm, field); \
+ } else { \
+ if (RB_PARENT(elm, field) && \
+ (elm == RB_LEFT(RB_PARENT(elm, field), field))) \
+ elm = RB_PARENT(elm, field); \
+ else { \
+ while (RB_PARENT(elm, field) && \
+ (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\
+ elm = RB_PARENT(elm, field); \
+ elm = RB_PARENT(elm, field); \
+ } \
+ } \
+ return (elm); \
+} \
+ \
+struct type * \
+name##_RB_MINMAX(struct name *head, int val) \
+{ \
+ struct type *tmp = RB_ROOT(head); \
+ struct type *parent = NULL; \
+ while (tmp) { \
+ parent = tmp; \
+ if (val < 0) \
+ tmp = RB_LEFT(tmp, field); \
+ else \
+ tmp = RB_RIGHT(tmp, field); \
+ } \
+ return (parent); \
+}
+
+#define RB_NEGINF -1
+#define RB_INF 1
+
+#define RB_INSERT(name, x, y) name##_RB_INSERT(x, y)
+#define RB_REMOVE(name, x, y) name##_RB_REMOVE(x, y)
+#define RB_FIND(name, x, y) name##_RB_FIND(x, y)
+#define RB_NEXT(name, x, y) name##_RB_NEXT(y)
+#define RB_MIN(name, x) name##_RB_MINMAX(x, RB_NEGINF)
+#define RB_MAX(name, x) name##_RB_MINMAX(x, RB_INF)
+
+#define RB_FOREACH(x, name, head) \
+ for ((x) = RB_MIN(name, head); \
+ (x) != NULL; \
+ (x) = name##_RB_NEXT(x))
+
+#endif /* _SYS_TREE_H_ */
diff --git a/ipc/chromium/src/third_party/libevent/android/event2/event-config.h b/ipc/chromium/src/third_party/libevent/android/event2/event-config.h
new file mode 100644
index 0000000000..3be94e0ef4
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/android/event2/event-config.h
@@ -0,0 +1,606 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if libevent should build without support for a debug mode */
+/* #undef EVENT__DISABLE_DEBUG_MODE */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define to 1 if you have the `accept4' function. */
+#if __ANDROID_API__ >= 21
+#define EVENT__HAVE_ACCEPT4 1
+#else
+/* #undef EVENT__HAVE_ACCEPT4 */
+#endif
+
+/* Define to 1 if you have the <afunix.h> header file. */
+/* #undef EVENT__HAVE_AFUNIX_H */
+
+/* Define to 1 if you have the `arc4random' function. */
+#define EVENT__HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+/* #undef EVENT__HAVE_ARC4RANDOM_ADDRANDOM */
+
+/* Define to 1 if you have the `arc4random_buf' function. */
+#define EVENT__HAVE_ARC4RANDOM_BUF 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define EVENT__HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
+ don't. */
+/* #undef EVENT__HAVE_DECL_CTL_KERN */
+
+/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
+ don't. */
+/* #undef EVENT__HAVE_DECL_KERN_ARND */
+
+/* Define if /dev/poll is available */
+/* #undef EVENT__HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+#define EVENT__HAVE_EPOLL 1
+
+/* Define to 1 if you have the `epoll_create1' function. */
+/* #undef EVENT__HAVE_EPOLL_CREATE1 */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+#define EVENT__HAVE_EPOLL_CTL 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define EVENT__HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the `eventfd' function. */
+#define EVENT__HAVE_EVENTFD 1
+
+/* Define if your system supports event ports */
+/* #undef EVENT__HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+#define EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if the system has the type `fd_mask'. */
+/* #undef EVENT__HAVE_FD_MASK */
+
+/* Do we have getaddrinfo()? */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define EVENT__HAVE_GETEUID 1
+
+/* Define this if you have any gethostbyname_r() */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
+
+/* Define this if gethostbyname_r takes 3 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if gethostbyname_r takes 5 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if gethostbyname_r takes 6 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
+
+/* Define to 1 if you have the `getifaddrs' function. */
+/* #undef EVENT__HAVE_GETIFADDRS */
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getrandom' function. */
+/* #undef EVENT__HAVE_GETRANDOM */
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+/* #undef EVENT__HAVE_IFADDRS_H */
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#define EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#define EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+/* #undef EVENT__HAVE_ISSETUGID */
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef EVENT__HAVE_KQUEUE */
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+/* #undef EVENT__HAVE_LIBWS2_32 */
+
+/* Define if the system has zlib */
+#define EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+/* #undef EVENT__HAVE_MACH_ABSOLUTE_TIME */
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_H */
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_TIME_H */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+#define EVENT__HAVE_NETINET_IN6_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define if the system has openssl */
+/* #undef EVENT__HAVE_OPENSSL */
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+/* #undef EVENT__HAVE_OPENSSL_SSL_H */
+
+/* Define to 1 if you have the `pipe' function. */
+#define EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#define EVENT__HAVE_PIPE2 1
+
+/* Define to 1 if you have the `poll' function. */
+#define EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef EVENT__HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef EVENT__HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+#define EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#define EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#define EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `setenv' function. */
+#define EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#define EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+/* #undef EVENT__HAVE_SIGNAL */
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef EVENT__HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+#define EVENT__HAVE_STRLCPY 1
+
+/* Define to 1 if you have the `strsep' function. */
+#define EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+
+/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+
+/* Define to 1 if the system has the type `struct linger'. */
+#define EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if you have the `sysctl' function. */
+/* #undef EVENT__HAVE_SYSCTL */
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+#define EVENT__HAVE_SYS_EPOLL_H 1
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+#define EVENT__HAVE_SYS_EVENTFD_H 1
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#define EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+/* #undef EVENT__HAVE_SYS_RANDOM_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#define EVENT__HAVE_SYS_SENDFILE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+/* #undef EVENT__HAVE_SYS_SYSCTL_H */
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_TIMERFD_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#define EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define to 1 if you have the `timerfd_create' function. */
+#define EVENT__HAVE_TIMERFD_CREATE 1
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#define EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `usleep' function. */
+#define EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+/* #undef EVENT__HAVE_WORKING_KQUEUE */
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define EVENT__HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+/* #undef EVENT__HAVE__GMTIME64 */
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+/* #undef EVENT__HAVE__GMTIME64_S */
+
+/* Define to 1 if compiler have __FUNCTION__ */
+#define EVENT__HAVE___FUNCTION__ 1
+
+/* Define to 1 if compiler have __func__ */
+#define EVENT__HAVE___func__ 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define EVENT__LT_OBJDIR ".libs/"
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME "libevent"
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING "libevent 2.1.12-stable"
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME "libevent"
+
+/* Define to the home page for this package. */
+#define EVENT__PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION "2.1.12-stable"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* ------------------------------------------------------------------------ */
+/* MOZILLA NOTE: the following constants are hand-modified to be suitable */
+/* for both 32-bit and 64-bit platforms. See README.mozilla for details. */
+/* ------------------------------------------------------------------------ */
+
+/* The size of `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_LONG 8
+#else
+#define EVENT__SIZEOF_LONG 4
+#endif
+
+/* The size of `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_OFF_T 8
+#else
+#define EVENT__SIZEOF_OFF_T 4
+#endif
+
+/* The size of `pthread_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_PTHREAD_T 8
+#else
+#define EVENT__SIZEOF_PTHREAD_T 4
+#endif
+
+/* The size of `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_SIZE_T 8
+#else
+#define EVENT__SIZEOF_SIZE_T 4
+#endif
+
+/* The size of `time_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_TIME_T 8
+#else
+#define EVENT__SIZEOF_TIME_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_VOID_P 8
+#else
+#define EVENT__SIZEOF_VOID_P 4
+#endif
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Enable large inode numbers on Mac OS X 10.5. */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+/* #undef __func__ */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to unsigned int if you dont have it */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef ssize_t */
+
+#endif /* event2/event-config.h */
diff --git a/ipc/chromium/src/third_party/libevent/arc4random.c b/ipc/chromium/src/third_party/libevent/arc4random.c
new file mode 100644
index 0000000000..8729f6b92f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/arc4random.c
@@ -0,0 +1,546 @@
+/* Portable arc4random.c based on arc4random.c from OpenBSD.
+ * Portable version by Chris Davis, adapted for Libevent by Nick Mathewson
+ * Copyright (c) 2010 Chris Davis, Niels Provos, and Nick Mathewson
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Note that in Libevent, this file isn't compiled directly. Instead,
+ * it's included from evutil_rand.c
+ */
+
+/*
+ * Copyright (c) 1996, David Mazieres <dm@uun.org>
+ * Copyright (c) 2008, Damien Miller <djm@openbsd.org>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+/*
+ * Arc4 random number generator for OpenBSD.
+ *
+ * This code is derived from section 17.1 of Applied Cryptography,
+ * second edition, which describes a stream cipher allegedly
+ * compatible with RSA Labs "RC4" cipher (the actual description of
+ * which is a trade secret). The same algorithm is used as a stream
+ * cipher called "arcfour" in Tatu Ylonen's ssh package.
+ *
+ * Here the stream cipher has been modified always to include the time
+ * when initializing the state. That makes it impossible to
+ * regenerate the same random sequence twice, so this can't be used
+ * for encryption, but will generate good random numbers.
+ *
+ * RC4 is a registered trademark of RSA Laboratories.
+ */
+
+#ifndef ARC4RANDOM_EXPORT
+#define ARC4RANDOM_EXPORT
+#endif
+
+#ifndef ARC4RANDOM_UINT32
+#define ARC4RANDOM_UINT32 uint32_t
+#endif
+
+#ifndef ARC4RANDOM_NO_INCLUDES
+#include "evconfig-private.h"
+#ifdef _WIN32
+#include <wincrypt.h>
+#include <process.h>
+#include <winerror.h>
+#else
+#include <fcntl.h>
+#include <unistd.h>
+#include <sys/param.h>
+#include <sys/time.h>
+#ifdef EVENT__HAVE_SYS_SYSCTL_H
+#include <sys/sysctl.h>
+#endif
+#ifdef EVENT__HAVE_SYS_RANDOM_H
+#include <sys/random.h>
+#endif
+#endif
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+#endif
+
+/* Add platform entropy 32 bytes (256 bits) at a time. */
+#define ADD_ENTROPY 32
+
+/* Re-seed from the platform RNG after generating this many bytes. */
+#define BYTES_BEFORE_RESEED 1600000
+
+struct arc4_stream {
+ unsigned char i;
+ unsigned char j;
+ unsigned char s[256];
+};
+
+#ifdef _WIN32
+#define getpid _getpid
+#define pid_t int
+#endif
+
+static int rs_initialized;
+static struct arc4_stream rs;
+static pid_t arc4_stir_pid;
+static int arc4_count;
+
+static inline unsigned char arc4_getbyte(void);
+
+static inline void
+arc4_init(void)
+{
+ int n;
+
+ for (n = 0; n < 256; n++)
+ rs.s[n] = n;
+ rs.i = 0;
+ rs.j = 0;
+}
+
+static inline void
+arc4_addrandom(const unsigned char *dat, int datlen)
+{
+ int n;
+ unsigned char si;
+
+ rs.i--;
+ for (n = 0; n < 256; n++) {
+ rs.i = (rs.i + 1);
+ si = rs.s[rs.i];
+ rs.j = (rs.j + si + dat[n % datlen]);
+ rs.s[rs.i] = rs.s[rs.j];
+ rs.s[rs.j] = si;
+ }
+ rs.j = rs.i;
+}
+
+#ifndef _WIN32
+static ssize_t
+read_all(int fd, unsigned char *buf, size_t count)
+{
+ size_t numread = 0;
+ ssize_t result;
+
+ while (numread < count) {
+ result = read(fd, buf+numread, count-numread);
+ if (result<0)
+ return -1;
+ else if (result == 0)
+ break;
+ numread += result;
+ }
+
+ return (ssize_t)numread;
+}
+#endif
+
+#ifdef _WIN32
+#define TRY_SEED_WIN32
+static int
+arc4_seed_win32(void)
+{
+ /* This is adapted from Tor's crypto_seed_rng() */
+ static int provider_set = 0;
+ static HCRYPTPROV provider;
+ unsigned char buf[ADD_ENTROPY];
+
+ if (!provider_set) {
+ if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT)) {
+ if (GetLastError() != (DWORD)NTE_BAD_KEYSET)
+ return -1;
+ }
+ provider_set = 1;
+ }
+ if (!CryptGenRandom(provider, sizeof(buf), buf))
+ return -1;
+ arc4_addrandom(buf, sizeof(buf));
+ evutil_memclear_(buf, sizeof(buf));
+ return 0;
+}
+#endif
+
+#if defined(EVENT__HAVE_GETRANDOM)
+#define TRY_SEED_GETRANDOM
+static int
+arc4_seed_getrandom(void)
+{
+ unsigned char buf[ADD_ENTROPY];
+ size_t len, n;
+ unsigned i;
+ int any_set;
+
+ memset(buf, 0, sizeof(buf));
+
+ for (len = 0; len < sizeof(buf); len += n) {
+ n = sizeof(buf) - len;
+
+ if (0 == getrandom(&buf[len], n, 0))
+ return -1;
+ }
+ /* make sure that the buffer actually got set. */
+ for (i=0,any_set=0; i<sizeof(buf); ++i) {
+ any_set |= buf[i];
+ }
+ if (!any_set)
+ return -1;
+
+ arc4_addrandom(buf, sizeof(buf));
+ evutil_memclear_(buf, sizeof(buf));
+ return 0;
+}
+#endif /* EVENT__HAVE_GETRANDOM */
+
+#if defined(EVENT__HAVE_SYS_SYSCTL_H) && defined(EVENT__HAVE_SYSCTL)
+#if EVENT__HAVE_DECL_CTL_KERN && EVENT__HAVE_DECL_KERN_ARND
+#define TRY_SEED_SYSCTL_BSD
+static int
+arc4_seed_sysctl_bsd(void)
+{
+ /* Based on code from William Ahern and from OpenBSD, this function
+ * tries to use the KERN_ARND syscall to get entropy from the kernel.
+ * This can work even if /dev/urandom is inaccessible for some reason
+ * (e.g., we're running in a chroot). */
+ int mib[] = { CTL_KERN, KERN_ARND };
+ unsigned char buf[ADD_ENTROPY];
+ size_t len, n;
+ int i, any_set;
+
+ memset(buf, 0, sizeof(buf));
+
+ len = sizeof(buf);
+ if (sysctl(mib, 2, buf, &len, NULL, 0) == -1) {
+ for (len = 0; len < sizeof(buf); len += sizeof(unsigned)) {
+ n = sizeof(unsigned);
+ if (n + len > sizeof(buf))
+ n = len - sizeof(buf);
+ if (sysctl(mib, 2, &buf[len], &n, NULL, 0) == -1)
+ return -1;
+ }
+ }
+ /* make sure that the buffer actually got set. */
+ for (i=any_set=0; i<sizeof(buf); ++i) {
+ any_set |= buf[i];
+ }
+ if (!any_set)
+ return -1;
+
+ arc4_addrandom(buf, sizeof(buf));
+ evutil_memclear_(buf, sizeof(buf));
+ return 0;
+}
+#endif
+#endif /* defined(EVENT__HAVE_SYS_SYSCTL_H) */
+
+#ifdef __linux__
+#define TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
+static int
+arc4_seed_proc_sys_kernel_random_uuid(void)
+{
+ /* Occasionally, somebody will make /proc/sys accessible in a chroot,
+ * but not /dev/urandom. Let's try /proc/sys/kernel/random/uuid.
+ * Its format is stupid, so we need to decode it from hex.
+ */
+ int fd;
+ char buf[128];
+ unsigned char entropy[64];
+ int bytes, n, i, nybbles;
+ for (bytes = 0; bytes<ADD_ENTROPY; ) {
+ fd = evutil_open_closeonexec_("/proc/sys/kernel/random/uuid", O_RDONLY, 0);
+ if (fd < 0)
+ return -1;
+ n = read(fd, buf, sizeof(buf));
+ close(fd);
+ if (n<=0)
+ return -1;
+ memset(entropy, 0, sizeof(entropy));
+ for (i=nybbles=0; i<n; ++i) {
+ if (EVUTIL_ISXDIGIT_(buf[i])) {
+ int nyb = evutil_hex_char_to_int_(buf[i]);
+ if (nybbles & 1) {
+ entropy[nybbles/2] |= nyb;
+ } else {
+ entropy[nybbles/2] |= nyb<<4;
+ }
+ ++nybbles;
+ }
+ }
+ if (nybbles < 2)
+ return -1;
+ arc4_addrandom(entropy, nybbles/2);
+ bytes += nybbles/2;
+ }
+ evutil_memclear_(entropy, sizeof(entropy));
+ evutil_memclear_(buf, sizeof(buf));
+ return 0;
+}
+#endif
+
+#ifndef _WIN32
+#define TRY_SEED_URANDOM
+static char *arc4random_urandom_filename = NULL;
+
+static int arc4_seed_urandom_helper_(const char *fname)
+{
+ unsigned char buf[ADD_ENTROPY];
+ int fd;
+ size_t n;
+
+ fd = evutil_open_closeonexec_(fname, O_RDONLY, 0);
+ if (fd<0)
+ return -1;
+ n = read_all(fd, buf, sizeof(buf));
+ close(fd);
+ if (n != sizeof(buf))
+ return -1;
+ arc4_addrandom(buf, sizeof(buf));
+ evutil_memclear_(buf, sizeof(buf));
+ return 0;
+}
+
+static int
+arc4_seed_urandom(void)
+{
+ /* This is adapted from Tor's crypto_seed_rng() */
+ static const char *filenames[] = {
+ "/dev/srandom", "/dev/urandom", "/dev/random", NULL
+ };
+ int i;
+ if (arc4random_urandom_filename)
+ return arc4_seed_urandom_helper_(arc4random_urandom_filename);
+
+ for (i = 0; filenames[i]; ++i) {
+ if (arc4_seed_urandom_helper_(filenames[i]) == 0) {
+ return 0;
+ }
+ }
+
+ return -1;
+}
+#endif
+
+static int
+arc4_seed(void)
+{
+ int ok = 0;
+ /* We try every method that might work, and don't give up even if one
+ * does seem to work. There's no real harm in over-seeding, and if
+ * one of these sources turns out to be broken, that would be bad. */
+#ifdef TRY_SEED_WIN32
+ if (0 == arc4_seed_win32())
+ ok = 1;
+#endif
+#ifdef TRY_SEED_GETRANDOM
+ if (0 == arc4_seed_getrandom())
+ ok = 1;
+#endif
+#ifdef TRY_SEED_URANDOM
+ if (0 == arc4_seed_urandom())
+ ok = 1;
+#endif
+#ifdef TRY_SEED_PROC_SYS_KERNEL_RANDOM_UUID
+ if (arc4random_urandom_filename == NULL &&
+ 0 == arc4_seed_proc_sys_kernel_random_uuid())
+ ok = 1;
+#endif
+#ifdef TRY_SEED_SYSCTL_BSD
+ if (0 == arc4_seed_sysctl_bsd())
+ ok = 1;
+#endif
+ return ok ? 0 : -1;
+}
+
+static int
+arc4_stir(void)
+{
+ int i;
+
+ if (!rs_initialized) {
+ arc4_init();
+ rs_initialized = 1;
+ }
+
+ if (0 != arc4_seed())
+ return -1;
+
+ /*
+ * Discard early keystream, as per recommendations in
+ * "Weaknesses in the Key Scheduling Algorithm of RC4" by
+ * Scott Fluhrer, Itsik Mantin, and Adi Shamir.
+ * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
+ *
+ * Ilya Mironov's "(Not So) Random Shuffles of RC4" suggests that
+ * we drop at least 2*256 bytes, with 12*256 as a conservative
+ * value.
+ *
+ * RFC4345 says to drop 6*256.
+ *
+ * At least some versions of this code drop 4*256, in a mistaken
+ * belief that "words" in the Fluhrer/Mantin/Shamir paper refers
+ * to processor words.
+ *
+ * We add another sect to the cargo cult, and choose 12*256.
+ */
+ for (i = 0; i < 12*256; i++)
+ (void)arc4_getbyte();
+
+ arc4_count = BYTES_BEFORE_RESEED;
+
+ return 0;
+}
+
+
+static void
+arc4_stir_if_needed(void)
+{
+ pid_t pid = getpid();
+
+ if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
+ {
+ arc4_stir_pid = pid;
+ arc4_stir();
+ }
+}
+
+static inline unsigned char
+arc4_getbyte(void)
+{
+ unsigned char si, sj;
+
+ rs.i = (rs.i + 1);
+ si = rs.s[rs.i];
+ rs.j = (rs.j + si);
+ sj = rs.s[rs.j];
+ rs.s[rs.i] = sj;
+ rs.s[rs.j] = si;
+ return (rs.s[(si + sj) & 0xff]);
+}
+
+static inline unsigned int
+arc4_getword(void)
+{
+ unsigned int val;
+
+ val = arc4_getbyte() << 24;
+ val |= arc4_getbyte() << 16;
+ val |= arc4_getbyte() << 8;
+ val |= arc4_getbyte();
+
+ return val;
+}
+
+#ifndef ARC4RANDOM_NOSTIR
+ARC4RANDOM_EXPORT int
+arc4random_stir(void)
+{
+ int val;
+ ARC4_LOCK_();
+ val = arc4_stir();
+ ARC4_UNLOCK_();
+ return val;
+}
+#endif
+
+#ifndef ARC4RANDOM_NOADDRANDOM
+ARC4RANDOM_EXPORT void
+arc4random_addrandom(const unsigned char *dat, int datlen)
+{
+ int j;
+ ARC4_LOCK_();
+ if (!rs_initialized)
+ arc4_stir();
+ for (j = 0; j < datlen; j += 256) {
+ /* arc4_addrandom() ignores all but the first 256 bytes of
+ * its input. We want to make sure to look at ALL the
+ * data in 'dat', just in case the user is doing something
+ * crazy like passing us all the files in /var/log. */
+ arc4_addrandom(dat + j, datlen - j);
+ }
+ ARC4_UNLOCK_();
+}
+#endif
+
+#ifndef ARC4RANDOM_NORANDOM
+ARC4RANDOM_EXPORT ARC4RANDOM_UINT32
+arc4random(void)
+{
+ ARC4RANDOM_UINT32 val;
+ ARC4_LOCK_();
+ arc4_count -= 4;
+ arc4_stir_if_needed();
+ val = arc4_getword();
+ ARC4_UNLOCK_();
+ return val;
+}
+#endif
+
+ARC4RANDOM_EXPORT void
+arc4random_buf(void *buf_, size_t n)
+{
+ unsigned char *buf = buf_;
+ ARC4_LOCK_();
+ arc4_stir_if_needed();
+ while (n--) {
+ if (--arc4_count <= 0)
+ arc4_stir();
+ buf[n] = arc4_getbyte();
+ }
+ ARC4_UNLOCK_();
+}
+
+#ifndef ARC4RANDOM_NOUNIFORM
+/*
+ * Calculate a uniformly distributed random number less than upper_bound
+ * avoiding "modulo bias".
+ *
+ * Uniformity is achieved by generating new random numbers until the one
+ * returned is outside the range [0, 2**32 % upper_bound). This
+ * guarantees the selected random number will be inside
+ * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
+ * after reduction modulo upper_bound.
+ */
+ARC4RANDOM_EXPORT unsigned int
+arc4random_uniform(unsigned int upper_bound)
+{
+ ARC4RANDOM_UINT32 r, min;
+
+ if (upper_bound < 2)
+ return 0;
+
+#if (UINT_MAX > 0xffffffffUL)
+ min = 0x100000000UL % upper_bound;
+#else
+ /* Calculate (2**32 % upper_bound) avoiding 64-bit math */
+ if (upper_bound > 0x80000000)
+ min = 1 + ~upper_bound; /* 2**32 - upper_bound */
+ else {
+ /* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
+ min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
+ }
+#endif
+
+ /*
+ * This could theoretically loop forever but each retry has
+ * p > 0.5 (worst case, usually far better) of selecting a
+ * number inside the range we need, so it should rarely need
+ * to re-roll.
+ */
+ for (;;) {
+ r = arc4random();
+ if (r >= min)
+ break;
+ }
+
+ return r % upper_bound;
+}
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/autogen.sh b/ipc/chromium/src/third_party/libevent/autogen.sh
new file mode 100755
index 0000000000..bcfe937a60
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/autogen.sh
@@ -0,0 +1,22 @@
+#!/bin/sh
+
+MAKE=make
+if command -v gmake >/dev/null 2>/dev/null; then
+ MAKE=gmake
+fi
+$MAKE maintainer-clean >/dev/null 2>/dev/null
+
+if [ -x "`which autoreconf 2>/dev/null`" ] ; then
+ exec autoreconf -ivf
+fi
+
+LIBTOOLIZE=libtoolize
+SYSNAME=`uname`
+if [ "x$SYSNAME" = "xDarwin" ] ; then
+ LIBTOOLIZE=glibtoolize
+fi
+aclocal -I m4 && \
+ autoheader && \
+ $LIBTOOLIZE && \
+ autoconf && \
+ automake --add-missing --force-missing --copy
diff --git a/ipc/chromium/src/third_party/libevent/bsd/event2/event-config.h b/ipc/chromium/src/third_party/libevent/bsd/event2/event-config.h
new file mode 100644
index 0000000000..5f5836a818
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bsd/event2/event-config.h
@@ -0,0 +1,614 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if libevent should build without support for a debug mode */
+/* #undef EVENT__DISABLE_DEBUG_MODE */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define to 1 if you have the `accept4' function. */
+#define EVENT__HAVE_ACCEPT4 1
+
+/* Define to 1 if you have the <afunix.h> header file. */
+/* #undef EVENT__HAVE_AFUNIX_H */
+
+/* Define to 1 if you have the `arc4random' function. */
+#define EVENT__HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+#if defined(__DragonFly__) || defined(__NetBSD__)
+#define EVENT__HAVE_ARC4RANDOM_ADDRANDOM 1
+#endif
+
+/* Define to 1 if you have the `arc4random_buf' function. */
+#define EVENT__HAVE_ARC4RANDOM_BUF 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define EVENT__HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_CTL_KERN 1
+
+/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_KERN_ARND 1
+
+/* Define if /dev/poll is available */
+/* #undef EVENT__HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+/* #undef EVENT__HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_create1' function. */
+/* #undef EVENT__HAVE_EPOLL_CREATE1 */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef EVENT__HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define EVENT__HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the `eventfd' function. */
+/* #undef EVENT__HAVE_EVENTFD */
+
+/* Define if your system supports event ports */
+/* #undef EVENT__HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+#define EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if the system has the type `fd_mask'. */
+#define EVENT__HAVE_FD_MASK 1
+
+/* Do we have getaddrinfo()? */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define EVENT__HAVE_GETEUID 1
+
+/* Define this if you have any gethostbyname_r() */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
+
+/* Define this if gethostbyname_r takes 3 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if gethostbyname_r takes 5 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if gethostbyname_r takes 6 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#define EVENT__HAVE_GETIFADDRS 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getrandom' function. */
+#if !defined(__OpenBSD__)
+#define EVENT__HAVE_GETRANDOM 1
+#endif
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define EVENT__HAVE_IFADDRS_H 1
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#define EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#define EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+#define EVENT__HAVE_ISSETUGID 1
+
+/* Define to 1 if you have the `kqueue' function. */
+#define EVENT__HAVE_KQUEUE 1
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+/* #undef EVENT__HAVE_LIBWS2_32 */
+
+/* Define if the system has zlib */
+#define EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+/* #undef EVENT__HAVE_MACH_ABSOLUTE_TIME */
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_H */
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_TIME_H */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define if the system has openssl */
+/* #undef EVENT__HAVE_OPENSSL */
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+/* #undef EVENT__HAVE_OPENSSL_SSL_H */
+
+/* Define to 1 if you have the `pipe' function. */
+#define EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#define EVENT__HAVE_PIPE2 1
+
+/* Define to 1 if you have the `poll' function. */
+#define EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef EVENT__HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef EVENT__HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+#define EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#define EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#define EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `setenv' function. */
+#define EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#define EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+#define EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef EVENT__HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+#define EVENT__HAVE_STRLCPY 1
+
+/* Define to 1 if you have the `strsep' function. */
+#define EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 */
+
+/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 */
+
+/* Define to 1 if the system has the type `struct linger'. */
+#define EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if you have the `sysctl' function. */
+#define EVENT__HAVE_SYSCTL 1
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENTFD_H */
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+#define EVENT__HAVE_SYS_EVENT_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#define EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+#if !defined(__OpenBSD__)
+#define EVENT__HAVE_SYS_RANDOM_H 1
+#endif
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+/* #undef EVENT__HAVE_SYS_SENDFILE_H */
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+#define EVENT__HAVE_SYS_SYSCTL_H 1
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_TIMERFD_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#define EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define to 1 if you have the `timerfd_create' function. */
+/* #undef EVENT__HAVE_TIMERFD_CREATE */
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#define EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `usleep' function. */
+#define EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+#define EVENT__HAVE_WORKING_KQUEUE 1
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define EVENT__HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+/* #undef EVENT__HAVE__GMTIME64 */
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+/* #undef EVENT__HAVE__GMTIME64_S */
+
+/* Define to 1 if compiler have __FUNCTION__ */
+#define EVENT__HAVE___FUNCTION__ 1
+
+/* Define to 1 if compiler have __func__ */
+#define EVENT__HAVE___func__ 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define EVENT__LT_OBJDIR ".libs/"
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME "libevent"
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING "libevent 2.1.12-stable"
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME "libevent"
+
+/* Define to the home page for this package. */
+#define EVENT__PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION "2.1.12-stable"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* ------------------------------------------------------------------------ */
+/* MOZILLA NOTE: the following constants are hand-modified to be suitable */
+/* for both 32-bit and 64-bit platforms. See README.mozilla for details. */
+/* ------------------------------------------------------------------------ */
+
+/* The size of `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_LONG 8
+#else
+#define EVENT__SIZEOF_LONG 4
+#endif
+
+/* The size of `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#define EVENT__SIZEOF_OFF_T 8
+
+/* The size of `pthread_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_PTHREAD_T 8
+#else
+#define EVENT__SIZEOF_PTHREAD_T 4
+#endif
+
+/* The size of `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_SIZE_T 8
+#else
+#define EVENT__SIZEOF_SIZE_T 4
+#endif
+
+/* ------------------------------------------------------------------------------------- */
+/* MOZILLA NOTE: some BSD system increased time_t size from 32-bit to 64-bit */
+/* OpenBSD https://www.openbsd.org/55.html */
+/* NetBSD https://man.netbsd.org/NetBSD-9.1/time.3 */
+/* FreeBSD/powerpc https://lists.freebsd.org/pipermail/freebsd-ppc/2017-June/008907.html */
+/* ------------------------------------------------------------------------------------- */
+/* The size of `time_t', as computed by sizeof. */
+#if defined(__LP64__) || defined(__OpenBSD__) || defined(__NetBSD__) || (defined(__FreeBSD__) && !defined(__i386__))
+#define EVENT__SIZEOF_TIME_T 8
+#else
+#define EVENT__SIZEOF_TIME_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_VOID_P 8
+#else
+#define EVENT__SIZEOF_VOID_P 4
+#endif
+
+/* ------------------------------------------------------------------------ */
+/* END MOZILLA NOTE */
+/* ------------------------------------------------------------------------ */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Enable large inode numbers on Mac OS X 10.5. */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+/* #undef __func__ */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to unsigned int if you dont have it */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef ssize_t */
+
+#endif /* event2/event-config.h */
diff --git a/ipc/chromium/src/third_party/libevent/buffer.c b/ipc/chromium/src/third_party/libevent/buffer.c
new file mode 100644
index 0000000000..3524b3504d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/buffer.c
@@ -0,0 +1,3467 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <io.h>
+#endif
+
+#ifdef EVENT__HAVE_VASPRINTF
+/* If we have vasprintf, we need to define _GNU_SOURCE before we include
+ * stdio.h. This comes from evconfig-private.h.
+ */
+#endif
+
+#include <sys/types.h>
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_MMAN_H
+#include <sys/mman.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_SENDFILE_H
+#include <sys/sendfile.h>
+#endif
+#ifdef EVENT__HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/thread.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#include "evbuffer-internal.h"
+#include "bufferevent-internal.h"
+#include "event-internal.h"
+
+/* some systems do not have MAP_FAILED */
+#ifndef MAP_FAILED
+#define MAP_FAILED ((void *)-1)
+#endif
+
+/* send file support */
+#if defined(EVENT__HAVE_SYS_SENDFILE_H) && defined(EVENT__HAVE_SENDFILE) && defined(__linux__)
+#define USE_SENDFILE 1
+#define SENDFILE_IS_LINUX 1
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__FreeBSD__)
+#define USE_SENDFILE 1
+#define SENDFILE_IS_FREEBSD 1
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__APPLE__)
+#define USE_SENDFILE 1
+#define SENDFILE_IS_MACOSX 1
+#elif defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+#define USE_SENDFILE 1
+#define SENDFILE_IS_SOLARIS 1
+#endif
+
+/* Mask of user-selectable callback flags. */
+#define EVBUFFER_CB_USER_FLAGS 0xffff
+/* Mask of all internal-use-only flags. */
+#define EVBUFFER_CB_INTERNAL_FLAGS 0xffff0000
+
+/* Flag set if the callback is using the cb_obsolete function pointer */
+#define EVBUFFER_CB_OBSOLETE 0x00040000
+
+/* evbuffer_chain support */
+#define CHAIN_SPACE_PTR(ch) ((ch)->buffer + (ch)->misalign + (ch)->off)
+#define CHAIN_SPACE_LEN(ch) ((ch)->flags & EVBUFFER_IMMUTABLE ? \
+ 0 : (ch)->buffer_len - ((ch)->misalign + (ch)->off))
+
+#define CHAIN_PINNED(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_ANY) != 0)
+#define CHAIN_PINNED_R(ch) (((ch)->flags & EVBUFFER_MEM_PINNED_R) != 0)
+
+/* evbuffer_ptr support */
+#define PTR_NOT_FOUND(ptr) do { \
+ (ptr)->pos = -1; \
+ (ptr)->internal_.chain = NULL; \
+ (ptr)->internal_.pos_in_chain = 0; \
+} while (0)
+
+static void evbuffer_chain_align(struct evbuffer_chain *chain);
+static int evbuffer_chain_should_realign(struct evbuffer_chain *chain,
+ size_t datalen);
+static void evbuffer_deferred_callback(struct event_callback *cb, void *arg);
+static int evbuffer_ptr_memcmp(const struct evbuffer *buf,
+ const struct evbuffer_ptr *pos, const char *mem, size_t len);
+static struct evbuffer_chain *evbuffer_expand_singlechain(struct evbuffer *buf,
+ size_t datlen);
+static int evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
+ size_t howfar);
+static int evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg);
+static inline void evbuffer_chain_incref(struct evbuffer_chain *chain);
+
+static struct evbuffer_chain *
+evbuffer_chain_new(size_t size)
+{
+ struct evbuffer_chain *chain;
+ size_t to_alloc;
+
+ if (size > EVBUFFER_CHAIN_MAX - EVBUFFER_CHAIN_SIZE)
+ return (NULL);
+
+ size += EVBUFFER_CHAIN_SIZE;
+
+ /* get the next largest memory that can hold the buffer */
+ if (size < EVBUFFER_CHAIN_MAX / 2) {
+ to_alloc = MIN_BUFFER_SIZE;
+ while (to_alloc < size) {
+ to_alloc <<= 1;
+ }
+ } else {
+ to_alloc = size;
+ }
+
+ /* we get everything in one chunk */
+ if ((chain = mm_malloc(to_alloc)) == NULL)
+ return (NULL);
+
+ memset(chain, 0, EVBUFFER_CHAIN_SIZE);
+
+ chain->buffer_len = to_alloc - EVBUFFER_CHAIN_SIZE;
+
+ /* this way we can manipulate the buffer to different addresses,
+ * which is required for mmap for example.
+ */
+ chain->buffer = EVBUFFER_CHAIN_EXTRA(unsigned char, chain);
+
+ chain->refcnt = 1;
+
+ return (chain);
+}
+
+static inline void
+evbuffer_chain_free(struct evbuffer_chain *chain)
+{
+ EVUTIL_ASSERT(chain->refcnt > 0);
+ if (--chain->refcnt > 0) {
+ /* chain is still referenced by other chains */
+ return;
+ }
+
+ if (CHAIN_PINNED(chain)) {
+ /* will get freed once no longer dangling */
+ chain->refcnt++;
+ chain->flags |= EVBUFFER_DANGLING;
+ return;
+ }
+
+ /* safe to release chain, it's either a referencing
+ * chain or all references to it have been freed */
+ if (chain->flags & EVBUFFER_REFERENCE) {
+ struct evbuffer_chain_reference *info =
+ EVBUFFER_CHAIN_EXTRA(
+ struct evbuffer_chain_reference,
+ chain);
+ if (info->cleanupfn)
+ (*info->cleanupfn)(chain->buffer,
+ chain->buffer_len,
+ info->extra);
+ }
+ if (chain->flags & EVBUFFER_FILESEGMENT) {
+ struct evbuffer_chain_file_segment *info =
+ EVBUFFER_CHAIN_EXTRA(
+ struct evbuffer_chain_file_segment,
+ chain);
+ if (info->segment) {
+#ifdef _WIN32
+ if (info->segment->is_mapping)
+ UnmapViewOfFile(chain->buffer);
+#endif
+ evbuffer_file_segment_free(info->segment);
+ }
+ }
+ if (chain->flags & EVBUFFER_MULTICAST) {
+ struct evbuffer_multicast_parent *info =
+ EVBUFFER_CHAIN_EXTRA(
+ struct evbuffer_multicast_parent,
+ chain);
+ /* referencing chain is being freed, decrease
+ * refcounts of source chain and associated
+ * evbuffer (which get freed once both reach
+ * zero) */
+ EVUTIL_ASSERT(info->source != NULL);
+ EVUTIL_ASSERT(info->parent != NULL);
+ EVBUFFER_LOCK(info->source);
+ evbuffer_chain_free(info->parent);
+ evbuffer_decref_and_unlock_(info->source);
+ }
+
+ mm_free(chain);
+}
+
+static void
+evbuffer_free_all_chains(struct evbuffer_chain *chain)
+{
+ struct evbuffer_chain *next;
+ for (; chain; chain = next) {
+ next = chain->next;
+ evbuffer_chain_free(chain);
+ }
+}
+
+#ifndef NDEBUG
+static int
+evbuffer_chains_all_empty(struct evbuffer_chain *chain)
+{
+ for (; chain; chain = chain->next) {
+ if (chain->off)
+ return 0;
+ }
+ return 1;
+}
+#else
+/* The definition is needed for EVUTIL_ASSERT, which uses sizeof to avoid
+"unused variable" warnings. */
+static inline int evbuffer_chains_all_empty(struct evbuffer_chain *chain) {
+ return 1;
+}
+#endif
+
+/* Free all trailing chains in 'buf' that are neither pinned nor empty, prior
+ * to replacing them all with a new chain. Return a pointer to the place
+ * where the new chain will go.
+ *
+ * Internal; requires lock. The caller must fix up buf->last and buf->first
+ * as needed; they might have been freed.
+ */
+static struct evbuffer_chain **
+evbuffer_free_trailing_empty_chains(struct evbuffer *buf)
+{
+ struct evbuffer_chain **ch = buf->last_with_datap;
+ /* Find the first victim chain. It might be *last_with_datap */
+ while ((*ch) && ((*ch)->off != 0 || CHAIN_PINNED(*ch)))
+ ch = &(*ch)->next;
+ if (*ch) {
+ EVUTIL_ASSERT(evbuffer_chains_all_empty(*ch));
+ evbuffer_free_all_chains(*ch);
+ *ch = NULL;
+ }
+ return ch;
+}
+
+/* Add a single chain 'chain' to the end of 'buf', freeing trailing empty
+ * chains as necessary. Requires lock. Does not schedule callbacks.
+ */
+static void
+evbuffer_chain_insert(struct evbuffer *buf,
+ struct evbuffer_chain *chain)
+{
+ ASSERT_EVBUFFER_LOCKED(buf);
+ if (*buf->last_with_datap == NULL) {
+ /* There are no chains data on the buffer at all. */
+ EVUTIL_ASSERT(buf->last_with_datap == &buf->first);
+ EVUTIL_ASSERT(buf->first == NULL);
+ buf->first = buf->last = chain;
+ } else {
+ struct evbuffer_chain **chp;
+ chp = evbuffer_free_trailing_empty_chains(buf);
+ *chp = chain;
+ if (chain->off)
+ buf->last_with_datap = chp;
+ buf->last = chain;
+ }
+ buf->total_len += chain->off;
+}
+
+static inline struct evbuffer_chain *
+evbuffer_chain_insert_new(struct evbuffer *buf, size_t datlen)
+{
+ struct evbuffer_chain *chain;
+ if ((chain = evbuffer_chain_new(datlen)) == NULL)
+ return NULL;
+ evbuffer_chain_insert(buf, chain);
+ return chain;
+}
+
+void
+evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag)
+{
+ EVUTIL_ASSERT((chain->flags & flag) == 0);
+ chain->flags |= flag;
+}
+
+void
+evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag)
+{
+ EVUTIL_ASSERT((chain->flags & flag) != 0);
+ chain->flags &= ~flag;
+ if (chain->flags & EVBUFFER_DANGLING)
+ evbuffer_chain_free(chain);
+}
+
+static inline void
+evbuffer_chain_incref(struct evbuffer_chain *chain)
+{
+ ++chain->refcnt;
+}
+
+struct evbuffer *
+evbuffer_new(void)
+{
+ struct evbuffer *buffer;
+
+ buffer = mm_calloc(1, sizeof(struct evbuffer));
+ if (buffer == NULL)
+ return (NULL);
+
+ LIST_INIT(&buffer->callbacks);
+ buffer->refcnt = 1;
+ buffer->last_with_datap = &buffer->first;
+
+ return (buffer);
+}
+
+int
+evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+ EVBUFFER_LOCK(buf);
+ buf->flags |= (ev_uint32_t)flags;
+ EVBUFFER_UNLOCK(buf);
+ return 0;
+}
+
+int
+evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags)
+{
+ EVBUFFER_LOCK(buf);
+ buf->flags &= ~(ev_uint32_t)flags;
+ EVBUFFER_UNLOCK(buf);
+ return 0;
+}
+
+void
+evbuffer_incref_(struct evbuffer *buf)
+{
+ EVBUFFER_LOCK(buf);
+ ++buf->refcnt;
+ EVBUFFER_UNLOCK(buf);
+}
+
+void
+evbuffer_incref_and_lock_(struct evbuffer *buf)
+{
+ EVBUFFER_LOCK(buf);
+ ++buf->refcnt;
+}
+
+int
+evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base)
+{
+ EVBUFFER_LOCK(buffer);
+ buffer->cb_queue = base;
+ buffer->deferred_cbs = 1;
+ event_deferred_cb_init_(&buffer->deferred,
+ event_base_get_npriorities(base) / 2,
+ evbuffer_deferred_callback, buffer);
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+int
+evbuffer_enable_locking(struct evbuffer *buf, void *lock)
+{
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+ return -1;
+#else
+ if (buf->lock)
+ return -1;
+
+ if (!lock) {
+ EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ if (!lock)
+ return -1;
+ buf->lock = lock;
+ buf->own_lock = 1;
+ } else {
+ buf->lock = lock;
+ buf->own_lock = 0;
+ }
+
+ return 0;
+#endif
+}
+
+void
+evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev)
+{
+ EVBUFFER_LOCK(buf);
+ buf->parent = bev;
+ EVBUFFER_UNLOCK(buf);
+}
+
+static void
+evbuffer_run_callbacks(struct evbuffer *buffer, int running_deferred)
+{
+ struct evbuffer_cb_entry *cbent, *next;
+ struct evbuffer_cb_info info;
+ size_t new_size;
+ ev_uint32_t mask, masked_val;
+ int clear = 1;
+
+ if (running_deferred) {
+ mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+ masked_val = EVBUFFER_CB_ENABLED;
+ } else if (buffer->deferred_cbs) {
+ mask = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+ masked_val = EVBUFFER_CB_NODEFER|EVBUFFER_CB_ENABLED;
+ /* Don't zero-out n_add/n_del, since the deferred callbacks
+ will want to see them. */
+ clear = 0;
+ } else {
+ mask = EVBUFFER_CB_ENABLED;
+ masked_val = EVBUFFER_CB_ENABLED;
+ }
+
+ ASSERT_EVBUFFER_LOCKED(buffer);
+
+ if (LIST_EMPTY(&buffer->callbacks)) {
+ buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
+ return;
+ }
+ if (buffer->n_add_for_cb == 0 && buffer->n_del_for_cb == 0)
+ return;
+
+ new_size = buffer->total_len;
+ info.orig_size = new_size + buffer->n_del_for_cb - buffer->n_add_for_cb;
+ info.n_added = buffer->n_add_for_cb;
+ info.n_deleted = buffer->n_del_for_cb;
+ if (clear) {
+ buffer->n_add_for_cb = 0;
+ buffer->n_del_for_cb = 0;
+ }
+ for (cbent = LIST_FIRST(&buffer->callbacks);
+ cbent != LIST_END(&buffer->callbacks);
+ cbent = next) {
+ /* Get the 'next' pointer now in case this callback decides
+ * to remove itself or something. */
+ next = LIST_NEXT(cbent, next);
+
+ if ((cbent->flags & mask) != masked_val)
+ continue;
+
+ if ((cbent->flags & EVBUFFER_CB_OBSOLETE))
+ cbent->cb.cb_obsolete(buffer,
+ info.orig_size, new_size, cbent->cbarg);
+ else
+ cbent->cb.cb_func(buffer, &info, cbent->cbarg);
+ }
+}
+
+void
+evbuffer_invoke_callbacks_(struct evbuffer *buffer)
+{
+ if (LIST_EMPTY(&buffer->callbacks)) {
+ buffer->n_add_for_cb = buffer->n_del_for_cb = 0;
+ return;
+ }
+
+ if (buffer->deferred_cbs) {
+ if (event_deferred_cb_schedule_(buffer->cb_queue, &buffer->deferred)) {
+ evbuffer_incref_and_lock_(buffer);
+ if (buffer->parent)
+ bufferevent_incref_(buffer->parent);
+ EVBUFFER_UNLOCK(buffer);
+ }
+ }
+
+ evbuffer_run_callbacks(buffer, 0);
+}
+
+static void
+evbuffer_deferred_callback(struct event_callback *cb, void *arg)
+{
+ struct bufferevent *parent = NULL;
+ struct evbuffer *buffer = arg;
+
+ /* XXXX It would be better to run these callbacks without holding the
+ * lock */
+ EVBUFFER_LOCK(buffer);
+ parent = buffer->parent;
+ evbuffer_run_callbacks(buffer, 1);
+ evbuffer_decref_and_unlock_(buffer);
+ if (parent)
+ bufferevent_decref_(parent);
+}
+
+static void
+evbuffer_remove_all_callbacks(struct evbuffer *buffer)
+{
+ struct evbuffer_cb_entry *cbent;
+
+ while ((cbent = LIST_FIRST(&buffer->callbacks))) {
+ LIST_REMOVE(cbent, next);
+ mm_free(cbent);
+ }
+}
+
+void
+evbuffer_decref_and_unlock_(struct evbuffer *buffer)
+{
+ struct evbuffer_chain *chain, *next;
+ ASSERT_EVBUFFER_LOCKED(buffer);
+
+ EVUTIL_ASSERT(buffer->refcnt > 0);
+
+ if (--buffer->refcnt > 0) {
+ EVBUFFER_UNLOCK(buffer);
+ return;
+ }
+
+ for (chain = buffer->first; chain != NULL; chain = next) {
+ next = chain->next;
+ evbuffer_chain_free(chain);
+ }
+ evbuffer_remove_all_callbacks(buffer);
+ if (buffer->deferred_cbs)
+ event_deferred_cb_cancel_(buffer->cb_queue, &buffer->deferred);
+
+ EVBUFFER_UNLOCK(buffer);
+ if (buffer->own_lock)
+ EVTHREAD_FREE_LOCK(buffer->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ mm_free(buffer);
+}
+
+void
+evbuffer_free(struct evbuffer *buffer)
+{
+ EVBUFFER_LOCK(buffer);
+ evbuffer_decref_and_unlock_(buffer);
+}
+
+void
+evbuffer_lock(struct evbuffer *buf)
+{
+ EVBUFFER_LOCK(buf);
+}
+
+void
+evbuffer_unlock(struct evbuffer *buf)
+{
+ EVBUFFER_UNLOCK(buf);
+}
+
+size_t
+evbuffer_get_length(const struct evbuffer *buffer)
+{
+ size_t result;
+
+ EVBUFFER_LOCK(buffer);
+
+ result = (buffer->total_len);
+
+ EVBUFFER_UNLOCK(buffer);
+
+ return result;
+}
+
+size_t
+evbuffer_get_contiguous_space(const struct evbuffer *buf)
+{
+ struct evbuffer_chain *chain;
+ size_t result;
+
+ EVBUFFER_LOCK(buf);
+ chain = buf->first;
+ result = (chain != NULL ? chain->off : 0);
+ EVBUFFER_UNLOCK(buf);
+
+ return result;
+}
+
+size_t
+evbuffer_add_iovec(struct evbuffer * buf, struct evbuffer_iovec * vec, int n_vec) {
+ int n;
+ size_t res;
+ size_t to_alloc;
+
+ EVBUFFER_LOCK(buf);
+
+ res = to_alloc = 0;
+
+ for (n = 0; n < n_vec; n++) {
+ to_alloc += vec[n].iov_len;
+ }
+
+ if (evbuffer_expand_fast_(buf, to_alloc, 2) < 0) {
+ goto done;
+ }
+
+ for (n = 0; n < n_vec; n++) {
+ /* XXX each 'add' call here does a bunch of setup that's
+ * obviated by evbuffer_expand_fast_, and some cleanup that we
+ * would like to do only once. Instead we should just extract
+ * the part of the code that's needed. */
+
+ if (evbuffer_add(buf, vec[n].iov_base, vec[n].iov_len) < 0) {
+ goto done;
+ }
+
+ res += vec[n].iov_len;
+ }
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return res;
+}
+
+int
+evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
+ struct evbuffer_iovec *vec, int n_vecs)
+{
+ struct evbuffer_chain *chain, **chainp;
+ int n = -1;
+
+ EVBUFFER_LOCK(buf);
+ if (buf->freeze_end)
+ goto done;
+ if (n_vecs < 1)
+ goto done;
+ if (n_vecs == 1) {
+ if ((chain = evbuffer_expand_singlechain(buf, size)) == NULL)
+ goto done;
+
+ vec[0].iov_base = (void *)CHAIN_SPACE_PTR(chain);
+ vec[0].iov_len = (size_t)CHAIN_SPACE_LEN(chain);
+ EVUTIL_ASSERT(size<0 || (size_t)vec[0].iov_len >= (size_t)size);
+ n = 1;
+ } else {
+ if (evbuffer_expand_fast_(buf, size, n_vecs)<0)
+ goto done;
+ n = evbuffer_read_setup_vecs_(buf, size, vec, n_vecs,
+ &chainp, 0);
+ }
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return n;
+
+}
+
+static int
+advance_last_with_data(struct evbuffer *buf)
+{
+ int n = 0;
+ struct evbuffer_chain **chainp = buf->last_with_datap;
+
+ ASSERT_EVBUFFER_LOCKED(buf);
+
+ if (!*chainp)
+ return 0;
+
+ while ((*chainp)->next) {
+ chainp = &(*chainp)->next;
+ if ((*chainp)->off)
+ buf->last_with_datap = chainp;
+ ++n;
+ }
+ return n;
+}
+
+int
+evbuffer_commit_space(struct evbuffer *buf,
+ struct evbuffer_iovec *vec, int n_vecs)
+{
+ struct evbuffer_chain *chain, **firstchainp, **chainp;
+ int result = -1;
+ size_t added = 0;
+ int i;
+
+ EVBUFFER_LOCK(buf);
+
+ if (buf->freeze_end)
+ goto done;
+ if (n_vecs == 0) {
+ result = 0;
+ goto done;
+ } else if (n_vecs == 1 &&
+ (buf->last && vec[0].iov_base == (void *)CHAIN_SPACE_PTR(buf->last))) {
+ /* The user only got or used one chain; it might not
+ * be the first one with space in it. */
+ if ((size_t)vec[0].iov_len > (size_t)CHAIN_SPACE_LEN(buf->last))
+ goto done;
+ buf->last->off += vec[0].iov_len;
+ added = vec[0].iov_len;
+ if (added)
+ advance_last_with_data(buf);
+ goto okay;
+ }
+
+ /* Advance 'firstchain' to the first chain with space in it. */
+ firstchainp = buf->last_with_datap;
+ if (!*firstchainp)
+ goto done;
+ if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
+ firstchainp = &(*firstchainp)->next;
+ }
+
+ chain = *firstchainp;
+ /* pass 1: make sure that the pointers and lengths of vecs[] are in
+ * bounds before we try to commit anything. */
+ for (i=0; i<n_vecs; ++i) {
+ if (!chain)
+ goto done;
+ if (vec[i].iov_base != (void *)CHAIN_SPACE_PTR(chain) ||
+ (size_t)vec[i].iov_len > CHAIN_SPACE_LEN(chain))
+ goto done;
+ chain = chain->next;
+ }
+ /* pass 2: actually adjust all the chains. */
+ chainp = firstchainp;
+ for (i=0; i<n_vecs; ++i) {
+ (*chainp)->off += vec[i].iov_len;
+ added += vec[i].iov_len;
+ if (vec[i].iov_len) {
+ buf->last_with_datap = chainp;
+ }
+ chainp = &(*chainp)->next;
+ }
+
+okay:
+ buf->total_len += added;
+ buf->n_add_for_cb += added;
+ result = 0;
+ evbuffer_invoke_callbacks_(buf);
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+static inline int
+HAS_PINNED_R(struct evbuffer *buf)
+{
+ return (buf->last && CHAIN_PINNED_R(buf->last));
+}
+
+static inline void
+ZERO_CHAIN(struct evbuffer *dst)
+{
+ ASSERT_EVBUFFER_LOCKED(dst);
+ dst->first = NULL;
+ dst->last = NULL;
+ dst->last_with_datap = &(dst)->first;
+ dst->total_len = 0;
+}
+
+/* Prepares the contents of src to be moved to another buffer by removing
+ * read-pinned chains. The first pinned chain is saved in first, and the
+ * last in last. If src has no read-pinned chains, first and last are set
+ * to NULL. */
+static int
+PRESERVE_PINNED(struct evbuffer *src, struct evbuffer_chain **first,
+ struct evbuffer_chain **last)
+{
+ struct evbuffer_chain *chain, **pinned;
+
+ ASSERT_EVBUFFER_LOCKED(src);
+
+ if (!HAS_PINNED_R(src)) {
+ *first = *last = NULL;
+ return 0;
+ }
+
+ pinned = src->last_with_datap;
+ if (!CHAIN_PINNED_R(*pinned))
+ pinned = &(*pinned)->next;
+ EVUTIL_ASSERT(CHAIN_PINNED_R(*pinned));
+ chain = *first = *pinned;
+ *last = src->last;
+
+ /* If there's data in the first pinned chain, we need to allocate
+ * a new chain and copy the data over. */
+ if (chain->off) {
+ struct evbuffer_chain *tmp;
+
+ EVUTIL_ASSERT(pinned == src->last_with_datap);
+ tmp = evbuffer_chain_new(chain->off);
+ if (!tmp)
+ return -1;
+ memcpy(tmp->buffer, chain->buffer + chain->misalign,
+ chain->off);
+ tmp->off = chain->off;
+ *src->last_with_datap = tmp;
+ src->last = tmp;
+ chain->misalign += chain->off;
+ chain->off = 0;
+ } else {
+ src->last = *src->last_with_datap;
+ *pinned = NULL;
+ }
+
+ return 0;
+}
+
+static inline void
+RESTORE_PINNED(struct evbuffer *src, struct evbuffer_chain *pinned,
+ struct evbuffer_chain *last)
+{
+ ASSERT_EVBUFFER_LOCKED(src);
+
+ if (!pinned) {
+ ZERO_CHAIN(src);
+ return;
+ }
+
+ src->first = pinned;
+ src->last = last;
+ src->last_with_datap = &src->first;
+ src->total_len = 0;
+}
+
+static inline void
+COPY_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+ ASSERT_EVBUFFER_LOCKED(dst);
+ ASSERT_EVBUFFER_LOCKED(src);
+ dst->first = src->first;
+ if (src->last_with_datap == &src->first)
+ dst->last_with_datap = &dst->first;
+ else
+ dst->last_with_datap = src->last_with_datap;
+ dst->last = src->last;
+ dst->total_len = src->total_len;
+}
+
+static void
+APPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+ struct evbuffer_chain **chp;
+
+ ASSERT_EVBUFFER_LOCKED(dst);
+ ASSERT_EVBUFFER_LOCKED(src);
+
+ chp = evbuffer_free_trailing_empty_chains(dst);
+ *chp = src->first;
+
+ if (src->last_with_datap == &src->first)
+ dst->last_with_datap = chp;
+ else
+ dst->last_with_datap = src->last_with_datap;
+ dst->last = src->last;
+ dst->total_len += src->total_len;
+}
+
+static inline void
+APPEND_CHAIN_MULTICAST(struct evbuffer *dst, struct evbuffer *src)
+{
+ struct evbuffer_chain *tmp;
+ struct evbuffer_chain *chain = src->first;
+ struct evbuffer_multicast_parent *extra;
+
+ ASSERT_EVBUFFER_LOCKED(dst);
+ ASSERT_EVBUFFER_LOCKED(src);
+
+ for (; chain; chain = chain->next) {
+ if (!chain->off || chain->flags & EVBUFFER_DANGLING) {
+ /* skip empty chains */
+ continue;
+ }
+
+ tmp = evbuffer_chain_new(sizeof(struct evbuffer_multicast_parent));
+ if (!tmp) {
+ event_warn("%s: out of memory", __func__);
+ return;
+ }
+ extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_multicast_parent, tmp);
+ /* reference evbuffer containing source chain so it
+ * doesn't get released while the chain is still
+ * being referenced to */
+ evbuffer_incref_(src);
+ extra->source = src;
+ /* reference source chain which now becomes immutable */
+ evbuffer_chain_incref(chain);
+ extra->parent = chain;
+ chain->flags |= EVBUFFER_IMMUTABLE;
+ tmp->buffer_len = chain->buffer_len;
+ tmp->misalign = chain->misalign;
+ tmp->off = chain->off;
+ tmp->flags |= EVBUFFER_MULTICAST|EVBUFFER_IMMUTABLE;
+ tmp->buffer = chain->buffer;
+ evbuffer_chain_insert(dst, tmp);
+ }
+}
+
+static void
+PREPEND_CHAIN(struct evbuffer *dst, struct evbuffer *src)
+{
+ ASSERT_EVBUFFER_LOCKED(dst);
+ ASSERT_EVBUFFER_LOCKED(src);
+ src->last->next = dst->first;
+ dst->first = src->first;
+ dst->total_len += src->total_len;
+ if (*dst->last_with_datap == NULL) {
+ if (src->last_with_datap == &(src)->first)
+ dst->last_with_datap = &dst->first;
+ else
+ dst->last_with_datap = src->last_with_datap;
+ } else if (dst->last_with_datap == &dst->first) {
+ dst->last_with_datap = &src->last->next;
+ }
+}
+
+int
+evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+ struct evbuffer_chain *pinned, *last;
+ size_t in_total_len, out_total_len;
+ int result = 0;
+
+ EVBUFFER_LOCK2(inbuf, outbuf);
+ in_total_len = inbuf->total_len;
+ out_total_len = outbuf->total_len;
+
+ if (in_total_len == 0 || outbuf == inbuf)
+ goto done;
+
+ if (outbuf->freeze_end || inbuf->freeze_start) {
+ result = -1;
+ goto done;
+ }
+
+ if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
+ result = -1;
+ goto done;
+ }
+
+ if (out_total_len == 0) {
+ /* There might be an empty chain at the start of outbuf; free
+ * it. */
+ evbuffer_free_all_chains(outbuf->first);
+ COPY_CHAIN(outbuf, inbuf);
+ } else {
+ APPEND_CHAIN(outbuf, inbuf);
+ }
+
+ RESTORE_PINNED(inbuf, pinned, last);
+
+ inbuf->n_del_for_cb += in_total_len;
+ outbuf->n_add_for_cb += in_total_len;
+
+ evbuffer_invoke_callbacks_(inbuf);
+ evbuffer_invoke_callbacks_(outbuf);
+
+done:
+ EVBUFFER_UNLOCK2(inbuf, outbuf);
+ return result;
+}
+
+int
+evbuffer_add_buffer_reference(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+ size_t in_total_len, out_total_len;
+ struct evbuffer_chain *chain;
+ int result = 0;
+
+ EVBUFFER_LOCK2(inbuf, outbuf);
+ in_total_len = inbuf->total_len;
+ out_total_len = outbuf->total_len;
+ chain = inbuf->first;
+
+ if (in_total_len == 0)
+ goto done;
+
+ if (outbuf->freeze_end || outbuf == inbuf) {
+ result = -1;
+ goto done;
+ }
+
+ for (; chain; chain = chain->next) {
+ if ((chain->flags & (EVBUFFER_FILESEGMENT|EVBUFFER_SENDFILE|EVBUFFER_MULTICAST)) != 0) {
+ /* chain type can not be referenced */
+ result = -1;
+ goto done;
+ }
+ }
+
+ if (out_total_len == 0) {
+ /* There might be an empty chain at the start of outbuf; free
+ * it. */
+ evbuffer_free_all_chains(outbuf->first);
+ }
+ APPEND_CHAIN_MULTICAST(outbuf, inbuf);
+
+ outbuf->n_add_for_cb += in_total_len;
+ evbuffer_invoke_callbacks_(outbuf);
+
+done:
+ EVBUFFER_UNLOCK2(inbuf, outbuf);
+ return result;
+}
+
+int
+evbuffer_prepend_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf)
+{
+ struct evbuffer_chain *pinned, *last;
+ size_t in_total_len, out_total_len;
+ int result = 0;
+
+ EVBUFFER_LOCK2(inbuf, outbuf);
+
+ in_total_len = inbuf->total_len;
+ out_total_len = outbuf->total_len;
+
+ if (!in_total_len || inbuf == outbuf)
+ goto done;
+
+ if (outbuf->freeze_start || inbuf->freeze_start) {
+ result = -1;
+ goto done;
+ }
+
+ if (PRESERVE_PINNED(inbuf, &pinned, &last) < 0) {
+ result = -1;
+ goto done;
+ }
+
+ if (out_total_len == 0) {
+ /* There might be an empty chain at the start of outbuf; free
+ * it. */
+ evbuffer_free_all_chains(outbuf->first);
+ COPY_CHAIN(outbuf, inbuf);
+ } else {
+ PREPEND_CHAIN(outbuf, inbuf);
+ }
+
+ RESTORE_PINNED(inbuf, pinned, last);
+
+ inbuf->n_del_for_cb += in_total_len;
+ outbuf->n_add_for_cb += in_total_len;
+
+ evbuffer_invoke_callbacks_(inbuf);
+ evbuffer_invoke_callbacks_(outbuf);
+done:
+ EVBUFFER_UNLOCK2(inbuf, outbuf);
+ return result;
+}
+
+int
+evbuffer_drain(struct evbuffer *buf, size_t len)
+{
+ struct evbuffer_chain *chain, *next;
+ size_t remaining, old_len;
+ int result = 0;
+
+ EVBUFFER_LOCK(buf);
+ old_len = buf->total_len;
+
+ if (old_len == 0)
+ goto done;
+
+ if (buf->freeze_start) {
+ result = -1;
+ goto done;
+ }
+
+ if (len >= old_len && !HAS_PINNED_R(buf)) {
+ len = old_len;
+ for (chain = buf->first; chain != NULL; chain = next) {
+ next = chain->next;
+ evbuffer_chain_free(chain);
+ }
+
+ ZERO_CHAIN(buf);
+ } else {
+ if (len >= old_len)
+ len = old_len;
+
+ buf->total_len -= len;
+ remaining = len;
+ for (chain = buf->first;
+ remaining >= chain->off;
+ chain = next) {
+ next = chain->next;
+ remaining -= chain->off;
+
+ if (chain == *buf->last_with_datap) {
+ buf->last_with_datap = &buf->first;
+ }
+ if (&chain->next == buf->last_with_datap)
+ buf->last_with_datap = &buf->first;
+
+ if (CHAIN_PINNED_R(chain)) {
+ EVUTIL_ASSERT(remaining == 0);
+ chain->misalign += chain->off;
+ chain->off = 0;
+ break;
+ } else
+ evbuffer_chain_free(chain);
+ }
+
+ buf->first = chain;
+ EVUTIL_ASSERT(remaining <= chain->off);
+ chain->misalign += remaining;
+ chain->off -= remaining;
+ }
+
+ buf->n_del_for_cb += len;
+ /* Tell someone about changes in this buffer */
+ evbuffer_invoke_callbacks_(buf);
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+/* Reads data from an event buffer and drains the bytes read */
+int
+evbuffer_remove(struct evbuffer *buf, void *data_out, size_t datlen)
+{
+ ev_ssize_t n;
+ EVBUFFER_LOCK(buf);
+ n = evbuffer_copyout_from(buf, NULL, data_out, datlen);
+ if (n > 0) {
+ if (evbuffer_drain(buf, n)<0)
+ n = -1;
+ }
+ EVBUFFER_UNLOCK(buf);
+ return (int)n;
+}
+
+ev_ssize_t
+evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen)
+{
+ return evbuffer_copyout_from(buf, NULL, data_out, datlen);
+}
+
+ev_ssize_t
+evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos,
+ void *data_out, size_t datlen)
+{
+ /*XXX fails badly on sendfile case. */
+ struct evbuffer_chain *chain;
+ char *data = data_out;
+ size_t nread;
+ ev_ssize_t result = 0;
+ size_t pos_in_chain;
+
+ EVBUFFER_LOCK(buf);
+
+ if (pos) {
+ if (datlen > (size_t)(EV_SSIZE_MAX - pos->pos)) {
+ result = -1;
+ goto done;
+ }
+ chain = pos->internal_.chain;
+ pos_in_chain = pos->internal_.pos_in_chain;
+ if (datlen + pos->pos > buf->total_len)
+ datlen = buf->total_len - pos->pos;
+ } else {
+ chain = buf->first;
+ pos_in_chain = 0;
+ if (datlen > buf->total_len)
+ datlen = buf->total_len;
+ }
+
+
+ if (datlen == 0)
+ goto done;
+
+ if (buf->freeze_start) {
+ result = -1;
+ goto done;
+ }
+
+ nread = datlen;
+
+ while (datlen && datlen >= chain->off - pos_in_chain) {
+ size_t copylen = chain->off - pos_in_chain;
+ memcpy(data,
+ chain->buffer + chain->misalign + pos_in_chain,
+ copylen);
+ data += copylen;
+ datlen -= copylen;
+
+ chain = chain->next;
+ pos_in_chain = 0;
+ EVUTIL_ASSERT(chain || datlen==0);
+ }
+
+ if (datlen) {
+ EVUTIL_ASSERT(chain);
+ EVUTIL_ASSERT(datlen+pos_in_chain <= chain->off);
+
+ memcpy(data, chain->buffer + chain->misalign + pos_in_chain,
+ datlen);
+ }
+
+ result = nread;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+/* reads data from the src buffer to the dst buffer, avoids memcpy as
+ * possible. */
+/* XXXX should return ev_ssize_t */
+int
+evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
+ size_t datlen)
+{
+ /*XXX We should have an option to force this to be zero-copy.*/
+
+ /*XXX can fail badly on sendfile case. */
+ struct evbuffer_chain *chain, *previous;
+ size_t nread = 0;
+ int result;
+
+ EVBUFFER_LOCK2(src, dst);
+
+ chain = previous = src->first;
+
+ if (datlen == 0 || dst == src) {
+ result = 0;
+ goto done;
+ }
+
+ if (dst->freeze_end || src->freeze_start) {
+ result = -1;
+ goto done;
+ }
+
+ /* short-cut if there is no more data buffered */
+ if (datlen >= src->total_len) {
+ datlen = src->total_len;
+ evbuffer_add_buffer(dst, src);
+ result = (int)datlen; /*XXXX should return ev_ssize_t*/
+ goto done;
+ }
+
+ /* removes chains if possible */
+ while (chain->off <= datlen) {
+ /* We can't remove the last with data from src unless we
+ * remove all chains, in which case we would have done the if
+ * block above */
+ EVUTIL_ASSERT(chain != *src->last_with_datap);
+ nread += chain->off;
+ datlen -= chain->off;
+ previous = chain;
+ if (src->last_with_datap == &chain->next)
+ src->last_with_datap = &src->first;
+ chain = chain->next;
+ }
+
+ if (chain != src->first) {
+ /* we can remove the chain */
+ struct evbuffer_chain **chp;
+ chp = evbuffer_free_trailing_empty_chains(dst);
+
+ if (dst->first == NULL) {
+ dst->first = src->first;
+ } else {
+ *chp = src->first;
+ }
+ dst->last = previous;
+ previous->next = NULL;
+ src->first = chain;
+ advance_last_with_data(dst);
+
+ dst->total_len += nread;
+ dst->n_add_for_cb += nread;
+ }
+
+ /* we know that there is more data in the src buffer than
+ * we want to read, so we manually drain the chain */
+ evbuffer_add(dst, chain->buffer + chain->misalign, datlen);
+ chain->misalign += datlen;
+ chain->off -= datlen;
+ nread += datlen;
+
+ /* You might think we would want to increment dst->n_add_for_cb
+ * here too. But evbuffer_add above already took care of that.
+ */
+ src->total_len -= nread;
+ src->n_del_for_cb += nread;
+
+ if (nread) {
+ evbuffer_invoke_callbacks_(dst);
+ evbuffer_invoke_callbacks_(src);
+ }
+ result = (int)nread;/*XXXX should change return type */
+
+done:
+ EVBUFFER_UNLOCK2(src, dst);
+ return result;
+}
+
+unsigned char *
+evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size)
+{
+ struct evbuffer_chain *chain, *next, *tmp, *last_with_data;
+ unsigned char *buffer, *result = NULL;
+ ev_ssize_t remaining;
+ int removed_last_with_data = 0;
+ int removed_last_with_datap = 0;
+
+ EVBUFFER_LOCK(buf);
+
+ chain = buf->first;
+
+ if (size < 0)
+ size = buf->total_len;
+ /* if size > buf->total_len, we cannot guarantee to the user that she
+ * is going to have a long enough buffer afterwards; so we return
+ * NULL */
+ if (size == 0 || (size_t)size > buf->total_len)
+ goto done;
+
+ /* No need to pull up anything; the first size bytes are
+ * already here. */
+ if (chain->off >= (size_t)size) {
+ result = chain->buffer + chain->misalign;
+ goto done;
+ }
+
+ /* Make sure that none of the chains we need to copy from is pinned. */
+ remaining = size - chain->off;
+ EVUTIL_ASSERT(remaining >= 0);
+ for (tmp=chain->next; tmp; tmp=tmp->next) {
+ if (CHAIN_PINNED(tmp))
+ goto done;
+ if (tmp->off >= (size_t)remaining)
+ break;
+ remaining -= tmp->off;
+ }
+
+ if (CHAIN_PINNED(chain)) {
+ size_t old_off = chain->off;
+ if (CHAIN_SPACE_LEN(chain) < size - chain->off) {
+ /* not enough room at end of chunk. */
+ goto done;
+ }
+ buffer = CHAIN_SPACE_PTR(chain);
+ tmp = chain;
+ tmp->off = size;
+ size -= old_off;
+ chain = chain->next;
+ } else if (chain->buffer_len - chain->misalign >= (size_t)size) {
+ /* already have enough space in the first chain */
+ size_t old_off = chain->off;
+ buffer = chain->buffer + chain->misalign + chain->off;
+ tmp = chain;
+ tmp->off = size;
+ size -= old_off;
+ chain = chain->next;
+ } else {
+ if ((tmp = evbuffer_chain_new(size)) == NULL) {
+ event_warn("%s: out of memory", __func__);
+ goto done;
+ }
+ buffer = tmp->buffer;
+ tmp->off = size;
+ buf->first = tmp;
+ }
+
+ /* TODO(niels): deal with buffers that point to NULL like sendfile */
+
+ /* Copy and free every chunk that will be entirely pulled into tmp */
+ last_with_data = *buf->last_with_datap;
+ for (; chain != NULL && (size_t)size >= chain->off; chain = next) {
+ next = chain->next;
+
+ if (chain->buffer) {
+ memcpy(buffer, chain->buffer + chain->misalign, chain->off);
+ size -= chain->off;
+ buffer += chain->off;
+ }
+ if (chain == last_with_data)
+ removed_last_with_data = 1;
+ if (&chain->next == buf->last_with_datap)
+ removed_last_with_datap = 1;
+
+ evbuffer_chain_free(chain);
+ }
+
+ if (chain != NULL) {
+ memcpy(buffer, chain->buffer + chain->misalign, size);
+ chain->misalign += size;
+ chain->off -= size;
+ } else {
+ buf->last = tmp;
+ }
+
+ tmp->next = chain;
+
+ if (removed_last_with_data) {
+ buf->last_with_datap = &buf->first;
+ } else if (removed_last_with_datap) {
+ if (buf->first->next && buf->first->next->off)
+ buf->last_with_datap = &buf->first->next;
+ else
+ buf->last_with_datap = &buf->first;
+ }
+
+ result = (tmp->buffer + tmp->misalign);
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+/*
+ * Reads a line terminated by either '\r\n', '\n\r' or '\r' or '\n'.
+ * The returned buffer needs to be freed by the called.
+ */
+char *
+evbuffer_readline(struct evbuffer *buffer)
+{
+ return evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY);
+}
+
+static inline ev_ssize_t
+evbuffer_strchr(struct evbuffer_ptr *it, const char chr)
+{
+ struct evbuffer_chain *chain = it->internal_.chain;
+ size_t i = it->internal_.pos_in_chain;
+ while (chain != NULL) {
+ char *buffer = (char *)chain->buffer + chain->misalign;
+ char *cp = memchr(buffer+i, chr, chain->off-i);
+ if (cp) {
+ it->internal_.chain = chain;
+ it->internal_.pos_in_chain = cp - buffer;
+ it->pos += (cp - buffer - i);
+ return it->pos;
+ }
+ it->pos += chain->off - i;
+ i = 0;
+ chain = chain->next;
+ }
+
+ return (-1);
+}
+
+static inline char *
+find_eol_char(char *s, size_t len)
+{
+#define CHUNK_SZ 128
+ /* Lots of benchmarking found this approach to be faster in practice
+ * than doing two memchrs over the whole buffer, doin a memchr on each
+ * char of the buffer, or trying to emulate memchr by hand. */
+ char *s_end, *cr, *lf;
+ s_end = s+len;
+ while (s < s_end) {
+ size_t chunk = (s + CHUNK_SZ < s_end) ? CHUNK_SZ : (s_end - s);
+ cr = memchr(s, '\r', chunk);
+ lf = memchr(s, '\n', chunk);
+ if (cr) {
+ if (lf && lf < cr)
+ return lf;
+ return cr;
+ } else if (lf) {
+ return lf;
+ }
+ s += CHUNK_SZ;
+ }
+
+ return NULL;
+#undef CHUNK_SZ
+}
+
+static ev_ssize_t
+evbuffer_find_eol_char(struct evbuffer_ptr *it)
+{
+ struct evbuffer_chain *chain = it->internal_.chain;
+ size_t i = it->internal_.pos_in_chain;
+ while (chain != NULL) {
+ char *buffer = (char *)chain->buffer + chain->misalign;
+ char *cp = find_eol_char(buffer+i, chain->off-i);
+ if (cp) {
+ it->internal_.chain = chain;
+ it->internal_.pos_in_chain = cp - buffer;
+ it->pos += (cp - buffer) - i;
+ return it->pos;
+ }
+ it->pos += chain->off - i;
+ i = 0;
+ chain = chain->next;
+ }
+
+ return (-1);
+}
+
+static inline size_t
+evbuffer_strspn(
+ struct evbuffer_ptr *ptr, const char *chrset)
+{
+ size_t count = 0;
+ struct evbuffer_chain *chain = ptr->internal_.chain;
+ size_t i = ptr->internal_.pos_in_chain;
+
+ if (!chain)
+ return 0;
+
+ while (1) {
+ char *buffer = (char *)chain->buffer + chain->misalign;
+ for (; i < chain->off; ++i) {
+ const char *p = chrset;
+ while (*p) {
+ if (buffer[i] == *p++)
+ goto next;
+ }
+ ptr->internal_.chain = chain;
+ ptr->internal_.pos_in_chain = i;
+ ptr->pos += count;
+ return count;
+ next:
+ ++count;
+ }
+ i = 0;
+
+ if (! chain->next) {
+ ptr->internal_.chain = chain;
+ ptr->internal_.pos_in_chain = i;
+ ptr->pos += count;
+ return count;
+ }
+
+ chain = chain->next;
+ }
+}
+
+
+static inline int
+evbuffer_getchr(struct evbuffer_ptr *it)
+{
+ struct evbuffer_chain *chain = it->internal_.chain;
+ size_t off = it->internal_.pos_in_chain;
+
+ if (chain == NULL)
+ return -1;
+
+ return (unsigned char)chain->buffer[chain->misalign + off];
+}
+
+struct evbuffer_ptr
+evbuffer_search_eol(struct evbuffer *buffer,
+ struct evbuffer_ptr *start, size_t *eol_len_out,
+ enum evbuffer_eol_style eol_style)
+{
+ struct evbuffer_ptr it, it2;
+ size_t extra_drain = 0;
+ int ok = 0;
+
+ /* Avoid locking in trivial edge cases */
+ if (start && start->internal_.chain == NULL) {
+ PTR_NOT_FOUND(&it);
+ if (eol_len_out)
+ *eol_len_out = extra_drain;
+ return it;
+ }
+
+ EVBUFFER_LOCK(buffer);
+
+ if (start) {
+ memcpy(&it, start, sizeof(it));
+ } else {
+ it.pos = 0;
+ it.internal_.chain = buffer->first;
+ it.internal_.pos_in_chain = 0;
+ }
+
+ /* the eol_style determines our first stop character and how many
+ * characters we are going to drain afterwards. */
+ switch (eol_style) {
+ case EVBUFFER_EOL_ANY:
+ if (evbuffer_find_eol_char(&it) < 0)
+ goto done;
+ memcpy(&it2, &it, sizeof(it));
+ extra_drain = evbuffer_strspn(&it2, "\r\n");
+ break;
+ case EVBUFFER_EOL_CRLF_STRICT: {
+ it = evbuffer_search(buffer, "\r\n", 2, &it);
+ if (it.pos < 0)
+ goto done;
+ extra_drain = 2;
+ break;
+ }
+ case EVBUFFER_EOL_CRLF: {
+ ev_ssize_t start_pos = it.pos;
+ /* Look for a LF ... */
+ if (evbuffer_strchr(&it, '\n') < 0)
+ goto done;
+ extra_drain = 1;
+ /* ... optionally preceeded by a CR. */
+ if (it.pos == start_pos)
+ break; /* If the first character is \n, don't back up */
+ /* This potentially does an extra linear walk over the first
+ * few chains. Probably, that's not too expensive unless you
+ * have a really pathological setup. */
+ memcpy(&it2, &it, sizeof(it));
+ if (evbuffer_ptr_subtract(buffer, &it2, 1)<0)
+ break;
+ if (evbuffer_getchr(&it2) == '\r') {
+ memcpy(&it, &it2, sizeof(it));
+ extra_drain = 2;
+ }
+ break;
+ }
+ case EVBUFFER_EOL_LF:
+ if (evbuffer_strchr(&it, '\n') < 0)
+ goto done;
+ extra_drain = 1;
+ break;
+ case EVBUFFER_EOL_NUL:
+ if (evbuffer_strchr(&it, '\0') < 0)
+ goto done;
+ extra_drain = 1;
+ break;
+ default:
+ goto done;
+ }
+
+ ok = 1;
+done:
+ EVBUFFER_UNLOCK(buffer);
+
+ if (!ok)
+ PTR_NOT_FOUND(&it);
+ if (eol_len_out)
+ *eol_len_out = extra_drain;
+
+ return it;
+}
+
+char *
+evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
+ enum evbuffer_eol_style eol_style)
+{
+ struct evbuffer_ptr it;
+ char *line;
+ size_t n_to_copy=0, extra_drain=0;
+ char *result = NULL;
+
+ EVBUFFER_LOCK(buffer);
+
+ if (buffer->freeze_start) {
+ goto done;
+ }
+
+ it = evbuffer_search_eol(buffer, NULL, &extra_drain, eol_style);
+ if (it.pos < 0)
+ goto done;
+ n_to_copy = it.pos;
+
+ if ((line = mm_malloc(n_to_copy+1)) == NULL) {
+ event_warn("%s: out of memory", __func__);
+ goto done;
+ }
+
+ evbuffer_remove(buffer, line, n_to_copy);
+ line[n_to_copy] = '\0';
+
+ evbuffer_drain(buffer, extra_drain);
+ result = line;
+done:
+ EVBUFFER_UNLOCK(buffer);
+
+ if (n_read_out)
+ *n_read_out = result ? n_to_copy : 0;
+
+ return result;
+}
+
+#define EVBUFFER_CHAIN_MAX_AUTO_SIZE 4096
+
+/* Adds data to an event buffer */
+
+int
+evbuffer_add(struct evbuffer *buf, const void *data_in, size_t datlen)
+{
+ struct evbuffer_chain *chain, *tmp;
+ const unsigned char *data = data_in;
+ size_t remain, to_alloc;
+ int result = -1;
+
+ EVBUFFER_LOCK(buf);
+
+ if (buf->freeze_end) {
+ goto done;
+ }
+ /* Prevent buf->total_len overflow */
+ if (datlen > EV_SIZE_MAX - buf->total_len) {
+ goto done;
+ }
+
+ if (*buf->last_with_datap == NULL) {
+ chain = buf->last;
+ } else {
+ chain = *buf->last_with_datap;
+ }
+
+ /* If there are no chains allocated for this buffer, allocate one
+ * big enough to hold all the data. */
+ if (chain == NULL) {
+ chain = evbuffer_chain_new(datlen);
+ if (!chain)
+ goto done;
+ evbuffer_chain_insert(buf, chain);
+ }
+
+ if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
+ /* Always true for mutable buffers */
+ EVUTIL_ASSERT(chain->misalign >= 0 &&
+ (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
+ remain = chain->buffer_len - (size_t)chain->misalign - chain->off;
+ if (remain >= datlen) {
+ /* there's enough space to hold all the data in the
+ * current last chain */
+ memcpy(chain->buffer + chain->misalign + chain->off,
+ data, datlen);
+ chain->off += datlen;
+ buf->total_len += datlen;
+ buf->n_add_for_cb += datlen;
+ goto out;
+ } else if (!CHAIN_PINNED(chain) &&
+ evbuffer_chain_should_realign(chain, datlen)) {
+ /* we can fit the data into the misalignment */
+ evbuffer_chain_align(chain);
+
+ memcpy(chain->buffer + chain->off, data, datlen);
+ chain->off += datlen;
+ buf->total_len += datlen;
+ buf->n_add_for_cb += datlen;
+ goto out;
+ }
+ } else {
+ /* we cannot write any data to the last chain */
+ remain = 0;
+ }
+
+ /* we need to add another chain */
+ to_alloc = chain->buffer_len;
+ if (to_alloc <= EVBUFFER_CHAIN_MAX_AUTO_SIZE/2)
+ to_alloc <<= 1;
+ if (datlen > to_alloc)
+ to_alloc = datlen;
+ tmp = evbuffer_chain_new(to_alloc);
+ if (tmp == NULL)
+ goto done;
+
+ if (remain) {
+ memcpy(chain->buffer + chain->misalign + chain->off,
+ data, remain);
+ chain->off += remain;
+ buf->total_len += remain;
+ buf->n_add_for_cb += remain;
+ }
+
+ data += remain;
+ datlen -= remain;
+
+ memcpy(tmp->buffer, data, datlen);
+ tmp->off = datlen;
+ evbuffer_chain_insert(buf, tmp);
+ buf->n_add_for_cb += datlen;
+
+out:
+ evbuffer_invoke_callbacks_(buf);
+ result = 0;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+int
+evbuffer_prepend(struct evbuffer *buf, const void *data, size_t datlen)
+{
+ struct evbuffer_chain *chain, *tmp;
+ int result = -1;
+
+ EVBUFFER_LOCK(buf);
+
+ if (datlen == 0) {
+ result = 0;
+ goto done;
+ }
+ if (buf->freeze_start) {
+ goto done;
+ }
+ if (datlen > EV_SIZE_MAX - buf->total_len) {
+ goto done;
+ }
+
+ chain = buf->first;
+
+ if (chain == NULL) {
+ chain = evbuffer_chain_new(datlen);
+ if (!chain)
+ goto done;
+ evbuffer_chain_insert(buf, chain);
+ }
+
+ /* we cannot touch immutable buffers */
+ if ((chain->flags & EVBUFFER_IMMUTABLE) == 0) {
+ /* Always true for mutable buffers */
+ EVUTIL_ASSERT(chain->misalign >= 0 &&
+ (ev_uint64_t)chain->misalign <= EVBUFFER_CHAIN_MAX);
+
+ /* If this chain is empty, we can treat it as
+ * 'empty at the beginning' rather than 'empty at the end' */
+ if (chain->off == 0)
+ chain->misalign = chain->buffer_len;
+
+ if ((size_t)chain->misalign >= datlen) {
+ /* we have enough space to fit everything */
+ memcpy(chain->buffer + chain->misalign - datlen,
+ data, datlen);
+ chain->off += datlen;
+ chain->misalign -= datlen;
+ buf->total_len += datlen;
+ buf->n_add_for_cb += datlen;
+ goto out;
+ } else if (chain->misalign) {
+ /* we can only fit some of the data. */
+ memcpy(chain->buffer,
+ (char*)data + datlen - chain->misalign,
+ (size_t)chain->misalign);
+ chain->off += (size_t)chain->misalign;
+ buf->total_len += (size_t)chain->misalign;
+ buf->n_add_for_cb += (size_t)chain->misalign;
+ datlen -= (size_t)chain->misalign;
+ chain->misalign = 0;
+ }
+ }
+
+ /* we need to add another chain */
+ if ((tmp = evbuffer_chain_new(datlen)) == NULL)
+ goto done;
+ buf->first = tmp;
+ if (buf->last_with_datap == &buf->first && chain->off)
+ buf->last_with_datap = &tmp->next;
+
+ tmp->next = chain;
+
+ tmp->off = datlen;
+ EVUTIL_ASSERT(datlen <= tmp->buffer_len);
+ tmp->misalign = tmp->buffer_len - datlen;
+
+ memcpy(tmp->buffer + tmp->misalign, data, datlen);
+ buf->total_len += datlen;
+ buf->n_add_for_cb += datlen;
+
+out:
+ evbuffer_invoke_callbacks_(buf);
+ result = 0;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+/** Helper: realigns the memory in chain->buffer so that misalign is 0. */
+static void
+evbuffer_chain_align(struct evbuffer_chain *chain)
+{
+ EVUTIL_ASSERT(!(chain->flags & EVBUFFER_IMMUTABLE));
+ EVUTIL_ASSERT(!(chain->flags & EVBUFFER_MEM_PINNED_ANY));
+ memmove(chain->buffer, chain->buffer + chain->misalign, chain->off);
+ chain->misalign = 0;
+}
+
+#define MAX_TO_COPY_IN_EXPAND 4096
+#define MAX_TO_REALIGN_IN_EXPAND 2048
+
+/** Helper: return true iff we should realign chain to fit datalen bytes of
+ data in it. */
+static int
+evbuffer_chain_should_realign(struct evbuffer_chain *chain,
+ size_t datlen)
+{
+ return chain->buffer_len - chain->off >= datlen &&
+ (chain->off < chain->buffer_len / 2) &&
+ (chain->off <= MAX_TO_REALIGN_IN_EXPAND);
+}
+
+/* Expands the available space in the event buffer to at least datlen, all in
+ * a single chunk. Return that chunk. */
+static struct evbuffer_chain *
+evbuffer_expand_singlechain(struct evbuffer *buf, size_t datlen)
+{
+ struct evbuffer_chain *chain, **chainp;
+ struct evbuffer_chain *result = NULL;
+ ASSERT_EVBUFFER_LOCKED(buf);
+
+ chainp = buf->last_with_datap;
+
+ /* XXX If *chainp is no longer writeable, but has enough space in its
+ * misalign, this might be a bad idea: we could still use *chainp, not
+ * (*chainp)->next. */
+ if (*chainp && CHAIN_SPACE_LEN(*chainp) == 0)
+ chainp = &(*chainp)->next;
+
+ /* 'chain' now points to the first chain with writable space (if any)
+ * We will either use it, realign it, replace it, or resize it. */
+ chain = *chainp;
+
+ if (chain == NULL ||
+ (chain->flags & (EVBUFFER_IMMUTABLE|EVBUFFER_MEM_PINNED_ANY))) {
+ /* We can't use the last_with_data chain at all. Just add a
+ * new one that's big enough. */
+ goto insert_new;
+ }
+
+ /* If we can fit all the data, then we don't have to do anything */
+ if (CHAIN_SPACE_LEN(chain) >= datlen) {
+ result = chain;
+ goto ok;
+ }
+
+ /* If the chain is completely empty, just replace it by adding a new
+ * empty chain. */
+ if (chain->off == 0) {
+ goto insert_new;
+ }
+
+ /* If the misalignment plus the remaining space fulfills our data
+ * needs, we could just force an alignment to happen. Afterwards, we
+ * have enough space. But only do this if we're saving a lot of space
+ * and not moving too much data. Otherwise the space savings are
+ * probably offset by the time lost in copying.
+ */
+ if (evbuffer_chain_should_realign(chain, datlen)) {
+ evbuffer_chain_align(chain);
+ result = chain;
+ goto ok;
+ }
+
+ /* At this point, we can either resize the last chunk with space in
+ * it, use the next chunk after it, or If we add a new chunk, we waste
+ * CHAIN_SPACE_LEN(chain) bytes in the former last chunk. If we
+ * resize, we have to copy chain->off bytes.
+ */
+
+ /* Would expanding this chunk be affordable and worthwhile? */
+ if (CHAIN_SPACE_LEN(chain) < chain->buffer_len / 8 ||
+ chain->off > MAX_TO_COPY_IN_EXPAND ||
+ datlen >= (EVBUFFER_CHAIN_MAX - chain->off)) {
+ /* It's not worth resizing this chain. Can the next one be
+ * used? */
+ if (chain->next && CHAIN_SPACE_LEN(chain->next) >= datlen) {
+ /* Yes, we can just use the next chain (which should
+ * be empty. */
+ result = chain->next;
+ goto ok;
+ } else {
+ /* No; append a new chain (which will free all
+ * terminal empty chains.) */
+ goto insert_new;
+ }
+ } else {
+ /* Okay, we're going to try to resize this chain: Not doing so
+ * would waste at least 1/8 of its current allocation, and we
+ * can do so without having to copy more than
+ * MAX_TO_COPY_IN_EXPAND bytes. */
+ /* figure out how much space we need */
+ size_t length = chain->off + datlen;
+ struct evbuffer_chain *tmp = evbuffer_chain_new(length);
+ if (tmp == NULL)
+ goto err;
+
+ /* copy the data over that we had so far */
+ tmp->off = chain->off;
+ memcpy(tmp->buffer, chain->buffer + chain->misalign,
+ chain->off);
+ /* fix up the list */
+ EVUTIL_ASSERT(*chainp == chain);
+ result = *chainp = tmp;
+
+ if (buf->last == chain)
+ buf->last = tmp;
+
+ tmp->next = chain->next;
+ evbuffer_chain_free(chain);
+ goto ok;
+ }
+
+insert_new:
+ result = evbuffer_chain_insert_new(buf, datlen);
+ if (!result)
+ goto err;
+ok:
+ EVUTIL_ASSERT(result);
+ EVUTIL_ASSERT(CHAIN_SPACE_LEN(result) >= datlen);
+err:
+ return result;
+}
+
+/* Make sure that datlen bytes are available for writing in the last n
+ * chains. Never copies or moves data. */
+int
+evbuffer_expand_fast_(struct evbuffer *buf, size_t datlen, int n)
+{
+ struct evbuffer_chain *chain = buf->last, *tmp, *next;
+ size_t avail;
+ int used;
+
+ ASSERT_EVBUFFER_LOCKED(buf);
+ EVUTIL_ASSERT(n >= 2);
+
+ if (chain == NULL || (chain->flags & EVBUFFER_IMMUTABLE)) {
+ /* There is no last chunk, or we can't touch the last chunk.
+ * Just add a new chunk. */
+ chain = evbuffer_chain_new(datlen);
+ if (chain == NULL)
+ return (-1);
+
+ evbuffer_chain_insert(buf, chain);
+ return (0);
+ }
+
+ used = 0; /* number of chains we're using space in. */
+ avail = 0; /* how much space they have. */
+ /* How many bytes can we stick at the end of buffer as it is? Iterate
+ * over the chains at the end of the buffer, tring to see how much
+ * space we have in the first n. */
+ for (chain = *buf->last_with_datap; chain; chain = chain->next) {
+ if (chain->off) {
+ size_t space = (size_t) CHAIN_SPACE_LEN(chain);
+ EVUTIL_ASSERT(chain == *buf->last_with_datap);
+ if (space) {
+ avail += space;
+ ++used;
+ }
+ } else {
+ /* No data in chain; realign it. */
+ chain->misalign = 0;
+ avail += chain->buffer_len;
+ ++used;
+ }
+ if (avail >= datlen) {
+ /* There is already enough space. Just return */
+ return (0);
+ }
+ if (used == n)
+ break;
+ }
+
+ /* There wasn't enough space in the first n chains with space in
+ * them. Either add a new chain with enough space, or replace all
+ * empty chains with one that has enough space, depending on n. */
+ if (used < n) {
+ /* The loop ran off the end of the chains before it hit n
+ * chains; we can add another. */
+ EVUTIL_ASSERT(chain == NULL);
+
+ tmp = evbuffer_chain_new(datlen - avail);
+ if (tmp == NULL)
+ return (-1);
+
+ buf->last->next = tmp;
+ buf->last = tmp;
+ /* (we would only set last_with_data if we added the first
+ * chain. But if the buffer had no chains, we would have
+ * just allocated a new chain earlier) */
+ return (0);
+ } else {
+ /* Nuke _all_ the empty chains. */
+ int rmv_all = 0; /* True iff we removed last_with_data. */
+ chain = *buf->last_with_datap;
+ if (!chain->off) {
+ EVUTIL_ASSERT(chain == buf->first);
+ rmv_all = 1;
+ avail = 0;
+ } else {
+ /* can't overflow, since only mutable chains have
+ * huge misaligns. */
+ avail = (size_t) CHAIN_SPACE_LEN(chain);
+ chain = chain->next;
+ }
+
+
+ for (; chain; chain = next) {
+ next = chain->next;
+ EVUTIL_ASSERT(chain->off == 0);
+ evbuffer_chain_free(chain);
+ }
+ EVUTIL_ASSERT(datlen >= avail);
+ tmp = evbuffer_chain_new(datlen - avail);
+ if (tmp == NULL) {
+ if (rmv_all) {
+ ZERO_CHAIN(buf);
+ } else {
+ buf->last = *buf->last_with_datap;
+ (*buf->last_with_datap)->next = NULL;
+ }
+ return (-1);
+ }
+
+ if (rmv_all) {
+ buf->first = buf->last = tmp;
+ buf->last_with_datap = &buf->first;
+ } else {
+ (*buf->last_with_datap)->next = tmp;
+ buf->last = tmp;
+ }
+ return (0);
+ }
+}
+
+int
+evbuffer_expand(struct evbuffer *buf, size_t datlen)
+{
+ struct evbuffer_chain *chain;
+
+ EVBUFFER_LOCK(buf);
+ chain = evbuffer_expand_singlechain(buf, datlen);
+ EVBUFFER_UNLOCK(buf);
+ return chain ? 0 : -1;
+}
+
+/*
+ * Reads data from a file descriptor into a buffer.
+ */
+
+#if defined(EVENT__HAVE_SYS_UIO_H) || defined(_WIN32)
+#define USE_IOVEC_IMPL
+#endif
+
+#ifdef USE_IOVEC_IMPL
+
+#ifdef EVENT__HAVE_SYS_UIO_H
+/* number of iovec we use for writev, fragmentation is going to determine
+ * how much we end up writing */
+
+#define DEFAULT_WRITE_IOVEC 128
+
+#if defined(UIO_MAXIOV) && UIO_MAXIOV < DEFAULT_WRITE_IOVEC
+#define NUM_WRITE_IOVEC UIO_MAXIOV
+#elif defined(IOV_MAX) && IOV_MAX < DEFAULT_WRITE_IOVEC
+#define NUM_WRITE_IOVEC IOV_MAX
+#else
+#define NUM_WRITE_IOVEC DEFAULT_WRITE_IOVEC
+#endif
+
+#define IOV_TYPE struct iovec
+#define IOV_PTR_FIELD iov_base
+#define IOV_LEN_FIELD iov_len
+#define IOV_LEN_TYPE size_t
+#else
+#define NUM_WRITE_IOVEC 16
+#define IOV_TYPE WSABUF
+#define IOV_PTR_FIELD buf
+#define IOV_LEN_FIELD len
+#define IOV_LEN_TYPE unsigned long
+#endif
+#endif
+#define NUM_READ_IOVEC 4
+
+#define EVBUFFER_MAX_READ 4096
+
+/** Helper function to figure out which space to use for reading data into
+ an evbuffer. Internal use only.
+
+ @param buf The buffer to read into
+ @param howmuch How much we want to read.
+ @param vecs An array of two or more iovecs or WSABUFs.
+ @param n_vecs_avail The length of vecs
+ @param chainp A pointer to a variable to hold the first chain we're
+ reading into.
+ @param exact Boolean: if true, we do not provide more than 'howmuch'
+ space in the vectors, even if more space is available.
+ @return The number of buffers we're using.
+ */
+int
+evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
+ struct evbuffer_iovec *vecs, int n_vecs_avail,
+ struct evbuffer_chain ***chainp, int exact)
+{
+ struct evbuffer_chain *chain;
+ struct evbuffer_chain **firstchainp;
+ size_t so_far;
+ int i;
+ ASSERT_EVBUFFER_LOCKED(buf);
+
+ if (howmuch < 0)
+ return -1;
+
+ so_far = 0;
+ /* Let firstchain be the first chain with any space on it */
+ firstchainp = buf->last_with_datap;
+ EVUTIL_ASSERT(*firstchainp);
+ if (CHAIN_SPACE_LEN(*firstchainp) == 0) {
+ firstchainp = &(*firstchainp)->next;
+ }
+
+ chain = *firstchainp;
+ EVUTIL_ASSERT(chain);
+ for (i = 0; i < n_vecs_avail && so_far < (size_t)howmuch; ++i) {
+ size_t avail = (size_t) CHAIN_SPACE_LEN(chain);
+ if (avail > (howmuch - so_far) && exact)
+ avail = howmuch - so_far;
+ vecs[i].iov_base = (void *)CHAIN_SPACE_PTR(chain);
+ vecs[i].iov_len = avail;
+ so_far += avail;
+ chain = chain->next;
+ }
+
+ *chainp = firstchainp;
+ return i;
+}
+
+static int
+get_n_bytes_readable_on_socket(evutil_socket_t fd)
+{
+#if defined(FIONREAD) && defined(_WIN32)
+ unsigned long lng = EVBUFFER_MAX_READ;
+ if (ioctlsocket(fd, FIONREAD, &lng) < 0)
+ return -1;
+ /* Can overflow, but mostly harmlessly. XXXX */
+ return (int)lng;
+#elif defined(FIONREAD)
+ int n = EVBUFFER_MAX_READ;
+ if (ioctl(fd, FIONREAD, &n) < 0)
+ return -1;
+ return n;
+#else
+ return EVBUFFER_MAX_READ;
+#endif
+}
+
+/* TODO(niels): should this function return ev_ssize_t and take ev_ssize_t
+ * as howmuch? */
+int
+evbuffer_read(struct evbuffer *buf, evutil_socket_t fd, int howmuch)
+{
+ struct evbuffer_chain **chainp;
+ int n;
+ int result;
+
+#ifdef USE_IOVEC_IMPL
+ int nvecs, i, remaining;
+#else
+ struct evbuffer_chain *chain;
+ unsigned char *p;
+#endif
+
+ EVBUFFER_LOCK(buf);
+
+ if (buf->freeze_end) {
+ result = -1;
+ goto done;
+ }
+
+ n = get_n_bytes_readable_on_socket(fd);
+ if (n <= 0 || n > EVBUFFER_MAX_READ)
+ n = EVBUFFER_MAX_READ;
+ if (howmuch < 0 || howmuch > n)
+ howmuch = n;
+
+#ifdef USE_IOVEC_IMPL
+ /* Since we can use iovecs, we're willing to use the last
+ * NUM_READ_IOVEC chains. */
+ if (evbuffer_expand_fast_(buf, howmuch, NUM_READ_IOVEC) == -1) {
+ result = -1;
+ goto done;
+ } else {
+ IOV_TYPE vecs[NUM_READ_IOVEC];
+#ifdef EVBUFFER_IOVEC_IS_NATIVE_
+ nvecs = evbuffer_read_setup_vecs_(buf, howmuch, vecs,
+ NUM_READ_IOVEC, &chainp, 1);
+#else
+ /* We aren't using the native struct iovec. Therefore,
+ we are on win32. */
+ struct evbuffer_iovec ev_vecs[NUM_READ_IOVEC];
+ nvecs = evbuffer_read_setup_vecs_(buf, howmuch, ev_vecs, 2,
+ &chainp, 1);
+
+ for (i=0; i < nvecs; ++i)
+ WSABUF_FROM_EVBUFFER_IOV(&vecs[i], &ev_vecs[i]);
+#endif
+
+#ifdef _WIN32
+ {
+ DWORD bytesRead;
+ DWORD flags=0;
+ if (WSARecv(fd, vecs, nvecs, &bytesRead, &flags, NULL, NULL)) {
+ /* The read failed. It might be a close,
+ * or it might be an error. */
+ if (WSAGetLastError() == WSAECONNABORTED)
+ n = 0;
+ else
+ n = -1;
+ } else
+ n = bytesRead;
+ }
+#else
+ n = readv(fd, vecs, nvecs);
+#endif
+ }
+
+#else /*!USE_IOVEC_IMPL*/
+ /* If we don't have FIONREAD, we might waste some space here */
+ /* XXX we _will_ waste some space here if there is any space left
+ * over on buf->last. */
+ if ((chain = evbuffer_expand_singlechain(buf, howmuch)) == NULL) {
+ result = -1;
+ goto done;
+ }
+
+ /* We can append new data at this point */
+ p = chain->buffer + chain->misalign + chain->off;
+
+#ifndef _WIN32
+ n = read(fd, p, howmuch);
+#else
+ n = recv(fd, p, howmuch, 0);
+#endif
+#endif /* USE_IOVEC_IMPL */
+
+ if (n == -1) {
+ result = -1;
+ goto done;
+ }
+ if (n == 0) {
+ result = 0;
+ goto done;
+ }
+
+#ifdef USE_IOVEC_IMPL
+ remaining = n;
+ for (i=0; i < nvecs; ++i) {
+ /* can't overflow, since only mutable chains have
+ * huge misaligns. */
+ size_t space = (size_t) CHAIN_SPACE_LEN(*chainp);
+ /* XXXX This is a kludge that can waste space in perverse
+ * situations. */
+ if (space > EVBUFFER_CHAIN_MAX)
+ space = EVBUFFER_CHAIN_MAX;
+ if ((ev_ssize_t)space < remaining) {
+ (*chainp)->off += space;
+ remaining -= (int)space;
+ } else {
+ (*chainp)->off += remaining;
+ buf->last_with_datap = chainp;
+ break;
+ }
+ chainp = &(*chainp)->next;
+ }
+#else
+ chain->off += n;
+ advance_last_with_data(buf);
+#endif
+ buf->total_len += n;
+ buf->n_add_for_cb += n;
+
+ /* Tell someone about changes in this buffer */
+ evbuffer_invoke_callbacks_(buf);
+ result = n;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+#ifdef USE_IOVEC_IMPL
+static inline int
+evbuffer_write_iovec(struct evbuffer *buffer, evutil_socket_t fd,
+ ev_ssize_t howmuch)
+{
+ IOV_TYPE iov[NUM_WRITE_IOVEC];
+ struct evbuffer_chain *chain = buffer->first;
+ int n, i = 0;
+
+ if (howmuch < 0)
+ return -1;
+
+ ASSERT_EVBUFFER_LOCKED(buffer);
+ /* XXX make this top out at some maximal data length? if the
+ * buffer has (say) 1MB in it, split over 128 chains, there's
+ * no way it all gets written in one go. */
+ while (chain != NULL && i < NUM_WRITE_IOVEC && howmuch) {
+#ifdef USE_SENDFILE
+ /* we cannot write the file info via writev */
+ if (chain->flags & EVBUFFER_SENDFILE)
+ break;
+#endif
+ iov[i].IOV_PTR_FIELD = (void *) (chain->buffer + chain->misalign);
+ if ((size_t)howmuch >= chain->off) {
+ /* XXXcould be problematic when windows supports mmap*/
+ iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)chain->off;
+ howmuch -= chain->off;
+ } else {
+ /* XXXcould be problematic when windows supports mmap*/
+ iov[i++].IOV_LEN_FIELD = (IOV_LEN_TYPE)howmuch;
+ break;
+ }
+ chain = chain->next;
+ }
+ if (! i)
+ return 0;
+
+#ifdef _WIN32
+ {
+ DWORD bytesSent;
+ if (WSASend(fd, iov, i, &bytesSent, 0, NULL, NULL))
+ n = -1;
+ else
+ n = bytesSent;
+ }
+#else
+ n = writev(fd, iov, i);
+#endif
+ return (n);
+}
+#endif
+
+#ifdef USE_SENDFILE
+static inline int
+evbuffer_write_sendfile(struct evbuffer *buffer, evutil_socket_t dest_fd,
+ ev_ssize_t howmuch)
+{
+ struct evbuffer_chain *chain = buffer->first;
+ struct evbuffer_chain_file_segment *info =
+ EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment,
+ chain);
+ const int source_fd = info->segment->fd;
+#if defined(SENDFILE_IS_MACOSX) || defined(SENDFILE_IS_FREEBSD)
+ int res;
+ ev_off_t len = chain->off;
+#elif defined(SENDFILE_IS_LINUX) || defined(SENDFILE_IS_SOLARIS)
+ ev_ssize_t res;
+ off_t offset = chain->misalign;
+#endif
+
+ ASSERT_EVBUFFER_LOCKED(buffer);
+
+#if defined(SENDFILE_IS_MACOSX)
+ res = sendfile(source_fd, dest_fd, chain->misalign, &len, NULL, 0);
+ if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
+ return (-1);
+
+ return (len);
+#elif defined(SENDFILE_IS_FREEBSD)
+ res = sendfile(source_fd, dest_fd, chain->misalign, chain->off, NULL, &len, 0);
+ if (res == -1 && !EVUTIL_ERR_RW_RETRIABLE(errno))
+ return (-1);
+
+ return (len);
+#elif defined(SENDFILE_IS_LINUX)
+ /* TODO(niels): implement splice */
+ res = sendfile(dest_fd, source_fd, &offset, chain->off);
+ if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
+ /* if this is EAGAIN or EINTR return 0; otherwise, -1 */
+ return (0);
+ }
+ return (res);
+#elif defined(SENDFILE_IS_SOLARIS)
+ {
+ const off_t offset_orig = offset;
+ res = sendfile(dest_fd, source_fd, &offset, chain->off);
+ if (res == -1 && EVUTIL_ERR_RW_RETRIABLE(errno)) {
+ if (offset - offset_orig)
+ return offset - offset_orig;
+ /* if this is EAGAIN or EINTR and no bytes were
+ * written, return 0 */
+ return (0);
+ }
+ return (res);
+ }
+#endif
+}
+#endif
+
+int
+evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
+ ev_ssize_t howmuch)
+{
+ int n = -1;
+
+ EVBUFFER_LOCK(buffer);
+
+ if (buffer->freeze_start) {
+ goto done;
+ }
+
+ if (howmuch < 0 || (size_t)howmuch > buffer->total_len)
+ howmuch = buffer->total_len;
+
+ if (howmuch > 0) {
+#ifdef USE_SENDFILE
+ struct evbuffer_chain *chain = buffer->first;
+ if (chain != NULL && (chain->flags & EVBUFFER_SENDFILE))
+ n = evbuffer_write_sendfile(buffer, fd, howmuch);
+ else {
+#endif
+#ifdef USE_IOVEC_IMPL
+ n = evbuffer_write_iovec(buffer, fd, howmuch);
+#elif defined(_WIN32)
+ /* XXX(nickm) Don't disable this code until we know if
+ * the WSARecv code above works. */
+ void *p = evbuffer_pullup(buffer, howmuch);
+ EVUTIL_ASSERT(p || !howmuch);
+ n = send(fd, p, howmuch, 0);
+#else
+ void *p = evbuffer_pullup(buffer, howmuch);
+ EVUTIL_ASSERT(p || !howmuch);
+ n = write(fd, p, howmuch);
+#endif
+#ifdef USE_SENDFILE
+ }
+#endif
+ }
+
+ if (n > 0)
+ evbuffer_drain(buffer, n);
+
+done:
+ EVBUFFER_UNLOCK(buffer);
+ return (n);
+}
+
+int
+evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd)
+{
+ return evbuffer_write_atmost(buffer, fd, -1);
+}
+
+unsigned char *
+evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len)
+{
+ unsigned char *search;
+ struct evbuffer_ptr ptr;
+
+ EVBUFFER_LOCK(buffer);
+
+ ptr = evbuffer_search(buffer, (const char *)what, len, NULL);
+ if (ptr.pos < 0) {
+ search = NULL;
+ } else {
+ search = evbuffer_pullup(buffer, ptr.pos + len);
+ if (search)
+ search += ptr.pos;
+ }
+ EVBUFFER_UNLOCK(buffer);
+ return search;
+}
+
+/* Subract <b>howfar</b> from the position of <b>pos</b> within
+ * <b>buf</b>. Returns 0 on success, -1 on failure.
+ *
+ * This isn't exposed yet, because of potential inefficiency issues.
+ * Maybe it should be. */
+static int
+evbuffer_ptr_subtract(struct evbuffer *buf, struct evbuffer_ptr *pos,
+ size_t howfar)
+{
+ if (pos->pos < 0)
+ return -1;
+ if (howfar > (size_t)pos->pos)
+ return -1;
+ if (pos->internal_.chain && howfar <= pos->internal_.pos_in_chain) {
+ pos->internal_.pos_in_chain -= howfar;
+ pos->pos -= howfar;
+ return 0;
+ } else {
+ const size_t newpos = pos->pos - howfar;
+ /* Here's the inefficient part: it walks over the
+ * chains until we hit newpos. */
+ return evbuffer_ptr_set(buf, pos, newpos, EVBUFFER_PTR_SET);
+ }
+}
+
+int
+evbuffer_ptr_set(struct evbuffer *buf, struct evbuffer_ptr *pos,
+ size_t position, enum evbuffer_ptr_how how)
+{
+ size_t left = position;
+ struct evbuffer_chain *chain = NULL;
+ int result = 0;
+
+ EVBUFFER_LOCK(buf);
+
+ switch (how) {
+ case EVBUFFER_PTR_SET:
+ chain = buf->first;
+ pos->pos = position;
+ position = 0;
+ break;
+ case EVBUFFER_PTR_ADD:
+ /* this avoids iterating over all previous chains if
+ we just want to advance the position */
+ if (pos->pos < 0 || EV_SIZE_MAX - position < (size_t)pos->pos) {
+ EVBUFFER_UNLOCK(buf);
+ return -1;
+ }
+ chain = pos->internal_.chain;
+ pos->pos += position;
+ position = pos->internal_.pos_in_chain;
+ break;
+ }
+
+ EVUTIL_ASSERT(EV_SIZE_MAX - left >= position);
+ while (chain && position + left >= chain->off) {
+ left -= chain->off - position;
+ chain = chain->next;
+ position = 0;
+ }
+ if (chain) {
+ pos->internal_.chain = chain;
+ pos->internal_.pos_in_chain = position + left;
+ } else if (left == 0) {
+ /* The first byte in the (nonexistent) chain after the last chain */
+ pos->internal_.chain = NULL;
+ pos->internal_.pos_in_chain = 0;
+ } else {
+ PTR_NOT_FOUND(pos);
+ result = -1;
+ }
+
+ EVBUFFER_UNLOCK(buf);
+
+ return result;
+}
+
+/**
+ Compare the bytes in buf at position pos to the len bytes in mem. Return
+ less than 0, 0, or greater than 0 as memcmp.
+ */
+static int
+evbuffer_ptr_memcmp(const struct evbuffer *buf, const struct evbuffer_ptr *pos,
+ const char *mem, size_t len)
+{
+ struct evbuffer_chain *chain;
+ size_t position;
+ int r;
+
+ ASSERT_EVBUFFER_LOCKED(buf);
+
+ if (pos->pos < 0 ||
+ EV_SIZE_MAX - len < (size_t)pos->pos ||
+ pos->pos + len > buf->total_len)
+ return -1;
+
+ chain = pos->internal_.chain;
+ position = pos->internal_.pos_in_chain;
+ while (len && chain) {
+ size_t n_comparable;
+ if (len + position > chain->off)
+ n_comparable = chain->off - position;
+ else
+ n_comparable = len;
+ r = memcmp(chain->buffer + chain->misalign + position, mem,
+ n_comparable);
+ if (r)
+ return r;
+ mem += n_comparable;
+ len -= n_comparable;
+ position = 0;
+ chain = chain->next;
+ }
+
+ return 0;
+}
+
+struct evbuffer_ptr
+evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start)
+{
+ return evbuffer_search_range(buffer, what, len, start, NULL);
+}
+
+struct evbuffer_ptr
+evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end)
+{
+ struct evbuffer_ptr pos;
+ struct evbuffer_chain *chain, *last_chain = NULL;
+ const unsigned char *p;
+ char first;
+
+ EVBUFFER_LOCK(buffer);
+
+ if (start) {
+ memcpy(&pos, start, sizeof(pos));
+ chain = pos.internal_.chain;
+ } else {
+ pos.pos = 0;
+ chain = pos.internal_.chain = buffer->first;
+ pos.internal_.pos_in_chain = 0;
+ }
+
+ if (end)
+ last_chain = end->internal_.chain;
+
+ if (!len || len > EV_SSIZE_MAX)
+ goto done;
+
+ first = what[0];
+
+ while (chain) {
+ const unsigned char *start_at =
+ chain->buffer + chain->misalign +
+ pos.internal_.pos_in_chain;
+ p = memchr(start_at, first,
+ chain->off - pos.internal_.pos_in_chain);
+ if (p) {
+ pos.pos += p - start_at;
+ pos.internal_.pos_in_chain += p - start_at;
+ if (!evbuffer_ptr_memcmp(buffer, &pos, what, len)) {
+ if (end && pos.pos + (ev_ssize_t)len > end->pos)
+ goto not_found;
+ else
+ goto done;
+ }
+ ++pos.pos;
+ ++pos.internal_.pos_in_chain;
+ if (pos.internal_.pos_in_chain == chain->off) {
+ chain = pos.internal_.chain = chain->next;
+ pos.internal_.pos_in_chain = 0;
+ }
+ } else {
+ if (chain == last_chain)
+ goto not_found;
+ pos.pos += chain->off - pos.internal_.pos_in_chain;
+ chain = pos.internal_.chain = chain->next;
+ pos.internal_.pos_in_chain = 0;
+ }
+ }
+
+not_found:
+ PTR_NOT_FOUND(&pos);
+done:
+ EVBUFFER_UNLOCK(buffer);
+ return pos;
+}
+
+int
+evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
+ struct evbuffer_ptr *start_at,
+ struct evbuffer_iovec *vec, int n_vec)
+{
+ struct evbuffer_chain *chain;
+ int idx = 0;
+ ev_ssize_t len_so_far = 0;
+
+ /* Avoid locking in trivial edge cases */
+ if (start_at && start_at->internal_.chain == NULL)
+ return 0;
+
+ EVBUFFER_LOCK(buffer);
+
+ if (start_at) {
+ chain = start_at->internal_.chain;
+ len_so_far = chain->off
+ - start_at->internal_.pos_in_chain;
+ idx = 1;
+ if (n_vec > 0) {
+ vec[0].iov_base = (void *)(chain->buffer + chain->misalign
+ + start_at->internal_.pos_in_chain);
+ vec[0].iov_len = len_so_far;
+ }
+ chain = chain->next;
+ } else {
+ chain = buffer->first;
+ }
+
+ if (n_vec == 0 && len < 0) {
+ /* If no vectors are provided and they asked for "everything",
+ * pretend they asked for the actual available amount. */
+ len = buffer->total_len;
+ if (start_at) {
+ len -= start_at->pos;
+ }
+ }
+
+ while (chain) {
+ if (len >= 0 && len_so_far >= len)
+ break;
+ if (idx<n_vec) {
+ vec[idx].iov_base = (void *)(chain->buffer + chain->misalign);
+ vec[idx].iov_len = chain->off;
+ } else if (len<0) {
+ break;
+ }
+ ++idx;
+ len_so_far += chain->off;
+ chain = chain->next;
+ }
+
+ EVBUFFER_UNLOCK(buffer);
+
+ return idx;
+}
+
+
+int
+evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
+{
+ char *buffer;
+ size_t space;
+ int sz, result = -1;
+ va_list aq;
+ struct evbuffer_chain *chain;
+
+
+ EVBUFFER_LOCK(buf);
+
+ if (buf->freeze_end) {
+ goto done;
+ }
+
+ /* make sure that at least some space is available */
+ if ((chain = evbuffer_expand_singlechain(buf, 64)) == NULL)
+ goto done;
+
+ for (;;) {
+#if 0
+ size_t used = chain->misalign + chain->off;
+ buffer = (char *)chain->buffer + chain->misalign + chain->off;
+ EVUTIL_ASSERT(chain->buffer_len >= used);
+ space = chain->buffer_len - used;
+#endif
+ buffer = (char*) CHAIN_SPACE_PTR(chain);
+ space = (size_t) CHAIN_SPACE_LEN(chain);
+
+#ifndef va_copy
+#define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list))
+#endif
+ va_copy(aq, ap);
+
+ sz = evutil_vsnprintf(buffer, space, fmt, aq);
+
+ va_end(aq);
+
+ if (sz < 0)
+ goto done;
+ if (INT_MAX >= EVBUFFER_CHAIN_MAX &&
+ (size_t)sz >= EVBUFFER_CHAIN_MAX)
+ goto done;
+ if ((size_t)sz < space) {
+ chain->off += sz;
+ buf->total_len += sz;
+ buf->n_add_for_cb += sz;
+
+ advance_last_with_data(buf);
+ evbuffer_invoke_callbacks_(buf);
+ result = sz;
+ goto done;
+ }
+ if ((chain = evbuffer_expand_singlechain(buf, sz + 1)) == NULL)
+ goto done;
+ }
+ /* NOTREACHED */
+
+done:
+ EVBUFFER_UNLOCK(buf);
+ return result;
+}
+
+int
+evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
+{
+ int res = -1;
+ va_list ap;
+
+ va_start(ap, fmt);
+ res = evbuffer_add_vprintf(buf, fmt, ap);
+ va_end(ap);
+
+ return (res);
+}
+
+int
+evbuffer_add_reference(struct evbuffer *outbuf,
+ const void *data, size_t datlen,
+ evbuffer_ref_cleanup_cb cleanupfn, void *extra)
+{
+ struct evbuffer_chain *chain;
+ struct evbuffer_chain_reference *info;
+ int result = -1;
+
+ chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_reference));
+ if (!chain)
+ return (-1);
+ chain->flags |= EVBUFFER_REFERENCE | EVBUFFER_IMMUTABLE;
+ chain->buffer = (unsigned char *)data;
+ chain->buffer_len = datlen;
+ chain->off = datlen;
+
+ info = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_reference, chain);
+ info->cleanupfn = cleanupfn;
+ info->extra = extra;
+
+ EVBUFFER_LOCK(outbuf);
+ if (outbuf->freeze_end) {
+ /* don't call chain_free; we do not want to actually invoke
+ * the cleanup function */
+ mm_free(chain);
+ goto done;
+ }
+ evbuffer_chain_insert(outbuf, chain);
+ outbuf->n_add_for_cb += datlen;
+
+ evbuffer_invoke_callbacks_(outbuf);
+
+ result = 0;
+done:
+ EVBUFFER_UNLOCK(outbuf);
+
+ return result;
+}
+
+/* TODO(niels): we may want to add to automagically convert to mmap, in
+ * case evbuffer_remove() or evbuffer_pullup() are being used.
+ */
+struct evbuffer_file_segment *
+evbuffer_file_segment_new(
+ int fd, ev_off_t offset, ev_off_t length, unsigned flags)
+{
+ struct evbuffer_file_segment *seg =
+ mm_calloc(sizeof(struct evbuffer_file_segment), 1);
+ if (!seg)
+ return NULL;
+ seg->refcnt = 1;
+ seg->fd = fd;
+ seg->flags = flags;
+ seg->file_offset = offset;
+ seg->cleanup_cb = NULL;
+ seg->cleanup_cb_arg = NULL;
+#ifdef _WIN32
+#ifndef lseek
+#define lseek _lseeki64
+#endif
+#ifndef fstat
+#define fstat _fstat
+#endif
+#ifndef stat
+#define stat _stat
+#endif
+#endif
+ if (length == -1) {
+ struct stat st;
+ if (fstat(fd, &st) < 0)
+ goto err;
+ length = st.st_size;
+ }
+ seg->length = length;
+
+ if (offset < 0 || length < 0 ||
+ ((ev_uint64_t)length > EVBUFFER_CHAIN_MAX) ||
+ (ev_uint64_t)offset > (ev_uint64_t)(EVBUFFER_CHAIN_MAX - length))
+ goto err;
+
+#if defined(USE_SENDFILE)
+ if (!(flags & EVBUF_FS_DISABLE_SENDFILE)) {
+ seg->can_sendfile = 1;
+ goto done;
+ }
+#endif
+
+ if (evbuffer_file_segment_materialize(seg)<0)
+ goto err;
+
+#if defined(USE_SENDFILE)
+done:
+#endif
+ if (!(flags & EVBUF_FS_DISABLE_LOCKING)) {
+ EVTHREAD_ALLOC_LOCK(seg->lock, 0);
+ }
+ return seg;
+err:
+ mm_free(seg);
+ return NULL;
+}
+
+#ifdef EVENT__HAVE_MMAP
+static long
+get_page_size(void)
+{
+#ifdef SC_PAGE_SIZE
+ return sysconf(SC_PAGE_SIZE);
+#elif defined(_SC_PAGE_SIZE)
+ return sysconf(_SC_PAGE_SIZE);
+#else
+ return 1;
+#endif
+}
+#endif
+
+/* DOCDOC */
+/* Requires lock */
+static int
+evbuffer_file_segment_materialize(struct evbuffer_file_segment *seg)
+{
+ const unsigned flags = seg->flags;
+ const int fd = seg->fd;
+ const ev_off_t length = seg->length;
+ const ev_off_t offset = seg->file_offset;
+
+ if (seg->contents)
+ return 0; /* already materialized */
+
+#if defined(EVENT__HAVE_MMAP)
+ if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
+ off_t offset_rounded = 0, offset_leftover = 0;
+ void *mapped;
+ if (offset) {
+ /* mmap implementations don't generally like us
+ * to have an offset that isn't a round */
+ long page_size = get_page_size();
+ if (page_size == -1)
+ goto err;
+ offset_leftover = offset % page_size;
+ offset_rounded = offset - offset_leftover;
+ }
+ mapped = mmap(NULL, length + offset_leftover,
+ PROT_READ,
+#ifdef MAP_NOCACHE
+ MAP_NOCACHE | /* ??? */
+#endif
+#ifdef MAP_FILE
+ MAP_FILE |
+#endif
+ MAP_PRIVATE,
+ fd, offset_rounded);
+ if (mapped == MAP_FAILED) {
+ event_warn("%s: mmap(%d, %d, %zu) failed",
+ __func__, fd, 0, (size_t)(offset + length));
+ } else {
+ seg->mapping = mapped;
+ seg->contents = (char*)mapped+offset_leftover;
+ seg->mmap_offset = 0;
+ seg->is_mapping = 1;
+ goto done;
+ }
+ }
+#endif
+#ifdef _WIN32
+ if (!(flags & EVBUF_FS_DISABLE_MMAP)) {
+ intptr_t h = _get_osfhandle(fd);
+ HANDLE m;
+ ev_uint64_t total_size = length+offset;
+ if ((HANDLE)h == INVALID_HANDLE_VALUE)
+ goto err;
+ m = CreateFileMapping((HANDLE)h, NULL, PAGE_READONLY,
+ (total_size >> 32), total_size & 0xfffffffful,
+ NULL);
+ if (m != INVALID_HANDLE_VALUE) { /* Does h leak? */
+ seg->mapping_handle = m;
+ seg->mmap_offset = offset;
+ seg->is_mapping = 1;
+ goto done;
+ }
+ }
+#endif
+ {
+ ev_off_t start_pos = lseek(fd, 0, SEEK_CUR), pos;
+ ev_off_t read_so_far = 0;
+ char *mem;
+ int e;
+ ev_ssize_t n = 0;
+ if (!(mem = mm_malloc(length)))
+ goto err;
+ if (start_pos < 0) {
+ mm_free(mem);
+ goto err;
+ }
+ if (lseek(fd, offset, SEEK_SET) < 0) {
+ mm_free(mem);
+ goto err;
+ }
+ while (read_so_far < length) {
+ n = read(fd, mem+read_so_far, length-read_so_far);
+ if (n <= 0)
+ break;
+ read_so_far += n;
+ }
+
+ e = errno;
+ pos = lseek(fd, start_pos, SEEK_SET);
+ if (n < 0 || (n == 0 && length > read_so_far)) {
+ mm_free(mem);
+ errno = e;
+ goto err;
+ } else if (pos < 0) {
+ mm_free(mem);
+ goto err;
+ }
+
+ seg->contents = mem;
+ }
+
+done:
+ return 0;
+err:
+ return -1;
+}
+
+void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
+ evbuffer_file_segment_cleanup_cb cb, void* arg)
+{
+ EVUTIL_ASSERT(seg->refcnt > 0);
+ seg->cleanup_cb = cb;
+ seg->cleanup_cb_arg = arg;
+}
+
+void
+evbuffer_file_segment_free(struct evbuffer_file_segment *seg)
+{
+ int refcnt;
+ EVLOCK_LOCK(seg->lock, 0);
+ refcnt = --seg->refcnt;
+ EVLOCK_UNLOCK(seg->lock, 0);
+ if (refcnt > 0)
+ return;
+ EVUTIL_ASSERT(refcnt == 0);
+
+ if (seg->is_mapping) {
+#ifdef _WIN32
+ CloseHandle(seg->mapping_handle);
+#elif defined (EVENT__HAVE_MMAP)
+ off_t offset_leftover;
+ offset_leftover = seg->file_offset % get_page_size();
+ if (munmap(seg->mapping, seg->length + offset_leftover) == -1)
+ event_warn("%s: munmap failed", __func__);
+#endif
+ } else if (seg->contents) {
+ mm_free(seg->contents);
+ }
+
+ if ((seg->flags & EVBUF_FS_CLOSE_ON_FREE) && seg->fd >= 0) {
+ close(seg->fd);
+ }
+
+ if (seg->cleanup_cb) {
+ (*seg->cleanup_cb)((struct evbuffer_file_segment const*)seg,
+ seg->flags, seg->cleanup_cb_arg);
+ seg->cleanup_cb = NULL;
+ seg->cleanup_cb_arg = NULL;
+ }
+
+ EVTHREAD_FREE_LOCK(seg->lock, 0);
+ mm_free(seg);
+}
+
+int
+evbuffer_add_file_segment(struct evbuffer *buf,
+ struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length)
+{
+ struct evbuffer_chain *chain;
+ struct evbuffer_chain_file_segment *extra;
+ int can_use_sendfile = 0;
+
+ EVBUFFER_LOCK(buf);
+ EVLOCK_LOCK(seg->lock, 0);
+ if (buf->flags & EVBUFFER_FLAG_DRAINS_TO_FD) {
+ can_use_sendfile = 1;
+ } else {
+ if (!seg->contents) {
+ if (evbuffer_file_segment_materialize(seg)<0) {
+ EVLOCK_UNLOCK(seg->lock, 0);
+ EVBUFFER_UNLOCK(buf);
+ return -1;
+ }
+ }
+ }
+ EVLOCK_UNLOCK(seg->lock, 0);
+
+ if (buf->freeze_end)
+ goto err;
+
+ if (length < 0) {
+ if (offset > seg->length)
+ goto err;
+ length = seg->length - offset;
+ }
+
+ /* Can we actually add this? */
+ if (offset+length > seg->length)
+ goto err;
+
+ chain = evbuffer_chain_new(sizeof(struct evbuffer_chain_file_segment));
+ if (!chain)
+ goto err;
+ extra = EVBUFFER_CHAIN_EXTRA(struct evbuffer_chain_file_segment, chain);
+
+ chain->flags |= EVBUFFER_IMMUTABLE|EVBUFFER_FILESEGMENT;
+ if (can_use_sendfile && seg->can_sendfile) {
+ chain->flags |= EVBUFFER_SENDFILE;
+ chain->misalign = seg->file_offset + offset;
+ chain->off = length;
+ chain->buffer_len = chain->misalign + length;
+ } else if (seg->is_mapping) {
+#ifdef _WIN32
+ ev_uint64_t total_offset = seg->mmap_offset+offset;
+ ev_uint64_t offset_rounded=0, offset_remaining=0;
+ LPVOID data;
+ if (total_offset) {
+ SYSTEM_INFO si;
+ memset(&si, 0, sizeof(si)); /* cargo cult */
+ GetSystemInfo(&si);
+ offset_remaining = total_offset % si.dwAllocationGranularity;
+ offset_rounded = total_offset - offset_remaining;
+ }
+ data = MapViewOfFile(
+ seg->mapping_handle,
+ FILE_MAP_READ,
+ offset_rounded >> 32,
+ offset_rounded & 0xfffffffful,
+ length + offset_remaining);
+ if (data == NULL) {
+ mm_free(chain);
+ goto err;
+ }
+ chain->buffer = (unsigned char*) data;
+ chain->buffer_len = length+offset_remaining;
+ chain->misalign = offset_remaining;
+ chain->off = length;
+#else
+ chain->buffer = (unsigned char*)(seg->contents + offset);
+ chain->buffer_len = length;
+ chain->off = length;
+#endif
+ } else {
+ chain->buffer = (unsigned char*)(seg->contents + offset);
+ chain->buffer_len = length;
+ chain->off = length;
+ }
+
+ EVLOCK_LOCK(seg->lock, 0);
+ ++seg->refcnt;
+ EVLOCK_UNLOCK(seg->lock, 0);
+ extra->segment = seg;
+ buf->n_add_for_cb += length;
+ evbuffer_chain_insert(buf, chain);
+
+ evbuffer_invoke_callbacks_(buf);
+
+ EVBUFFER_UNLOCK(buf);
+
+ return 0;
+err:
+ EVBUFFER_UNLOCK(buf);
+ evbuffer_file_segment_free(seg); /* Lowers the refcount */
+ return -1;
+}
+
+int
+evbuffer_add_file(struct evbuffer *buf, int fd, ev_off_t offset, ev_off_t length)
+{
+ struct evbuffer_file_segment *seg;
+ unsigned flags = EVBUF_FS_CLOSE_ON_FREE;
+ int r;
+
+ seg = evbuffer_file_segment_new(fd, offset, length, flags);
+ if (!seg)
+ return -1;
+ r = evbuffer_add_file_segment(buf, seg, 0, length);
+ if (r == 0)
+ evbuffer_file_segment_free(seg);
+ return r;
+}
+
+int
+evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg)
+{
+ EVBUFFER_LOCK(buffer);
+
+ if (!LIST_EMPTY(&buffer->callbacks))
+ evbuffer_remove_all_callbacks(buffer);
+
+ if (cb) {
+ struct evbuffer_cb_entry *ent =
+ evbuffer_add_cb(buffer, NULL, cbarg);
+ if (!ent) {
+ EVBUFFER_UNLOCK(buffer);
+ return -1;
+ }
+ ent->cb.cb_obsolete = cb;
+ ent->flags |= EVBUFFER_CB_OBSOLETE;
+ }
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+struct evbuffer_cb_entry *
+evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
+{
+ struct evbuffer_cb_entry *e;
+ if (! (e = mm_calloc(1, sizeof(struct evbuffer_cb_entry))))
+ return NULL;
+ EVBUFFER_LOCK(buffer);
+ e->cb.cb_func = cb;
+ e->cbarg = cbarg;
+ e->flags = EVBUFFER_CB_ENABLED;
+ LIST_INSERT_HEAD(&buffer->callbacks, e, next);
+ EVBUFFER_UNLOCK(buffer);
+ return e;
+}
+
+int
+evbuffer_remove_cb_entry(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *ent)
+{
+ EVBUFFER_LOCK(buffer);
+ LIST_REMOVE(ent, next);
+ EVBUFFER_UNLOCK(buffer);
+ mm_free(ent);
+ return 0;
+}
+
+int
+evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg)
+{
+ struct evbuffer_cb_entry *cbent;
+ int result = -1;
+ EVBUFFER_LOCK(buffer);
+ LIST_FOREACH(cbent, &buffer->callbacks, next) {
+ if (cb == cbent->cb.cb_func && cbarg == cbent->cbarg) {
+ result = evbuffer_remove_cb_entry(buffer, cbent);
+ goto done;
+ }
+ }
+done:
+ EVBUFFER_UNLOCK(buffer);
+ return result;
+}
+
+int
+evbuffer_cb_set_flags(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *cb, ev_uint32_t flags)
+{
+ /* the user isn't allowed to mess with these. */
+ flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
+ EVBUFFER_LOCK(buffer);
+ cb->flags |= flags;
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+int
+evbuffer_cb_clear_flags(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *cb, ev_uint32_t flags)
+{
+ /* the user isn't allowed to mess with these. */
+ flags &= ~EVBUFFER_CB_INTERNAL_FLAGS;
+ EVBUFFER_LOCK(buffer);
+ cb->flags &= ~flags;
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+int
+evbuffer_freeze(struct evbuffer *buffer, int start)
+{
+ EVBUFFER_LOCK(buffer);
+ if (start)
+ buffer->freeze_start = 1;
+ else
+ buffer->freeze_end = 1;
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+int
+evbuffer_unfreeze(struct evbuffer *buffer, int start)
+{
+ EVBUFFER_LOCK(buffer);
+ if (start)
+ buffer->freeze_start = 0;
+ else
+ buffer->freeze_end = 0;
+ EVBUFFER_UNLOCK(buffer);
+ return 0;
+}
+
+#if 0
+void
+evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
+{
+ if (!(cb->flags & EVBUFFER_CB_SUSPENDED)) {
+ cb->size_before_suspend = evbuffer_get_length(buffer);
+ cb->flags |= EVBUFFER_CB_SUSPENDED;
+ }
+}
+
+void
+evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb)
+{
+ if ((cb->flags & EVBUFFER_CB_SUSPENDED)) {
+ unsigned call = (cb->flags & EVBUFFER_CB_CALL_ON_UNSUSPEND);
+ size_t sz = cb->size_before_suspend;
+ cb->flags &= ~(EVBUFFER_CB_SUSPENDED|
+ EVBUFFER_CB_CALL_ON_UNSUSPEND);
+ cb->size_before_suspend = 0;
+ if (call && (cb->flags & EVBUFFER_CB_ENABLED)) {
+ cb->cb(buffer, sz, evbuffer_get_length(buffer), cb->cbarg);
+ }
+ }
+}
+#endif
+
+int
+evbuffer_get_callbacks_(struct evbuffer *buffer, struct event_callback **cbs,
+ int max_cbs)
+{
+ int r = 0;
+ EVBUFFER_LOCK(buffer);
+ if (buffer->deferred_cbs) {
+ if (max_cbs < 1) {
+ r = -1;
+ goto done;
+ }
+ cbs[0] = &buffer->deferred;
+ r = 1;
+ }
+done:
+ EVBUFFER_UNLOCK(buffer);
+ return r;
+}
diff --git a/ipc/chromium/src/third_party/libevent/buffer_iocp.c b/ipc/chromium/src/third_party/libevent/buffer_iocp.c
new file mode 100644
index 0000000000..2af0c49cc6
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/buffer_iocp.c
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ @file buffer_iocp.c
+
+ This module implements overlapped read and write functions for evbuffer
+ objects on Windows.
+*/
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+#include "event2/thread.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#include "evbuffer-internal.h"
+#include "iocp-internal.h"
+#include "mm-internal.h"
+
+#include <winsock2.h>
+#include <winerror.h>
+#include <windows.h>
+#include <stdio.h>
+
+#define MAX_WSABUFS 16
+
+/** An evbuffer that can handle overlapped IO. */
+struct evbuffer_overlapped {
+ struct evbuffer buffer;
+ /** The socket that we're doing overlapped IO on. */
+ evutil_socket_t fd;
+
+ /** pending I/O type */
+ unsigned read_in_progress : 1;
+ unsigned write_in_progress : 1;
+
+ /** The first pinned chain in the buffer. */
+ struct evbuffer_chain *first_pinned;
+
+ /** How many chains are pinned; how many of the fields in buffers
+ * are we using. */
+ int n_buffers;
+ WSABUF buffers[MAX_WSABUFS];
+};
+
+/** Given an evbuffer, return the correponding evbuffer structure, or NULL if
+ * the evbuffer isn't overlapped. */
+static inline struct evbuffer_overlapped *
+upcast_evbuffer(struct evbuffer *buf)
+{
+ if (!buf || !buf->is_overlapped)
+ return NULL;
+ return EVUTIL_UPCAST(buf, struct evbuffer_overlapped, buffer);
+}
+
+/** Unpin all the chains noted as pinned in 'eo'. */
+static void
+pin_release(struct evbuffer_overlapped *eo, unsigned flag)
+{
+ int i;
+ struct evbuffer_chain *next, *chain = eo->first_pinned;
+
+ for (i = 0; i < eo->n_buffers; ++i) {
+ EVUTIL_ASSERT(chain);
+ next = chain->next;
+ evbuffer_chain_unpin_(chain, flag);
+ chain = next;
+ }
+}
+
+void
+evbuffer_commit_read_(struct evbuffer *evbuf, ev_ssize_t nBytes)
+{
+ struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
+ struct evbuffer_chain **chainp;
+ size_t remaining, len;
+ unsigned i;
+
+ EVBUFFER_LOCK(evbuf);
+ EVUTIL_ASSERT(buf->read_in_progress && !buf->write_in_progress);
+ EVUTIL_ASSERT(nBytes >= 0); /* XXXX Can this be false? */
+
+ evbuffer_unfreeze(evbuf, 0);
+
+ chainp = evbuf->last_with_datap;
+ if (!((*chainp)->flags & EVBUFFER_MEM_PINNED_R))
+ chainp = &(*chainp)->next;
+ remaining = nBytes;
+ for (i = 0; remaining > 0 && i < (unsigned)buf->n_buffers; ++i) {
+ EVUTIL_ASSERT(*chainp);
+ len = buf->buffers[i].len;
+ if (remaining < len)
+ len = remaining;
+ (*chainp)->off += len;
+ evbuf->last_with_datap = chainp;
+ remaining -= len;
+ chainp = &(*chainp)->next;
+ }
+
+ pin_release(buf, EVBUFFER_MEM_PINNED_R);
+
+ buf->read_in_progress = 0;
+
+ evbuf->total_len += nBytes;
+ evbuf->n_add_for_cb += nBytes;
+
+ evbuffer_invoke_callbacks_(evbuf);
+
+ evbuffer_decref_and_unlock_(evbuf);
+}
+
+void
+evbuffer_commit_write_(struct evbuffer *evbuf, ev_ssize_t nBytes)
+{
+ struct evbuffer_overlapped *buf = upcast_evbuffer(evbuf);
+
+ EVBUFFER_LOCK(evbuf);
+ EVUTIL_ASSERT(buf->write_in_progress && !buf->read_in_progress);
+ evbuffer_unfreeze(evbuf, 1);
+ evbuffer_drain(evbuf, nBytes);
+ pin_release(buf,EVBUFFER_MEM_PINNED_W);
+ buf->write_in_progress = 0;
+ evbuffer_decref_and_unlock_(evbuf);
+}
+
+struct evbuffer *
+evbuffer_overlapped_new_(evutil_socket_t fd)
+{
+ struct evbuffer_overlapped *evo;
+
+ evo = mm_calloc(1, sizeof(struct evbuffer_overlapped));
+ if (!evo)
+ return NULL;
+
+ LIST_INIT(&evo->buffer.callbacks);
+ evo->buffer.refcnt = 1;
+ evo->buffer.last_with_datap = &evo->buffer.first;
+
+ evo->buffer.is_overlapped = 1;
+ evo->fd = fd;
+
+ return &evo->buffer;
+}
+
+int
+evbuffer_launch_write_(struct evbuffer *buf, ev_ssize_t at_most,
+ struct event_overlapped *ol)
+{
+ struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+ int r = -1;
+ int i;
+ struct evbuffer_chain *chain;
+ DWORD bytesSent;
+
+ if (!buf) {
+ /* No buffer, or it isn't overlapped */
+ return -1;
+ }
+
+ EVBUFFER_LOCK(buf);
+ EVUTIL_ASSERT(!buf_o->read_in_progress);
+ if (buf->freeze_start || buf_o->write_in_progress)
+ goto done;
+ if (!buf->total_len) {
+ /* Nothing to write */
+ r = 0;
+ goto done;
+ } else if (at_most < 0 || (size_t)at_most > buf->total_len) {
+ at_most = buf->total_len;
+ }
+ evbuffer_freeze(buf, 1);
+
+ buf_o->first_pinned = NULL;
+ buf_o->n_buffers = 0;
+ memset(buf_o->buffers, 0, sizeof(buf_o->buffers));
+
+ chain = buf_o->first_pinned = buf->first;
+
+ for (i=0; i < MAX_WSABUFS && chain; ++i, chain=chain->next) {
+ WSABUF *b = &buf_o->buffers[i];
+ b->buf = (char*)( chain->buffer + chain->misalign );
+ evbuffer_chain_pin_(chain, EVBUFFER_MEM_PINNED_W);
+
+ if ((size_t)at_most > chain->off) {
+ /* XXXX Cast is safe for now, since win32 has no
+ mmaped chains. But later, we need to have this
+ add more WSAbufs if chain->off is greater than
+ ULONG_MAX */
+ b->len = (unsigned long)chain->off;
+ at_most -= chain->off;
+ } else {
+ b->len = (unsigned long)at_most;
+ ++i;
+ break;
+ }
+ }
+
+ buf_o->n_buffers = i;
+ evbuffer_incref_(buf);
+ if (WSASend(buf_o->fd, buf_o->buffers, i, &bytesSent, 0,
+ &ol->overlapped, NULL)) {
+ int error = WSAGetLastError();
+ if (error != WSA_IO_PENDING) {
+ /* An actual error. */
+ pin_release(buf_o, EVBUFFER_MEM_PINNED_W);
+ evbuffer_unfreeze(buf, 1);
+ evbuffer_free(buf); /* decref */
+ goto done;
+ }
+ }
+
+ buf_o->write_in_progress = 1;
+ r = 0;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return r;
+}
+
+int
+evbuffer_launch_read_(struct evbuffer *buf, size_t at_most,
+ struct event_overlapped *ol)
+{
+ struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+ int r = -1, i;
+ int nvecs;
+ int npin=0;
+ struct evbuffer_chain *chain=NULL, **chainp;
+ DWORD bytesRead;
+ DWORD flags = 0;
+ struct evbuffer_iovec vecs[MAX_WSABUFS];
+
+ if (!buf_o)
+ return -1;
+ EVBUFFER_LOCK(buf);
+ EVUTIL_ASSERT(!buf_o->write_in_progress);
+ if (buf->freeze_end || buf_o->read_in_progress)
+ goto done;
+
+ buf_o->first_pinned = NULL;
+ buf_o->n_buffers = 0;
+ memset(buf_o->buffers, 0, sizeof(buf_o->buffers));
+
+ if (evbuffer_expand_fast_(buf, at_most, MAX_WSABUFS) == -1)
+ goto done;
+ evbuffer_freeze(buf, 0);
+
+ nvecs = evbuffer_read_setup_vecs_(buf, at_most,
+ vecs, MAX_WSABUFS, &chainp, 1);
+ for (i=0;i<nvecs;++i) {
+ WSABUF_FROM_EVBUFFER_IOV(
+ &buf_o->buffers[i],
+ &vecs[i]);
+ }
+
+ buf_o->n_buffers = nvecs;
+ buf_o->first_pinned = chain = *chainp;
+
+ npin=0;
+ for ( ; chain; chain = chain->next) {
+ evbuffer_chain_pin_(chain, EVBUFFER_MEM_PINNED_R);
+ ++npin;
+ }
+ EVUTIL_ASSERT(npin == nvecs);
+
+ evbuffer_incref_(buf);
+ if (WSARecv(buf_o->fd, buf_o->buffers, nvecs, &bytesRead, &flags,
+ &ol->overlapped, NULL)) {
+ int error = WSAGetLastError();
+ if (error != WSA_IO_PENDING) {
+ /* An actual error. */
+ pin_release(buf_o, EVBUFFER_MEM_PINNED_R);
+ evbuffer_unfreeze(buf, 0);
+ evbuffer_free(buf); /* decref */
+ goto done;
+ }
+ }
+
+ buf_o->read_in_progress = 1;
+ r = 0;
+done:
+ EVBUFFER_UNLOCK(buf);
+ return r;
+}
+
+evutil_socket_t
+evbuffer_overlapped_get_fd_(struct evbuffer *buf)
+{
+ struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+ return buf_o ? buf_o->fd : -1;
+}
+
+void
+evbuffer_overlapped_set_fd_(struct evbuffer *buf, evutil_socket_t fd)
+{
+ struct evbuffer_overlapped *buf_o = upcast_evbuffer(buf);
+ EVBUFFER_LOCK(buf);
+ /* XXX is this right?, should it cancel current I/O operations? */
+ if (buf_o)
+ buf_o->fd = fd;
+ EVBUFFER_UNLOCK(buf);
+}
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent-internal.h b/ipc/chromium/src/third_party/libevent/bufferevent-internal.h
new file mode 100644
index 0000000000..87ab9ad9c0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent-internal.h
@@ -0,0 +1,518 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef BUFFEREVENT_INTERNAL_H_INCLUDED_
+#define BUFFEREVENT_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "event2/event_struct.h"
+#include "evconfig-private.h"
+#include "event2/util.h"
+#include "defer-internal.h"
+#include "evthread-internal.h"
+#include "event2/thread.h"
+#include "ratelim-internal.h"
+#include "event2/bufferevent_struct.h"
+
+#include "ipv6-internal.h"
+#ifdef _WIN32
+#include <ws2tcpip.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+/* These flags are reasons that we might be declining to actually enable
+ reading or writing on a bufferevent.
+ */
+
+/* On a all bufferevents, for reading: used when we have read up to the
+ watermark value.
+
+ On a filtering bufferevent, for writing: used when the underlying
+ bufferevent's write buffer has been filled up to its watermark
+ value.
+*/
+#define BEV_SUSPEND_WM 0x01
+/* On a base bufferevent: when we have emptied a bandwidth buckets */
+#define BEV_SUSPEND_BW 0x02
+/* On a base bufferevent: when we have emptied the group's bandwidth bucket. */
+#define BEV_SUSPEND_BW_GROUP 0x04
+/* On a socket bufferevent: can't do any operations while we're waiting for
+ * name lookup to finish. */
+#define BEV_SUSPEND_LOOKUP 0x08
+/* On a base bufferevent, for reading: used when a filter has choked this
+ * (underlying) bufferevent because it has stopped reading from it. */
+#define BEV_SUSPEND_FILT_READ 0x10
+
+typedef ev_uint16_t bufferevent_suspend_flags;
+
+struct bufferevent_rate_limit_group {
+ /** List of all members in the group */
+ LIST_HEAD(rlim_group_member_list, bufferevent_private) members;
+ /** Current limits for the group. */
+ struct ev_token_bucket rate_limit;
+ struct ev_token_bucket_cfg rate_limit_cfg;
+
+ /** True iff we don't want to read from any member of the group.until
+ * the token bucket refills. */
+ unsigned read_suspended : 1;
+ /** True iff we don't want to write from any member of the group.until
+ * the token bucket refills. */
+ unsigned write_suspended : 1;
+ /** True iff we were unable to suspend one of the bufferevents in the
+ * group for reading the last time we tried, and we should try
+ * again. */
+ unsigned pending_unsuspend_read : 1;
+ /** True iff we were unable to suspend one of the bufferevents in the
+ * group for writing the last time we tried, and we should try
+ * again. */
+ unsigned pending_unsuspend_write : 1;
+
+ /*@{*/
+ /** Total number of bytes read or written in this group since last
+ * reset. */
+ ev_uint64_t total_read;
+ ev_uint64_t total_written;
+ /*@}*/
+
+ /** The number of bufferevents in the group. */
+ int n_members;
+
+ /** The smallest number of bytes that any member of the group should
+ * be limited to read or write at a time. */
+ ev_ssize_t min_share;
+ ev_ssize_t configured_min_share;
+
+ /** Timeout event that goes off once a tick, when the bucket is ready
+ * to refill. */
+ struct event master_refill_event;
+
+ /** Seed for weak random number generator. Protected by 'lock' */
+ struct evutil_weakrand_state weakrand_seed;
+
+ /** Lock to protect the members of this group. This lock should nest
+ * within every bufferevent lock: if you are holding this lock, do
+ * not assume you can lock another bufferevent. */
+ void *lock;
+};
+
+/** Fields for rate-limiting a single bufferevent. */
+struct bufferevent_rate_limit {
+ /* Linked-list elements for storing this bufferevent_private in a
+ * group.
+ *
+ * Note that this field is supposed to be protected by the group
+ * lock */
+ LIST_ENTRY(bufferevent_private) next_in_group;
+ /** The rate-limiting group for this bufferevent, or NULL if it is
+ * only rate-limited on its own. */
+ struct bufferevent_rate_limit_group *group;
+
+ /* This bufferevent's current limits. */
+ struct ev_token_bucket limit;
+ /* Pointer to the rate-limit configuration for this bufferevent.
+ * Can be shared. XXX reference-count this? */
+ struct ev_token_bucket_cfg *cfg;
+
+ /* Timeout event used when one this bufferevent's buckets are
+ * empty. */
+ struct event refill_bucket_event;
+};
+
+/** Parts of the bufferevent structure that are shared among all bufferevent
+ * types, but not exposed in bufferevent_struct.h. */
+struct bufferevent_private {
+ /** The underlying bufferevent structure. */
+ struct bufferevent bev;
+
+ /** Evbuffer callback to enforce watermarks on input. */
+ struct evbuffer_cb_entry *read_watermarks_cb;
+
+ /** If set, we should free the lock when we free the bufferevent. */
+ unsigned own_lock : 1;
+
+ /** Flag: set if we have deferred callbacks and a read callback is
+ * pending. */
+ unsigned readcb_pending : 1;
+ /** Flag: set if we have deferred callbacks and a write callback is
+ * pending. */
+ unsigned writecb_pending : 1;
+ /** Flag: set if we are currently busy connecting. */
+ unsigned connecting : 1;
+ /** Flag: set if a connect failed prematurely; this is a hack for
+ * getting around the bufferevent abstraction. */
+ unsigned connection_refused : 1;
+ /** Set to the events pending if we have deferred callbacks and
+ * an events callback is pending. */
+ short eventcb_pending;
+
+ /** If set, read is suspended until one or more conditions are over.
+ * The actual value here is a bitfield of those conditions; see the
+ * BEV_SUSPEND_* flags above. */
+ bufferevent_suspend_flags read_suspended;
+
+ /** If set, writing is suspended until one or more conditions are over.
+ * The actual value here is a bitfield of those conditions; see the
+ * BEV_SUSPEND_* flags above. */
+ bufferevent_suspend_flags write_suspended;
+
+ /** Set to the current socket errno if we have deferred callbacks and
+ * an events callback is pending. */
+ int errno_pending;
+
+ /** The DNS error code for bufferevent_socket_connect_hostname */
+ int dns_error;
+
+ /** Used to implement deferred callbacks */
+ struct event_callback deferred;
+
+ /** The options this bufferevent was constructed with */
+ enum bufferevent_options options;
+
+ /** Current reference count for this bufferevent. */
+ int refcnt;
+
+ /** Lock for this bufferevent. Shared by the inbuf and the outbuf.
+ * If NULL, locking is disabled. */
+ void *lock;
+
+ /** No matter how big our bucket gets, don't try to read more than this
+ * much in a single read operation. */
+ ev_ssize_t max_single_read;
+
+ /** No matter how big our bucket gets, don't try to write more than this
+ * much in a single write operation. */
+ ev_ssize_t max_single_write;
+
+ /** Rate-limiting information for this bufferevent */
+ struct bufferevent_rate_limit *rate_limiting;
+
+ /* Saved conn_addr, to extract IP address from it.
+ *
+ * Because some servers may reset/close connection without waiting clients,
+ * in that case we can't extract IP address even in close_cb.
+ * So we need to save it, just after we connected to remote server, or
+ * after resolving (to avoid extra dns requests during retrying, since UDP
+ * is slow) */
+ union {
+ struct sockaddr_in6 in6;
+ struct sockaddr_in in;
+ } conn_address;
+
+ struct evdns_getaddrinfo_request *dns_request;
+};
+
+/** Possible operations for a control callback. */
+enum bufferevent_ctrl_op {
+ BEV_CTRL_SET_FD,
+ BEV_CTRL_GET_FD,
+ BEV_CTRL_GET_UNDERLYING,
+ BEV_CTRL_CANCEL_ALL
+};
+
+/** Possible data types for a control callback */
+union bufferevent_ctrl_data {
+ void *ptr;
+ evutil_socket_t fd;
+};
+
+/**
+ Implementation table for a bufferevent: holds function pointers and other
+ information to make the various bufferevent types work.
+*/
+struct bufferevent_ops {
+ /** The name of the bufferevent's type. */
+ const char *type;
+ /** At what offset into the implementation type will we find a
+ bufferevent structure?
+
+ Example: if the type is implemented as
+ struct bufferevent_x {
+ int extra_data;
+ struct bufferevent bev;
+ }
+ then mem_offset should be offsetof(struct bufferevent_x, bev)
+ */
+ off_t mem_offset;
+
+ /** Enables one or more of EV_READ|EV_WRITE on a bufferevent. Does
+ not need to adjust the 'enabled' field. Returns 0 on success, -1
+ on failure.
+ */
+ int (*enable)(struct bufferevent *, short);
+
+ /** Disables one or more of EV_READ|EV_WRITE on a bufferevent. Does
+ not need to adjust the 'enabled' field. Returns 0 on success, -1
+ on failure.
+ */
+ int (*disable)(struct bufferevent *, short);
+
+ /** Detatches the bufferevent from related data structures. Called as
+ * soon as its reference count reaches 0. */
+ void (*unlink)(struct bufferevent *);
+
+ /** Free any storage and deallocate any extra data or structures used
+ in this implementation. Called when the bufferevent is
+ finalized.
+ */
+ void (*destruct)(struct bufferevent *);
+
+ /** Called when the timeouts on the bufferevent have changed.*/
+ int (*adj_timeouts)(struct bufferevent *);
+
+ /** Called to flush data. */
+ int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode);
+
+ /** Called to access miscellaneous fields. */
+ int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+};
+
+extern const struct bufferevent_ops bufferevent_ops_socket;
+extern const struct bufferevent_ops bufferevent_ops_filter;
+extern const struct bufferevent_ops bufferevent_ops_pair;
+
+#define BEV_IS_SOCKET(bevp) ((bevp)->be_ops == &bufferevent_ops_socket)
+#define BEV_IS_FILTER(bevp) ((bevp)->be_ops == &bufferevent_ops_filter)
+#define BEV_IS_PAIR(bevp) ((bevp)->be_ops == &bufferevent_ops_pair)
+
+#if defined(EVENT__HAVE_OPENSSL)
+extern const struct bufferevent_ops bufferevent_ops_openssl;
+#define BEV_IS_OPENSSL(bevp) ((bevp)->be_ops == &bufferevent_ops_openssl)
+#else
+#define BEV_IS_OPENSSL(bevp) 0
+#endif
+
+#ifdef _WIN32
+extern const struct bufferevent_ops bufferevent_ops_async;
+#define BEV_IS_ASYNC(bevp) ((bevp)->be_ops == &bufferevent_ops_async)
+#else
+#define BEV_IS_ASYNC(bevp) 0
+#endif
+
+/** Initialize the shared parts of a bufferevent. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_init_common_(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);
+
+/** For internal use: temporarily stop all reads on bufev, until the conditions
+ * in 'what' are over. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);
+/** For internal use: clear the conditions 'what' on bufev, and re-enable
+ * reading if there are no conditions left. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what);
+
+/** For internal use: temporarily stop all writes on bufev, until the conditions
+ * in 'what' are over. */
+void bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);
+/** For internal use: clear the conditions 'what' on bufev, and re-enable
+ * writing if there are no conditions left. */
+void bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what);
+
+#define bufferevent_wm_suspend_read(b) \
+ bufferevent_suspend_read_((b), BEV_SUSPEND_WM)
+#define bufferevent_wm_unsuspend_read(b) \
+ bufferevent_unsuspend_read_((b), BEV_SUSPEND_WM)
+
+/*
+ Disable a bufferevent. Equivalent to bufferevent_disable(), but
+ first resets 'connecting' flag to force EV_WRITE down for sure.
+
+ XXXX this method will go away in the future; try not to add new users.
+ See comment in evhttp_connection_reset_() for discussion.
+
+ @param bufev the bufferevent to be disabled
+ @param event any combination of EV_READ | EV_WRITE.
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_disable()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_disable_hard_(struct bufferevent *bufev, short event);
+
+/** Internal: Set up locking on a bufferevent. If lock is set, use it.
+ * Otherwise, use a new lock. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_enable_locking_(struct bufferevent *bufev, void *lock);
+/** Internal: backwards compat macro for the now public function
+ * Increment the reference count on bufev. */
+#define bufferevent_incref_(bufev) bufferevent_incref(bufev)
+/** Internal: Lock bufev and increase its reference count.
+ * unlocking it otherwise. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_incref_and_lock_(struct bufferevent *bufev);
+/** Internal: backwards compat macro for the now public function
+ * Decrement the reference count on bufev. Returns 1 if it freed
+ * the bufferevent.*/
+#define bufferevent_decref_(bufev) bufferevent_decref(bufev)
+
+/** Internal: Drop the reference count on bufev, freeing as necessary, and
+ * unlocking it otherwise. Returns 1 if it freed the bufferevent. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decref_and_unlock_(struct bufferevent *bufev);
+
+/** Internal: If callbacks are deferred and we have a read callback, schedule
+ * a readcb. Otherwise just run the readcb. Ignores watermarks. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_run_readcb_(struct bufferevent *bufev, int options);
+/** Internal: If callbacks are deferred and we have a write callback, schedule
+ * a writecb. Otherwise just run the writecb. Ignores watermarks. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_run_writecb_(struct bufferevent *bufev, int options);
+/** Internal: If callbacks are deferred and we have an eventcb, schedule
+ * it to run with events "what". Otherwise just run the eventcb.
+ * See bufferevent_trigger_event for meaning of "options". */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_run_eventcb_(struct bufferevent *bufev, short what, int options);
+
+/** Internal: Run or schedule (if deferred or options contain
+ * BEV_TRIG_DEFER_CALLBACKS) I/O callbacks specified in iotype.
+ * Must already hold the bufev lock. Honors watermarks unless
+ * BEV_TRIG_IGNORE_WATERMARKS is in options. */
+static inline void bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options);
+
+/* Making this inline since all of the common-case calls to this function in
+ * libevent use constant arguments. */
+static inline void
+bufferevent_trigger_nolock_(struct bufferevent *bufev, short iotype, int options)
+{
+ if ((iotype & EV_READ) && ((options & BEV_TRIG_IGNORE_WATERMARKS) ||
+ evbuffer_get_length(bufev->input) >= bufev->wm_read.low))
+ bufferevent_run_readcb_(bufev, options);
+ if ((iotype & EV_WRITE) && ((options & BEV_TRIG_IGNORE_WATERMARKS) ||
+ evbuffer_get_length(bufev->output) <= bufev->wm_write.low))
+ bufferevent_run_writecb_(bufev, options);
+}
+
+/** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in
+ * which case add ev with no timeout. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_add_event_(struct event *ev, const struct timeval *tv);
+
+/* =========
+ * These next functions implement timeouts for bufferevents that aren't doing
+ * anything else with ev_read and ev_write, to handle timeouts.
+ * ========= */
+/** Internal use: Set up the ev_read and ev_write callbacks so that
+ * the other "generic_timeout" functions will work on it. Call this from
+ * the constructor function. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev);
+/** Internal use: Add or delete the generic timeout events as appropriate.
+ * (If an event is enabled and a timeout is set, we add the event. Otherwise
+ * we delete it.) Call this from anything that changes the timeout values,
+ * that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_generic_adj_timeouts_(struct bufferevent *bev);
+EVENT2_EXPORT_SYMBOL
+int bufferevent_generic_adj_existing_timeouts_(struct bufferevent *bev);
+
+EVENT2_EXPORT_SYMBOL
+enum bufferevent_options bufferevent_get_options_(struct bufferevent *bev);
+
+EVENT2_EXPORT_SYMBOL
+const struct sockaddr*
+bufferevent_socket_get_conn_address_(struct bufferevent *bev);
+
+EVENT2_EXPORT_SYMBOL
+void
+bufferevent_socket_set_conn_address_fd_(struct bufferevent *bev, evutil_socket_t fd);
+
+EVENT2_EXPORT_SYMBOL
+void
+bufferevent_socket_set_conn_address_(struct bufferevent *bev, struct sockaddr *addr, size_t addrlen);
+
+
+/** Internal use: We have just successfully read data into an inbuf, so
+ * reset the read timeout (if any). */
+#define BEV_RESET_GENERIC_READ_TIMEOUT(bev) \
+ do { \
+ if (evutil_timerisset(&(bev)->timeout_read)) \
+ event_add(&(bev)->ev_read, &(bev)->timeout_read); \
+ } while (0)
+/** Internal use: We have just successfully written data from an inbuf, so
+ * reset the read timeout (if any). */
+#define BEV_RESET_GENERIC_WRITE_TIMEOUT(bev) \
+ do { \
+ if (evutil_timerisset(&(bev)->timeout_write)) \
+ event_add(&(bev)->ev_write, &(bev)->timeout_write); \
+ } while (0)
+#define BEV_DEL_GENERIC_READ_TIMEOUT(bev) \
+ event_del(&(bev)->ev_read)
+#define BEV_DEL_GENERIC_WRITE_TIMEOUT(bev) \
+ event_del(&(bev)->ev_write)
+
+
+/** Internal: Given a bufferevent, return its corresponding
+ * bufferevent_private. */
+#define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev)
+
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+#define BEV_LOCK(b) EVUTIL_NIL_STMT_
+#define BEV_UNLOCK(b) EVUTIL_NIL_STMT_
+#else
+/** Internal: Grab the lock (if any) on a bufferevent */
+#define BEV_LOCK(b) do { \
+ struct bufferevent_private *locking = BEV_UPCAST(b); \
+ EVLOCK_LOCK(locking->lock, 0); \
+ } while (0)
+
+/** Internal: Release the lock (if any) on a bufferevent */
+#define BEV_UNLOCK(b) do { \
+ struct bufferevent_private *locking = BEV_UPCAST(b); \
+ EVLOCK_UNLOCK(locking->lock, 0); \
+ } while (0)
+#endif
+
+
+/* ==== For rate-limiting. */
+
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decrement_write_buckets_(struct bufferevent_private *bev,
+ ev_ssize_t bytes);
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decrement_read_buckets_(struct bufferevent_private *bev,
+ ev_ssize_t bytes);
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_read_max_(struct bufferevent_private *bev);
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_write_max_(struct bufferevent_private *bev);
+
+int bufferevent_ratelim_init_(struct bufferevent_private *bev);
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* BUFFEREVENT_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent.c b/ipc/chromium/src/third_party/libevent/bufferevent.c
new file mode 100644
index 0000000000..08c0486c08
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent.c
@@ -0,0 +1,1036 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/event.h"
+#include "event-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "evbuffer-internal.h"
+#include "util-internal.h"
+
+static void bufferevent_cancel_all_(struct bufferevent *bev);
+static void bufferevent_finalize_cb_(struct event_callback *evcb, void *arg_);
+
+void
+bufferevent_suspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ BEV_LOCK(bufev);
+ if (!bufev_private->read_suspended)
+ bufev->be_ops->disable(bufev, EV_READ);
+ bufev_private->read_suspended |= what;
+ BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_unsuspend_read_(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ BEV_LOCK(bufev);
+ bufev_private->read_suspended &= ~what;
+ if (!bufev_private->read_suspended && (bufev->enabled & EV_READ))
+ bufev->be_ops->enable(bufev, EV_READ);
+ BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_suspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ BEV_LOCK(bufev);
+ if (!bufev_private->write_suspended)
+ bufev->be_ops->disable(bufev, EV_WRITE);
+ bufev_private->write_suspended |= what;
+ BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_unsuspend_write_(struct bufferevent *bufev, bufferevent_suspend_flags what)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ BEV_LOCK(bufev);
+ bufev_private->write_suspended &= ~what;
+ if (!bufev_private->write_suspended && (bufev->enabled & EV_WRITE))
+ bufev->be_ops->enable(bufev, EV_WRITE);
+ BEV_UNLOCK(bufev);
+}
+
+/**
+ * Sometimes bufferevent's implementation can overrun high watermarks
+ * (one of examples is openssl) and in this case if the read callback
+ * will not handle enough data do over condition above the read
+ * callback will never be called again (due to suspend above).
+ *
+ * To avoid this we are scheduling read callback again here, but only
+ * from the user callback to avoid multiple scheduling:
+ * - when the data had been added to it
+ * - when the data had been drained from it (user specified read callback)
+ */
+static void bufferevent_inbuf_wm_check(struct bufferevent *bev)
+{
+ if (!bev->wm_read.high)
+ return;
+ if (!(bev->enabled & EV_READ))
+ return;
+ if (evbuffer_get_length(bev->input) < bev->wm_read.high)
+ return;
+
+ bufferevent_trigger(bev, EV_READ, BEV_OPT_DEFER_CALLBACKS);
+}
+
+/* Callback to implement watermarks on the input buffer. Only enabled
+ * if the watermark is set. */
+static void
+bufferevent_inbuf_wm_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+ struct bufferevent *bufev = arg;
+ size_t size;
+
+ size = evbuffer_get_length(buf);
+
+ if (size >= bufev->wm_read.high)
+ bufferevent_wm_suspend_read(bufev);
+ else
+ bufferevent_wm_unsuspend_read(bufev);
+}
+
+static void
+bufferevent_run_deferred_callbacks_locked(struct event_callback *cb, void *arg)
+{
+ struct bufferevent_private *bufev_private = arg;
+ struct bufferevent *bufev = &bufev_private->bev;
+
+ BEV_LOCK(bufev);
+ if ((bufev_private->eventcb_pending & BEV_EVENT_CONNECTED) &&
+ bufev->errorcb) {
+ /* The "connected" happened before any reads or writes, so
+ send it first. */
+ bufev_private->eventcb_pending &= ~BEV_EVENT_CONNECTED;
+ bufev->errorcb(bufev, BEV_EVENT_CONNECTED, bufev->cbarg);
+ }
+ if (bufev_private->readcb_pending && bufev->readcb) {
+ bufev_private->readcb_pending = 0;
+ bufev->readcb(bufev, bufev->cbarg);
+ bufferevent_inbuf_wm_check(bufev);
+ }
+ if (bufev_private->writecb_pending && bufev->writecb) {
+ bufev_private->writecb_pending = 0;
+ bufev->writecb(bufev, bufev->cbarg);
+ }
+ if (bufev_private->eventcb_pending && bufev->errorcb) {
+ short what = bufev_private->eventcb_pending;
+ int err = bufev_private->errno_pending;
+ bufev_private->eventcb_pending = 0;
+ bufev_private->errno_pending = 0;
+ EVUTIL_SET_SOCKET_ERROR(err);
+ bufev->errorcb(bufev, what, bufev->cbarg);
+ }
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+static void
+bufferevent_run_deferred_callbacks_unlocked(struct event_callback *cb, void *arg)
+{
+ struct bufferevent_private *bufev_private = arg;
+ struct bufferevent *bufev = &bufev_private->bev;
+
+ BEV_LOCK(bufev);
+#define UNLOCKED(stmt) \
+ do { BEV_UNLOCK(bufev); stmt; BEV_LOCK(bufev); } while(0)
+
+ if ((bufev_private->eventcb_pending & BEV_EVENT_CONNECTED) &&
+ bufev->errorcb) {
+ /* The "connected" happened before any reads or writes, so
+ send it first. */
+ bufferevent_event_cb errorcb = bufev->errorcb;
+ void *cbarg = bufev->cbarg;
+ bufev_private->eventcb_pending &= ~BEV_EVENT_CONNECTED;
+ UNLOCKED(errorcb(bufev, BEV_EVENT_CONNECTED, cbarg));
+ }
+ if (bufev_private->readcb_pending && bufev->readcb) {
+ bufferevent_data_cb readcb = bufev->readcb;
+ void *cbarg = bufev->cbarg;
+ bufev_private->readcb_pending = 0;
+ UNLOCKED(readcb(bufev, cbarg));
+ bufferevent_inbuf_wm_check(bufev);
+ }
+ if (bufev_private->writecb_pending && bufev->writecb) {
+ bufferevent_data_cb writecb = bufev->writecb;
+ void *cbarg = bufev->cbarg;
+ bufev_private->writecb_pending = 0;
+ UNLOCKED(writecb(bufev, cbarg));
+ }
+ if (bufev_private->eventcb_pending && bufev->errorcb) {
+ bufferevent_event_cb errorcb = bufev->errorcb;
+ void *cbarg = bufev->cbarg;
+ short what = bufev_private->eventcb_pending;
+ int err = bufev_private->errno_pending;
+ bufev_private->eventcb_pending = 0;
+ bufev_private->errno_pending = 0;
+ EVUTIL_SET_SOCKET_ERROR(err);
+ UNLOCKED(errorcb(bufev,what,cbarg));
+ }
+ bufferevent_decref_and_unlock_(bufev);
+#undef UNLOCKED
+}
+
+#define SCHEDULE_DEFERRED(bevp) \
+ do { \
+ if (event_deferred_cb_schedule_( \
+ (bevp)->bev.ev_base, \
+ &(bevp)->deferred)) \
+ bufferevent_incref_(&(bevp)->bev); \
+ } while (0)
+
+
+void
+bufferevent_run_readcb_(struct bufferevent *bufev, int options)
+{
+ /* Requires that we hold the lock and a reference */
+ struct bufferevent_private *p = BEV_UPCAST(bufev);
+ if (bufev->readcb == NULL)
+ return;
+ if ((p->options|options) & BEV_OPT_DEFER_CALLBACKS) {
+ p->readcb_pending = 1;
+ SCHEDULE_DEFERRED(p);
+ } else {
+ bufev->readcb(bufev, bufev->cbarg);
+ bufferevent_inbuf_wm_check(bufev);
+ }
+}
+
+void
+bufferevent_run_writecb_(struct bufferevent *bufev, int options)
+{
+ /* Requires that we hold the lock and a reference */
+ struct bufferevent_private *p = BEV_UPCAST(bufev);
+ if (bufev->writecb == NULL)
+ return;
+ if ((p->options|options) & BEV_OPT_DEFER_CALLBACKS) {
+ p->writecb_pending = 1;
+ SCHEDULE_DEFERRED(p);
+ } else {
+ bufev->writecb(bufev, bufev->cbarg);
+ }
+}
+
+#define BEV_TRIG_ALL_OPTS ( \
+ BEV_TRIG_IGNORE_WATERMARKS| \
+ BEV_TRIG_DEFER_CALLBACKS \
+ )
+
+void
+bufferevent_trigger(struct bufferevent *bufev, short iotype, int options)
+{
+ bufferevent_incref_and_lock_(bufev);
+ bufferevent_trigger_nolock_(bufev, iotype, options&BEV_TRIG_ALL_OPTS);
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+void
+bufferevent_run_eventcb_(struct bufferevent *bufev, short what, int options)
+{
+ /* Requires that we hold the lock and a reference */
+ struct bufferevent_private *p = BEV_UPCAST(bufev);
+ if (bufev->errorcb == NULL)
+ return;
+ if ((p->options|options) & BEV_OPT_DEFER_CALLBACKS) {
+ p->eventcb_pending |= what;
+ p->errno_pending = EVUTIL_SOCKET_ERROR();
+ SCHEDULE_DEFERRED(p);
+ } else {
+ bufev->errorcb(bufev, what, bufev->cbarg);
+ }
+}
+
+void
+bufferevent_trigger_event(struct bufferevent *bufev, short what, int options)
+{
+ bufferevent_incref_and_lock_(bufev);
+ bufferevent_run_eventcb_(bufev, what, options&BEV_TRIG_ALL_OPTS);
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+int
+bufferevent_init_common_(struct bufferevent_private *bufev_private,
+ struct event_base *base,
+ const struct bufferevent_ops *ops,
+ enum bufferevent_options options)
+{
+ struct bufferevent *bufev = &bufev_private->bev;
+
+ if (!bufev->input) {
+ if ((bufev->input = evbuffer_new()) == NULL)
+ goto err;
+ }
+
+ if (!bufev->output) {
+ if ((bufev->output = evbuffer_new()) == NULL)
+ goto err;
+ }
+
+ bufev_private->refcnt = 1;
+ bufev->ev_base = base;
+
+ /* Disable timeouts. */
+ evutil_timerclear(&bufev->timeout_read);
+ evutil_timerclear(&bufev->timeout_write);
+
+ bufev->be_ops = ops;
+
+ if (bufferevent_ratelim_init_(bufev_private))
+ goto err;
+
+ /*
+ * Set to EV_WRITE so that using bufferevent_write is going to
+ * trigger a callback. Reading needs to be explicitly enabled
+ * because otherwise no data will be available.
+ */
+ bufev->enabled = EV_WRITE;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (options & BEV_OPT_THREADSAFE) {
+ if (bufferevent_enable_locking_(bufev, NULL) < 0)
+ goto err;
+ }
+#endif
+ if ((options & (BEV_OPT_DEFER_CALLBACKS|BEV_OPT_UNLOCK_CALLBACKS))
+ == BEV_OPT_UNLOCK_CALLBACKS) {
+ event_warnx("UNLOCK_CALLBACKS requires DEFER_CALLBACKS");
+ goto err;
+ }
+ if (options & BEV_OPT_UNLOCK_CALLBACKS)
+ event_deferred_cb_init_(
+ &bufev_private->deferred,
+ event_base_get_npriorities(base) / 2,
+ bufferevent_run_deferred_callbacks_unlocked,
+ bufev_private);
+ else
+ event_deferred_cb_init_(
+ &bufev_private->deferred,
+ event_base_get_npriorities(base) / 2,
+ bufferevent_run_deferred_callbacks_locked,
+ bufev_private);
+
+ bufev_private->options = options;
+
+ evbuffer_set_parent_(bufev->input, bufev);
+ evbuffer_set_parent_(bufev->output, bufev);
+
+ return 0;
+
+err:
+ if (bufev->input) {
+ evbuffer_free(bufev->input);
+ bufev->input = NULL;
+ }
+ if (bufev->output) {
+ evbuffer_free(bufev->output);
+ bufev->output = NULL;
+ }
+ return -1;
+}
+
+void
+bufferevent_setcb(struct bufferevent *bufev,
+ bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+ bufferevent_event_cb eventcb, void *cbarg)
+{
+ BEV_LOCK(bufev);
+
+ bufev->readcb = readcb;
+ bufev->writecb = writecb;
+ bufev->errorcb = eventcb;
+
+ bufev->cbarg = cbarg;
+ BEV_UNLOCK(bufev);
+}
+
+void
+bufferevent_getcb(struct bufferevent *bufev,
+ bufferevent_data_cb *readcb_ptr,
+ bufferevent_data_cb *writecb_ptr,
+ bufferevent_event_cb *eventcb_ptr,
+ void **cbarg_ptr)
+{
+ BEV_LOCK(bufev);
+ if (readcb_ptr)
+ *readcb_ptr = bufev->readcb;
+ if (writecb_ptr)
+ *writecb_ptr = bufev->writecb;
+ if (eventcb_ptr)
+ *eventcb_ptr = bufev->errorcb;
+ if (cbarg_ptr)
+ *cbarg_ptr = bufev->cbarg;
+
+ BEV_UNLOCK(bufev);
+}
+
+struct evbuffer *
+bufferevent_get_input(struct bufferevent *bufev)
+{
+ return bufev->input;
+}
+
+struct evbuffer *
+bufferevent_get_output(struct bufferevent *bufev)
+{
+ return bufev->output;
+}
+
+struct event_base *
+bufferevent_get_base(struct bufferevent *bufev)
+{
+ return bufev->ev_base;
+}
+
+int
+bufferevent_get_priority(const struct bufferevent *bufev)
+{
+ if (event_initialized(&bufev->ev_read)) {
+ return event_get_priority(&bufev->ev_read);
+ } else {
+ return event_base_get_npriorities(bufev->ev_base) / 2;
+ }
+}
+
+int
+bufferevent_write(struct bufferevent *bufev, const void *data, size_t size)
+{
+ if (evbuffer_add(bufev->output, data, size) == -1)
+ return (-1);
+
+ return 0;
+}
+
+int
+bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf)
+{
+ if (evbuffer_add_buffer(bufev->output, buf) == -1)
+ return (-1);
+
+ return 0;
+}
+
+size_t
+bufferevent_read(struct bufferevent *bufev, void *data, size_t size)
+{
+ return (evbuffer_remove(bufev->input, data, size));
+}
+
+int
+bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf)
+{
+ return (evbuffer_add_buffer(buf, bufev->input));
+}
+
+int
+bufferevent_enable(struct bufferevent *bufev, short event)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ short impl_events = event;
+ int r = 0;
+
+ bufferevent_incref_and_lock_(bufev);
+ if (bufev_private->read_suspended)
+ impl_events &= ~EV_READ;
+ if (bufev_private->write_suspended)
+ impl_events &= ~EV_WRITE;
+
+ bufev->enabled |= event;
+
+ if (impl_events && bufev->be_ops->enable(bufev, impl_events) < 0)
+ r = -1;
+ if (r)
+ event_debug(("%s: cannot enable 0x%hx on %p", __func__, event, bufev));
+
+ bufferevent_decref_and_unlock_(bufev);
+ return r;
+}
+
+int
+bufferevent_set_timeouts(struct bufferevent *bufev,
+ const struct timeval *tv_read,
+ const struct timeval *tv_write)
+{
+ int r = 0;
+ BEV_LOCK(bufev);
+ if (tv_read) {
+ bufev->timeout_read = *tv_read;
+ } else {
+ evutil_timerclear(&bufev->timeout_read);
+ }
+ if (tv_write) {
+ bufev->timeout_write = *tv_write;
+ } else {
+ evutil_timerclear(&bufev->timeout_write);
+ }
+
+ if (bufev->be_ops->adj_timeouts)
+ r = bufev->be_ops->adj_timeouts(bufev);
+ BEV_UNLOCK(bufev);
+
+ return r;
+}
+
+
+/* Obsolete; use bufferevent_set_timeouts */
+void
+bufferevent_settimeout(struct bufferevent *bufev,
+ int timeout_read, int timeout_write)
+{
+ struct timeval tv_read, tv_write;
+ struct timeval *ptv_read = NULL, *ptv_write = NULL;
+
+ memset(&tv_read, 0, sizeof(tv_read));
+ memset(&tv_write, 0, sizeof(tv_write));
+
+ if (timeout_read) {
+ tv_read.tv_sec = timeout_read;
+ ptv_read = &tv_read;
+ }
+ if (timeout_write) {
+ tv_write.tv_sec = timeout_write;
+ ptv_write = &tv_write;
+ }
+
+ bufferevent_set_timeouts(bufev, ptv_read, ptv_write);
+}
+
+
+int
+bufferevent_disable_hard_(struct bufferevent *bufev, short event)
+{
+ int r = 0;
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+
+ BEV_LOCK(bufev);
+ bufev->enabled &= ~event;
+
+ bufev_private->connecting = 0;
+ if (bufev->be_ops->disable(bufev, event) < 0)
+ r = -1;
+
+ BEV_UNLOCK(bufev);
+ return r;
+}
+
+int
+bufferevent_disable(struct bufferevent *bufev, short event)
+{
+ int r = 0;
+
+ BEV_LOCK(bufev);
+ bufev->enabled &= ~event;
+
+ if (bufev->be_ops->disable(bufev, event) < 0)
+ r = -1;
+ if (r)
+ event_debug(("%s: cannot disable 0x%hx on %p", __func__, event, bufev));
+
+ BEV_UNLOCK(bufev);
+ return r;
+}
+
+/*
+ * Sets the water marks
+ */
+
+void
+bufferevent_setwatermark(struct bufferevent *bufev, short events,
+ size_t lowmark, size_t highmark)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+
+ BEV_LOCK(bufev);
+ if (events & EV_WRITE) {
+ bufev->wm_write.low = lowmark;
+ bufev->wm_write.high = highmark;
+ }
+
+ if (events & EV_READ) {
+ bufev->wm_read.low = lowmark;
+ bufev->wm_read.high = highmark;
+
+ if (highmark) {
+ /* There is now a new high-water mark for read.
+ enable the callback if needed, and see if we should
+ suspend/bufferevent_wm_unsuspend. */
+
+ if (bufev_private->read_watermarks_cb == NULL) {
+ bufev_private->read_watermarks_cb =
+ evbuffer_add_cb(bufev->input,
+ bufferevent_inbuf_wm_cb,
+ bufev);
+ }
+ evbuffer_cb_set_flags(bufev->input,
+ bufev_private->read_watermarks_cb,
+ EVBUFFER_CB_ENABLED|EVBUFFER_CB_NODEFER);
+
+ if (evbuffer_get_length(bufev->input) >= highmark)
+ bufferevent_wm_suspend_read(bufev);
+ else if (evbuffer_get_length(bufev->input) < highmark)
+ bufferevent_wm_unsuspend_read(bufev);
+ } else {
+ /* There is now no high-water mark for read. */
+ if (bufev_private->read_watermarks_cb)
+ evbuffer_cb_clear_flags(bufev->input,
+ bufev_private->read_watermarks_cb,
+ EVBUFFER_CB_ENABLED);
+ bufferevent_wm_unsuspend_read(bufev);
+ }
+ }
+ BEV_UNLOCK(bufev);
+}
+
+int
+bufferevent_getwatermark(struct bufferevent *bufev, short events,
+ size_t *lowmark, size_t *highmark)
+{
+ if (events == EV_WRITE) {
+ BEV_LOCK(bufev);
+ if (lowmark)
+ *lowmark = bufev->wm_write.low;
+ if (highmark)
+ *highmark = bufev->wm_write.high;
+ BEV_UNLOCK(bufev);
+ return 0;
+ }
+
+ if (events == EV_READ) {
+ BEV_LOCK(bufev);
+ if (lowmark)
+ *lowmark = bufev->wm_read.low;
+ if (highmark)
+ *highmark = bufev->wm_read.high;
+ BEV_UNLOCK(bufev);
+ return 0;
+ }
+ return -1;
+}
+
+int
+bufferevent_flush(struct bufferevent *bufev,
+ short iotype,
+ enum bufferevent_flush_mode mode)
+{
+ int r = -1;
+ BEV_LOCK(bufev);
+ if (bufev->be_ops->flush)
+ r = bufev->be_ops->flush(bufev, iotype, mode);
+ BEV_UNLOCK(bufev);
+ return r;
+}
+
+void
+bufferevent_incref_and_lock_(struct bufferevent *bufev)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ BEV_LOCK(bufev);
+ ++bufev_private->refcnt;
+}
+
+#if 0
+static void
+bufferevent_transfer_lock_ownership_(struct bufferevent *donor,
+ struct bufferevent *recipient)
+{
+ struct bufferevent_private *d = BEV_UPCAST(donor);
+ struct bufferevent_private *r = BEV_UPCAST(recipient);
+ if (d->lock != r->lock)
+ return;
+ if (r->own_lock)
+ return;
+ if (d->own_lock) {
+ d->own_lock = 0;
+ r->own_lock = 1;
+ }
+}
+#endif
+
+int
+bufferevent_decref_and_unlock_(struct bufferevent *bufev)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ int n_cbs = 0;
+#define MAX_CBS 16
+ struct event_callback *cbs[MAX_CBS];
+
+ EVUTIL_ASSERT(bufev_private->refcnt > 0);
+
+ if (--bufev_private->refcnt) {
+ BEV_UNLOCK(bufev);
+ return 0;
+ }
+
+ if (bufev->be_ops->unlink)
+ bufev->be_ops->unlink(bufev);
+
+ /* Okay, we're out of references. Let's finalize this once all the
+ * callbacks are done running. */
+ cbs[0] = &bufev->ev_read.ev_evcallback;
+ cbs[1] = &bufev->ev_write.ev_evcallback;
+ cbs[2] = &bufev_private->deferred;
+ n_cbs = 3;
+ if (bufev_private->rate_limiting) {
+ struct event *e = &bufev_private->rate_limiting->refill_bucket_event;
+ if (event_initialized(e))
+ cbs[n_cbs++] = &e->ev_evcallback;
+ }
+ n_cbs += evbuffer_get_callbacks_(bufev->input, cbs+n_cbs, MAX_CBS-n_cbs);
+ n_cbs += evbuffer_get_callbacks_(bufev->output, cbs+n_cbs, MAX_CBS-n_cbs);
+
+ event_callback_finalize_many_(bufev->ev_base, n_cbs, cbs,
+ bufferevent_finalize_cb_);
+
+#undef MAX_CBS
+ BEV_UNLOCK(bufev);
+
+ return 1;
+}
+
+static void
+bufferevent_finalize_cb_(struct event_callback *evcb, void *arg_)
+{
+ struct bufferevent *bufev = arg_;
+ struct bufferevent *underlying;
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+
+ BEV_LOCK(bufev);
+ underlying = bufferevent_get_underlying(bufev);
+
+ /* Clean up the shared info */
+ if (bufev->be_ops->destruct)
+ bufev->be_ops->destruct(bufev);
+
+ /* XXX what happens if refcnt for these buffers is > 1?
+ * The buffers can share a lock with this bufferevent object,
+ * but the lock might be destroyed below. */
+ /* evbuffer will free the callbacks */
+ evbuffer_free(bufev->input);
+ evbuffer_free(bufev->output);
+
+ if (bufev_private->rate_limiting) {
+ if (bufev_private->rate_limiting->group)
+ bufferevent_remove_from_rate_limit_group_internal_(bufev,0);
+ mm_free(bufev_private->rate_limiting);
+ bufev_private->rate_limiting = NULL;
+ }
+
+
+ BEV_UNLOCK(bufev);
+
+ if (bufev_private->own_lock)
+ EVTHREAD_FREE_LOCK(bufev_private->lock,
+ EVTHREAD_LOCKTYPE_RECURSIVE);
+
+ /* Free the actual allocated memory. */
+ mm_free(((char*)bufev) - bufev->be_ops->mem_offset);
+
+ /* Release the reference to underlying now that we no longer need the
+ * reference to it. We wait this long mainly in case our lock is
+ * shared with underlying.
+ *
+ * The 'destruct' function will also drop a reference to underlying
+ * if BEV_OPT_CLOSE_ON_FREE is set.
+ *
+ * XXX Should we/can we just refcount evbuffer/bufferevent locks?
+ * It would probably save us some headaches.
+ */
+ if (underlying)
+ bufferevent_decref_(underlying);
+}
+
+int
+bufferevent_decref(struct bufferevent *bufev)
+{
+ BEV_LOCK(bufev);
+ return bufferevent_decref_and_unlock_(bufev);
+}
+
+void
+bufferevent_free(struct bufferevent *bufev)
+{
+ BEV_LOCK(bufev);
+ bufferevent_setcb(bufev, NULL, NULL, NULL, NULL);
+ bufferevent_cancel_all_(bufev);
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+void
+bufferevent_incref(struct bufferevent *bufev)
+{
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+
+ /* XXX: now that this function is public, we might want to
+ * - return the count from this function
+ * - create a new function to atomically grab the current refcount
+ */
+ BEV_LOCK(bufev);
+ ++bufev_private->refcnt;
+ BEV_UNLOCK(bufev);
+}
+
+int
+bufferevent_enable_locking_(struct bufferevent *bufev, void *lock)
+{
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+ return -1;
+#else
+ struct bufferevent *underlying;
+
+ if (BEV_UPCAST(bufev)->lock)
+ return -1;
+ underlying = bufferevent_get_underlying(bufev);
+
+ if (!lock && underlying && BEV_UPCAST(underlying)->lock) {
+ lock = BEV_UPCAST(underlying)->lock;
+ BEV_UPCAST(bufev)->lock = lock;
+ BEV_UPCAST(bufev)->own_lock = 0;
+ } else if (!lock) {
+ EVTHREAD_ALLOC_LOCK(lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ if (!lock)
+ return -1;
+ BEV_UPCAST(bufev)->lock = lock;
+ BEV_UPCAST(bufev)->own_lock = 1;
+ } else {
+ BEV_UPCAST(bufev)->lock = lock;
+ BEV_UPCAST(bufev)->own_lock = 0;
+ }
+ evbuffer_enable_locking(bufev->input, lock);
+ evbuffer_enable_locking(bufev->output, lock);
+
+ if (underlying && !BEV_UPCAST(underlying)->lock)
+ bufferevent_enable_locking_(underlying, lock);
+
+ return 0;
+#endif
+}
+
+int
+bufferevent_setfd(struct bufferevent *bev, evutil_socket_t fd)
+{
+ union bufferevent_ctrl_data d;
+ int res = -1;
+ d.fd = fd;
+ BEV_LOCK(bev);
+ if (bev->be_ops->ctrl)
+ res = bev->be_ops->ctrl(bev, BEV_CTRL_SET_FD, &d);
+ if (res)
+ event_debug(("%s: cannot set fd for %p to "EV_SOCK_FMT, __func__, bev, fd));
+ BEV_UNLOCK(bev);
+ return res;
+}
+
+evutil_socket_t
+bufferevent_getfd(struct bufferevent *bev)
+{
+ union bufferevent_ctrl_data d;
+ int res = -1;
+ d.fd = -1;
+ BEV_LOCK(bev);
+ if (bev->be_ops->ctrl)
+ res = bev->be_ops->ctrl(bev, BEV_CTRL_GET_FD, &d);
+ if (res)
+ event_debug(("%s: cannot get fd for %p", __func__, bev));
+ BEV_UNLOCK(bev);
+ return (res<0) ? -1 : d.fd;
+}
+
+enum bufferevent_options
+bufferevent_get_options_(struct bufferevent *bev)
+{
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ enum bufferevent_options options;
+
+ BEV_LOCK(bev);
+ options = bev_p->options;
+ BEV_UNLOCK(bev);
+ return options;
+}
+
+
+static void
+bufferevent_cancel_all_(struct bufferevent *bev)
+{
+ union bufferevent_ctrl_data d;
+ memset(&d, 0, sizeof(d));
+ BEV_LOCK(bev);
+ if (bev->be_ops->ctrl)
+ bev->be_ops->ctrl(bev, BEV_CTRL_CANCEL_ALL, &d);
+ BEV_UNLOCK(bev);
+}
+
+short
+bufferevent_get_enabled(struct bufferevent *bufev)
+{
+ short r;
+ BEV_LOCK(bufev);
+ r = bufev->enabled;
+ BEV_UNLOCK(bufev);
+ return r;
+}
+
+struct bufferevent *
+bufferevent_get_underlying(struct bufferevent *bev)
+{
+ union bufferevent_ctrl_data d;
+ int res = -1;
+ d.ptr = NULL;
+ BEV_LOCK(bev);
+ if (bev->be_ops->ctrl)
+ res = bev->be_ops->ctrl(bev, BEV_CTRL_GET_UNDERLYING, &d);
+ BEV_UNLOCK(bev);
+ return (res<0) ? NULL : d.ptr;
+}
+
+static void
+bufferevent_generic_read_timeout_cb(evutil_socket_t fd, short event, void *ctx)
+{
+ struct bufferevent *bev = ctx;
+ bufferevent_incref_and_lock_(bev);
+ bufferevent_disable(bev, EV_READ);
+ bufferevent_run_eventcb_(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_READING, 0);
+ bufferevent_decref_and_unlock_(bev);
+}
+static void
+bufferevent_generic_write_timeout_cb(evutil_socket_t fd, short event, void *ctx)
+{
+ struct bufferevent *bev = ctx;
+ bufferevent_incref_and_lock_(bev);
+ bufferevent_disable(bev, EV_WRITE);
+ bufferevent_run_eventcb_(bev, BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING, 0);
+ bufferevent_decref_and_unlock_(bev);
+}
+
+void
+bufferevent_init_generic_timeout_cbs_(struct bufferevent *bev)
+{
+ event_assign(&bev->ev_read, bev->ev_base, -1, EV_FINALIZE,
+ bufferevent_generic_read_timeout_cb, bev);
+ event_assign(&bev->ev_write, bev->ev_base, -1, EV_FINALIZE,
+ bufferevent_generic_write_timeout_cb, bev);
+}
+
+int
+bufferevent_generic_adj_timeouts_(struct bufferevent *bev)
+{
+ const short enabled = bev->enabled;
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ int r1=0, r2=0;
+ if ((enabled & EV_READ) && !bev_p->read_suspended &&
+ evutil_timerisset(&bev->timeout_read))
+ r1 = event_add(&bev->ev_read, &bev->timeout_read);
+ else
+ r1 = event_del(&bev->ev_read);
+
+ if ((enabled & EV_WRITE) && !bev_p->write_suspended &&
+ evutil_timerisset(&bev->timeout_write) &&
+ evbuffer_get_length(bev->output))
+ r2 = event_add(&bev->ev_write, &bev->timeout_write);
+ else
+ r2 = event_del(&bev->ev_write);
+ if (r1 < 0 || r2 < 0)
+ return -1;
+ return 0;
+}
+
+int
+bufferevent_generic_adj_existing_timeouts_(struct bufferevent *bev)
+{
+ int r = 0;
+ if (event_pending(&bev->ev_read, EV_READ, NULL)) {
+ if (evutil_timerisset(&bev->timeout_read)) {
+ if (bufferevent_add_event_(&bev->ev_read, &bev->timeout_read) < 0)
+ r = -1;
+ } else {
+ event_remove_timer(&bev->ev_read);
+ }
+ }
+ if (event_pending(&bev->ev_write, EV_WRITE, NULL)) {
+ if (evutil_timerisset(&bev->timeout_write)) {
+ if (bufferevent_add_event_(&bev->ev_write, &bev->timeout_write) < 0)
+ r = -1;
+ } else {
+ event_remove_timer(&bev->ev_write);
+ }
+ }
+ return r;
+}
+
+int
+bufferevent_add_event_(struct event *ev, const struct timeval *tv)
+{
+ if (!evutil_timerisset(tv))
+ return event_add(ev, NULL);
+ else
+ return event_add(ev, tv);
+}
+
+/* For use by user programs only; internally, we should be calling
+ either bufferevent_incref_and_lock_(), or BEV_LOCK. */
+void
+bufferevent_lock(struct bufferevent *bev)
+{
+ bufferevent_incref_and_lock_(bev);
+}
+
+void
+bufferevent_unlock(struct bufferevent *bev)
+{
+ bufferevent_decref_and_unlock_(bev);
+}
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_async.c b/ipc/chromium/src/third_party/libevent/bufferevent_async.c
new file mode 100644
index 0000000000..40c7c5e8d0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_async.c
@@ -0,0 +1,706 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <winerror.h>
+#include <ws2tcpip.h>
+#endif
+
+#include <sys/queue.h>
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+#include "iocp-internal.h"
+
+#ifndef SO_UPDATE_CONNECT_CONTEXT
+/* Mingw is sometimes missing this */
+#define SO_UPDATE_CONNECT_CONTEXT 0x7010
+#endif
+
+/* prototypes */
+static int be_async_enable(struct bufferevent *, short);
+static int be_async_disable(struct bufferevent *, short);
+static void be_async_destruct(struct bufferevent *);
+static int be_async_flush(struct bufferevent *, short, enum bufferevent_flush_mode);
+static int be_async_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+struct bufferevent_async {
+ struct bufferevent_private bev;
+ struct event_overlapped connect_overlapped;
+ struct event_overlapped read_overlapped;
+ struct event_overlapped write_overlapped;
+ size_t read_in_progress;
+ size_t write_in_progress;
+ unsigned ok : 1;
+ unsigned read_added : 1;
+ unsigned write_added : 1;
+};
+
+const struct bufferevent_ops bufferevent_ops_async = {
+ "socket_async",
+ evutil_offsetof(struct bufferevent_async, bev.bev),
+ be_async_enable,
+ be_async_disable,
+ NULL, /* Unlink */
+ be_async_destruct,
+ bufferevent_generic_adj_timeouts_,
+ be_async_flush,
+ be_async_ctrl,
+};
+
+static inline void
+be_async_run_eventcb(struct bufferevent *bev, short what, int options)
+{ bufferevent_run_eventcb_(bev, what, options|BEV_TRIG_DEFER_CALLBACKS); }
+
+static inline void
+be_async_trigger_nolock(struct bufferevent *bev, short what, int options)
+{ bufferevent_trigger_nolock_(bev, what, options|BEV_TRIG_DEFER_CALLBACKS); }
+
+static inline int
+fatal_error(int err)
+{
+ switch (err) {
+ /* We may have already associated this fd with a port.
+ * Let's hope it's this port, and that the error code
+ * for doing this neer changes. */
+ case ERROR_INVALID_PARAMETER:
+ return 0;
+ }
+ return 1;
+}
+
+static inline struct bufferevent_async *
+upcast(struct bufferevent *bev)
+{
+ struct bufferevent_async *bev_a;
+ if (!BEV_IS_ASYNC(bev))
+ return NULL;
+ bev_a = EVUTIL_UPCAST(bev, struct bufferevent_async, bev.bev);
+ return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_connect(struct event_overlapped *eo)
+{
+ struct bufferevent_async *bev_a;
+ bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, connect_overlapped);
+ EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+ return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_read(struct event_overlapped *eo)
+{
+ struct bufferevent_async *bev_a;
+ bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, read_overlapped);
+ EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+ return bev_a;
+}
+
+static inline struct bufferevent_async *
+upcast_write(struct event_overlapped *eo)
+{
+ struct bufferevent_async *bev_a;
+ bev_a = EVUTIL_UPCAST(eo, struct bufferevent_async, write_overlapped);
+ EVUTIL_ASSERT(BEV_IS_ASYNC(&bev_a->bev.bev));
+ return bev_a;
+}
+
+static void
+bev_async_del_write(struct bufferevent_async *beva)
+{
+ struct bufferevent *bev = &beva->bev.bev;
+
+ if (beva->write_added) {
+ beva->write_added = 0;
+ event_base_del_virtual_(bev->ev_base);
+ }
+}
+
+static void
+bev_async_del_read(struct bufferevent_async *beva)
+{
+ struct bufferevent *bev = &beva->bev.bev;
+
+ if (beva->read_added) {
+ beva->read_added = 0;
+ event_base_del_virtual_(bev->ev_base);
+ }
+}
+
+static void
+bev_async_add_write(struct bufferevent_async *beva)
+{
+ struct bufferevent *bev = &beva->bev.bev;
+
+ if (!beva->write_added) {
+ beva->write_added = 1;
+ event_base_add_virtual_(bev->ev_base);
+ }
+}
+
+static void
+bev_async_add_read(struct bufferevent_async *beva)
+{
+ struct bufferevent *bev = &beva->bev.bev;
+
+ if (!beva->read_added) {
+ beva->read_added = 1;
+ event_base_add_virtual_(bev->ev_base);
+ }
+}
+
+static void
+bev_async_consider_writing(struct bufferevent_async *beva)
+{
+ size_t at_most;
+ int limit;
+ struct bufferevent *bev = &beva->bev.bev;
+
+ /* Don't write if there's a write in progress, or we do not
+ * want to write, or when there's nothing left to write. */
+ if (beva->write_in_progress || beva->bev.connecting)
+ return;
+ if (!beva->ok || !(bev->enabled&EV_WRITE) ||
+ !evbuffer_get_length(bev->output)) {
+ bev_async_del_write(beva);
+ return;
+ }
+
+ at_most = evbuffer_get_length(bev->output);
+
+ /* This is safe so long as bufferevent_get_write_max never returns
+ * more than INT_MAX. That's true for now. XXXX */
+ limit = (int)bufferevent_get_write_max_(&beva->bev);
+ if (at_most >= (size_t)limit && limit >= 0)
+ at_most = limit;
+
+ if (beva->bev.write_suspended) {
+ bev_async_del_write(beva);
+ return;
+ }
+
+ /* XXXX doesn't respect low-water mark very well. */
+ bufferevent_incref_(bev);
+ if (evbuffer_launch_write_(bev->output, at_most,
+ &beva->write_overlapped)) {
+ bufferevent_decref_(bev);
+ beva->ok = 0;
+ be_async_run_eventcb(bev, BEV_EVENT_ERROR, 0);
+ } else {
+ beva->write_in_progress = at_most;
+ bufferevent_decrement_write_buckets_(&beva->bev, at_most);
+ bev_async_add_write(beva);
+ }
+}
+
+static void
+bev_async_consider_reading(struct bufferevent_async *beva)
+{
+ size_t cur_size;
+ size_t read_high;
+ size_t at_most;
+ int limit;
+ struct bufferevent *bev = &beva->bev.bev;
+
+ /* Don't read if there is a read in progress, or we do not
+ * want to read. */
+ if (beva->read_in_progress || beva->bev.connecting)
+ return;
+ if (!beva->ok || !(bev->enabled&EV_READ)) {
+ bev_async_del_read(beva);
+ return;
+ }
+
+ /* Don't read if we're full */
+ cur_size = evbuffer_get_length(bev->input);
+ read_high = bev->wm_read.high;
+ if (read_high) {
+ if (cur_size >= read_high) {
+ bev_async_del_read(beva);
+ return;
+ }
+ at_most = read_high - cur_size;
+ } else {
+ at_most = 16384; /* FIXME totally magic. */
+ }
+
+ /* XXXX This over-commits. */
+ /* XXXX see also not above on cast on bufferevent_get_write_max_() */
+ limit = (int)bufferevent_get_read_max_(&beva->bev);
+ if (at_most >= (size_t)limit && limit >= 0)
+ at_most = limit;
+
+ if (beva->bev.read_suspended) {
+ bev_async_del_read(beva);
+ return;
+ }
+
+ bufferevent_incref_(bev);
+ if (evbuffer_launch_read_(bev->input, at_most, &beva->read_overlapped)) {
+ beva->ok = 0;
+ be_async_run_eventcb(bev, BEV_EVENT_ERROR, 0);
+ bufferevent_decref_(bev);
+ } else {
+ beva->read_in_progress = at_most;
+ bufferevent_decrement_read_buckets_(&beva->bev, at_most);
+ bev_async_add_read(beva);
+ }
+
+ return;
+}
+
+static void
+be_async_outbuf_callback(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+ struct bufferevent *bev = arg;
+ struct bufferevent_async *bev_async = upcast(bev);
+
+ /* If we added data to the outbuf and were not writing before,
+ * we may want to write now. */
+
+ bufferevent_incref_and_lock_(bev);
+
+ if (cbinfo->n_added)
+ bev_async_consider_writing(bev_async);
+
+ bufferevent_decref_and_unlock_(bev);
+}
+
+static void
+be_async_inbuf_callback(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+ struct bufferevent *bev = arg;
+ struct bufferevent_async *bev_async = upcast(bev);
+
+ /* If we drained data from the inbuf and were not reading before,
+ * we may want to read now */
+
+ bufferevent_incref_and_lock_(bev);
+
+ if (cbinfo->n_deleted)
+ bev_async_consider_reading(bev_async);
+
+ bufferevent_decref_and_unlock_(bev);
+}
+
+static int
+be_async_enable(struct bufferevent *buf, short what)
+{
+ struct bufferevent_async *bev_async = upcast(buf);
+
+ if (!bev_async->ok)
+ return -1;
+
+ if (bev_async->bev.connecting) {
+ /* Don't launch anything during connection attempts. */
+ return 0;
+ }
+
+ if (what & EV_READ)
+ BEV_RESET_GENERIC_READ_TIMEOUT(buf);
+ if (what & EV_WRITE)
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(buf);
+
+ /* If we newly enable reading or writing, and we aren't reading or
+ writing already, consider launching a new read or write. */
+
+ if (what & EV_READ)
+ bev_async_consider_reading(bev_async);
+ if (what & EV_WRITE)
+ bev_async_consider_writing(bev_async);
+ return 0;
+}
+
+static int
+be_async_disable(struct bufferevent *bev, short what)
+{
+ struct bufferevent_async *bev_async = upcast(bev);
+ /* XXXX If we disable reading or writing, we may want to consider
+ * canceling any in-progress read or write operation, though it might
+ * not work. */
+
+ if (what & EV_READ) {
+ BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+ bev_async_del_read(bev_async);
+ }
+ if (what & EV_WRITE) {
+ BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+ bev_async_del_write(bev_async);
+ }
+
+ return 0;
+}
+
+static void
+be_async_destruct(struct bufferevent *bev)
+{
+ struct bufferevent_async *bev_async = upcast(bev);
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ evutil_socket_t fd;
+
+ EVUTIL_ASSERT(!upcast(bev)->write_in_progress &&
+ !upcast(bev)->read_in_progress);
+
+ bev_async_del_read(bev_async);
+ bev_async_del_write(bev_async);
+
+ fd = evbuffer_overlapped_get_fd_(bev->input);
+ if (fd != (evutil_socket_t)EVUTIL_INVALID_SOCKET &&
+ (bev_p->options & BEV_OPT_CLOSE_ON_FREE)) {
+ evutil_closesocket(fd);
+ evbuffer_overlapped_set_fd_(bev->input, EVUTIL_INVALID_SOCKET);
+ }
+}
+
+/* GetQueuedCompletionStatus doesn't reliably yield WSA error codes, so
+ * we use WSAGetOverlappedResult to translate. */
+static void
+bev_async_set_wsa_error(struct bufferevent *bev, struct event_overlapped *eo)
+{
+ DWORD bytes, flags;
+ evutil_socket_t fd;
+
+ fd = evbuffer_overlapped_get_fd_(bev->input);
+ WSAGetOverlappedResult(fd, &eo->overlapped, &bytes, FALSE, &flags);
+}
+
+static int
+be_async_flush(struct bufferevent *bev, short what,
+ enum bufferevent_flush_mode mode)
+{
+ return 0;
+}
+
+static void
+connect_complete(struct event_overlapped *eo, ev_uintptr_t key,
+ ev_ssize_t nbytes, int ok)
+{
+ struct bufferevent_async *bev_a = upcast_connect(eo);
+ struct bufferevent *bev = &bev_a->bev.bev;
+ evutil_socket_t sock;
+
+ BEV_LOCK(bev);
+
+ EVUTIL_ASSERT(bev_a->bev.connecting);
+ bev_a->bev.connecting = 0;
+ sock = evbuffer_overlapped_get_fd_(bev_a->bev.bev.input);
+ /* XXXX Handle error? */
+ setsockopt(sock, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0);
+
+ if (ok)
+ bufferevent_async_set_connected_(bev);
+ else
+ bev_async_set_wsa_error(bev, eo);
+
+ be_async_run_eventcb(bev, ok ? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR, 0);
+
+ event_base_del_virtual_(bev->ev_base);
+
+ bufferevent_decref_and_unlock_(bev);
+}
+
+static void
+read_complete(struct event_overlapped *eo, ev_uintptr_t key,
+ ev_ssize_t nbytes, int ok)
+{
+ struct bufferevent_async *bev_a = upcast_read(eo);
+ struct bufferevent *bev = &bev_a->bev.bev;
+ short what = BEV_EVENT_READING;
+ ev_ssize_t amount_unread;
+ BEV_LOCK(bev);
+ EVUTIL_ASSERT(bev_a->read_in_progress);
+
+ amount_unread = bev_a->read_in_progress - nbytes;
+ evbuffer_commit_read_(bev->input, nbytes);
+ bev_a->read_in_progress = 0;
+ if (amount_unread)
+ bufferevent_decrement_read_buckets_(&bev_a->bev, -amount_unread);
+
+ if (!ok)
+ bev_async_set_wsa_error(bev, eo);
+
+ if (bev_a->ok) {
+ if (ok && nbytes) {
+ BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+ be_async_trigger_nolock(bev, EV_READ, 0);
+ bev_async_consider_reading(bev_a);
+ } else if (!ok) {
+ what |= BEV_EVENT_ERROR;
+ bev_a->ok = 0;
+ be_async_run_eventcb(bev, what, 0);
+ } else if (!nbytes) {
+ what |= BEV_EVENT_EOF;
+ bev_a->ok = 0;
+ be_async_run_eventcb(bev, what, 0);
+ }
+ }
+
+ bufferevent_decref_and_unlock_(bev);
+}
+
+static void
+write_complete(struct event_overlapped *eo, ev_uintptr_t key,
+ ev_ssize_t nbytes, int ok)
+{
+ struct bufferevent_async *bev_a = upcast_write(eo);
+ struct bufferevent *bev = &bev_a->bev.bev;
+ short what = BEV_EVENT_WRITING;
+ ev_ssize_t amount_unwritten;
+
+ BEV_LOCK(bev);
+ EVUTIL_ASSERT(bev_a->write_in_progress);
+
+ amount_unwritten = bev_a->write_in_progress - nbytes;
+ evbuffer_commit_write_(bev->output, nbytes);
+ bev_a->write_in_progress = 0;
+
+ if (amount_unwritten)
+ bufferevent_decrement_write_buckets_(&bev_a->bev,
+ -amount_unwritten);
+
+
+ if (!ok)
+ bev_async_set_wsa_error(bev, eo);
+
+ if (bev_a->ok) {
+ if (ok && nbytes) {
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+ be_async_trigger_nolock(bev, EV_WRITE, 0);
+ bev_async_consider_writing(bev_a);
+ } else if (!ok) {
+ what |= BEV_EVENT_ERROR;
+ bev_a->ok = 0;
+ be_async_run_eventcb(bev, what, 0);
+ } else if (!nbytes) {
+ what |= BEV_EVENT_EOF;
+ bev_a->ok = 0;
+ be_async_run_eventcb(bev, what, 0);
+ }
+ }
+
+ bufferevent_decref_and_unlock_(bev);
+}
+
+struct bufferevent *
+bufferevent_async_new_(struct event_base *base,
+ evutil_socket_t fd, int options)
+{
+ struct bufferevent_async *bev_a;
+ struct bufferevent *bev;
+ struct event_iocp_port *iocp;
+
+ options |= BEV_OPT_THREADSAFE;
+
+ if (!(iocp = event_base_get_iocp_(base)))
+ return NULL;
+
+ if (fd >= 0 && event_iocp_port_associate_(iocp, fd, 1)<0) {
+ if (fatal_error(GetLastError()))
+ return NULL;
+ }
+
+ if (!(bev_a = mm_calloc(1, sizeof(struct bufferevent_async))))
+ return NULL;
+
+ bev = &bev_a->bev.bev;
+ if (!(bev->input = evbuffer_overlapped_new_(fd))) {
+ mm_free(bev_a);
+ return NULL;
+ }
+ if (!(bev->output = evbuffer_overlapped_new_(fd))) {
+ evbuffer_free(bev->input);
+ mm_free(bev_a);
+ return NULL;
+ }
+
+ if (bufferevent_init_common_(&bev_a->bev, base, &bufferevent_ops_async,
+ options)<0)
+ goto err;
+
+ evbuffer_add_cb(bev->input, be_async_inbuf_callback, bev);
+ evbuffer_add_cb(bev->output, be_async_outbuf_callback, bev);
+
+ event_overlapped_init_(&bev_a->connect_overlapped, connect_complete);
+ event_overlapped_init_(&bev_a->read_overlapped, read_complete);
+ event_overlapped_init_(&bev_a->write_overlapped, write_complete);
+
+ bufferevent_init_generic_timeout_cbs_(bev);
+
+ bev_a->ok = fd >= 0;
+
+ return bev;
+err:
+ bufferevent_free(&bev_a->bev.bev);
+ return NULL;
+}
+
+void
+bufferevent_async_set_connected_(struct bufferevent *bev)
+{
+ struct bufferevent_async *bev_async = upcast(bev);
+ bev_async->ok = 1;
+ /* Now's a good time to consider reading/writing */
+ be_async_enable(bev, bev->enabled);
+}
+
+int
+bufferevent_async_can_connect_(struct bufferevent *bev)
+{
+ const struct win32_extension_fns *ext =
+ event_get_win32_extension_fns_();
+
+ if (BEV_IS_ASYNC(bev) &&
+ event_base_get_iocp_(bev->ev_base) &&
+ ext && ext->ConnectEx)
+ return 1;
+
+ return 0;
+}
+
+int
+bufferevent_async_connect_(struct bufferevent *bev, evutil_socket_t fd,
+ const struct sockaddr *sa, int socklen)
+{
+ BOOL rc;
+ struct bufferevent_async *bev_async = upcast(bev);
+ struct sockaddr_storage ss;
+ const struct win32_extension_fns *ext =
+ event_get_win32_extension_fns_();
+
+ EVUTIL_ASSERT(ext && ext->ConnectEx && fd >= 0 && sa != NULL);
+
+ /* ConnectEx() requires that the socket be bound to an address
+ * with bind() before using, otherwise it will fail. We attempt
+ * to issue a bind() here, taking into account that the error
+ * code is set to WSAEINVAL when the socket is already bound. */
+ memset(&ss, 0, sizeof(ss));
+ if (sa->sa_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in *)&ss;
+ sin->sin_family = AF_INET;
+ sin->sin_addr.s_addr = INADDR_ANY;
+ } else if (sa->sa_family == AF_INET6) {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&ss;
+ sin6->sin6_family = AF_INET6;
+ sin6->sin6_addr = in6addr_any;
+ } else {
+ /* Well, the user will have to bind() */
+ return -1;
+ }
+ if (bind(fd, (struct sockaddr *)&ss, sizeof(ss)) < 0 &&
+ WSAGetLastError() != WSAEINVAL)
+ return -1;
+
+ event_base_add_virtual_(bev->ev_base);
+ bufferevent_incref_(bev);
+ rc = ext->ConnectEx(fd, sa, socklen, NULL, 0, NULL,
+ &bev_async->connect_overlapped.overlapped);
+ if (rc || WSAGetLastError() == ERROR_IO_PENDING)
+ return 0;
+
+ event_base_del_virtual_(bev->ev_base);
+ bufferevent_decref_(bev);
+
+ return -1;
+}
+
+static int
+be_async_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+ union bufferevent_ctrl_data *data)
+{
+ switch (op) {
+ case BEV_CTRL_GET_FD:
+ data->fd = evbuffer_overlapped_get_fd_(bev->input);
+ return 0;
+ case BEV_CTRL_SET_FD: {
+ struct bufferevent_async *bev_a = upcast(bev);
+ struct event_iocp_port *iocp;
+
+ if (data->fd == evbuffer_overlapped_get_fd_(bev->input))
+ return 0;
+ if (!(iocp = event_base_get_iocp_(bev->ev_base)))
+ return -1;
+ if (event_iocp_port_associate_(iocp, data->fd, 1) < 0) {
+ if (fatal_error(GetLastError()))
+ return -1;
+ }
+ evbuffer_overlapped_set_fd_(bev->input, data->fd);
+ evbuffer_overlapped_set_fd_(bev->output, data->fd);
+ bev_a->ok = data->fd >= 0;
+ return 0;
+ }
+ case BEV_CTRL_CANCEL_ALL: {
+ struct bufferevent_async *bev_a = upcast(bev);
+ evutil_socket_t fd = evbuffer_overlapped_get_fd_(bev->input);
+ if (fd != (evutil_socket_t)EVUTIL_INVALID_SOCKET &&
+ (bev_a->bev.options & BEV_OPT_CLOSE_ON_FREE)) {
+ closesocket(fd);
+ evbuffer_overlapped_set_fd_(bev->input, EVUTIL_INVALID_SOCKET);
+ }
+ bev_a->ok = 0;
+ return 0;
+ }
+ case BEV_CTRL_GET_UNDERLYING:
+ default:
+ return -1;
+ }
+}
+
+
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_filter.c b/ipc/chromium/src/third_party/libevent/bufferevent_filter.c
new file mode 100644
index 0000000000..a7bdedddfe
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_filter.c
@@ -0,0 +1,625 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#include "event2/event-config.h"
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+
+/* prototypes */
+static int be_filter_enable(struct bufferevent *, short);
+static int be_filter_disable(struct bufferevent *, short);
+static void be_filter_unlink(struct bufferevent *);
+static void be_filter_destruct(struct bufferevent *);
+
+static void be_filter_readcb(struct bufferevent *, void *);
+static void be_filter_writecb(struct bufferevent *, void *);
+static void be_filter_eventcb(struct bufferevent *, short, void *);
+static int be_filter_flush(struct bufferevent *bufev,
+ short iotype, enum bufferevent_flush_mode mode);
+static int be_filter_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+static void bufferevent_filtered_inbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo, void *arg);
+
+static void bufferevent_filtered_outbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *info, void *arg);
+
+struct bufferevent_filtered {
+ struct bufferevent_private bev;
+
+ /** The bufferevent that we read/write filtered data from/to. */
+ struct bufferevent *underlying;
+ /** A callback on our inbuf to notice somebory removes data */
+ struct evbuffer_cb_entry *inbuf_cb;
+ /** A callback on our outbuf to notice when somebody adds data */
+ struct evbuffer_cb_entry *outbuf_cb;
+ /** True iff we have received an EOF callback from the underlying
+ * bufferevent. */
+ unsigned got_eof;
+
+ /** Function to free context when we're done. */
+ void (*free_context)(void *);
+ /** Input filter */
+ bufferevent_filter_cb process_in;
+ /** Output filter */
+ bufferevent_filter_cb process_out;
+ /** User-supplied argument to the filters. */
+ void *context;
+};
+
+const struct bufferevent_ops bufferevent_ops_filter = {
+ "filter",
+ evutil_offsetof(struct bufferevent_filtered, bev.bev),
+ be_filter_enable,
+ be_filter_disable,
+ be_filter_unlink,
+ be_filter_destruct,
+ bufferevent_generic_adj_timeouts_,
+ be_filter_flush,
+ be_filter_ctrl,
+};
+
+/* Given a bufferevent that's really the bev filter of a bufferevent_filtered,
+ * return that bufferevent_filtered. Returns NULL otherwise.*/
+static inline struct bufferevent_filtered *
+upcast(struct bufferevent *bev)
+{
+ struct bufferevent_filtered *bev_f;
+ if (!BEV_IS_FILTER(bev))
+ return NULL;
+ bev_f = (void*)( ((char*)bev) -
+ evutil_offsetof(struct bufferevent_filtered, bev.bev));
+ EVUTIL_ASSERT(BEV_IS_FILTER(&bev_f->bev.bev));
+ return bev_f;
+}
+
+#define downcast(bev_f) (&(bev_f)->bev.bev)
+
+/** Return 1 iff bevf's underlying bufferevent's output buffer is at or
+ * over its high watermark such that we should not write to it in a given
+ * flush mode. */
+static int
+be_underlying_writebuf_full(struct bufferevent_filtered *bevf,
+ enum bufferevent_flush_mode state)
+{
+ struct bufferevent *u = bevf->underlying;
+ return state == BEV_NORMAL &&
+ u->wm_write.high &&
+ evbuffer_get_length(u->output) >= u->wm_write.high;
+}
+
+/** Return 1 if our input buffer is at or over its high watermark such that we
+ * should not write to it in a given flush mode. */
+static int
+be_readbuf_full(struct bufferevent_filtered *bevf,
+ enum bufferevent_flush_mode state)
+{
+ struct bufferevent *bufev = downcast(bevf);
+ return state == BEV_NORMAL &&
+ bufev->wm_read.high &&
+ evbuffer_get_length(bufev->input) >= bufev->wm_read.high;
+}
+
+
+/* Filter to use when we're created with a NULL filter. */
+static enum bufferevent_filter_result
+be_null_filter(struct evbuffer *src, struct evbuffer *dst, ev_ssize_t lim,
+ enum bufferevent_flush_mode state, void *ctx)
+{
+ (void)state;
+ if (evbuffer_remove_buffer(src, dst, lim) >= 0)
+ return BEV_OK;
+ else
+ return BEV_ERROR;
+}
+
+struct bufferevent *
+bufferevent_filter_new(struct bufferevent *underlying,
+ bufferevent_filter_cb input_filter,
+ bufferevent_filter_cb output_filter,
+ int options,
+ void (*free_context)(void *),
+ void *ctx)
+{
+ struct bufferevent_filtered *bufev_f;
+ int tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+ if (!underlying)
+ return NULL;
+
+ if (!input_filter)
+ input_filter = be_null_filter;
+ if (!output_filter)
+ output_filter = be_null_filter;
+
+ bufev_f = mm_calloc(1, sizeof(struct bufferevent_filtered));
+ if (!bufev_f)
+ return NULL;
+
+ if (bufferevent_init_common_(&bufev_f->bev, underlying->ev_base,
+ &bufferevent_ops_filter, tmp_options) < 0) {
+ mm_free(bufev_f);
+ return NULL;
+ }
+ if (options & BEV_OPT_THREADSAFE) {
+ bufferevent_enable_locking_(downcast(bufev_f), NULL);
+ }
+
+ bufev_f->underlying = underlying;
+
+ bufev_f->process_in = input_filter;
+ bufev_f->process_out = output_filter;
+ bufev_f->free_context = free_context;
+ bufev_f->context = ctx;
+
+ bufferevent_setcb(bufev_f->underlying,
+ be_filter_readcb, be_filter_writecb, be_filter_eventcb, bufev_f);
+
+ bufev_f->inbuf_cb = evbuffer_add_cb(downcast(bufev_f)->input,
+ bufferevent_filtered_inbuf_cb, bufev_f);
+ evbuffer_cb_clear_flags(downcast(bufev_f)->input, bufev_f->inbuf_cb,
+ EVBUFFER_CB_ENABLED);
+
+ bufev_f->outbuf_cb = evbuffer_add_cb(downcast(bufev_f)->output,
+ bufferevent_filtered_outbuf_cb, bufev_f);
+
+ bufferevent_init_generic_timeout_cbs_(downcast(bufev_f));
+ bufferevent_incref_(underlying);
+
+ bufferevent_enable(underlying, EV_READ|EV_WRITE);
+ bufferevent_suspend_read_(underlying, BEV_SUSPEND_FILT_READ);
+
+ return downcast(bufev_f);
+}
+
+static void
+be_filter_unlink(struct bufferevent *bev)
+{
+ struct bufferevent_filtered *bevf = upcast(bev);
+ EVUTIL_ASSERT(bevf);
+
+ if (bevf->bev.options & BEV_OPT_CLOSE_ON_FREE) {
+ /* Yes, there is also a decref in bufferevent_decref_.
+ * That decref corresponds to the incref when we set
+ * underlying for the first time. This decref is an
+ * extra one to remove the last reference.
+ */
+ if (BEV_UPCAST(bevf->underlying)->refcnt < 2) {
+ event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
+ "bufferevent with too few references");
+ } else {
+ bufferevent_free(bevf->underlying);
+ }
+ } else {
+ if (bevf->underlying) {
+ if (bevf->underlying->errorcb == be_filter_eventcb)
+ bufferevent_setcb(bevf->underlying,
+ NULL, NULL, NULL, NULL);
+ bufferevent_unsuspend_read_(bevf->underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+ }
+}
+
+static void
+be_filter_destruct(struct bufferevent *bev)
+{
+ struct bufferevent_filtered *bevf = upcast(bev);
+ EVUTIL_ASSERT(bevf);
+ if (bevf->free_context)
+ bevf->free_context(bevf->context);
+
+ if (bevf->inbuf_cb)
+ evbuffer_remove_cb_entry(bev->input, bevf->inbuf_cb);
+
+ if (bevf->outbuf_cb)
+ evbuffer_remove_cb_entry(bev->output, bevf->outbuf_cb);
+}
+
+static int
+be_filter_enable(struct bufferevent *bev, short event)
+{
+ struct bufferevent_filtered *bevf = upcast(bev);
+ if (event & EV_WRITE)
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+ if (event & EV_READ) {
+ BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+ bufferevent_unsuspend_read_(bevf->underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+ return 0;
+}
+
+static int
+be_filter_disable(struct bufferevent *bev, short event)
+{
+ struct bufferevent_filtered *bevf = upcast(bev);
+ if (event & EV_WRITE)
+ BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+ if (event & EV_READ) {
+ BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+ bufferevent_suspend_read_(bevf->underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+ return 0;
+}
+
+static enum bufferevent_filter_result
+be_filter_process_input(struct bufferevent_filtered *bevf,
+ enum bufferevent_flush_mode state,
+ int *processed_out)
+{
+ enum bufferevent_filter_result res;
+ struct bufferevent *bev = downcast(bevf);
+
+ if (state == BEV_NORMAL) {
+ /* If we're in 'normal' mode, don't urge data on the filter
+ * unless we're reading data and under our high-water mark.*/
+ if (!(bev->enabled & EV_READ) ||
+ be_readbuf_full(bevf, state))
+ return BEV_OK;
+ }
+
+ do {
+ ev_ssize_t limit = -1;
+ if (state == BEV_NORMAL && bev->wm_read.high)
+ limit = bev->wm_read.high -
+ evbuffer_get_length(bev->input);
+
+ res = bevf->process_in(bevf->underlying->input,
+ bev->input, limit, state, bevf->context);
+
+ if (res == BEV_OK)
+ *processed_out = 1;
+ } while (res == BEV_OK &&
+ (bev->enabled & EV_READ) &&
+ evbuffer_get_length(bevf->underlying->input) &&
+ !be_readbuf_full(bevf, state));
+
+ if (*processed_out)
+ BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+
+ return res;
+}
+
+
+static enum bufferevent_filter_result
+be_filter_process_output(struct bufferevent_filtered *bevf,
+ enum bufferevent_flush_mode state,
+ int *processed_out)
+{
+ /* Requires references and lock: might call writecb */
+ enum bufferevent_filter_result res = BEV_OK;
+ struct bufferevent *bufev = downcast(bevf);
+ int again = 0;
+
+ if (state == BEV_NORMAL) {
+ /* If we're in 'normal' mode, don't urge data on the
+ * filter unless we're writing data, and the underlying
+ * bufferevent is accepting data, and we have data to
+ * give the filter. If we're in 'flush' or 'finish',
+ * call the filter no matter what. */
+ if (!(bufev->enabled & EV_WRITE) ||
+ be_underlying_writebuf_full(bevf, state) ||
+ !evbuffer_get_length(bufev->output))
+ return BEV_OK;
+ }
+
+ /* disable the callback that calls this function
+ when the user adds to the output buffer. */
+ evbuffer_cb_clear_flags(bufev->output, bevf->outbuf_cb,
+ EVBUFFER_CB_ENABLED);
+
+ do {
+ int processed = 0;
+ again = 0;
+
+ do {
+ ev_ssize_t limit = -1;
+ if (state == BEV_NORMAL &&
+ bevf->underlying->wm_write.high)
+ limit = bevf->underlying->wm_write.high -
+ evbuffer_get_length(bevf->underlying->output);
+
+ res = bevf->process_out(downcast(bevf)->output,
+ bevf->underlying->output,
+ limit,
+ state,
+ bevf->context);
+
+ if (res == BEV_OK)
+ processed = *processed_out = 1;
+ } while (/* Stop if the filter wasn't successful...*/
+ res == BEV_OK &&
+ /* Or if we aren't writing any more. */
+ (bufev->enabled & EV_WRITE) &&
+ /* Of if we have nothing more to write and we are
+ * not flushing. */
+ evbuffer_get_length(bufev->output) &&
+ /* Or if we have filled the underlying output buffer. */
+ !be_underlying_writebuf_full(bevf,state));
+
+ if (processed) {
+ /* call the write callback.*/
+ bufferevent_trigger_nolock_(bufev, EV_WRITE, 0);
+
+ if (res == BEV_OK &&
+ (bufev->enabled & EV_WRITE) &&
+ evbuffer_get_length(bufev->output) &&
+ !be_underlying_writebuf_full(bevf, state)) {
+ again = 1;
+ }
+ }
+ } while (again);
+
+ /* reenable the outbuf_cb */
+ evbuffer_cb_set_flags(bufev->output,bevf->outbuf_cb,
+ EVBUFFER_CB_ENABLED);
+
+ if (*processed_out)
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bufev);
+
+ return res;
+}
+
+/* Called when the size of our outbuf changes. */
+static void
+bufferevent_filtered_outbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo, void *arg)
+{
+ struct bufferevent_filtered *bevf = arg;
+ struct bufferevent *bev = downcast(bevf);
+
+ if (cbinfo->n_added) {
+ int processed_any = 0;
+ /* Somebody added more data to the output buffer. Try to
+ * process it, if we should. */
+ bufferevent_incref_and_lock_(bev);
+ be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
+ bufferevent_decref_and_unlock_(bev);
+ }
+}
+
+static void
+be_filter_read_nolock_(struct bufferevent *underlying, void *me_)
+{
+ struct bufferevent_filtered *bevf = me_;
+ enum bufferevent_filter_result res;
+ enum bufferevent_flush_mode state;
+ struct bufferevent *bufev = downcast(bevf);
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bufev);
+ int processed_any = 0;
+
+ // It's possible our refcount is 0 at this point if another thread free'd our filterevent
+ EVUTIL_ASSERT(bufev_private->refcnt >= 0);
+
+ // If our refcount is > 0
+ if (bufev_private->refcnt > 0) {
+
+ if (bevf->got_eof)
+ state = BEV_FINISHED;
+ else
+ state = BEV_NORMAL;
+
+ /* XXXX use return value */
+ res = be_filter_process_input(bevf, state, &processed_any);
+ (void)res;
+
+ /* XXX This should be in process_input, not here. There are
+ * other places that can call process-input, and they should
+ * force readcb calls as needed. */
+ if (processed_any) {
+ bufferevent_trigger_nolock_(bufev, EV_READ, 0);
+ if (evbuffer_get_length(underlying->input) > 0 &&
+ be_readbuf_full(bevf, state)) {
+ /* data left in underlying buffer and filter input buffer
+ * hit its read high watermark.
+ * Schedule callback to avoid data gets stuck in underlying
+ * input buffer.
+ */
+ evbuffer_cb_set_flags(bufev->input, bevf->inbuf_cb,
+ EVBUFFER_CB_ENABLED);
+ }
+ }
+ }
+}
+
+/* Called when the size of our inbuf changes. */
+static void
+bufferevent_filtered_inbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo, void *arg)
+{
+ struct bufferevent_filtered *bevf = arg;
+ enum bufferevent_flush_mode state;
+ struct bufferevent *bev = downcast(bevf);
+
+ BEV_LOCK(bev);
+
+ if (bevf->got_eof)
+ state = BEV_FINISHED;
+ else
+ state = BEV_NORMAL;
+
+
+ if (!be_readbuf_full(bevf, state)) {
+ /* opportunity to read data which was left in underlying
+ * input buffer because filter input buffer hit read
+ * high watermark.
+ */
+ evbuffer_cb_clear_flags(bev->input, bevf->inbuf_cb,
+ EVBUFFER_CB_ENABLED);
+ if (evbuffer_get_length(bevf->underlying->input) > 0)
+ be_filter_read_nolock_(bevf->underlying, bevf);
+ }
+
+ BEV_UNLOCK(bev);
+}
+
+/* Called when the underlying socket has read. */
+static void
+be_filter_readcb(struct bufferevent *underlying, void *me_)
+{
+ struct bufferevent_filtered *bevf = me_;
+ struct bufferevent *bev = downcast(bevf);
+
+ BEV_LOCK(bev);
+
+ be_filter_read_nolock_(underlying, me_);
+
+ BEV_UNLOCK(bev);
+}
+
+/* Called when the underlying socket has drained enough that we can write to
+ it. */
+static void
+be_filter_writecb(struct bufferevent *underlying, void *me_)
+{
+ struct bufferevent_filtered *bevf = me_;
+ struct bufferevent *bev = downcast(bevf);
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bev);
+ int processed_any = 0;
+
+ BEV_LOCK(bev);
+
+ // It's possible our refcount is 0 at this point if another thread free'd our filterevent
+ EVUTIL_ASSERT(bufev_private->refcnt >= 0);
+
+ // If our refcount is > 0
+ if (bufev_private->refcnt > 0) {
+ be_filter_process_output(bevf, BEV_NORMAL, &processed_any);
+ }
+
+ BEV_UNLOCK(bev);
+}
+
+/* Called when the underlying socket has given us an error */
+static void
+be_filter_eventcb(struct bufferevent *underlying, short what, void *me_)
+{
+ struct bufferevent_filtered *bevf = me_;
+ struct bufferevent *bev = downcast(bevf);
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bev);
+
+ BEV_LOCK(bev);
+
+ // It's possible our refcount is 0 at this point if another thread free'd our filterevent
+ EVUTIL_ASSERT(bufev_private->refcnt >= 0);
+
+ // If our refcount is > 0
+ if (bufev_private->refcnt > 0) {
+
+ /* All we can really to is tell our own eventcb. */
+ bufferevent_run_eventcb_(bev, what, 0);
+ }
+
+ BEV_UNLOCK(bev);
+}
+
+static int
+be_filter_flush(struct bufferevent *bufev,
+ short iotype, enum bufferevent_flush_mode mode)
+{
+ struct bufferevent_filtered *bevf = upcast(bufev);
+ int processed_any = 0;
+ EVUTIL_ASSERT(bevf);
+
+ bufferevent_incref_and_lock_(bufev);
+
+ if (iotype & EV_READ) {
+ be_filter_process_input(bevf, mode, &processed_any);
+ }
+ if (iotype & EV_WRITE) {
+ be_filter_process_output(bevf, mode, &processed_any);
+ }
+ /* XXX check the return value? */
+ /* XXX does this want to recursively call lower-level flushes? */
+ bufferevent_flush(bevf->underlying, iotype, mode);
+
+ bufferevent_decref_and_unlock_(bufev);
+
+ return processed_any;
+}
+
+static int
+be_filter_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+ union bufferevent_ctrl_data *data)
+{
+ struct bufferevent_filtered *bevf;
+ switch (op) {
+ case BEV_CTRL_GET_UNDERLYING:
+ bevf = upcast(bev);
+ data->ptr = bevf->underlying;
+ return 0;
+ case BEV_CTRL_SET_FD:
+ case BEV_CTRL_GET_FD:
+ bevf = upcast(bev);
+
+ if (bevf->underlying &&
+ bevf->underlying->be_ops &&
+ bevf->underlying->be_ops->ctrl) {
+ return (bevf->underlying->be_ops->ctrl)(bevf->underlying, op, data);
+ }
+ EVUTIL_FALLTHROUGH;
+
+ case BEV_CTRL_CANCEL_ALL:
+ EVUTIL_FALLTHROUGH;
+ default:
+ return -1;
+ }
+
+ return -1;
+}
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_openssl.c b/ipc/chromium/src/third_party/libevent/bufferevent_openssl.c
new file mode 100644
index 0000000000..b51b834bca
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_openssl.c
@@ -0,0 +1,1524 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// Get rid of OSX 10.7 and greater deprecation warnings.
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_ssl.h"
+#include "event2/buffer.h"
+#include "event2/event.h"
+
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "log-internal.h"
+
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include "openssl-compat.h"
+
+/*
+ * Define an OpenSSL bio that targets a bufferevent.
+ */
+
+/* --------------------
+ A BIO is an OpenSSL abstraction that handles reading and writing data. The
+ library will happily speak SSL over anything that implements a BIO
+ interface.
+
+ Here we define a BIO implementation that directs its output to a
+ bufferevent. We'll want to use this only when none of OpenSSL's built-in
+ IO mechanisms work for us.
+ -------------------- */
+
+/* every BIO type needs its own integer type value. */
+#define BIO_TYPE_LIBEVENT 57
+/* ???? Arguably, we should set BIO_TYPE_FILTER or BIO_TYPE_SOURCE_SINK on
+ * this. */
+
+#if 0
+static void
+print_err(int val)
+{
+ int err;
+ printf("Error was %d\n", val);
+
+ while ((err = ERR_get_error())) {
+ const char *msg = (const char*)ERR_reason_error_string(err);
+ const char *lib = (const char*)ERR_lib_error_string(err);
+ const char *func = (const char*)ERR_func_error_string(err);
+
+ printf("%s in %s %s\n", msg, lib, func);
+ }
+}
+#else
+#define print_err(v) ((void)0)
+#endif
+
+/* Called to initialize a new BIO */
+static int
+bio_bufferevent_new(BIO *b)
+{
+ BIO_set_init(b, 0);
+ BIO_set_data(b, NULL); /* We'll be putting the bufferevent in this field.*/
+ return 1;
+}
+
+/* Called to uninitialize the BIO. */
+static int
+bio_bufferevent_free(BIO *b)
+{
+ if (!b)
+ return 0;
+ if (BIO_get_shutdown(b)) {
+ if (BIO_get_init(b) && BIO_get_data(b))
+ bufferevent_free(BIO_get_data(b));
+ BIO_free(b);
+ }
+ return 1;
+}
+
+/* Called to extract data from the BIO. */
+static int
+bio_bufferevent_read(BIO *b, char *out, int outlen)
+{
+ int r = 0;
+ struct evbuffer *input;
+
+ BIO_clear_retry_flags(b);
+
+ if (!out)
+ return 0;
+ if (!BIO_get_data(b))
+ return -1;
+
+ input = bufferevent_get_input(BIO_get_data(b));
+ if (evbuffer_get_length(input) == 0) {
+ /* If there's no data to read, say so. */
+ BIO_set_retry_read(b);
+ return -1;
+ } else {
+ r = evbuffer_remove(input, out, outlen);
+ }
+
+ return r;
+}
+
+/* Called to write data into the BIO */
+static int
+bio_bufferevent_write(BIO *b, const char *in, int inlen)
+{
+ struct bufferevent *bufev = BIO_get_data(b);
+ struct evbuffer *output;
+ size_t outlen;
+
+ BIO_clear_retry_flags(b);
+
+ if (!BIO_get_data(b))
+ return -1;
+
+ output = bufferevent_get_output(bufev);
+ outlen = evbuffer_get_length(output);
+
+ /* Copy only as much data onto the output buffer as can fit under the
+ * high-water mark. */
+ if (bufev->wm_write.high && bufev->wm_write.high <= (outlen+inlen)) {
+ if (bufev->wm_write.high <= outlen) {
+ /* If no data can fit, we'll need to retry later. */
+ BIO_set_retry_write(b);
+ return -1;
+ }
+ inlen = bufev->wm_write.high - outlen;
+ }
+
+ EVUTIL_ASSERT(inlen > 0);
+ evbuffer_add(output, in, inlen);
+ return inlen;
+}
+
+/* Called to handle various requests */
+static long
+bio_bufferevent_ctrl(BIO *b, int cmd, long num, void *ptr)
+{
+ struct bufferevent *bufev = BIO_get_data(b);
+ long ret = 1;
+
+ switch (cmd) {
+ case BIO_CTRL_GET_CLOSE:
+ ret = BIO_get_shutdown(b);
+ break;
+ case BIO_CTRL_SET_CLOSE:
+ BIO_set_shutdown(b, (int)num);
+ break;
+ case BIO_CTRL_PENDING:
+ ret = evbuffer_get_length(bufferevent_get_input(bufev)) != 0;
+ break;
+ case BIO_CTRL_WPENDING:
+ ret = evbuffer_get_length(bufferevent_get_output(bufev)) != 0;
+ break;
+ /* XXXX These two are given a special-case treatment because
+ * of cargo-cultism. I should come up with a better reason. */
+ case BIO_CTRL_DUP:
+ case BIO_CTRL_FLUSH:
+ ret = 1;
+ break;
+ default:
+ ret = 0;
+ break;
+ }
+ return ret;
+}
+
+/* Called to write a string to the BIO */
+static int
+bio_bufferevent_puts(BIO *b, const char *s)
+{
+ return bio_bufferevent_write(b, s, strlen(s));
+}
+
+/* Method table for the bufferevent BIO */
+static BIO_METHOD *methods_bufferevent;
+
+/* Return the method table for the bufferevents BIO */
+static BIO_METHOD *
+BIO_s_bufferevent(void)
+{
+ if (methods_bufferevent == NULL) {
+ methods_bufferevent = BIO_meth_new(BIO_TYPE_LIBEVENT, "bufferevent");
+ if (methods_bufferevent == NULL)
+ return NULL;
+ BIO_meth_set_write(methods_bufferevent, bio_bufferevent_write);
+ BIO_meth_set_read(methods_bufferevent, bio_bufferevent_read);
+ BIO_meth_set_puts(methods_bufferevent, bio_bufferevent_puts);
+ BIO_meth_set_ctrl(methods_bufferevent, bio_bufferevent_ctrl);
+ BIO_meth_set_create(methods_bufferevent, bio_bufferevent_new);
+ BIO_meth_set_destroy(methods_bufferevent, bio_bufferevent_free);
+ }
+ return methods_bufferevent;
+}
+
+/* Create a new BIO to wrap communication around a bufferevent. If close_flag
+ * is true, the bufferevent will be freed when the BIO is closed. */
+static BIO *
+BIO_new_bufferevent(struct bufferevent *bufferevent)
+{
+ BIO *result;
+ if (!bufferevent)
+ return NULL;
+ if (!(result = BIO_new(BIO_s_bufferevent())))
+ return NULL;
+ BIO_set_init(result, 1);
+ BIO_set_data(result, bufferevent);
+ /* We don't tell the BIO to close the bufferevent; we do it ourselves on
+ * be_openssl_destruct() */
+ BIO_set_shutdown(result, 0);
+ return result;
+}
+
+/* --------------------
+ Now, here's the OpenSSL-based implementation of bufferevent.
+
+ The implementation comes in two flavors: one that connects its SSL object
+ to an underlying bufferevent using a BIO_bufferevent, and one that has the
+ SSL object connect to a socket directly. The latter should generally be
+ faster, except on Windows, where your best bet is using a
+ bufferevent_async.
+
+ (OpenSSL supports many other BIO types, too. But we can't use any unless
+ we have a good way to get notified when they become readable/writable.)
+ -------------------- */
+
+struct bio_data_counts {
+ unsigned long n_written;
+ unsigned long n_read;
+};
+
+struct bufferevent_openssl {
+ /* Shared fields with common bufferevent implementation code.
+ If we were set up with an underlying bufferevent, we use the
+ events here as timers only. If we have an SSL, then we use
+ the events as socket events.
+ */
+ struct bufferevent_private bev;
+ /* An underlying bufferevent that we're directing our output to.
+ If it's NULL, then we're connected to an fd, not an evbuffer. */
+ struct bufferevent *underlying;
+ /* The SSL object doing our encryption. */
+ SSL *ssl;
+
+ /* A callback that's invoked when data arrives on our outbuf so we
+ know to write data to the SSL. */
+ struct evbuffer_cb_entry *outbuf_cb;
+
+ /* A count of how much data the bios have read/written total. Used
+ for rate-limiting. */
+ struct bio_data_counts counts;
+
+ /* If this value is greater than 0, then the last SSL_write blocked,
+ * and we need to try it again with this many bytes. */
+ ev_ssize_t last_write;
+
+#define NUM_ERRORS 3
+ ev_uint32_t errors[NUM_ERRORS];
+
+ /* When we next get available space, we should say "read" instead of
+ "write". This can happen if there's a renegotiation during a read
+ operation. */
+ unsigned read_blocked_on_write : 1;
+ /* When we next get data, we should say "write" instead of "read". */
+ unsigned write_blocked_on_read : 1;
+ /* Treat TCP close before SSL close on SSL >= v3 as clean EOF. */
+ unsigned allow_dirty_shutdown : 1;
+ /* XXX */
+ unsigned n_errors : 2;
+
+ /* Are we currently connecting, accepting, or doing IO? */
+ unsigned state : 2;
+ /* If we reset fd, we sould reset state too */
+ unsigned old_state : 2;
+};
+
+static int be_openssl_enable(struct bufferevent *, short);
+static int be_openssl_disable(struct bufferevent *, short);
+static void be_openssl_unlink(struct bufferevent *);
+static void be_openssl_destruct(struct bufferevent *);
+static int be_openssl_adj_timeouts(struct bufferevent *);
+static int be_openssl_flush(struct bufferevent *bufev,
+ short iotype, enum bufferevent_flush_mode mode);
+static int be_openssl_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+const struct bufferevent_ops bufferevent_ops_openssl = {
+ "ssl",
+ evutil_offsetof(struct bufferevent_openssl, bev.bev),
+ be_openssl_enable,
+ be_openssl_disable,
+ be_openssl_unlink,
+ be_openssl_destruct,
+ be_openssl_adj_timeouts,
+ be_openssl_flush,
+ be_openssl_ctrl,
+};
+
+/* Given a bufferevent, return a pointer to the bufferevent_openssl that
+ * contains it, if any. */
+static inline struct bufferevent_openssl *
+upcast(struct bufferevent *bev)
+{
+ struct bufferevent_openssl *bev_o;
+ if (!BEV_IS_OPENSSL(bev))
+ return NULL;
+ bev_o = (void*)( ((char*)bev) -
+ evutil_offsetof(struct bufferevent_openssl, bev.bev));
+ EVUTIL_ASSERT(BEV_IS_OPENSSL(&bev_o->bev.bev));
+ return bev_o;
+}
+
+static inline void
+put_error(struct bufferevent_openssl *bev_ssl, unsigned long err)
+{
+ if (bev_ssl->n_errors == NUM_ERRORS)
+ return;
+ /* The error type according to openssl is "unsigned long", but
+ openssl never uses more than 32 bits of it. It _can't_ use more
+ than 32 bits of it, since it needs to report errors on systems
+ where long is only 32 bits.
+ */
+ bev_ssl->errors[bev_ssl->n_errors++] = (ev_uint32_t) err;
+}
+
+/* Have the base communications channel (either the underlying bufferevent or
+ * ev_read and ev_write) start reading. Take the read-blocked-on-write flag
+ * into account. */
+static int
+start_reading(struct bufferevent_openssl *bev_ssl)
+{
+ if (bev_ssl->underlying) {
+ bufferevent_unsuspend_read_(bev_ssl->underlying,
+ BEV_SUSPEND_FILT_READ);
+ return 0;
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ int r;
+ r = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
+ if (r == 0 && bev_ssl->read_blocked_on_write)
+ r = bufferevent_add_event_(&bev->ev_write,
+ &bev->timeout_write);
+ return r;
+ }
+}
+
+/* Have the base communications channel (either the underlying bufferevent or
+ * ev_read and ev_write) start writing. Take the write-blocked-on-read flag
+ * into account. */
+static int
+start_writing(struct bufferevent_openssl *bev_ssl)
+{
+ int r = 0;
+ if (bev_ssl->underlying) {
+ if (bev_ssl->write_blocked_on_read) {
+ bufferevent_unsuspend_read_(bev_ssl->underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ r = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
+ if (!r && bev_ssl->write_blocked_on_read)
+ r = bufferevent_add_event_(&bev->ev_read,
+ &bev->timeout_read);
+ }
+ return r;
+}
+
+static void
+stop_reading(struct bufferevent_openssl *bev_ssl)
+{
+ if (bev_ssl->write_blocked_on_read)
+ return;
+ if (bev_ssl->underlying) {
+ bufferevent_suspend_read_(bev_ssl->underlying,
+ BEV_SUSPEND_FILT_READ);
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ event_del(&bev->ev_read);
+ }
+}
+
+static void
+stop_writing(struct bufferevent_openssl *bev_ssl)
+{
+ if (bev_ssl->read_blocked_on_write)
+ return;
+ if (bev_ssl->underlying) {
+ bufferevent_unsuspend_read_(bev_ssl->underlying,
+ BEV_SUSPEND_FILT_READ);
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ event_del(&bev->ev_write);
+ }
+}
+
+static int
+set_rbow(struct bufferevent_openssl *bev_ssl)
+{
+ if (!bev_ssl->underlying)
+ stop_reading(bev_ssl);
+ bev_ssl->read_blocked_on_write = 1;
+ return start_writing(bev_ssl);
+}
+
+static int
+set_wbor(struct bufferevent_openssl *bev_ssl)
+{
+ if (!bev_ssl->underlying)
+ stop_writing(bev_ssl);
+ bev_ssl->write_blocked_on_read = 1;
+ return start_reading(bev_ssl);
+}
+
+static int
+clear_rbow(struct bufferevent_openssl *bev_ssl)
+{
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ int r = 0;
+ bev_ssl->read_blocked_on_write = 0;
+ if (!(bev->enabled & EV_WRITE))
+ stop_writing(bev_ssl);
+ if (bev->enabled & EV_READ)
+ r = start_reading(bev_ssl);
+ return r;
+}
+
+
+static int
+clear_wbor(struct bufferevent_openssl *bev_ssl)
+{
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ int r = 0;
+ bev_ssl->write_blocked_on_read = 0;
+ if (!(bev->enabled & EV_READ))
+ stop_reading(bev_ssl);
+ if (bev->enabled & EV_WRITE)
+ r = start_writing(bev_ssl);
+ return r;
+}
+
+static void
+conn_closed(struct bufferevent_openssl *bev_ssl, int when, int errcode, int ret)
+{
+ int event = BEV_EVENT_ERROR;
+ int dirty_shutdown = 0;
+ unsigned long err;
+
+ switch (errcode) {
+ case SSL_ERROR_ZERO_RETURN:
+ /* Possibly a clean shutdown. */
+ if (SSL_get_shutdown(bev_ssl->ssl) & SSL_RECEIVED_SHUTDOWN)
+ event = BEV_EVENT_EOF;
+ else
+ dirty_shutdown = 1;
+ break;
+ case SSL_ERROR_SYSCALL:
+ /* IO error; possibly a dirty shutdown. */
+ if ((ret == 0 || ret == -1) && ERR_peek_error() == 0)
+ dirty_shutdown = 1;
+ put_error(bev_ssl, errcode);
+ break;
+ case SSL_ERROR_SSL:
+ /* Protocol error. */
+ put_error(bev_ssl, errcode);
+ break;
+ case SSL_ERROR_WANT_X509_LOOKUP:
+ /* XXXX handle this. */
+ put_error(bev_ssl, errcode);
+ break;
+ case SSL_ERROR_NONE:
+ case SSL_ERROR_WANT_READ:
+ case SSL_ERROR_WANT_WRITE:
+ case SSL_ERROR_WANT_CONNECT:
+ case SSL_ERROR_WANT_ACCEPT:
+ default:
+ /* should be impossible; treat as normal error. */
+ event_warnx("BUG: Unexpected OpenSSL error code %d", errcode);
+ break;
+ }
+
+ while ((err = ERR_get_error())) {
+ put_error(bev_ssl, err);
+ }
+
+ if (dirty_shutdown && bev_ssl->allow_dirty_shutdown)
+ event = BEV_EVENT_EOF;
+
+ stop_reading(bev_ssl);
+ stop_writing(bev_ssl);
+
+ /* when is BEV_EVENT_{READING|WRITING} */
+ event = when | event;
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev, event, 0);
+}
+
+static void
+init_bio_counts(struct bufferevent_openssl *bev_ssl)
+{
+ BIO *rbio, *wbio;
+
+ wbio = SSL_get_wbio(bev_ssl->ssl);
+ bev_ssl->counts.n_written = wbio ? BIO_number_written(wbio) : 0;
+ rbio = SSL_get_rbio(bev_ssl->ssl);
+ bev_ssl->counts.n_read = rbio ? BIO_number_read(rbio) : 0;
+}
+
+static inline void
+decrement_buckets(struct bufferevent_openssl *bev_ssl)
+{
+ unsigned long num_w = BIO_number_written(SSL_get_wbio(bev_ssl->ssl));
+ unsigned long num_r = BIO_number_read(SSL_get_rbio(bev_ssl->ssl));
+ /* These next two subtractions can wrap around. That's okay. */
+ unsigned long w = num_w - bev_ssl->counts.n_written;
+ unsigned long r = num_r - bev_ssl->counts.n_read;
+ if (w)
+ bufferevent_decrement_write_buckets_(&bev_ssl->bev, w);
+ if (r)
+ bufferevent_decrement_read_buckets_(&bev_ssl->bev, r);
+ bev_ssl->counts.n_written = num_w;
+ bev_ssl->counts.n_read = num_r;
+}
+
+#define OP_MADE_PROGRESS 1
+#define OP_BLOCKED 2
+#define OP_ERR 4
+
+/* Return a bitmask of OP_MADE_PROGRESS (if we read anything); OP_BLOCKED (if
+ we're now blocked); and OP_ERR (if an error occurred). */
+static int
+do_read(struct bufferevent_openssl *bev_ssl, int n_to_read) {
+ /* Requires lock */
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ struct evbuffer *input = bev->input;
+ int r, n, i, n_used = 0, atmost;
+ struct evbuffer_iovec space[2];
+ int result = 0;
+
+ if (bev_ssl->bev.read_suspended)
+ return 0;
+
+ atmost = bufferevent_get_read_max_(&bev_ssl->bev);
+ if (n_to_read > atmost)
+ n_to_read = atmost;
+
+ n = evbuffer_reserve_space(input, n_to_read, space, 2);
+ if (n < 0)
+ return OP_ERR;
+
+ for (i=0; i<n; ++i) {
+ if (bev_ssl->bev.read_suspended)
+ break;
+ ERR_clear_error();
+ r = SSL_read(bev_ssl->ssl, space[i].iov_base, space[i].iov_len);
+ if (r>0) {
+ result |= OP_MADE_PROGRESS;
+ if (bev_ssl->read_blocked_on_write)
+ if (clear_rbow(bev_ssl) < 0)
+ return OP_ERR | result;
+ ++n_used;
+ space[i].iov_len = r;
+ decrement_buckets(bev_ssl);
+ } else {
+ int err = SSL_get_error(bev_ssl->ssl, r);
+ print_err(err);
+ switch (err) {
+ case SSL_ERROR_WANT_READ:
+ /* Can't read until underlying has more data. */
+ if (bev_ssl->read_blocked_on_write)
+ if (clear_rbow(bev_ssl) < 0)
+ return OP_ERR | result;
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ /* This read operation requires a write, and the
+ * underlying is full */
+ if (!bev_ssl->read_blocked_on_write)
+ if (set_rbow(bev_ssl) < 0)
+ return OP_ERR | result;
+ break;
+ default:
+ conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
+ break;
+ }
+ result |= OP_BLOCKED;
+ break; /* out of the loop */
+ }
+ }
+
+ if (n_used) {
+ evbuffer_commit_space(input, space, n_used);
+ if (bev_ssl->underlying)
+ BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+ }
+
+ return result;
+}
+
+/* Return a bitmask of OP_MADE_PROGRESS (if we wrote anything); OP_BLOCKED (if
+ we're now blocked); and OP_ERR (if an error occurred). */
+static int
+do_write(struct bufferevent_openssl *bev_ssl, int atmost)
+{
+ int i, r, n, n_written = 0;
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ struct evbuffer *output = bev->output;
+ struct evbuffer_iovec space[8];
+ int result = 0;
+
+ if (bev_ssl->last_write > 0)
+ atmost = bev_ssl->last_write;
+ else
+ atmost = bufferevent_get_write_max_(&bev_ssl->bev);
+
+ n = evbuffer_peek(output, atmost, NULL, space, 8);
+ if (n < 0)
+ return OP_ERR | result;
+
+ if (n > 8)
+ n = 8;
+ for (i=0; i < n; ++i) {
+ if (bev_ssl->bev.write_suspended)
+ break;
+
+ /* SSL_write will (reasonably) return 0 if we tell it to
+ send 0 data. Skip this case so we don't interpret the
+ result as an error */
+ if (space[i].iov_len == 0)
+ continue;
+
+ ERR_clear_error();
+ r = SSL_write(bev_ssl->ssl, space[i].iov_base,
+ space[i].iov_len);
+ if (r > 0) {
+ result |= OP_MADE_PROGRESS;
+ if (bev_ssl->write_blocked_on_read)
+ if (clear_wbor(bev_ssl) < 0)
+ return OP_ERR | result;
+ n_written += r;
+ bev_ssl->last_write = -1;
+ decrement_buckets(bev_ssl);
+ } else {
+ int err = SSL_get_error(bev_ssl->ssl, r);
+ print_err(err);
+ switch (err) {
+ case SSL_ERROR_WANT_WRITE:
+ /* Can't read until underlying has more data. */
+ if (bev_ssl->write_blocked_on_read)
+ if (clear_wbor(bev_ssl) < 0)
+ return OP_ERR | result;
+ bev_ssl->last_write = space[i].iov_len;
+ break;
+ case SSL_ERROR_WANT_READ:
+ /* This read operation requires a write, and the
+ * underlying is full */
+ if (!bev_ssl->write_blocked_on_read)
+ if (set_wbor(bev_ssl) < 0)
+ return OP_ERR | result;
+ bev_ssl->last_write = space[i].iov_len;
+ break;
+ default:
+ conn_closed(bev_ssl, BEV_EVENT_WRITING, err, r);
+ bev_ssl->last_write = -1;
+ break;
+ }
+ result |= OP_BLOCKED;
+ break;
+ }
+ }
+ if (n_written) {
+ evbuffer_drain(output, n_written);
+ if (bev_ssl->underlying)
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+ bufferevent_trigger_nolock_(bev, EV_WRITE, BEV_OPT_DEFER_CALLBACKS);
+ }
+ return result;
+}
+
+#define WRITE_FRAME 15000
+
+#define READ_DEFAULT 4096
+
+/* Try to figure out how many bytes to read; return 0 if we shouldn't be
+ * reading. */
+static int
+bytes_to_read(struct bufferevent_openssl *bev)
+{
+ struct evbuffer *input = bev->bev.bev.input;
+ struct event_watermark *wm = &bev->bev.bev.wm_read;
+ int result = READ_DEFAULT;
+ ev_ssize_t limit;
+ /* XXX 99% of this is generic code that nearly all bufferevents will
+ * want. */
+
+ if (bev->write_blocked_on_read) {
+ return 0;
+ }
+
+ if (! (bev->bev.bev.enabled & EV_READ)) {
+ return 0;
+ }
+
+ if (bev->bev.read_suspended) {
+ return 0;
+ }
+
+ if (wm->high) {
+ if (evbuffer_get_length(input) >= wm->high) {
+ return 0;
+ }
+
+ result = wm->high - evbuffer_get_length(input);
+ } else {
+ result = READ_DEFAULT;
+ }
+
+ /* Respect the rate limit */
+ limit = bufferevent_get_read_max_(&bev->bev);
+ if (result > limit) {
+ result = limit;
+ }
+
+ return result;
+}
+
+
+/* Things look readable. If write is blocked on read, write till it isn't.
+ * Read from the underlying buffer until we block or we hit our high-water
+ * mark.
+ */
+static void
+consider_reading(struct bufferevent_openssl *bev_ssl)
+{
+ int r;
+ int n_to_read;
+ int all_result_flags = 0;
+
+ while (bev_ssl->write_blocked_on_read) {
+ r = do_write(bev_ssl, WRITE_FRAME);
+ if (r & (OP_BLOCKED|OP_ERR))
+ break;
+ }
+ if (bev_ssl->write_blocked_on_read)
+ return;
+
+ n_to_read = bytes_to_read(bev_ssl);
+
+ while (n_to_read) {
+ r = do_read(bev_ssl, n_to_read);
+ all_result_flags |= r;
+
+ if (r & (OP_BLOCKED|OP_ERR))
+ break;
+
+ if (bev_ssl->bev.read_suspended)
+ break;
+
+ /* Read all pending data. This won't hit the network
+ * again, and will (most importantly) put us in a state
+ * where we don't need to read anything else until the
+ * socket is readable again. It'll potentially make us
+ * overrun our read high-watermark (somewhat
+ * regrettable). The damage to the rate-limit has
+ * already been done, since OpenSSL went and read a
+ * whole SSL record anyway. */
+ n_to_read = SSL_pending(bev_ssl->ssl);
+
+ /* XXX This if statement is actually a bad bug, added to avoid
+ * XXX a worse bug.
+ *
+ * The bad bug: It can potentially cause resource unfairness
+ * by reading too much data from the underlying bufferevent;
+ * it can potentially cause read looping if the underlying
+ * bufferevent is a bufferevent_pair and deferred callbacks
+ * aren't used.
+ *
+ * The worse bug: If we didn't do this, then we would
+ * potentially not read any more from bev_ssl->underlying
+ * until more data arrived there, which could lead to us
+ * waiting forever.
+ */
+ if (!n_to_read && bev_ssl->underlying)
+ n_to_read = bytes_to_read(bev_ssl);
+ }
+
+ if (all_result_flags & OP_MADE_PROGRESS) {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+
+ bufferevent_trigger_nolock_(bev, EV_READ, 0);
+ }
+
+ if (!bev_ssl->underlying) {
+ /* Should be redundant, but let's avoid busy-looping */
+ if (bev_ssl->bev.read_suspended ||
+ !(bev_ssl->bev.bev.enabled & EV_READ)) {
+ event_del(&bev_ssl->bev.bev.ev_read);
+ }
+ }
+}
+
+static void
+consider_writing(struct bufferevent_openssl *bev_ssl)
+{
+ int r;
+ struct evbuffer *output = bev_ssl->bev.bev.output;
+ struct evbuffer *target = NULL;
+ struct event_watermark *wm = NULL;
+
+ while (bev_ssl->read_blocked_on_write) {
+ r = do_read(bev_ssl, 1024); /* XXXX 1024 is a hack */
+ if (r & OP_MADE_PROGRESS) {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+
+ bufferevent_trigger_nolock_(bev, EV_READ, 0);
+ }
+ if (r & (OP_ERR|OP_BLOCKED))
+ break;
+ }
+ if (bev_ssl->read_blocked_on_write)
+ return;
+ if (bev_ssl->underlying) {
+ target = bev_ssl->underlying->output;
+ wm = &bev_ssl->underlying->wm_write;
+ }
+ while ((bev_ssl->bev.bev.enabled & EV_WRITE) &&
+ (! bev_ssl->bev.write_suspended) &&
+ evbuffer_get_length(output) &&
+ (!target || (! wm->high || evbuffer_get_length(target) < wm->high))) {
+ int n_to_write;
+ if (wm && wm->high)
+ n_to_write = wm->high - evbuffer_get_length(target);
+ else
+ n_to_write = WRITE_FRAME;
+ r = do_write(bev_ssl, n_to_write);
+ if (r & (OP_BLOCKED|OP_ERR))
+ break;
+ }
+
+ if (!bev_ssl->underlying) {
+ if (evbuffer_get_length(output) == 0) {
+ event_del(&bev_ssl->bev.bev.ev_write);
+ } else if (bev_ssl->bev.write_suspended ||
+ !(bev_ssl->bev.bev.enabled & EV_WRITE)) {
+ /* Should be redundant, but let's avoid busy-looping */
+ event_del(&bev_ssl->bev.bev.ev_write);
+ }
+ }
+}
+
+static void
+be_openssl_readcb(struct bufferevent *bev_base, void *ctx)
+{
+ struct bufferevent_openssl *bev_ssl = ctx;
+ consider_reading(bev_ssl);
+}
+
+static void
+be_openssl_writecb(struct bufferevent *bev_base, void *ctx)
+{
+ struct bufferevent_openssl *bev_ssl = ctx;
+ consider_writing(bev_ssl);
+}
+
+static void
+be_openssl_eventcb(struct bufferevent *bev_base, short what, void *ctx)
+{
+ struct bufferevent_openssl *bev_ssl = ctx;
+ int event = 0;
+
+ if (what & BEV_EVENT_EOF) {
+ if (bev_ssl->allow_dirty_shutdown)
+ event = BEV_EVENT_EOF;
+ else
+ event = BEV_EVENT_ERROR;
+ } else if (what & BEV_EVENT_TIMEOUT) {
+ /* We sure didn't set this. Propagate it to the user. */
+ event = what;
+ } else if (what & BEV_EVENT_ERROR) {
+ /* An error occurred on the connection. Propagate it to the user. */
+ event = what;
+ } else if (what & BEV_EVENT_CONNECTED) {
+ /* Ignore it. We're saying SSL_connect() already, which will
+ eat it. */
+ }
+ if (event)
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev, event, 0);
+}
+
+static void
+be_openssl_readeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+ struct bufferevent_openssl *bev_ssl = ptr;
+ bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
+ if (what == EV_TIMEOUT) {
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev,
+ BEV_EVENT_TIMEOUT|BEV_EVENT_READING, 0);
+ } else {
+ consider_reading(bev_ssl);
+ }
+ bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
+}
+
+static void
+be_openssl_writeeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+ struct bufferevent_openssl *bev_ssl = ptr;
+ bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
+ if (what == EV_TIMEOUT) {
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev,
+ BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING, 0);
+ } else {
+ consider_writing(bev_ssl);
+ }
+ bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
+}
+
+static evutil_socket_t
+be_openssl_auto_fd(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
+{
+ if (!bev_ssl->underlying) {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ if (event_initialized(&bev->ev_read) && fd < 0) {
+ fd = event_get_fd(&bev->ev_read);
+ }
+ }
+ return fd;
+}
+
+static int
+set_open_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
+{
+ if (bev_ssl->underlying) {
+ bufferevent_setcb(bev_ssl->underlying,
+ be_openssl_readcb, be_openssl_writecb, be_openssl_eventcb,
+ bev_ssl);
+ return 0;
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+ int rpending=0, wpending=0, r1=0, r2=0;
+
+ if (event_initialized(&bev->ev_read)) {
+ rpending = event_pending(&bev->ev_read, EV_READ, NULL);
+ wpending = event_pending(&bev->ev_write, EV_WRITE, NULL);
+
+ event_del(&bev->ev_read);
+ event_del(&bev->ev_write);
+ }
+
+ event_assign(&bev->ev_read, bev->ev_base, fd,
+ EV_READ|EV_PERSIST|EV_FINALIZE,
+ be_openssl_readeventcb, bev_ssl);
+ event_assign(&bev->ev_write, bev->ev_base, fd,
+ EV_WRITE|EV_PERSIST|EV_FINALIZE,
+ be_openssl_writeeventcb, bev_ssl);
+
+ if (rpending)
+ r1 = bufferevent_add_event_(&bev->ev_read, &bev->timeout_read);
+ if (wpending)
+ r2 = bufferevent_add_event_(&bev->ev_write, &bev->timeout_write);
+
+ return (r1<0 || r2<0) ? -1 : 0;
+ }
+}
+
+static int
+do_handshake(struct bufferevent_openssl *bev_ssl)
+{
+ int r;
+
+ switch (bev_ssl->state) {
+ default:
+ case BUFFEREVENT_SSL_OPEN:
+ EVUTIL_ASSERT(0);
+ return -1;
+ case BUFFEREVENT_SSL_CONNECTING:
+ case BUFFEREVENT_SSL_ACCEPTING:
+ ERR_clear_error();
+ r = SSL_do_handshake(bev_ssl->ssl);
+ break;
+ }
+ decrement_buckets(bev_ssl);
+
+ if (r==1) {
+ evutil_socket_t fd = event_get_fd(&bev_ssl->bev.bev.ev_read);
+ /* We're done! */
+ bev_ssl->state = BUFFEREVENT_SSL_OPEN;
+ set_open_callbacks(bev_ssl, fd); /* XXXX handle failure */
+ /* Call do_read and do_write as needed */
+ bufferevent_enable(&bev_ssl->bev.bev, bev_ssl->bev.bev.enabled);
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev,
+ BEV_EVENT_CONNECTED, 0);
+ return 1;
+ } else {
+ int err = SSL_get_error(bev_ssl->ssl, r);
+ print_err(err);
+ switch (err) {
+ case SSL_ERROR_WANT_WRITE:
+ stop_reading(bev_ssl);
+ return start_writing(bev_ssl);
+ case SSL_ERROR_WANT_READ:
+ stop_writing(bev_ssl);
+ return start_reading(bev_ssl);
+ default:
+ conn_closed(bev_ssl, BEV_EVENT_READING, err, r);
+ return -1;
+ }
+ }
+}
+
+static void
+be_openssl_handshakecb(struct bufferevent *bev_base, void *ctx)
+{
+ struct bufferevent_openssl *bev_ssl = ctx;
+ do_handshake(bev_ssl);/* XXX handle failure */
+}
+
+static void
+be_openssl_handshakeeventcb(evutil_socket_t fd, short what, void *ptr)
+{
+ struct bufferevent_openssl *bev_ssl = ptr;
+
+ bufferevent_incref_and_lock_(&bev_ssl->bev.bev);
+ if (what & EV_TIMEOUT) {
+ bufferevent_run_eventcb_(&bev_ssl->bev.bev, BEV_EVENT_TIMEOUT, 0);
+ } else
+ do_handshake(bev_ssl);/* XXX handle failure */
+ bufferevent_decref_and_unlock_(&bev_ssl->bev.bev);
+}
+
+static int
+set_handshake_callbacks(struct bufferevent_openssl *bev_ssl, evutil_socket_t fd)
+{
+ if (bev_ssl->underlying) {
+ bufferevent_setcb(bev_ssl->underlying,
+ be_openssl_handshakecb, be_openssl_handshakecb,
+ be_openssl_eventcb,
+ bev_ssl);
+
+ if (fd < 0)
+ return 0;
+
+ if (bufferevent_setfd(bev_ssl->underlying, fd))
+ return 1;
+
+ return do_handshake(bev_ssl);
+ } else {
+ struct bufferevent *bev = &bev_ssl->bev.bev;
+
+ if (event_initialized(&bev->ev_read)) {
+ event_del(&bev->ev_read);
+ event_del(&bev->ev_write);
+ }
+
+ event_assign(&bev->ev_read, bev->ev_base, fd,
+ EV_READ|EV_PERSIST|EV_FINALIZE,
+ be_openssl_handshakeeventcb, bev_ssl);
+ event_assign(&bev->ev_write, bev->ev_base, fd,
+ EV_WRITE|EV_PERSIST|EV_FINALIZE,
+ be_openssl_handshakeeventcb, bev_ssl);
+ if (fd >= 0)
+ bufferevent_enable(bev, bev->enabled);
+ return 0;
+ }
+}
+
+int
+bufferevent_ssl_renegotiate(struct bufferevent *bev)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+ if (!bev_ssl)
+ return -1;
+ if (SSL_renegotiate(bev_ssl->ssl) < 0)
+ return -1;
+ bev_ssl->state = BUFFEREVENT_SSL_CONNECTING;
+ if (set_handshake_callbacks(bev_ssl, be_openssl_auto_fd(bev_ssl, -1)) < 0)
+ return -1;
+ if (!bev_ssl->underlying)
+ return do_handshake(bev_ssl);
+ return 0;
+}
+
+static void
+be_openssl_outbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo, void *arg)
+{
+ struct bufferevent_openssl *bev_ssl = arg;
+ int r = 0;
+ /* XXX need to hold a reference here. */
+
+ if (cbinfo->n_added && bev_ssl->state == BUFFEREVENT_SSL_OPEN) {
+ if (cbinfo->orig_size == 0)
+ r = bufferevent_add_event_(&bev_ssl->bev.bev.ev_write,
+ &bev_ssl->bev.bev.timeout_write);
+
+ if (bev_ssl->underlying)
+ consider_writing(bev_ssl);
+ }
+ /* XXX Handle r < 0 */
+ (void)r;
+}
+
+
+static int
+be_openssl_enable(struct bufferevent *bev, short events)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+ int r1 = 0, r2 = 0;
+
+ if (events & EV_READ)
+ r1 = start_reading(bev_ssl);
+ if (events & EV_WRITE)
+ r2 = start_writing(bev_ssl);
+
+ if (bev_ssl->underlying) {
+ if (events & EV_READ)
+ BEV_RESET_GENERIC_READ_TIMEOUT(bev);
+ if (events & EV_WRITE)
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bev);
+
+ if (events & EV_READ)
+ consider_reading(bev_ssl);
+ if (events & EV_WRITE)
+ consider_writing(bev_ssl);
+ }
+ return (r1 < 0 || r2 < 0) ? -1 : 0;
+}
+
+static int
+be_openssl_disable(struct bufferevent *bev, short events)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+ if (events & EV_READ)
+ stop_reading(bev_ssl);
+ if (events & EV_WRITE)
+ stop_writing(bev_ssl);
+
+ if (bev_ssl->underlying) {
+ if (events & EV_READ)
+ BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+ if (events & EV_WRITE)
+ BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+ }
+ return 0;
+}
+
+static void
+be_openssl_unlink(struct bufferevent *bev)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+ if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
+ if (bev_ssl->underlying) {
+ if (BEV_UPCAST(bev_ssl->underlying)->refcnt < 2) {
+ event_warnx("BEV_OPT_CLOSE_ON_FREE set on an "
+ "bufferevent with too few references");
+ } else {
+ bufferevent_free(bev_ssl->underlying);
+ /* We still have a reference to it, via our
+ * BIO. So we don't drop this. */
+ // bev_ssl->underlying = NULL;
+ }
+ }
+ } else {
+ if (bev_ssl->underlying) {
+ if (bev_ssl->underlying->errorcb == be_openssl_eventcb)
+ bufferevent_setcb(bev_ssl->underlying,
+ NULL,NULL,NULL,NULL);
+ bufferevent_unsuspend_read_(bev_ssl->underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+ }
+}
+
+static void
+be_openssl_destruct(struct bufferevent *bev)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+ if (bev_ssl->bev.options & BEV_OPT_CLOSE_ON_FREE) {
+ if (! bev_ssl->underlying) {
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ BIO *bio = SSL_get_wbio(bev_ssl->ssl);
+ if (bio)
+ fd = BIO_get_fd(bio, NULL);
+ if (fd >= 0)
+ evutil_closesocket(fd);
+ }
+ SSL_free(bev_ssl->ssl);
+ }
+}
+
+static int
+be_openssl_adj_timeouts(struct bufferevent *bev)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+
+ if (bev_ssl->underlying) {
+ return bufferevent_generic_adj_timeouts_(bev);
+ } else {
+ return bufferevent_generic_adj_existing_timeouts_(bev);
+ }
+}
+
+static int
+be_openssl_flush(struct bufferevent *bufev,
+ short iotype, enum bufferevent_flush_mode mode)
+{
+ /* XXXX Implement this. */
+ return 0;
+}
+
+static int
+be_openssl_set_fd(struct bufferevent_openssl *bev_ssl,
+ enum bufferevent_ssl_state state, evutil_socket_t fd)
+{
+ bev_ssl->state = state;
+
+ switch (state) {
+ case BUFFEREVENT_SSL_ACCEPTING:
+ if (!SSL_clear(bev_ssl->ssl))
+ return -1;
+ SSL_set_accept_state(bev_ssl->ssl);
+ if (set_handshake_callbacks(bev_ssl, fd) < 0)
+ return -1;
+ break;
+ case BUFFEREVENT_SSL_CONNECTING:
+ if (!SSL_clear(bev_ssl->ssl))
+ return -1;
+ SSL_set_connect_state(bev_ssl->ssl);
+ if (set_handshake_callbacks(bev_ssl, fd) < 0)
+ return -1;
+ break;
+ case BUFFEREVENT_SSL_OPEN:
+ if (set_open_callbacks(bev_ssl, fd) < 0)
+ return -1;
+ break;
+ default:
+ return -1;
+ }
+
+ return 0;
+}
+
+static int
+be_openssl_ctrl(struct bufferevent *bev,
+ enum bufferevent_ctrl_op op, union bufferevent_ctrl_data *data)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bev);
+ switch (op) {
+ case BEV_CTRL_SET_FD:
+ if (!bev_ssl->underlying) {
+ BIO *bio;
+ bio = BIO_new_socket((int)data->fd, 0);
+ SSL_set_bio(bev_ssl->ssl, bio, bio);
+ } else {
+ BIO *bio;
+ if (!(bio = BIO_new_bufferevent(bev_ssl->underlying)))
+ return -1;
+ SSL_set_bio(bev_ssl->ssl, bio, bio);
+ }
+
+ return be_openssl_set_fd(bev_ssl, bev_ssl->old_state, data->fd);
+ case BEV_CTRL_GET_FD:
+ if (bev_ssl->underlying) {
+ data->fd = event_get_fd(&bev_ssl->underlying->ev_read);
+ } else {
+ data->fd = event_get_fd(&bev->ev_read);
+ }
+ return 0;
+ case BEV_CTRL_GET_UNDERLYING:
+ data->ptr = bev_ssl->underlying;
+ return 0;
+ case BEV_CTRL_CANCEL_ALL:
+ default:
+ return -1;
+ }
+}
+
+SSL *
+bufferevent_openssl_get_ssl(struct bufferevent *bufev)
+{
+ struct bufferevent_openssl *bev_ssl = upcast(bufev);
+ if (!bev_ssl)
+ return NULL;
+ return bev_ssl->ssl;
+}
+
+static struct bufferevent *
+bufferevent_openssl_new_impl(struct event_base *base,
+ struct bufferevent *underlying,
+ evutil_socket_t fd,
+ SSL *ssl,
+ enum bufferevent_ssl_state state,
+ int options)
+{
+ struct bufferevent_openssl *bev_ssl = NULL;
+ struct bufferevent_private *bev_p = NULL;
+ int tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+ /* Only one can be set. */
+ if (underlying != NULL && fd >= 0)
+ goto err;
+
+ if (!(bev_ssl = mm_calloc(1, sizeof(struct bufferevent_openssl))))
+ goto err;
+
+ bev_p = &bev_ssl->bev;
+
+ if (bufferevent_init_common_(bev_p, base,
+ &bufferevent_ops_openssl, tmp_options) < 0)
+ goto err;
+
+ /* Don't explode if we decide to realloc a chunk we're writing from in
+ * the output buffer. */
+ SSL_set_mode(ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
+
+ bev_ssl->underlying = underlying;
+ bev_ssl->ssl = ssl;
+
+ bev_ssl->outbuf_cb = evbuffer_add_cb(bev_p->bev.output,
+ be_openssl_outbuf_cb, bev_ssl);
+
+ if (options & BEV_OPT_THREADSAFE)
+ bufferevent_enable_locking_(&bev_ssl->bev.bev, NULL);
+
+ if (underlying) {
+ bufferevent_init_generic_timeout_cbs_(&bev_ssl->bev.bev);
+ bufferevent_incref_(underlying);
+ }
+
+ bev_ssl->old_state = state;
+ bev_ssl->last_write = -1;
+
+ init_bio_counts(bev_ssl);
+
+ fd = be_openssl_auto_fd(bev_ssl, fd);
+ if (be_openssl_set_fd(bev_ssl, state, fd))
+ goto err;
+
+ if (underlying) {
+ bufferevent_setwatermark(underlying, EV_READ, 0, 0);
+ bufferevent_enable(underlying, EV_READ|EV_WRITE);
+ if (state == BUFFEREVENT_SSL_OPEN)
+ bufferevent_suspend_read_(underlying,
+ BEV_SUSPEND_FILT_READ);
+ }
+
+ return &bev_ssl->bev.bev;
+err:
+ if (options & BEV_OPT_CLOSE_ON_FREE)
+ SSL_free(ssl);
+ if (bev_ssl) {
+ bev_ssl->ssl = NULL;
+ bufferevent_free(&bev_ssl->bev.bev);
+ }
+ return NULL;
+}
+
+struct bufferevent *
+bufferevent_openssl_filter_new(struct event_base *base,
+ struct bufferevent *underlying,
+ SSL *ssl,
+ enum bufferevent_ssl_state state,
+ int options)
+{
+ BIO *bio;
+ struct bufferevent *bev;
+
+ if (!underlying)
+ goto err;
+ if (!(bio = BIO_new_bufferevent(underlying)))
+ goto err;
+
+ SSL_set_bio(ssl, bio, bio);
+
+ bev = bufferevent_openssl_new_impl(
+ base, underlying, -1, ssl, state, options);
+ return bev;
+
+err:
+ if (options & BEV_OPT_CLOSE_ON_FREE)
+ SSL_free(ssl);
+ return NULL;
+}
+
+struct bufferevent *
+bufferevent_openssl_socket_new(struct event_base *base,
+ evutil_socket_t fd,
+ SSL *ssl,
+ enum bufferevent_ssl_state state,
+ int options)
+{
+ /* Does the SSL already have an fd? */
+ BIO *bio = SSL_get_wbio(ssl);
+ long have_fd = -1;
+
+ if (bio)
+ have_fd = BIO_get_fd(bio, NULL);
+
+ if (have_fd >= 0) {
+ /* The SSL is already configured with an fd. */
+ if (fd < 0) {
+ /* We should learn the fd from the SSL. */
+ fd = (evutil_socket_t) have_fd;
+ } else if (have_fd == (long)fd) {
+ /* We already know the fd from the SSL; do nothing */
+ } else {
+ /* We specified an fd different from that of the SSL.
+ This is probably an error on our part. Fail. */
+ goto err;
+ }
+ BIO_set_close(bio, 0);
+ } else {
+ /* The SSL isn't configured with a BIO with an fd. */
+ if (fd >= 0) {
+ /* ... and we have an fd we want to use. */
+ bio = BIO_new_socket((int)fd, 0);
+ SSL_set_bio(ssl, bio, bio);
+ } else {
+ /* Leave the fd unset. */
+ }
+ }
+
+ return bufferevent_openssl_new_impl(
+ base, NULL, fd, ssl, state, options);
+
+err:
+ if (options & BEV_OPT_CLOSE_ON_FREE)
+ SSL_free(ssl);
+ return NULL;
+}
+
+int
+bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev)
+{
+ int allow_dirty_shutdown = -1;
+ struct bufferevent_openssl *bev_ssl;
+ BEV_LOCK(bev);
+ bev_ssl = upcast(bev);
+ if (bev_ssl)
+ allow_dirty_shutdown = bev_ssl->allow_dirty_shutdown;
+ BEV_UNLOCK(bev);
+ return allow_dirty_shutdown;
+}
+
+void
+bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
+ int allow_dirty_shutdown)
+{
+ struct bufferevent_openssl *bev_ssl;
+ BEV_LOCK(bev);
+ bev_ssl = upcast(bev);
+ if (bev_ssl)
+ bev_ssl->allow_dirty_shutdown = !!allow_dirty_shutdown;
+ BEV_UNLOCK(bev);
+}
+
+unsigned long
+bufferevent_get_openssl_error(struct bufferevent *bev)
+{
+ unsigned long err = 0;
+ struct bufferevent_openssl *bev_ssl;
+ BEV_LOCK(bev);
+ bev_ssl = upcast(bev);
+ if (bev_ssl && bev_ssl->n_errors) {
+ err = bev_ssl->errors[--bev_ssl->n_errors];
+ }
+ BEV_UNLOCK(bev);
+ return err;
+}
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_pair.c b/ipc/chromium/src/third_party/libevent/bufferevent_pair.c
new file mode 100644
index 0000000000..f88cd751de
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_pair.c
@@ -0,0 +1,365 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/event.h"
+#include "defer-internal.h"
+#include "bufferevent-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+
+struct bufferevent_pair {
+ struct bufferevent_private bev;
+ struct bufferevent_pair *partner;
+ /* For ->destruct() lock checking */
+ struct bufferevent_pair *unlinked_partner;
+};
+
+
+/* Given a bufferevent that's really a bev part of a bufferevent_pair,
+ * return that bufferevent_filtered. Returns NULL otherwise.*/
+static inline struct bufferevent_pair *
+upcast(struct bufferevent *bev)
+{
+ struct bufferevent_pair *bev_p;
+ if (!BEV_IS_PAIR(bev))
+ return NULL;
+ bev_p = EVUTIL_UPCAST(bev, struct bufferevent_pair, bev.bev);
+ EVUTIL_ASSERT(BEV_IS_PAIR(&bev_p->bev.bev));
+ return bev_p;
+}
+
+#define downcast(bev_pair) (&(bev_pair)->bev.bev)
+
+static inline void
+incref_and_lock(struct bufferevent *b)
+{
+ struct bufferevent_pair *bevp;
+ bufferevent_incref_and_lock_(b);
+ bevp = upcast(b);
+ if (bevp->partner)
+ bufferevent_incref_and_lock_(downcast(bevp->partner));
+}
+
+static inline void
+decref_and_unlock(struct bufferevent *b)
+{
+ struct bufferevent_pair *bevp = upcast(b);
+ if (bevp->partner)
+ bufferevent_decref_and_unlock_(downcast(bevp->partner));
+ bufferevent_decref_and_unlock_(b);
+}
+
+/* XXX Handle close */
+
+static void be_pair_outbuf_cb(struct evbuffer *,
+ const struct evbuffer_cb_info *, void *);
+
+static struct bufferevent_pair *
+bufferevent_pair_elt_new(struct event_base *base,
+ int options)
+{
+ struct bufferevent_pair *bufev;
+ if (! (bufev = mm_calloc(1, sizeof(struct bufferevent_pair))))
+ return NULL;
+ if (bufferevent_init_common_(&bufev->bev, base, &bufferevent_ops_pair,
+ options)) {
+ mm_free(bufev);
+ return NULL;
+ }
+ if (!evbuffer_add_cb(bufev->bev.bev.output, be_pair_outbuf_cb, bufev)) {
+ bufferevent_free(downcast(bufev));
+ return NULL;
+ }
+
+ bufferevent_init_generic_timeout_cbs_(&bufev->bev.bev);
+
+ return bufev;
+}
+
+int
+bufferevent_pair_new(struct event_base *base, int options,
+ struct bufferevent *pair[2])
+{
+ struct bufferevent_pair *bufev1 = NULL, *bufev2 = NULL;
+ int tmp_options;
+
+ options |= BEV_OPT_DEFER_CALLBACKS;
+ tmp_options = options & ~BEV_OPT_THREADSAFE;
+
+ bufev1 = bufferevent_pair_elt_new(base, options);
+ if (!bufev1)
+ return -1;
+ bufev2 = bufferevent_pair_elt_new(base, tmp_options);
+ if (!bufev2) {
+ bufferevent_free(downcast(bufev1));
+ return -1;
+ }
+
+ if (options & BEV_OPT_THREADSAFE) {
+ /*XXXX check return */
+ bufferevent_enable_locking_(downcast(bufev2), bufev1->bev.lock);
+ }
+
+ bufev1->partner = bufev2;
+ bufev2->partner = bufev1;
+
+ evbuffer_freeze(downcast(bufev1)->input, 0);
+ evbuffer_freeze(downcast(bufev1)->output, 1);
+ evbuffer_freeze(downcast(bufev2)->input, 0);
+ evbuffer_freeze(downcast(bufev2)->output, 1);
+
+ pair[0] = downcast(bufev1);
+ pair[1] = downcast(bufev2);
+
+ return 0;
+}
+
+static void
+be_pair_transfer(struct bufferevent *src, struct bufferevent *dst,
+ int ignore_wm)
+{
+ size_t dst_size;
+ size_t n;
+
+ evbuffer_unfreeze(src->output, 1);
+ evbuffer_unfreeze(dst->input, 0);
+
+ if (dst->wm_read.high) {
+ dst_size = evbuffer_get_length(dst->input);
+ if (dst_size < dst->wm_read.high) {
+ n = dst->wm_read.high - dst_size;
+ evbuffer_remove_buffer(src->output, dst->input, n);
+ } else {
+ if (!ignore_wm)
+ goto done;
+ n = evbuffer_get_length(src->output);
+ evbuffer_add_buffer(dst->input, src->output);
+ }
+ } else {
+ n = evbuffer_get_length(src->output);
+ evbuffer_add_buffer(dst->input, src->output);
+ }
+
+ if (n) {
+ BEV_RESET_GENERIC_READ_TIMEOUT(dst);
+
+ if (evbuffer_get_length(dst->output))
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(dst);
+ else
+ BEV_DEL_GENERIC_WRITE_TIMEOUT(dst);
+ }
+
+ bufferevent_trigger_nolock_(dst, EV_READ, 0);
+ bufferevent_trigger_nolock_(src, EV_WRITE, 0);
+done:
+ evbuffer_freeze(src->output, 1);
+ evbuffer_freeze(dst->input, 0);
+}
+
+static inline int
+be_pair_wants_to_talk(struct bufferevent_pair *src,
+ struct bufferevent_pair *dst)
+{
+ return (downcast(src)->enabled & EV_WRITE) &&
+ (downcast(dst)->enabled & EV_READ) &&
+ !dst->bev.read_suspended &&
+ evbuffer_get_length(downcast(src)->output);
+}
+
+static void
+be_pair_outbuf_cb(struct evbuffer *outbuf,
+ const struct evbuffer_cb_info *info, void *arg)
+{
+ struct bufferevent_pair *bev_pair = arg;
+ struct bufferevent_pair *partner = bev_pair->partner;
+
+ incref_and_lock(downcast(bev_pair));
+
+ if (info->n_added > info->n_deleted && partner) {
+ /* We got more data. If the other side's reading, then
+ hand it over. */
+ if (be_pair_wants_to_talk(bev_pair, partner)) {
+ be_pair_transfer(downcast(bev_pair), downcast(partner), 0);
+ }
+ }
+
+ decref_and_unlock(downcast(bev_pair));
+}
+
+static int
+be_pair_enable(struct bufferevent *bufev, short events)
+{
+ struct bufferevent_pair *bev_p = upcast(bufev);
+ struct bufferevent_pair *partner = bev_p->partner;
+
+ incref_and_lock(bufev);
+
+ if (events & EV_READ) {
+ BEV_RESET_GENERIC_READ_TIMEOUT(bufev);
+ }
+ if ((events & EV_WRITE) && evbuffer_get_length(bufev->output))
+ BEV_RESET_GENERIC_WRITE_TIMEOUT(bufev);
+
+ /* We're starting to read! Does the other side have anything to write?*/
+ if ((events & EV_READ) && partner &&
+ be_pair_wants_to_talk(partner, bev_p)) {
+ be_pair_transfer(downcast(partner), bufev, 0);
+ }
+ /* We're starting to write! Does the other side want to read? */
+ if ((events & EV_WRITE) && partner &&
+ be_pair_wants_to_talk(bev_p, partner)) {
+ be_pair_transfer(bufev, downcast(partner), 0);
+ }
+ decref_and_unlock(bufev);
+ return 0;
+}
+
+static int
+be_pair_disable(struct bufferevent *bev, short events)
+{
+ if (events & EV_READ) {
+ BEV_DEL_GENERIC_READ_TIMEOUT(bev);
+ }
+ if (events & EV_WRITE) {
+ BEV_DEL_GENERIC_WRITE_TIMEOUT(bev);
+ }
+ return 0;
+}
+
+static void
+be_pair_unlink(struct bufferevent *bev)
+{
+ struct bufferevent_pair *bev_p = upcast(bev);
+
+ if (bev_p->partner) {
+ bev_p->unlinked_partner = bev_p->partner;
+ bev_p->partner->partner = NULL;
+ bev_p->partner = NULL;
+ }
+}
+
+/* Free *shared* lock in the latest be (since we share it between two of them). */
+static void
+be_pair_destruct(struct bufferevent *bev)
+{
+ struct bufferevent_pair *bev_p = upcast(bev);
+
+ /* Transfer ownership of the lock into partner, otherwise we will use
+ * already free'd lock during freeing second bev, see next example:
+ *
+ * bev1->own_lock = 1
+ * bev2->own_lock = 0
+ * bev2->lock = bev1->lock
+ *
+ * bufferevent_free(bev1) # refcnt == 0 -> unlink
+ * bufferevent_free(bev2) # refcnt == 0 -> unlink
+ *
+ * event_base_free() -> finilizers -> EVTHREAD_FREE_LOCK(bev1->lock)
+ * -> BEV_LOCK(bev2->lock) <-- already freed
+ *
+ * Where bev1 == pair[0], bev2 == pair[1].
+ */
+ if (bev_p->unlinked_partner && bev_p->bev.own_lock) {
+ bev_p->unlinked_partner->bev.own_lock = 1;
+ bev_p->bev.own_lock = 0;
+ }
+ bev_p->unlinked_partner = NULL;
+}
+
+static int
+be_pair_flush(struct bufferevent *bev, short iotype,
+ enum bufferevent_flush_mode mode)
+{
+ struct bufferevent_pair *bev_p = upcast(bev);
+ struct bufferevent *partner;
+
+ if (!bev_p->partner)
+ return -1;
+
+ if (mode == BEV_NORMAL)
+ return 0;
+
+ incref_and_lock(bev);
+
+ partner = downcast(bev_p->partner);
+
+ if ((iotype & EV_READ) != 0)
+ be_pair_transfer(partner, bev, 1);
+
+ if ((iotype & EV_WRITE) != 0)
+ be_pair_transfer(bev, partner, 1);
+
+ if (mode == BEV_FINISHED) {
+ short what = BEV_EVENT_EOF;
+ if (iotype & EV_READ)
+ what |= BEV_EVENT_WRITING;
+ if (iotype & EV_WRITE)
+ what |= BEV_EVENT_READING;
+ bufferevent_run_eventcb_(partner, what, 0);
+ }
+ decref_and_unlock(bev);
+ return 0;
+}
+
+struct bufferevent *
+bufferevent_pair_get_partner(struct bufferevent *bev)
+{
+ struct bufferevent_pair *bev_p;
+ struct bufferevent *partner = NULL;
+ bev_p = upcast(bev);
+ if (! bev_p)
+ return NULL;
+
+ incref_and_lock(bev);
+ if (bev_p->partner)
+ partner = downcast(bev_p->partner);
+ decref_and_unlock(bev);
+ return partner;
+}
+
+const struct bufferevent_ops bufferevent_ops_pair = {
+ "pair_elt",
+ evutil_offsetof(struct bufferevent_pair, bev.bev),
+ be_pair_enable,
+ be_pair_disable,
+ be_pair_unlink,
+ be_pair_destruct,
+ bufferevent_generic_adj_timeouts_,
+ be_pair_flush,
+ NULL, /* ctrl */
+};
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_ratelim.c b/ipc/chromium/src/third_party/libevent/bufferevent_ratelim.c
new file mode 100644
index 0000000000..2587496853
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_ratelim.c
@@ -0,0 +1,1089 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+#include <limits.h>
+#include <string.h>
+#include <stdlib.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/buffer.h"
+
+#include "ratelim-internal.h"
+
+#include "bufferevent-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "event-internal.h"
+
+int
+ev_token_bucket_init_(struct ev_token_bucket *bucket,
+ const struct ev_token_bucket_cfg *cfg,
+ ev_uint32_t current_tick,
+ int reinitialize)
+{
+ if (reinitialize) {
+ /* on reinitialization, we only clip downwards, since we've
+ already used who-knows-how-much bandwidth this tick. We
+ leave "last_updated" as it is; the next update will add the
+ appropriate amount of bandwidth to the bucket.
+ */
+ if (bucket->read_limit > (ev_int64_t) cfg->read_maximum)
+ bucket->read_limit = cfg->read_maximum;
+ if (bucket->write_limit > (ev_int64_t) cfg->write_maximum)
+ bucket->write_limit = cfg->write_maximum;
+ } else {
+ bucket->read_limit = cfg->read_rate;
+ bucket->write_limit = cfg->write_rate;
+ bucket->last_updated = current_tick;
+ }
+ return 0;
+}
+
+int
+ev_token_bucket_update_(struct ev_token_bucket *bucket,
+ const struct ev_token_bucket_cfg *cfg,
+ ev_uint32_t current_tick)
+{
+ /* It's okay if the tick number overflows, since we'll just
+ * wrap around when we do the unsigned substraction. */
+ unsigned n_ticks = current_tick - bucket->last_updated;
+
+ /* Make sure some ticks actually happened, and that time didn't
+ * roll back. */
+ if (n_ticks == 0 || n_ticks > INT_MAX)
+ return 0;
+
+ /* Naively, we would say
+ bucket->limit += n_ticks * cfg->rate;
+
+ if (bucket->limit > cfg->maximum)
+ bucket->limit = cfg->maximum;
+
+ But we're worried about overflow, so we do it like this:
+ */
+
+ if ((cfg->read_maximum - bucket->read_limit) / n_ticks < cfg->read_rate)
+ bucket->read_limit = cfg->read_maximum;
+ else
+ bucket->read_limit += n_ticks * cfg->read_rate;
+
+
+ if ((cfg->write_maximum - bucket->write_limit) / n_ticks < cfg->write_rate)
+ bucket->write_limit = cfg->write_maximum;
+ else
+ bucket->write_limit += n_ticks * cfg->write_rate;
+
+
+ bucket->last_updated = current_tick;
+
+ return 1;
+}
+
+static inline void
+bufferevent_update_buckets(struct bufferevent_private *bev)
+{
+ /* Must hold lock on bev. */
+ struct timeval now;
+ unsigned tick;
+ event_base_gettimeofday_cached(bev->bev.ev_base, &now);
+ tick = ev_token_bucket_get_tick_(&now, bev->rate_limiting->cfg);
+ if (tick != bev->rate_limiting->limit.last_updated)
+ ev_token_bucket_update_(&bev->rate_limiting->limit,
+ bev->rate_limiting->cfg, tick);
+}
+
+ev_uint32_t
+ev_token_bucket_get_tick_(const struct timeval *tv,
+ const struct ev_token_bucket_cfg *cfg)
+{
+ /* This computation uses two multiplies and a divide. We could do
+ * fewer if we knew that the tick length was an integer number of
+ * seconds, or if we knew it divided evenly into a second. We should
+ * investigate that more.
+ */
+
+ /* We cast to an ev_uint64_t first, since we don't want to overflow
+ * before we do the final divide. */
+ ev_uint64_t msec = (ev_uint64_t)tv->tv_sec * 1000 + tv->tv_usec / 1000;
+ return (unsigned)(msec / cfg->msec_per_tick);
+}
+
+struct ev_token_bucket_cfg *
+ev_token_bucket_cfg_new(size_t read_rate, size_t read_burst,
+ size_t write_rate, size_t write_burst,
+ const struct timeval *tick_len)
+{
+ struct ev_token_bucket_cfg *r;
+ struct timeval g;
+ if (! tick_len) {
+ g.tv_sec = 1;
+ g.tv_usec = 0;
+ tick_len = &g;
+ }
+ if (read_rate > read_burst || write_rate > write_burst ||
+ read_rate < 1 || write_rate < 1)
+ return NULL;
+ if (read_rate > EV_RATE_LIMIT_MAX ||
+ write_rate > EV_RATE_LIMIT_MAX ||
+ read_burst > EV_RATE_LIMIT_MAX ||
+ write_burst > EV_RATE_LIMIT_MAX)
+ return NULL;
+ r = mm_calloc(1, sizeof(struct ev_token_bucket_cfg));
+ if (!r)
+ return NULL;
+ r->read_rate = read_rate;
+ r->write_rate = write_rate;
+ r->read_maximum = read_burst;
+ r->write_maximum = write_burst;
+ memcpy(&r->tick_timeout, tick_len, sizeof(struct timeval));
+ r->msec_per_tick = (tick_len->tv_sec * 1000) +
+ (tick_len->tv_usec & COMMON_TIMEOUT_MICROSECONDS_MASK)/1000;
+ return r;
+}
+
+void
+ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg)
+{
+ mm_free(cfg);
+}
+
+/* Default values for max_single_read & max_single_write variables. */
+#define MAX_SINGLE_READ_DEFAULT 16384
+#define MAX_SINGLE_WRITE_DEFAULT 16384
+
+#define LOCK_GROUP(g) EVLOCK_LOCK((g)->lock, 0)
+#define UNLOCK_GROUP(g) EVLOCK_UNLOCK((g)->lock, 0)
+
+static int bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g);
+static int bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g);
+static void bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g);
+static void bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g);
+
+/** Helper: figure out the maximum amount we should write if is_write, or
+ the maximum amount we should read if is_read. Return that maximum, or
+ 0 if our bucket is wholly exhausted.
+ */
+static inline ev_ssize_t
+bufferevent_get_rlim_max_(struct bufferevent_private *bev, int is_write)
+{
+ /* needs lock on bev. */
+ ev_ssize_t max_so_far = is_write?bev->max_single_write:bev->max_single_read;
+
+#define LIM(x) \
+ (is_write ? (x).write_limit : (x).read_limit)
+
+#define GROUP_SUSPENDED(g) \
+ (is_write ? (g)->write_suspended : (g)->read_suspended)
+
+ /* Sets max_so_far to MIN(x, max_so_far) */
+#define CLAMPTO(x) \
+ do { \
+ if (max_so_far > (x)) \
+ max_so_far = (x); \
+ } while (0);
+
+ if (!bev->rate_limiting)
+ return max_so_far;
+
+ /* If rate-limiting is enabled at all, update the appropriate
+ bucket, and take the smaller of our rate limit and the group
+ rate limit.
+ */
+
+ if (bev->rate_limiting->cfg) {
+ bufferevent_update_buckets(bev);
+ max_so_far = LIM(bev->rate_limiting->limit);
+ }
+ if (bev->rate_limiting->group) {
+ struct bufferevent_rate_limit_group *g =
+ bev->rate_limiting->group;
+ ev_ssize_t share;
+ LOCK_GROUP(g);
+ if (GROUP_SUSPENDED(g)) {
+ /* We can get here if we failed to lock this
+ * particular bufferevent while suspending the whole
+ * group. */
+ if (is_write)
+ bufferevent_suspend_write_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ else
+ bufferevent_suspend_read_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ share = 0;
+ } else {
+ /* XXXX probably we should divide among the active
+ * members, not the total members. */
+ share = LIM(g->rate_limit) / g->n_members;
+ if (share < g->min_share)
+ share = g->min_share;
+ }
+ UNLOCK_GROUP(g);
+ CLAMPTO(share);
+ }
+
+ if (max_so_far < 0)
+ max_so_far = 0;
+ return max_so_far;
+}
+
+ev_ssize_t
+bufferevent_get_read_max_(struct bufferevent_private *bev)
+{
+ return bufferevent_get_rlim_max_(bev, 0);
+}
+
+ev_ssize_t
+bufferevent_get_write_max_(struct bufferevent_private *bev)
+{
+ return bufferevent_get_rlim_max_(bev, 1);
+}
+
+int
+bufferevent_decrement_read_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
+{
+ /* XXXXX Make sure all users of this function check its return value */
+ int r = 0;
+ /* need to hold lock on bev */
+ if (!bev->rate_limiting)
+ return 0;
+
+ if (bev->rate_limiting->cfg) {
+ bev->rate_limiting->limit.read_limit -= bytes;
+ if (bev->rate_limiting->limit.read_limit <= 0) {
+ bufferevent_suspend_read_(&bev->bev, BEV_SUSPEND_BW);
+ if (event_add(&bev->rate_limiting->refill_bucket_event,
+ &bev->rate_limiting->cfg->tick_timeout) < 0)
+ r = -1;
+ } else if (bev->read_suspended & BEV_SUSPEND_BW) {
+ if (!(bev->write_suspended & BEV_SUSPEND_BW))
+ event_del(&bev->rate_limiting->refill_bucket_event);
+ bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
+ }
+ }
+
+ if (bev->rate_limiting->group) {
+ LOCK_GROUP(bev->rate_limiting->group);
+ bev->rate_limiting->group->rate_limit.read_limit -= bytes;
+ bev->rate_limiting->group->total_read += bytes;
+ if (bev->rate_limiting->group->rate_limit.read_limit <= 0) {
+ bev_group_suspend_reading_(bev->rate_limiting->group);
+ } else if (bev->rate_limiting->group->read_suspended) {
+ bev_group_unsuspend_reading_(bev->rate_limiting->group);
+ }
+ UNLOCK_GROUP(bev->rate_limiting->group);
+ }
+
+ return r;
+}
+
+int
+bufferevent_decrement_write_buckets_(struct bufferevent_private *bev, ev_ssize_t bytes)
+{
+ /* XXXXX Make sure all users of this function check its return value */
+ int r = 0;
+ /* need to hold lock */
+ if (!bev->rate_limiting)
+ return 0;
+
+ if (bev->rate_limiting->cfg) {
+ bev->rate_limiting->limit.write_limit -= bytes;
+ if (bev->rate_limiting->limit.write_limit <= 0) {
+ bufferevent_suspend_write_(&bev->bev, BEV_SUSPEND_BW);
+ if (event_add(&bev->rate_limiting->refill_bucket_event,
+ &bev->rate_limiting->cfg->tick_timeout) < 0)
+ r = -1;
+ } else if (bev->write_suspended & BEV_SUSPEND_BW) {
+ if (!(bev->read_suspended & BEV_SUSPEND_BW))
+ event_del(&bev->rate_limiting->refill_bucket_event);
+ bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
+ }
+ }
+
+ if (bev->rate_limiting->group) {
+ LOCK_GROUP(bev->rate_limiting->group);
+ bev->rate_limiting->group->rate_limit.write_limit -= bytes;
+ bev->rate_limiting->group->total_written += bytes;
+ if (bev->rate_limiting->group->rate_limit.write_limit <= 0) {
+ bev_group_suspend_writing_(bev->rate_limiting->group);
+ } else if (bev->rate_limiting->group->write_suspended) {
+ bev_group_unsuspend_writing_(bev->rate_limiting->group);
+ }
+ UNLOCK_GROUP(bev->rate_limiting->group);
+ }
+
+ return r;
+}
+
+/** Stop reading on every bufferevent in <b>g</b> */
+static int
+bev_group_suspend_reading_(struct bufferevent_rate_limit_group *g)
+{
+ /* Needs group lock */
+ struct bufferevent_private *bev;
+ g->read_suspended = 1;
+ g->pending_unsuspend_read = 0;
+
+ /* Note that in this loop we call EVLOCK_TRY_LOCK_ instead of BEV_LOCK,
+ to prevent a deadlock. (Ordinarily, the group lock nests inside
+ the bufferevent locks. If we are unable to lock any individual
+ bufferevent, it will find out later when it looks at its limit
+ and sees that its group is suspended.)
+ */
+ LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+ if (EVLOCK_TRY_LOCK_(bev->lock)) {
+ bufferevent_suspend_read_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ EVLOCK_UNLOCK(bev->lock, 0);
+ }
+ }
+ return 0;
+}
+
+/** Stop writing on every bufferevent in <b>g</b> */
+static int
+bev_group_suspend_writing_(struct bufferevent_rate_limit_group *g)
+{
+ /* Needs group lock */
+ struct bufferevent_private *bev;
+ g->write_suspended = 1;
+ g->pending_unsuspend_write = 0;
+ LIST_FOREACH(bev, &g->members, rate_limiting->next_in_group) {
+ if (EVLOCK_TRY_LOCK_(bev->lock)) {
+ bufferevent_suspend_write_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ EVLOCK_UNLOCK(bev->lock, 0);
+ }
+ }
+ return 0;
+}
+
+/** Timer callback invoked on a single bufferevent with one or more exhausted
+ buckets when they are ready to refill. */
+static void
+bev_refill_callback_(evutil_socket_t fd, short what, void *arg)
+{
+ unsigned tick;
+ struct timeval now;
+ struct bufferevent_private *bev = arg;
+ int again = 0;
+ BEV_LOCK(&bev->bev);
+ if (!bev->rate_limiting || !bev->rate_limiting->cfg) {
+ BEV_UNLOCK(&bev->bev);
+ return;
+ }
+
+ /* First, update the bucket */
+ event_base_gettimeofday_cached(bev->bev.ev_base, &now);
+ tick = ev_token_bucket_get_tick_(&now,
+ bev->rate_limiting->cfg);
+ ev_token_bucket_update_(&bev->rate_limiting->limit,
+ bev->rate_limiting->cfg,
+ tick);
+
+ /* Now unsuspend any read/write operations as appropriate. */
+ if ((bev->read_suspended & BEV_SUSPEND_BW)) {
+ if (bev->rate_limiting->limit.read_limit > 0)
+ bufferevent_unsuspend_read_(&bev->bev, BEV_SUSPEND_BW);
+ else
+ again = 1;
+ }
+ if ((bev->write_suspended & BEV_SUSPEND_BW)) {
+ if (bev->rate_limiting->limit.write_limit > 0)
+ bufferevent_unsuspend_write_(&bev->bev, BEV_SUSPEND_BW);
+ else
+ again = 1;
+ }
+ if (again) {
+ /* One or more of the buckets may need another refill if they
+ started negative.
+
+ XXXX if we need to be quiet for more ticks, we should
+ maybe figure out what timeout we really want.
+ */
+ /* XXXX Handle event_add failure somehow */
+ event_add(&bev->rate_limiting->refill_bucket_event,
+ &bev->rate_limiting->cfg->tick_timeout);
+ }
+ BEV_UNLOCK(&bev->bev);
+}
+
+/** Helper: grab a random element from a bufferevent group.
+ *
+ * Requires that we hold the lock on the group.
+ */
+static struct bufferevent_private *
+bev_group_random_element_(struct bufferevent_rate_limit_group *group)
+{
+ int which;
+ struct bufferevent_private *bev;
+
+ /* requires group lock */
+
+ if (!group->n_members)
+ return NULL;
+
+ EVUTIL_ASSERT(! LIST_EMPTY(&group->members));
+
+ which = evutil_weakrand_range_(&group->weakrand_seed, group->n_members);
+
+ bev = LIST_FIRST(&group->members);
+ while (which--)
+ bev = LIST_NEXT(bev, rate_limiting->next_in_group);
+
+ return bev;
+}
+
+/** Iterate over the elements of a rate-limiting group 'g' with a random
+ starting point, assigning each to the variable 'bev', and executing the
+ block 'block'.
+
+ We do this in a half-baked effort to get fairness among group members.
+ XXX Round-robin or some kind of priority queue would be even more fair.
+ */
+#define FOREACH_RANDOM_ORDER(block) \
+ do { \
+ first = bev_group_random_element_(g); \
+ for (bev = first; bev != LIST_END(&g->members); \
+ bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
+ block ; \
+ } \
+ for (bev = LIST_FIRST(&g->members); bev && bev != first; \
+ bev = LIST_NEXT(bev, rate_limiting->next_in_group)) { \
+ block ; \
+ } \
+ } while (0)
+
+static void
+bev_group_unsuspend_reading_(struct bufferevent_rate_limit_group *g)
+{
+ int again = 0;
+ struct bufferevent_private *bev, *first;
+
+ g->read_suspended = 0;
+ FOREACH_RANDOM_ORDER({
+ if (EVLOCK_TRY_LOCK_(bev->lock)) {
+ bufferevent_unsuspend_read_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ EVLOCK_UNLOCK(bev->lock, 0);
+ } else {
+ again = 1;
+ }
+ });
+ g->pending_unsuspend_read = again;
+}
+
+static void
+bev_group_unsuspend_writing_(struct bufferevent_rate_limit_group *g)
+{
+ int again = 0;
+ struct bufferevent_private *bev, *first;
+ g->write_suspended = 0;
+
+ FOREACH_RANDOM_ORDER({
+ if (EVLOCK_TRY_LOCK_(bev->lock)) {
+ bufferevent_unsuspend_write_(&bev->bev,
+ BEV_SUSPEND_BW_GROUP);
+ EVLOCK_UNLOCK(bev->lock, 0);
+ } else {
+ again = 1;
+ }
+ });
+ g->pending_unsuspend_write = again;
+}
+
+/** Callback invoked every tick to add more elements to the group bucket
+ and unsuspend group members as needed.
+ */
+static void
+bev_group_refill_callback_(evutil_socket_t fd, short what, void *arg)
+{
+ struct bufferevent_rate_limit_group *g = arg;
+ unsigned tick;
+ struct timeval now;
+
+ event_base_gettimeofday_cached(event_get_base(&g->master_refill_event), &now);
+
+ LOCK_GROUP(g);
+
+ tick = ev_token_bucket_get_tick_(&now, &g->rate_limit_cfg);
+ ev_token_bucket_update_(&g->rate_limit, &g->rate_limit_cfg, tick);
+
+ if (g->pending_unsuspend_read ||
+ (g->read_suspended && (g->rate_limit.read_limit >= g->min_share))) {
+ bev_group_unsuspend_reading_(g);
+ }
+ if (g->pending_unsuspend_write ||
+ (g->write_suspended && (g->rate_limit.write_limit >= g->min_share))){
+ bev_group_unsuspend_writing_(g);
+ }
+
+ /* XXXX Rather than waiting to the next tick to unsuspend stuff
+ * with pending_unsuspend_write/read, we should do it on the
+ * next iteration of the mainloop.
+ */
+
+ UNLOCK_GROUP(g);
+}
+
+int
+bufferevent_set_rate_limit(struct bufferevent *bev,
+ struct ev_token_bucket_cfg *cfg)
+{
+ struct bufferevent_private *bevp = BEV_UPCAST(bev);
+ int r = -1;
+ struct bufferevent_rate_limit *rlim;
+ struct timeval now;
+ ev_uint32_t tick;
+ int reinit = 0, suspended = 0;
+ /* XXX reference-count cfg */
+
+ BEV_LOCK(bev);
+
+ if (cfg == NULL) {
+ if (bevp->rate_limiting) {
+ rlim = bevp->rate_limiting;
+ rlim->cfg = NULL;
+ bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
+ bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
+ if (event_initialized(&rlim->refill_bucket_event))
+ event_del(&rlim->refill_bucket_event);
+ }
+ r = 0;
+ goto done;
+ }
+
+ event_base_gettimeofday_cached(bev->ev_base, &now);
+ tick = ev_token_bucket_get_tick_(&now, cfg);
+
+ if (bevp->rate_limiting && bevp->rate_limiting->cfg == cfg) {
+ /* no-op */
+ r = 0;
+ goto done;
+ }
+ if (bevp->rate_limiting == NULL) {
+ rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
+ if (!rlim)
+ goto done;
+ bevp->rate_limiting = rlim;
+ } else {
+ rlim = bevp->rate_limiting;
+ }
+ reinit = rlim->cfg != NULL;
+
+ rlim->cfg = cfg;
+ ev_token_bucket_init_(&rlim->limit, cfg, tick, reinit);
+
+ if (reinit) {
+ EVUTIL_ASSERT(event_initialized(&rlim->refill_bucket_event));
+ event_del(&rlim->refill_bucket_event);
+ }
+ event_assign(&rlim->refill_bucket_event, bev->ev_base,
+ -1, EV_FINALIZE, bev_refill_callback_, bevp);
+
+ if (rlim->limit.read_limit > 0) {
+ bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
+ } else {
+ bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
+ suspended=1;
+ }
+ if (rlim->limit.write_limit > 0) {
+ bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
+ } else {
+ bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
+ suspended = 1;
+ }
+
+ if (suspended)
+ event_add(&rlim->refill_bucket_event, &cfg->tick_timeout);
+
+ r = 0;
+
+done:
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+struct bufferevent_rate_limit_group *
+bufferevent_rate_limit_group_new(struct event_base *base,
+ const struct ev_token_bucket_cfg *cfg)
+{
+ struct bufferevent_rate_limit_group *g;
+ struct timeval now;
+ ev_uint32_t tick;
+
+ event_base_gettimeofday_cached(base, &now);
+ tick = ev_token_bucket_get_tick_(&now, cfg);
+
+ g = mm_calloc(1, sizeof(struct bufferevent_rate_limit_group));
+ if (!g)
+ return NULL;
+ memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
+ LIST_INIT(&g->members);
+
+ ev_token_bucket_init_(&g->rate_limit, cfg, tick, 0);
+
+ event_assign(&g->master_refill_event, base, -1, EV_PERSIST|EV_FINALIZE,
+ bev_group_refill_callback_, g);
+ /*XXXX handle event_add failure */
+ event_add(&g->master_refill_event, &cfg->tick_timeout);
+
+ EVTHREAD_ALLOC_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+ bufferevent_rate_limit_group_set_min_share(g, 64);
+
+ evutil_weakrand_seed_(&g->weakrand_seed,
+ (ev_uint32_t) ((now.tv_sec + now.tv_usec) + (ev_intptr_t)g));
+
+ return g;
+}
+
+int
+bufferevent_rate_limit_group_set_cfg(
+ struct bufferevent_rate_limit_group *g,
+ const struct ev_token_bucket_cfg *cfg)
+{
+ int same_tick;
+ if (!g || !cfg)
+ return -1;
+
+ LOCK_GROUP(g);
+ same_tick = evutil_timercmp(
+ &g->rate_limit_cfg.tick_timeout, &cfg->tick_timeout, ==);
+ memcpy(&g->rate_limit_cfg, cfg, sizeof(g->rate_limit_cfg));
+
+ if (g->rate_limit.read_limit > (ev_ssize_t)cfg->read_maximum)
+ g->rate_limit.read_limit = cfg->read_maximum;
+ if (g->rate_limit.write_limit > (ev_ssize_t)cfg->write_maximum)
+ g->rate_limit.write_limit = cfg->write_maximum;
+
+ if (!same_tick) {
+ /* This can cause a hiccup in the schedule */
+ event_add(&g->master_refill_event, &cfg->tick_timeout);
+ }
+
+ /* The new limits might force us to adjust min_share differently. */
+ bufferevent_rate_limit_group_set_min_share(g, g->configured_min_share);
+
+ UNLOCK_GROUP(g);
+ return 0;
+}
+
+int
+bufferevent_rate_limit_group_set_min_share(
+ struct bufferevent_rate_limit_group *g,
+ size_t share)
+{
+ if (share > EV_SSIZE_MAX)
+ return -1;
+
+ g->configured_min_share = share;
+
+ /* Can't set share to less than the one-tick maximum. IOW, at steady
+ * state, at least one connection can go per tick. */
+ if (share > g->rate_limit_cfg.read_rate)
+ share = g->rate_limit_cfg.read_rate;
+ if (share > g->rate_limit_cfg.write_rate)
+ share = g->rate_limit_cfg.write_rate;
+
+ g->min_share = share;
+ return 0;
+}
+
+void
+bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *g)
+{
+ LOCK_GROUP(g);
+ EVUTIL_ASSERT(0 == g->n_members);
+ event_del(&g->master_refill_event);
+ UNLOCK_GROUP(g);
+ EVTHREAD_FREE_LOCK(g->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ mm_free(g);
+}
+
+int
+bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
+ struct bufferevent_rate_limit_group *g)
+{
+ int wsuspend, rsuspend;
+ struct bufferevent_private *bevp = BEV_UPCAST(bev);
+ BEV_LOCK(bev);
+
+ if (!bevp->rate_limiting) {
+ struct bufferevent_rate_limit *rlim;
+ rlim = mm_calloc(1, sizeof(struct bufferevent_rate_limit));
+ if (!rlim) {
+ BEV_UNLOCK(bev);
+ return -1;
+ }
+ event_assign(&rlim->refill_bucket_event, bev->ev_base,
+ -1, EV_FINALIZE, bev_refill_callback_, bevp);
+ bevp->rate_limiting = rlim;
+ }
+
+ if (bevp->rate_limiting->group == g) {
+ BEV_UNLOCK(bev);
+ return 0;
+ }
+ if (bevp->rate_limiting->group)
+ bufferevent_remove_from_rate_limit_group(bev);
+
+ LOCK_GROUP(g);
+ bevp->rate_limiting->group = g;
+ ++g->n_members;
+ LIST_INSERT_HEAD(&g->members, bevp, rate_limiting->next_in_group);
+
+ rsuspend = g->read_suspended;
+ wsuspend = g->write_suspended;
+
+ UNLOCK_GROUP(g);
+
+ if (rsuspend)
+ bufferevent_suspend_read_(bev, BEV_SUSPEND_BW_GROUP);
+ if (wsuspend)
+ bufferevent_suspend_write_(bev, BEV_SUSPEND_BW_GROUP);
+
+ BEV_UNLOCK(bev);
+ return 0;
+}
+
+int
+bufferevent_remove_from_rate_limit_group(struct bufferevent *bev)
+{
+ return bufferevent_remove_from_rate_limit_group_internal_(bev, 1);
+}
+
+int
+bufferevent_remove_from_rate_limit_group_internal_(struct bufferevent *bev,
+ int unsuspend)
+{
+ struct bufferevent_private *bevp = BEV_UPCAST(bev);
+ BEV_LOCK(bev);
+ if (bevp->rate_limiting && bevp->rate_limiting->group) {
+ struct bufferevent_rate_limit_group *g =
+ bevp->rate_limiting->group;
+ LOCK_GROUP(g);
+ bevp->rate_limiting->group = NULL;
+ --g->n_members;
+ LIST_REMOVE(bevp, rate_limiting->next_in_group);
+ UNLOCK_GROUP(g);
+ }
+ if (unsuspend) {
+ bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW_GROUP);
+ bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW_GROUP);
+ }
+ BEV_UNLOCK(bev);
+ return 0;
+}
+
+/* ===
+ * API functions to expose rate limits.
+ *
+ * Don't use these from inside Libevent; they're meant to be for use by
+ * the program.
+ * === */
+
+/* Mostly you don't want to use this function from inside libevent;
+ * bufferevent_get_read_max_() is more likely what you want*/
+ev_ssize_t
+bufferevent_get_read_limit(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
+ bufferevent_update_buckets(bevp);
+ r = bevp->rate_limiting->limit.read_limit;
+ } else {
+ r = EV_SSIZE_MAX;
+ }
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+/* Mostly you don't want to use this function from inside libevent;
+ * bufferevent_get_write_max_() is more likely what you want*/
+ev_ssize_t
+bufferevent_get_write_limit(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ if (bevp->rate_limiting && bevp->rate_limiting->cfg) {
+ bufferevent_update_buckets(bevp);
+ r = bevp->rate_limiting->limit.write_limit;
+ } else {
+ r = EV_SSIZE_MAX;
+ }
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+int
+bufferevent_set_max_single_read(struct bufferevent *bev, size_t size)
+{
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ if (size == 0 || size > EV_SSIZE_MAX)
+ bevp->max_single_read = MAX_SINGLE_READ_DEFAULT;
+ else
+ bevp->max_single_read = size;
+ BEV_UNLOCK(bev);
+ return 0;
+}
+
+int
+bufferevent_set_max_single_write(struct bufferevent *bev, size_t size)
+{
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ if (size == 0 || size > EV_SSIZE_MAX)
+ bevp->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
+ else
+ bevp->max_single_write = size;
+ BEV_UNLOCK(bev);
+ return 0;
+}
+
+ev_ssize_t
+bufferevent_get_max_single_read(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+
+ BEV_LOCK(bev);
+ r = BEV_UPCAST(bev)->max_single_read;
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_single_write(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+
+ BEV_LOCK(bev);
+ r = BEV_UPCAST(bev)->max_single_write;
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_to_read(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+ BEV_LOCK(bev);
+ r = bufferevent_get_read_max_(BEV_UPCAST(bev));
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+ev_ssize_t
+bufferevent_get_max_to_write(struct bufferevent *bev)
+{
+ ev_ssize_t r;
+ BEV_LOCK(bev);
+ r = bufferevent_get_write_max_(BEV_UPCAST(bev));
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+const struct ev_token_bucket_cfg *
+bufferevent_get_token_bucket_cfg(const struct bufferevent *bev) {
+ struct bufferevent_private *bufev_private = BEV_UPCAST(bev);
+ struct ev_token_bucket_cfg *cfg;
+
+ BEV_LOCK(bev);
+
+ if (bufev_private->rate_limiting) {
+ cfg = bufev_private->rate_limiting->cfg;
+ } else {
+ cfg = NULL;
+ }
+
+ BEV_UNLOCK(bev);
+
+ return cfg;
+}
+
+/* Mostly you don't want to use this function from inside libevent;
+ * bufferevent_get_read_max_() is more likely what you want*/
+ev_ssize_t
+bufferevent_rate_limit_group_get_read_limit(
+ struct bufferevent_rate_limit_group *grp)
+{
+ ev_ssize_t r;
+ LOCK_GROUP(grp);
+ r = grp->rate_limit.read_limit;
+ UNLOCK_GROUP(grp);
+ return r;
+}
+
+/* Mostly you don't want to use this function from inside libevent;
+ * bufferevent_get_write_max_() is more likely what you want. */
+ev_ssize_t
+bufferevent_rate_limit_group_get_write_limit(
+ struct bufferevent_rate_limit_group *grp)
+{
+ ev_ssize_t r;
+ LOCK_GROUP(grp);
+ r = grp->rate_limit.write_limit;
+ UNLOCK_GROUP(grp);
+ return r;
+}
+
+int
+bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr)
+{
+ int r = 0;
+ ev_ssize_t old_limit, new_limit;
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
+ old_limit = bevp->rate_limiting->limit.read_limit;
+
+ new_limit = (bevp->rate_limiting->limit.read_limit -= decr);
+ if (old_limit > 0 && new_limit <= 0) {
+ bufferevent_suspend_read_(bev, BEV_SUSPEND_BW);
+ if (event_add(&bevp->rate_limiting->refill_bucket_event,
+ &bevp->rate_limiting->cfg->tick_timeout) < 0)
+ r = -1;
+ } else if (old_limit <= 0 && new_limit > 0) {
+ if (!(bevp->write_suspended & BEV_SUSPEND_BW))
+ event_del(&bevp->rate_limiting->refill_bucket_event);
+ bufferevent_unsuspend_read_(bev, BEV_SUSPEND_BW);
+ }
+
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+int
+bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr)
+{
+ /* XXXX this is mostly copy-and-paste from
+ * bufferevent_decrement_read_limit */
+ int r = 0;
+ ev_ssize_t old_limit, new_limit;
+ struct bufferevent_private *bevp;
+ BEV_LOCK(bev);
+ bevp = BEV_UPCAST(bev);
+ EVUTIL_ASSERT(bevp->rate_limiting && bevp->rate_limiting->cfg);
+ old_limit = bevp->rate_limiting->limit.write_limit;
+
+ new_limit = (bevp->rate_limiting->limit.write_limit -= decr);
+ if (old_limit > 0 && new_limit <= 0) {
+ bufferevent_suspend_write_(bev, BEV_SUSPEND_BW);
+ if (event_add(&bevp->rate_limiting->refill_bucket_event,
+ &bevp->rate_limiting->cfg->tick_timeout) < 0)
+ r = -1;
+ } else if (old_limit <= 0 && new_limit > 0) {
+ if (!(bevp->read_suspended & BEV_SUSPEND_BW))
+ event_del(&bevp->rate_limiting->refill_bucket_event);
+ bufferevent_unsuspend_write_(bev, BEV_SUSPEND_BW);
+ }
+
+ BEV_UNLOCK(bev);
+ return r;
+}
+
+int
+bufferevent_rate_limit_group_decrement_read(
+ struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
+{
+ int r = 0;
+ ev_ssize_t old_limit, new_limit;
+ LOCK_GROUP(grp);
+ old_limit = grp->rate_limit.read_limit;
+ new_limit = (grp->rate_limit.read_limit -= decr);
+
+ if (old_limit > 0 && new_limit <= 0) {
+ bev_group_suspend_reading_(grp);
+ } else if (old_limit <= 0 && new_limit > 0) {
+ bev_group_unsuspend_reading_(grp);
+ }
+
+ UNLOCK_GROUP(grp);
+ return r;
+}
+
+int
+bufferevent_rate_limit_group_decrement_write(
+ struct bufferevent_rate_limit_group *grp, ev_ssize_t decr)
+{
+ int r = 0;
+ ev_ssize_t old_limit, new_limit;
+ LOCK_GROUP(grp);
+ old_limit = grp->rate_limit.write_limit;
+ new_limit = (grp->rate_limit.write_limit -= decr);
+
+ if (old_limit > 0 && new_limit <= 0) {
+ bev_group_suspend_writing_(grp);
+ } else if (old_limit <= 0 && new_limit > 0) {
+ bev_group_unsuspend_writing_(grp);
+ }
+
+ UNLOCK_GROUP(grp);
+ return r;
+}
+
+void
+bufferevent_rate_limit_group_get_totals(struct bufferevent_rate_limit_group *grp,
+ ev_uint64_t *total_read_out, ev_uint64_t *total_written_out)
+{
+ EVUTIL_ASSERT(grp != NULL);
+ if (total_read_out)
+ *total_read_out = grp->total_read;
+ if (total_written_out)
+ *total_written_out = grp->total_written;
+}
+
+void
+bufferevent_rate_limit_group_reset_totals(struct bufferevent_rate_limit_group *grp)
+{
+ grp->total_read = grp->total_written = 0;
+}
+
+int
+bufferevent_ratelim_init_(struct bufferevent_private *bev)
+{
+ bev->rate_limiting = NULL;
+ bev->max_single_read = MAX_SINGLE_READ_DEFAULT;
+ bev->max_single_write = MAX_SINGLE_WRITE_DEFAULT;
+
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/bufferevent_sock.c b/ipc/chromium/src/third_party/libevent/bufferevent_sock.c
new file mode 100644
index 0000000000..f40a8d9c57
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/bufferevent_sock.c
@@ -0,0 +1,707 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright (c) 2002-2006 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_STDARG_H
+#include <stdarg.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/event.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+#include "util-internal.h"
+#ifdef _WIN32
+#include "iocp-internal.h"
+#endif
+
+/* prototypes */
+static int be_socket_enable(struct bufferevent *, short);
+static int be_socket_disable(struct bufferevent *, short);
+static void be_socket_destruct(struct bufferevent *);
+static int be_socket_flush(struct bufferevent *, short, enum bufferevent_flush_mode);
+static int be_socket_ctrl(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
+
+static void be_socket_setfd(struct bufferevent *, evutil_socket_t);
+
+const struct bufferevent_ops bufferevent_ops_socket = {
+ "socket",
+ evutil_offsetof(struct bufferevent_private, bev),
+ be_socket_enable,
+ be_socket_disable,
+ NULL, /* unlink */
+ be_socket_destruct,
+ bufferevent_generic_adj_existing_timeouts_,
+ be_socket_flush,
+ be_socket_ctrl,
+};
+
+const struct sockaddr*
+bufferevent_socket_get_conn_address_(struct bufferevent *bev)
+{
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ return (struct sockaddr *)&bev_p->conn_address;
+}
+
+void
+bufferevent_socket_set_conn_address_fd_(struct bufferevent *bev,
+ evutil_socket_t fd)
+{
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+
+ socklen_t len = sizeof(bev_p->conn_address);
+
+ struct sockaddr *addr = (struct sockaddr *)&bev_p->conn_address;
+ if (addr->sa_family != AF_UNSPEC)
+ getpeername(fd, addr, &len);
+}
+
+void
+bufferevent_socket_set_conn_address_(struct bufferevent *bev,
+ struct sockaddr *addr, size_t addrlen)
+{
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ EVUTIL_ASSERT(addrlen <= sizeof(bev_p->conn_address));
+ memcpy(&bev_p->conn_address, addr, addrlen);
+}
+
+static void
+bufferevent_socket_outbuf_cb(struct evbuffer *buf,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+ struct bufferevent *bufev = arg;
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+
+ if (cbinfo->n_added &&
+ (bufev->enabled & EV_WRITE) &&
+ !event_pending(&bufev->ev_write, EV_WRITE, NULL) &&
+ !bufev_p->write_suspended) {
+ /* Somebody added data to the buffer, and we would like to
+ * write, and we were not writing. So, start writing. */
+ if (bufferevent_add_event_(&bufev->ev_write, &bufev->timeout_write) == -1) {
+ /* Should we log this? */
+ }
+ }
+}
+
+static void
+bufferevent_readcb(evutil_socket_t fd, short event, void *arg)
+{
+ struct bufferevent *bufev = arg;
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+ struct evbuffer *input;
+ int res = 0;
+ short what = BEV_EVENT_READING;
+ ev_ssize_t howmuch = -1, readmax=-1;
+
+ bufferevent_incref_and_lock_(bufev);
+
+ if (event == EV_TIMEOUT) {
+ /* Note that we only check for event==EV_TIMEOUT. If
+ * event==EV_TIMEOUT|EV_READ, we can safely ignore the
+ * timeout, since a read has occurred */
+ what |= BEV_EVENT_TIMEOUT;
+ goto error;
+ }
+
+ input = bufev->input;
+
+ /*
+ * If we have a high watermark configured then we don't want to
+ * read more data than would make us reach the watermark.
+ */
+ if (bufev->wm_read.high != 0) {
+ howmuch = bufev->wm_read.high - evbuffer_get_length(input);
+ /* we somehow lowered the watermark, stop reading */
+ if (howmuch <= 0) {
+ bufferevent_wm_suspend_read(bufev);
+ goto done;
+ }
+ }
+ readmax = bufferevent_get_read_max_(bufev_p);
+ if (howmuch < 0 || howmuch > readmax) /* The use of -1 for "unlimited"
+ * uglifies this code. XXXX */
+ howmuch = readmax;
+ if (bufev_p->read_suspended)
+ goto done;
+
+ evbuffer_unfreeze(input, 0);
+ res = evbuffer_read(input, fd, (int)howmuch); /* XXXX evbuffer_read would do better to take and return ev_ssize_t */
+ evbuffer_freeze(input, 0);
+
+ if (res == -1) {
+ int err = evutil_socket_geterror(fd);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ goto reschedule;
+ if (EVUTIL_ERR_CONNECT_REFUSED(err)) {
+ bufev_p->connection_refused = 1;
+ goto done;
+ }
+ /* error case */
+ what |= BEV_EVENT_ERROR;
+ } else if (res == 0) {
+ /* eof case */
+ what |= BEV_EVENT_EOF;
+ }
+
+ if (res <= 0)
+ goto error;
+
+ bufferevent_decrement_read_buckets_(bufev_p, res);
+
+ /* Invoke the user callback - must always be called last */
+ bufferevent_trigger_nolock_(bufev, EV_READ, 0);
+
+ goto done;
+
+ reschedule:
+ goto done;
+
+ error:
+ bufferevent_disable(bufev, EV_READ);
+ bufferevent_run_eventcb_(bufev, what, 0);
+
+ done:
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+static void
+bufferevent_writecb(evutil_socket_t fd, short event, void *arg)
+{
+ struct bufferevent *bufev = arg;
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+ int res = 0;
+ short what = BEV_EVENT_WRITING;
+ int connected = 0;
+ ev_ssize_t atmost = -1;
+
+ bufferevent_incref_and_lock_(bufev);
+
+ if (event == EV_TIMEOUT) {
+ /* Note that we only check for event==EV_TIMEOUT. If
+ * event==EV_TIMEOUT|EV_WRITE, we can safely ignore the
+ * timeout, since a read has occurred */
+ what |= BEV_EVENT_TIMEOUT;
+ goto error;
+ }
+ if (bufev_p->connecting) {
+ int c = evutil_socket_finished_connecting_(fd);
+ /* we need to fake the error if the connection was refused
+ * immediately - usually connection to localhost on BSD */
+ if (bufev_p->connection_refused) {
+ bufev_p->connection_refused = 0;
+ c = -1;
+ }
+
+ if (c == 0)
+ goto done;
+
+ bufev_p->connecting = 0;
+ if (c < 0) {
+ event_del(&bufev->ev_write);
+ event_del(&bufev->ev_read);
+ bufferevent_run_eventcb_(bufev, BEV_EVENT_ERROR, 0);
+ goto done;
+ } else {
+ connected = 1;
+ bufferevent_socket_set_conn_address_fd_(bufev, fd);
+#ifdef _WIN32
+ if (BEV_IS_ASYNC(bufev)) {
+ event_del(&bufev->ev_write);
+ bufferevent_async_set_connected_(bufev);
+ bufferevent_run_eventcb_(bufev,
+ BEV_EVENT_CONNECTED, 0);
+ goto done;
+ }
+#endif
+ bufferevent_run_eventcb_(bufev,
+ BEV_EVENT_CONNECTED, 0);
+ if (!(bufev->enabled & EV_WRITE) ||
+ bufev_p->write_suspended) {
+ event_del(&bufev->ev_write);
+ goto done;
+ }
+ }
+ }
+
+ atmost = bufferevent_get_write_max_(bufev_p);
+
+ if (bufev_p->write_suspended)
+ goto done;
+
+ if (evbuffer_get_length(bufev->output)) {
+ evbuffer_unfreeze(bufev->output, 1);
+ res = evbuffer_write_atmost(bufev->output, fd, atmost);
+ evbuffer_freeze(bufev->output, 1);
+ if (res == -1) {
+ int err = evutil_socket_geterror(fd);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ goto reschedule;
+ what |= BEV_EVENT_ERROR;
+ } else if (res == 0) {
+ /* eof case
+ XXXX Actually, a 0 on write doesn't indicate
+ an EOF. An ECONNRESET might be more typical.
+ */
+ what |= BEV_EVENT_EOF;
+ }
+ if (res <= 0)
+ goto error;
+
+ bufferevent_decrement_write_buckets_(bufev_p, res);
+ }
+
+ if (evbuffer_get_length(bufev->output) == 0) {
+ event_del(&bufev->ev_write);
+ }
+
+ /*
+ * Invoke the user callback if our buffer is drained or below the
+ * low watermark.
+ */
+ if (res || !connected) {
+ bufferevent_trigger_nolock_(bufev, EV_WRITE, 0);
+ }
+
+ goto done;
+
+ reschedule:
+ if (evbuffer_get_length(bufev->output) == 0) {
+ event_del(&bufev->ev_write);
+ }
+ goto done;
+
+ error:
+ bufferevent_disable(bufev, EV_WRITE);
+ bufferevent_run_eventcb_(bufev, what, 0);
+
+ done:
+ bufferevent_decref_and_unlock_(bufev);
+}
+
+struct bufferevent *
+bufferevent_socket_new(struct event_base *base, evutil_socket_t fd,
+ int options)
+{
+ struct bufferevent_private *bufev_p;
+ struct bufferevent *bufev;
+
+#ifdef _WIN32
+ if (base && event_base_get_iocp_(base))
+ return bufferevent_async_new_(base, fd, options);
+#endif
+
+ if ((bufev_p = mm_calloc(1, sizeof(struct bufferevent_private)))== NULL)
+ return NULL;
+
+ if (bufferevent_init_common_(bufev_p, base, &bufferevent_ops_socket,
+ options) < 0) {
+ mm_free(bufev_p);
+ return NULL;
+ }
+ bufev = &bufev_p->bev;
+ evbuffer_set_flags(bufev->output, EVBUFFER_FLAG_DRAINS_TO_FD);
+
+ event_assign(&bufev->ev_read, bufev->ev_base, fd,
+ EV_READ|EV_PERSIST|EV_FINALIZE, bufferevent_readcb, bufev);
+ event_assign(&bufev->ev_write, bufev->ev_base, fd,
+ EV_WRITE|EV_PERSIST|EV_FINALIZE, bufferevent_writecb, bufev);
+
+ evbuffer_add_cb(bufev->output, bufferevent_socket_outbuf_cb, bufev);
+
+ evbuffer_freeze(bufev->input, 0);
+ evbuffer_freeze(bufev->output, 1);
+
+ return bufev;
+}
+
+int
+bufferevent_socket_connect(struct bufferevent *bev,
+ const struct sockaddr *sa, int socklen)
+{
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bev);
+
+ evutil_socket_t fd;
+ int r = 0;
+ int result=-1;
+ int ownfd = 0;
+
+ bufferevent_incref_and_lock_(bev);
+
+ fd = bufferevent_getfd(bev);
+ if (fd < 0) {
+ if (!sa)
+ goto done;
+ fd = evutil_socket_(sa->sa_family,
+ SOCK_STREAM|EVUTIL_SOCK_NONBLOCK, 0);
+ if (fd < 0)
+ goto freesock;
+ ownfd = 1;
+ }
+ if (sa) {
+#ifdef _WIN32
+ if (bufferevent_async_can_connect_(bev)) {
+ bufferevent_setfd(bev, fd);
+ r = bufferevent_async_connect_(bev, fd, sa, socklen);
+ if (r < 0)
+ goto freesock;
+ bufev_p->connecting = 1;
+ result = 0;
+ goto done;
+ } else
+#endif
+ r = evutil_socket_connect_(&fd, sa, socklen);
+ if (r < 0)
+ goto freesock;
+ }
+#ifdef _WIN32
+ /* ConnectEx() isn't always around, even when IOCP is enabled.
+ * Here, we borrow the socket object's write handler to fall back
+ * on a non-blocking connect() when ConnectEx() is unavailable. */
+ if (BEV_IS_ASYNC(bev)) {
+ event_assign(&bev->ev_write, bev->ev_base, fd,
+ EV_WRITE|EV_PERSIST|EV_FINALIZE, bufferevent_writecb, bev);
+ }
+#endif
+ bufferevent_setfd(bev, fd);
+ if (r == 0) {
+ if (! be_socket_enable(bev, EV_WRITE)) {
+ bufev_p->connecting = 1;
+ result = 0;
+ goto done;
+ }
+ } else if (r == 1) {
+ /* The connect succeeded already. How very BSD of it. */
+ result = 0;
+ bufev_p->connecting = 1;
+ bufferevent_trigger_nolock_(bev, EV_WRITE, BEV_OPT_DEFER_CALLBACKS);
+ } else {
+ /* The connect failed already. How very BSD of it. */
+ result = 0;
+ bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR, BEV_OPT_DEFER_CALLBACKS);
+ bufferevent_disable(bev, EV_WRITE|EV_READ);
+ }
+
+ goto done;
+
+freesock:
+ if (ownfd)
+ evutil_closesocket(fd);
+done:
+ bufferevent_decref_and_unlock_(bev);
+ return result;
+}
+
+static void
+bufferevent_connect_getaddrinfo_cb(int result, struct evutil_addrinfo *ai,
+ void *arg)
+{
+ struct bufferevent *bev = arg;
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+ int r;
+ BEV_LOCK(bev);
+
+ bufferevent_unsuspend_write_(bev, BEV_SUSPEND_LOOKUP);
+ bufferevent_unsuspend_read_(bev, BEV_SUSPEND_LOOKUP);
+
+ bev_p->dns_request = NULL;
+
+ if (result == EVUTIL_EAI_CANCEL) {
+ bev_p->dns_error = result;
+ bufferevent_decref_and_unlock_(bev);
+ return;
+ }
+ if (result != 0) {
+ bev_p->dns_error = result;
+ bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR, 0);
+ bufferevent_decref_and_unlock_(bev);
+ if (ai)
+ evutil_freeaddrinfo(ai);
+ return;
+ }
+
+ /* XXX use the other addrinfos? */
+ bufferevent_socket_set_conn_address_(bev, ai->ai_addr, (int)ai->ai_addrlen);
+ r = bufferevent_socket_connect(bev, ai->ai_addr, (int)ai->ai_addrlen);
+ if (r < 0)
+ bufferevent_run_eventcb_(bev, BEV_EVENT_ERROR, 0);
+ bufferevent_decref_and_unlock_(bev);
+ evutil_freeaddrinfo(ai);
+}
+
+int
+bufferevent_socket_connect_hostname(struct bufferevent *bev,
+ struct evdns_base *evdns_base, int family, const char *hostname, int port)
+{
+ char portbuf[10];
+ struct evutil_addrinfo hint;
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+
+ if (family != AF_INET && family != AF_INET6 && family != AF_UNSPEC)
+ return -1;
+ if (port < 1 || port > 65535)
+ return -1;
+
+ memset(&hint, 0, sizeof(hint));
+ hint.ai_family = family;
+ hint.ai_protocol = IPPROTO_TCP;
+ hint.ai_socktype = SOCK_STREAM;
+
+ evutil_snprintf(portbuf, sizeof(portbuf), "%d", port);
+
+ BEV_LOCK(bev);
+ bev_p->dns_error = 0;
+
+ bufferevent_suspend_write_(bev, BEV_SUSPEND_LOOKUP);
+ bufferevent_suspend_read_(bev, BEV_SUSPEND_LOOKUP);
+
+ bufferevent_incref_(bev);
+ bev_p->dns_request = evutil_getaddrinfo_async_(evdns_base, hostname,
+ portbuf, &hint, bufferevent_connect_getaddrinfo_cb, bev);
+ BEV_UNLOCK(bev);
+
+ return 0;
+}
+
+int
+bufferevent_socket_get_dns_error(struct bufferevent *bev)
+{
+ int rv;
+ struct bufferevent_private *bev_p = BEV_UPCAST(bev);
+
+ BEV_LOCK(bev);
+ rv = bev_p->dns_error;
+ BEV_UNLOCK(bev);
+
+ return rv;
+}
+
+/*
+ * Create a new buffered event object.
+ *
+ * The read callback is invoked whenever we read new data.
+ * The write callback is invoked whenever the output buffer is drained.
+ * The error callback is invoked on a write/read error or on EOF.
+ *
+ * Both read and write callbacks maybe NULL. The error callback is not
+ * allowed to be NULL and have to be provided always.
+ */
+
+struct bufferevent *
+bufferevent_new(evutil_socket_t fd,
+ bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+ bufferevent_event_cb eventcb, void *cbarg)
+{
+ struct bufferevent *bufev;
+
+ if (!(bufev = bufferevent_socket_new(NULL, fd, 0)))
+ return NULL;
+
+ bufferevent_setcb(bufev, readcb, writecb, eventcb, cbarg);
+
+ return bufev;
+}
+
+
+static int
+be_socket_enable(struct bufferevent *bufev, short event)
+{
+ if (event & EV_READ &&
+ bufferevent_add_event_(&bufev->ev_read, &bufev->timeout_read) == -1)
+ return -1;
+ if (event & EV_WRITE &&
+ bufferevent_add_event_(&bufev->ev_write, &bufev->timeout_write) == -1)
+ return -1;
+ return 0;
+}
+
+static int
+be_socket_disable(struct bufferevent *bufev, short event)
+{
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+ if (event & EV_READ) {
+ if (event_del(&bufev->ev_read) == -1)
+ return -1;
+ }
+ /* Don't actually disable the write if we are trying to connect. */
+ if ((event & EV_WRITE) && ! bufev_p->connecting) {
+ if (event_del(&bufev->ev_write) == -1)
+ return -1;
+ }
+ return 0;
+}
+
+static void
+be_socket_destruct(struct bufferevent *bufev)
+{
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+ evutil_socket_t fd;
+ EVUTIL_ASSERT(BEV_IS_SOCKET(bufev));
+
+ fd = event_get_fd(&bufev->ev_read);
+
+ if ((bufev_p->options & BEV_OPT_CLOSE_ON_FREE) && fd >= 0)
+ EVUTIL_CLOSESOCKET(fd);
+
+ evutil_getaddrinfo_cancel_async_(bufev_p->dns_request);
+}
+
+static int
+be_socket_flush(struct bufferevent *bev, short iotype,
+ enum bufferevent_flush_mode mode)
+{
+ return 0;
+}
+
+
+static void
+be_socket_setfd(struct bufferevent *bufev, evutil_socket_t fd)
+{
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+
+ BEV_LOCK(bufev);
+ EVUTIL_ASSERT(BEV_IS_SOCKET(bufev));
+
+ event_del(&bufev->ev_read);
+ event_del(&bufev->ev_write);
+
+ evbuffer_unfreeze(bufev->input, 0);
+ evbuffer_unfreeze(bufev->output, 1);
+
+ event_assign(&bufev->ev_read, bufev->ev_base, fd,
+ EV_READ|EV_PERSIST|EV_FINALIZE, bufferevent_readcb, bufev);
+ event_assign(&bufev->ev_write, bufev->ev_base, fd,
+ EV_WRITE|EV_PERSIST|EV_FINALIZE, bufferevent_writecb, bufev);
+
+ if (fd >= 0)
+ bufferevent_enable(bufev, bufev->enabled);
+
+ evutil_getaddrinfo_cancel_async_(bufev_p->dns_request);
+
+ BEV_UNLOCK(bufev);
+}
+
+/* XXXX Should non-socket bufferevents support this? */
+int
+bufferevent_priority_set(struct bufferevent *bufev, int priority)
+{
+ int r = -1;
+ struct bufferevent_private *bufev_p = BEV_UPCAST(bufev);
+
+ BEV_LOCK(bufev);
+ if (BEV_IS_ASYNC(bufev) || BEV_IS_FILTER(bufev) || BEV_IS_PAIR(bufev))
+ goto done;
+
+ if (event_priority_set(&bufev->ev_read, priority) == -1)
+ goto done;
+ if (event_priority_set(&bufev->ev_write, priority) == -1)
+ goto done;
+
+ event_deferred_cb_set_priority_(&bufev_p->deferred, priority);
+
+ r = 0;
+done:
+ BEV_UNLOCK(bufev);
+ return r;
+}
+
+/* XXXX Should non-socket bufferevents support this? */
+int
+bufferevent_base_set(struct event_base *base, struct bufferevent *bufev)
+{
+ int res = -1;
+
+ BEV_LOCK(bufev);
+ if (!BEV_IS_SOCKET(bufev))
+ goto done;
+
+ bufev->ev_base = base;
+
+ res = event_base_set(base, &bufev->ev_read);
+ if (res == -1)
+ goto done;
+
+ res = event_base_set(base, &bufev->ev_write);
+done:
+ BEV_UNLOCK(bufev);
+ return res;
+}
+
+static int
+be_socket_ctrl(struct bufferevent *bev, enum bufferevent_ctrl_op op,
+ union bufferevent_ctrl_data *data)
+{
+ switch (op) {
+ case BEV_CTRL_SET_FD:
+ be_socket_setfd(bev, data->fd);
+ return 0;
+ case BEV_CTRL_GET_FD:
+ data->fd = event_get_fd(&bev->ev_read);
+ return 0;
+ case BEV_CTRL_GET_UNDERLYING:
+ case BEV_CTRL_CANCEL_ALL:
+ default:
+ return -1;
+ }
+}
diff --git a/ipc/chromium/src/third_party/libevent/changelist-internal.h b/ipc/chromium/src/third_party/libevent/changelist-internal.h
new file mode 100644
index 0000000000..98fc52aebf
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/changelist-internal.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef CHANGELIST_INTERNAL_H_INCLUDED_
+#define CHANGELIST_INTERNAL_H_INCLUDED_
+
+/*
+ A "changelist" is a list of all the fd status changes that should be made
+ between calls to the backend's dispatch function. There are a few reasons
+ that a backend would want to queue changes like this rather than processing
+ them immediately.
+
+ 1) Sometimes applications will add and delete the same event more than
+ once between calls to dispatch. Processing these changes immediately
+ is needless, and potentially expensive (especially if we're on a system
+ that makes one syscall per changed event).
+
+ 2) Sometimes we can coalesce multiple changes on the same fd into a single
+ syscall if we know about them in advance. For example, epoll can do an
+ add and a delete at the same time, but only if we have found out about
+ both of them before we tell epoll.
+
+ 3) Sometimes adding an event that we immediately delete can cause
+ unintended consequences: in kqueue, this makes pending events get
+ reported spuriously.
+ */
+
+#include "event2/util.h"
+
+/** Represents a */
+struct event_change {
+ /** The fd or signal whose events are to be changed */
+ evutil_socket_t fd;
+ /* The events that were enabled on the fd before any of these changes
+ were made. May include EV_READ or EV_WRITE. */
+ short old_events;
+
+ /* The changes that we want to make in reading and writing on this fd.
+ * If this is a signal, then read_change has EV_CHANGE_SIGNAL set,
+ * and write_change is unused. */
+ ev_uint8_t read_change;
+ ev_uint8_t write_change;
+ ev_uint8_t close_change;
+};
+
+/* Flags for read_change and write_change. */
+
+/* If set, add the event. */
+#define EV_CHANGE_ADD 0x01
+/* If set, delete the event. Exclusive with EV_CHANGE_ADD */
+#define EV_CHANGE_DEL 0x02
+/* If set, this event refers a signal, not an fd. */
+#define EV_CHANGE_SIGNAL EV_SIGNAL
+/* Set for persistent events. Currently not used. */
+#define EV_CHANGE_PERSIST EV_PERSIST
+/* Set for adding edge-triggered events. */
+#define EV_CHANGE_ET EV_ET
+
+/* The value of fdinfo_size that a backend should use if it is letting
+ * changelist handle its add and delete functions. */
+#define EVENT_CHANGELIST_FDINFO_SIZE sizeof(int)
+
+/** Set up the data fields in a changelist. */
+void event_changelist_init_(struct event_changelist *changelist);
+/** Remove every change in the changelist, and make corresponding changes
+ * in the event maps in the base. This function is generally used right
+ * after making all the changes in the changelist. */
+void event_changelist_remove_all_(struct event_changelist *changelist,
+ struct event_base *base);
+/** Free all memory held in a changelist. */
+void event_changelist_freemem_(struct event_changelist *changelist);
+
+/** Implementation of eventop_add that queues the event in a changelist. */
+int event_changelist_add_(struct event_base *base, evutil_socket_t fd, short old, short events,
+ void *p);
+/** Implementation of eventop_del that queues the event in a changelist. */
+int event_changelist_del_(struct event_base *base, evutil_socket_t fd, short old, short events,
+ void *p);
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/checkpatch.sh b/ipc/chromium/src/third_party/libevent/checkpatch.sh
new file mode 100755
index 0000000000..5393799dcd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/checkpatch.sh
@@ -0,0 +1,299 @@
+#!/usr/bin/env bash
+
+# TODO:
+# - inline replace
+# - clang-format-diff replacement
+# - uncrustify for patches (not git refs)
+# - maybe integrate into travis-ci?
+
+function usage()
+{
+ cat <<EOL
+$0 [ OPTS ] [ file-or-gitref [ ... ] ]
+
+Example:
+ # Chech HEAD git ref
+ $ $0 -r
+ $ $0 -r HEAD
+
+ # Check patch
+ $ git format-patch --stdout -1 | $0 -p
+ $ git show -1 | $0 -p
+
+ # Or via regular files
+ $ git format-patch --stdout -2
+ $ $0 *.patch
+
+ # Over a file
+ $ $0 -d event.c
+ $ $0 -d < event.c
+
+ # And print the whole file not only summary
+ $ $0 -f event.c
+ $ $0 -f < event.c
+
+OPTS:
+ -p - treat as patch
+ -f - treat as regular file
+ -d - treat as regular file and print diff
+ -r - treat as git revision (default)
+ -C - check using clang-format (default)
+ -U - check with uncrustify
+ -c - config for clang-format/uncrustify
+ -h - print this message
+EOL
+}
+function cfg()
+{
+ [ -z "${options[cfg]}" ] || {
+ echo "${options[cfg]}"
+ return
+ }
+
+ local dir="$(dirname "${BASH_SOURCE[0]}")"
+ [ "${options[clang]}" -eq 0 ] || {
+ echo "$dir/.clang-format"
+ return
+ }
+ [ "${options[uncrustify]}" -eq 0 ] || {
+ echo "$dir/.uncrustify"
+ return
+ }
+}
+function abort()
+{
+ local msg="$1"
+ shift
+
+ printf "$msg\n" "$@" >&2
+ exit 1
+}
+function default_arg()
+{
+ if [ "${options[ref]}" -eq 1 ]; then
+ echo "HEAD"
+ else
+ [ ! -t 0 ] || abort "<stdin> is a tty"
+ echo "/dev/stdin"
+ fi
+}
+function parse_options()
+{
+ options[patch]=0
+ options[file]=0
+ options[file_diff]=0
+ options[ref]=1
+ options[clang]=1
+ options[uncrustify]=0
+ options[cfg]=
+
+ local OPTARG OPTIND c
+ while getopts "pfrdCUc:h?" c; do
+ case "$c" in
+ p)
+ options[patch]=1
+ options[ref]=0
+ options[file]=0
+ options[file_diff]=0
+ ;;
+ f)
+ options[file]=1
+ options[ref]=0
+ options[patch]=0
+ options[file_diff]=0
+ ;;
+ r)
+ options[ref]=1
+ options[file]=0
+ options[patch]=0
+ options[file_diff]=0
+ ;;
+ d)
+ options[file_diff]=1
+ options[file]=0
+ options[patch]=0
+ options[ref]=0
+ ;;
+ C)
+ options[clang]=1
+ options[uncrustify]=0
+ ;;
+ U)
+ options[uncrustify]=1
+ options[clang]=0
+ ;;
+ c) options[cfg]="$OPTIND" ;;
+ ?|h)
+ usage
+ exit 0
+ ;;
+ *)
+ usage
+ exit 1
+ ;;
+ esac
+ done
+
+ options[cfg]="$(cfg)"
+
+ [ -f "${options[cfg]}" ] || \
+ abort "Config '%s' does not exist" "${options[cfg]}"
+
+ shift $((OPTIND - 1))
+ args=( "$@" )
+
+ if [ ${#args[@]} -eq 0 ]; then
+ # exit on error globally, not only in subshell
+ default_arg > /dev/null
+ args=( "$(default_arg)" )
+ fi
+
+ if [ "${args[0]}" = "/dev/stdin" ]; then
+ TMP_FILE="/tmp/libevent.checkpatch.$RANDOM"
+ cat > "$TMP_FILE"
+ trap "rm '$TMP_FILE'" EXIT
+
+ args[0]="$TMP_FILE"
+ fi
+}
+
+function diff() { command diff --color=always "$@"; }
+
+function clang_style()
+{
+ local c="${options[cfg]}"
+ echo "{ $(sed -e 's/#.*//' -e '/---/d' -e '/\.\.\./d' "$c" | tr $'\n' ,) }"
+}
+function clang_format() { clang-format -style="$(clang_style)" "$@"; }
+function clang_format_diff() { cat "$@" | clang-format-diff -p1 -style="$(clang_style)"; }
+# for non-bare repo will work
+function clang_format_git()
+{ git format-patch --stdout "$@" -1 | clang_format_diff; }
+
+function uncrustify() { command uncrustify -c "${options[cfg]}" "$@"; }
+function uncrustify_frag() { uncrustify -l C --frag "$@"; }
+function uncrustify_indent_off() { echo '/* *INDENT-OFF* */'; }
+function uncrustify_indent_on() { echo '/* *INDENT-ON* */'; }
+function git_hunk()
+{
+ local ref=$1 f=$2
+ shift 2
+ git cat-file -p $ref:$f
+}
+function uncrustify_git_indent_hunk()
+{
+ local start=$1 end=$2
+ shift 2
+
+ # Will be beatier with tee(1), but doh bash async substitution
+ { uncrustify_indent_off; git_hunk "$@" | head -n$((start - 1)); }
+ { uncrustify_indent_on; git_hunk "$@" | head -n$((end - 1)) | tail -n+$start; }
+ { uncrustify_indent_off; git_hunk "$@" | tail -n+$((end + 1)); }
+}
+function strip()
+{
+ local start=$1 end=$2
+ shift 2
+
+ # seek indent_{on,off}()
+ let start+=2
+ head -n$end | tail -n+$start
+}
+function patch_ranges()
+{
+ egrep -o '^@@ -[0-9]+(,[0-9]+|) \+[0-9]+(,[0-9]+|) @@' | \
+ cut -d' ' -f3
+}
+function git_ranges()
+{
+ local ref=$1 f=$2
+ shift 2
+
+ git diff -W $ref^..$ref -- $f | patch_ranges
+}
+function diff_substitute()
+{
+ local f="$1"
+ shift
+
+ sed \
+ -e "s#^--- /dev/fd.*\$#--- a/$f#" \
+ -e "s#^+++ /dev/fd.*\$#+++ b/$f#"
+}
+function uncrustify_git()
+{
+ local ref=$1 r f start end length
+ shift
+
+ local files=( $(git diff --name-only $ref^..$ref | egrep "\.(c|h)$") )
+ for f in "${files[@]}"; do
+ local ranges=( $(git_ranges $ref "$f") )
+ for r in "${ranges[@]}"; do
+ [[ ! "$r" =~ ^\+([0-9]+)(,([0-9]+)|)$ ]] && continue
+ start=${BASH_REMATCH[1]}
+ [ -n "${BASH_REMATCH[3]}" ] && \
+ length=${BASH_REMATCH[3]} || \
+ length=1
+ end=$((start + length))
+ echo "Range: $start:$end ($length)" >&2
+
+ diff -u \
+ <(uncrustify_git_indent_hunk $start $end $ref "$f" | strip $start $end) \
+ <(uncrustify_git_indent_hunk $start $end $ref "$f" | uncrustify_frag | strip $start $end) \
+ | diff_substitute "$f"
+ done
+ done
+}
+function uncrustify_diff() { abort "Not implemented"; }
+function uncrustify_file() { uncrustify -f "$@"; }
+
+function checker()
+{
+ local c=$1 u=$2
+ shift 2
+
+ [ "${options[clang]}" -eq 0 ] || {
+ $c "$@"
+ return
+ }
+ [ "${options[uncrustify]}" -eq 0 ] || {
+ $u "$@"
+ return
+ }
+}
+function check_patch() { checker clang_format_diff uncrustify_diff "$@"; }
+function check_file() { checker clang_format uncrustify_file "$@"; }
+function check_ref() { checker clang_format_git uncrustify_git "$@"; }
+
+function check_arg()
+{
+ [ "${options[patch]}" -eq 0 ] || {
+ check_patch "$@"
+ return
+ }
+ [ "${options[file]}" -eq 0 ] || {
+ check_file "$@"
+ return
+ }
+ [ "${options[file_diff]}" -eq 0 ] || {
+ diff -u "$@" <(check_file "$@") | diff_substitute "$@"
+ return
+ }
+ [ "${options[ref]}" -eq 0 ] || {
+ check_ref "$@"
+ return
+ }
+}
+
+function main()
+{
+ local a
+ for a in "${args}"; do
+ check_arg "$a"
+ done
+}
+
+declare -A options
+parse_options "$@"
+
+main "$@" | less -FRSX
diff --git a/ipc/chromium/src/third_party/libevent/cmake/AddCompilerFlags.cmake b/ipc/chromium/src/third_party/libevent/cmake/AddCompilerFlags.cmake
new file mode 100644
index 0000000000..9dc21d03ad
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/AddCompilerFlags.cmake
@@ -0,0 +1,13 @@
+include(CheckCCompilerFlag)
+
+macro(add_compiler_flags)
+ foreach(flag ${ARGN})
+ string(REGEX REPLACE "[-.+/:= ]" "_" _flag_esc "${flag}")
+
+ check_c_compiler_flag("${flag}" check_c_compiler_flag_${_flag_esc})
+
+ if (check_c_compiler_flag_${_flag_esc})
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}")
+ endif()
+ endforeach()
+endmacro()
diff --git a/ipc/chromium/src/third_party/libevent/cmake/AddEventLibrary.cmake b/ipc/chromium/src/third_party/libevent/cmake/AddEventLibrary.cmake
new file mode 100644
index 0000000000..04f5837e98
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/AddEventLibrary.cmake
@@ -0,0 +1,193 @@
+include(CMakeParseArguments)
+
+set(LIBEVENT_SHARED_LIBRARIES "")
+set(LIBEVENT_STATIC_LIBRARIES "")
+
+macro(set_event_shared_lib_flags LIB_NAME)
+ set_target_properties("${LIB_NAME}_shared" PROPERTIES
+ COMPILE_FLAGS ${ARGN})
+ set_target_properties("${LIB_NAME}_shared" PROPERTIES
+ LINK_FLAGS ${ARGN})
+endmacro()
+
+macro(generate_pkgconfig LIB_NAME)
+ set(prefix ${CMAKE_INSTALL_PREFIX})
+ set(exec_prefix ${CMAKE_INSTALL_PREFIX})
+ set(libdir ${CMAKE_INSTALL_PREFIX}/lib)
+ set(includedir ${CMAKE_INSTALL_PREFIX}/include)
+
+ set(VERSION ${EVENT_ABI_LIBVERSION})
+
+ set(LIBS "")
+ foreach (LIB ${LIB_PLATFORM})
+ set(LIBS "${LIBS} -L${LIB}")
+ endforeach()
+
+ set(OPENSSL_LIBS "")
+ foreach(LIB ${OPENSSL_LIBRARIES})
+ set(OPENSSL_LIBS "${OPENSSL_LIBS} -L${LIB}")
+ endforeach()
+
+ configure_file("lib${LIB_NAME}.pc.in" "lib${LIB_NAME}.pc" @ONLY)
+ install(
+ FILES "${CMAKE_CURRENT_BINARY_DIR}/lib${LIB_NAME}.pc"
+ DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig"
+ )
+endmacro()
+
+# LIB_NAME maybe event_core, event_extra, event_openssl, event_pthreads or event.
+# Targets whose LIB_NAME is not 'event' should be exported and installed.
+macro(export_install_target TYPE LIB_NAME OUTER_INCLUDES)
+ if("${LIB_NAME}" STREQUAL "event")
+ install(TARGETS "${LIB_NAME}_${TYPE}"
+ LIBRARY DESTINATION "lib" COMPONENT lib
+ ARCHIVE DESTINATION "lib" COMPONENT lib
+ RUNTIME DESTINATION "lib" COMPONENT lib
+ COMPONENT dev
+ )
+ else()
+ string(REPLACE "event_" "" PURE_NAME ${LIB_NAME})
+ string(TOUPPER ${TYPE} UPPER_TYPE)
+ list(APPEND LIBEVENT_${UPPER_TYPE}_LIBRARIES "${PURE_NAME}")
+ set(OUTER_INCS)
+ if (NOT "${OUTER_INCLUDES}" STREQUAL "NONE")
+ set(OUTER_INCS ${OUTER_INCLUDES})
+ endif()
+ target_include_directories("${LIB_NAME}_${TYPE}"
+ PUBLIC "$<INSTALL_INTERFACE:include>"
+ "$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>"
+ "$<BUILD_INTERFACE:${PROJECT_BINARY_DIR}/include>"
+ ${OUTER_INCS}
+ )
+ set_target_properties("${LIB_NAME}_${TYPE}" PROPERTIES EXPORT_NAME ${PURE_NAME})
+ export(TARGETS "${LIB_NAME}_${TYPE}"
+ NAMESPACE ${PROJECT_NAME}::
+ FILE "${PROJECT_BINARY_DIR}/LibeventTargets-${TYPE}.cmake"
+ APPEND
+ )
+ install(TARGETS "${LIB_NAME}_${TYPE}"
+ EXPORT LibeventTargets-${TYPE}
+ LIBRARY DESTINATION "lib" COMPONENT lib
+ ARCHIVE DESTINATION "lib" COMPONENT lib
+ RUNTIME DESTINATION "lib" COMPONENT lib
+ COMPONENT dev
+ )
+ endif()
+endmacro()
+
+# Global variables that it uses:
+# - EVENT_ABI_LIBVERSION
+# - EVENT_ABI_LIBVERSION_CURRENT
+# - EVENT_ABI_LIBVERSION_REVISION
+# - EVENT_ABI_LIBVERSION_AGE
+# - EVENT_PACKAGE_RELEASE
+# - CMAKE_THREAD_LIBS_INIT LIB_PLATFORM
+# - OPENSSL_LIBRARIES
+# - EVENT_SHARED_FLAGS
+# - EVENT_LIBRARY_STATIC
+# - EVENT_LIBRARY_SHARED
+#
+# Exported variables:
+# - LIBEVENT_SHARED_LIBRARIES
+# - LIBEVENT_STATIC_LIBRARIES
+macro(add_event_library LIB_NAME)
+ cmake_parse_arguments(LIB
+ "" # Options
+ "VERSION" # One val
+ "SOURCES;LIBRARIES;INNER_LIBRARIES;OUTER_INCLUDES" # Multi val
+ ${ARGN}
+ )
+
+ if ("${LIB_OUTER_INCLUDES}" STREQUAL "")
+ set(LIB_OUTER_INCLUDES NONE)
+ endif()
+ set(ADD_EVENT_LIBRARY_INTERFACE)
+
+ if (${EVENT_LIBRARY_STATIC})
+ add_library("${LIB_NAME}_static" STATIC ${LIB_SOURCES})
+ set_target_properties("${LIB_NAME}_static" PROPERTIES
+ OUTPUT_NAME "${LIB_NAME}"
+ CLEAN_DIRECT_OUTPUT 1)
+
+ if(LIB_INNER_LIBRARIES)
+ set(INNER_LIBRARIES "${LIB_INNER_LIBRARIES}_static")
+ endif()
+ target_link_libraries("${LIB_NAME}_static"
+ ${CMAKE_THREAD_LIBS_INIT}
+ ${LIB_PLATFORM}
+ ${INNER_LIBRARIES}
+ ${LIB_LIBRARIES})
+
+ export_install_target(static "${LIB_NAME}" "${LIB_OUTER_INCLUDES}")
+
+ set(ADD_EVENT_LIBRARY_INTERFACE "${LIB_NAME}_static")
+ endif()
+
+ if (${EVENT_LIBRARY_SHARED})
+ add_library("${LIB_NAME}_shared" SHARED ${LIB_SOURCES})
+
+ if(LIB_INNER_LIBRARIES)
+ set(INNER_LIBRARIES "${LIB_INNER_LIBRARIES}_shared")
+ endif()
+ target_link_libraries("${LIB_NAME}_shared"
+ ${CMAKE_THREAD_LIBS_INIT}
+ ${LIB_PLATFORM}
+ ${INNER_LIBRARIES}
+ ${LIB_LIBRARIES})
+
+ if (EVENT_SHARED_FLAGS)
+ set_event_shared_lib_flags("${LIB_NAME}" "${EVENT_SHARED_FLAGS}")
+ endif()
+
+ if (WIN32)
+ set_target_properties(
+ "${LIB_NAME}_shared" PROPERTIES
+ OUTPUT_NAME "${LIB_NAME}"
+ SOVERSION ${EVENT_ABI_LIBVERSION})
+ elseif (APPLE)
+ math(EXPR COMPATIBILITY_VERSION "${EVENT_ABI_LIBVERSION_CURRENT}+1")
+ math(EXPR CURRENT_MINUS_AGE "${EVENT_ABI_LIBVERSION_CURRENT}-${EVENT_ABI_LIBVERSION_AGE}")
+ set_target_properties(
+ "${LIB_NAME}_shared" PROPERTIES
+ OUTPUT_NAME "${LIB_NAME}-${EVENT_PACKAGE_RELEASE}.${CURRENT_MINUS_AGE}"
+ INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib"
+ LINK_FLAGS "-compatibility_version ${COMPATIBILITY_VERSION} -current_version ${COMPATIBILITY_VERSION}.${EVENT_ABI_LIBVERSION_REVISION}")
+ else()
+ math(EXPR CURRENT_MINUS_AGE "${EVENT_ABI_LIBVERSION_CURRENT}-${EVENT_ABI_LIBVERSION_AGE}")
+ set_target_properties(
+ "${LIB_NAME}_shared" PROPERTIES
+ OUTPUT_NAME "${LIB_NAME}-${EVENT_PACKAGE_RELEASE}"
+ VERSION "${CURRENT_MINUS_AGE}.${EVENT_ABI_LIBVERSION_AGE}.${EVENT_ABI_LIBVERSION_REVISION}"
+ SOVERSION "${CURRENT_MINUS_AGE}"
+ INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib")
+ endif()
+
+ if (NOT WIN32)
+ set(LIB_LINK_NAME
+ "${CMAKE_SHARED_LIBRARY_PREFIX}${LIB_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX}")
+
+ add_custom_command(TARGET ${LIB_NAME}_shared
+ POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E create_symlink
+ "$<TARGET_FILE_NAME:${LIB_NAME}_shared>"
+ "${LIB_LINK_NAME}"
+ WORKING_DIRECTORY "${CMAKE_LIBRARY_OUTPUT_DIRECTORY}")
+ endif()
+
+ export_install_target(shared "${LIB_NAME}" "${LIB_OUTER_INCLUDES}")
+
+ set(ADD_EVENT_LIBRARY_INTERFACE "${LIB_NAME}_shared")
+
+ if (NOT WIN32)
+ install(FILES
+ "$<TARGET_FILE_DIR:${LIB_NAME}_shared>/${LIB_LINK_NAME}"
+ DESTINATION "lib"
+ COMPONENT lib)
+ endif()
+ endif()
+
+ add_library(${LIB_NAME} INTERFACE)
+ target_link_libraries(${LIB_NAME} INTERFACE ${ADD_EVENT_LIBRARY_INTERFACE})
+
+ generate_pkgconfig("${LIB_NAME}")
+endmacro()
diff --git a/ipc/chromium/src/third_party/libevent/cmake/COPYING-CMAKE-SCRIPTS b/ipc/chromium/src/third_party/libevent/cmake/COPYING-CMAKE-SCRIPTS
new file mode 100644
index 0000000000..ab3c4d25d1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/COPYING-CMAKE-SCRIPTS
@@ -0,0 +1,22 @@
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the copyright
+ notice, this list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+3. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckConstExists.cmake b/ipc/chromium/src/third_party/libevent/cmake/CheckConstExists.cmake
new file mode 100644
index 0000000000..de074581df
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckConstExists.cmake
@@ -0,0 +1,25 @@
+include(CheckCSourceCompiles)
+
+macro(check_const_exists CONST FILES VARIABLE)
+ if (NOT DEFINED ${VARIABLE})
+ set(check_const_exists_source "")
+ foreach(file ${FILES})
+ set(check_const_exists_source
+ "${check_const_exists_source}
+ #include <${file}>")
+ endforeach()
+ set(check_const_exists_source
+ "${check_const_exists_source}
+ int main() { (void)${CONST}; return 0; }")
+
+ check_c_source_compiles("${check_const_exists_source}" ${VARIABLE})
+
+ if (${${VARIABLE}})
+ set(${VARIABLE} 1 CACHE INTERNAL "Have const ${CONST}")
+ message(STATUS "Looking for ${CONST} - found")
+ else()
+ set(${VARIABLE} 0 CACHE INTERNAL "Have const ${CONST}")
+ message(STATUS "Looking for ${CONST} - not found")
+ endif()
+ endif()
+endmacro(check_const_exists)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.c b/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.c
new file mode 100644
index 0000000000..d948fecf2b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.c
@@ -0,0 +1,14 @@
+#include <sys/types.h>
+
+#define KB ((off_t)1024)
+#define MB ((off_t)1024 * KB)
+#define GB ((off_t)1024 * MB)
+#define TB ((off_t)1024 * GB)
+int t2[(((64 * GB -1) % 671088649) == 268434537)
+ && (((TB - (64 * GB -1) + 255) % 1792151290) == 305159546)? 1: -1];
+
+int main()
+{
+ ;
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.cmake b/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.cmake
new file mode 100644
index 0000000000..1253440160
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckFileOffsetBits.cmake
@@ -0,0 +1,43 @@
+# - Check if _FILE_OFFSET_BITS macro needed for large files
+# CHECK_FILE_OFFSET_BITS ()
+#
+# The following variables may be set before calling this macro to
+# modify the way the check is run:
+#
+# CMAKE_REQUIRED_FLAGS = string of compile command line flags
+# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
+# CMAKE_REQUIRED_INCLUDES = list of include directories
+# Copyright (c) 2009, Michihiro NAKAJIMA
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+#INCLUDE(CheckCSourceCompiles)
+
+GET_FILENAME_COMPONENT(_selfdir_CheckFileOffsetBits
+ "${CMAKE_CURRENT_LIST_FILE}" PATH)
+
+MACRO (CHECK_FILE_OFFSET_BITS)
+ IF(NOT DEFINED _FILE_OFFSET_BITS)
+ MESSAGE(STATUS "Cheking _FILE_OFFSET_BITS for large files")
+ TRY_COMPILE(__WITHOUT_FILE_OFFSET_BITS_64
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${_selfdir_CheckFileOffsetBits}/CheckFileOffsetBits.c
+ COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS})
+ IF(NOT __WITHOUT_FILE_OFFSET_BITS_64)
+ TRY_COMPILE(__WITH_FILE_OFFSET_BITS_64
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${_selfdir_CheckFileOffsetBits}/CheckFileOffsetBits.c
+ COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS} -D_FILE_OFFSET_BITS=64)
+ ENDIF(NOT __WITHOUT_FILE_OFFSET_BITS_64)
+
+ IF(NOT __WITHOUT_FILE_OFFSET_BITS_64 AND __WITH_FILE_OFFSET_BITS_64)
+ SET(_FILE_OFFSET_BITS 64 CACHE INTERNAL "_FILE_OFFSET_BITS macro needed for large files")
+ MESSAGE(STATUS "Cheking _FILE_OFFSET_BITS for large files - needed")
+ ELSE(NOT __WITHOUT_FILE_OFFSET_BITS_64 AND __WITH_FILE_OFFSET_BITS_64)
+ SET(_FILE_OFFSET_BITS "" CACHE INTERNAL "_FILE_OFFSET_BITS macro needed for large files")
+ MESSAGE(STATUS "Cheking _FILE_OFFSET_BITS for large files - not needed")
+ ENDIF(NOT __WITHOUT_FILE_OFFSET_BITS_64 AND __WITH_FILE_OFFSET_BITS_64)
+ ENDIF(NOT DEFINED _FILE_OFFSET_BITS)
+
+ENDMACRO (CHECK_FILE_OFFSET_BITS)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckFunctionKeywords.cmake b/ipc/chromium/src/third_party/libevent/cmake/CheckFunctionKeywords.cmake
new file mode 100644
index 0000000000..3d968b8a6b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckFunctionKeywords.cmake
@@ -0,0 +1,14 @@
+include(CheckCSourceCompiles)
+
+macro(check_function_keywords _wordlist)
+ set(${_result} "")
+ foreach(flag ${_wordlist})
+ string(REGEX REPLACE "[-+/ ()]" "_" flagname "${flag}")
+ string(TOUPPER "${flagname}" flagname)
+ set(have_flag "HAVE_${flagname}")
+ check_c_source_compiles("${flag} void func(); void func() { } int main() { func(); return 0; }" ${have_flag})
+ if(${have_flag} AND NOT ${_result})
+ set(${_result} "${flag}")
+ endif(${have_flag} AND NOT ${_result})
+ endforeach(flag)
+endmacro(check_function_keywords)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.c.in b/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.c.in
new file mode 100644
index 0000000000..a97344ac3e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.c.in
@@ -0,0 +1,29 @@
+@CHECK_PROTOTYPE_DEFINITION_HEADER@
+
+static void cmakeRequireSymbol(int dummy, ...) {
+ (void) dummy;
+}
+
+static void checkSymbol(void) {
+#ifndef @CHECK_PROTOTYPE_DEFINITION_SYMBOL@
+ cmakeRequireSymbol(0, &@CHECK_PROTOTYPE_DEFINITION_SYMBOL@);
+#endif
+}
+
+@CHECK_PROTOTYPE_DEFINITION_PROTO@ {
+ return @CHECK_PROTOTYPE_DEFINITION_RETURN@;
+}
+
+#ifdef __CLASSIC_C__
+int main() {
+ int ac;
+ char*av[];
+#else
+int main(int ac, char *av[]) {
+#endif
+ checkSymbol();
+ if (ac > 1000) {
+ return *av[0];
+ }
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.cmake b/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.cmake
new file mode 100644
index 0000000000..940d1ff0ce
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckPrototypeDefinition.cmake
@@ -0,0 +1,82 @@
+# - Check if the protoype we expect is correct.
+# check_prototype_definition(FUNCTION PROTOTYPE RETURN HEADER VARIABLE)
+#
+# FUNCTION - The name of the function (used to check if prototype exists)
+# PROTOTYPE- The prototype to check.
+# RETURN - The return value of the function.
+# HEADER - The header files required.
+# VARIABLE - The variable to store the result.
+#
+# Example:
+#
+# check_prototype_definition(getpwent_r
+# "struct passwd *getpwent_r(struct passwd *src, char *buf, int buflen)"
+# "NULL"
+# "unistd.h;pwd.h"
+# SOLARIS_GETPWENT_R)
+#
+# The following variables may be set before calling this macro to
+# modify the way the check is run:
+#
+# CMAKE_REQUIRED_FLAGS = string of compile command line flags
+# CMAKE_REQUIRED_DEFINITIONS = list of macros to define (-DFOO=bar)
+# CMAKE_REQUIRED_INCLUDES = list of include directories
+# CMAKE_REQUIRED_LIBRARIES = list of libraries to link
+
+
+function(CHECK_PROTOTYPE_DEFINITION _FUNCTION _PROTOTYPE _RETURN _HEADER _VARIABLE)
+ if (${_VARIABLE} MATCHES "^${_VARIABLE}$")
+ set(CHECK_PROTOTYPE_DEFINITION_CONTENT "/* */\n")
+
+ set(CHECK_PROTOTYPE_DEFINITION_FLAGS ${CMAKE_REQUIRED_FLAGS})
+ if (CMAKE_REQUIRED_LIBRARIES)
+ set(CHECK_PROTOTYPE_DEFINITION_LIBS
+ "-DLINK_LIBRARIES:STRING=${CMAKE_REQUIRED_LIBRARIES}")
+ else(CMAKE_REQUIRED_LIBRARIES)
+ set(CHECK_PROTOTYPE_DEFINITION_LIBS)
+ endif(CMAKE_REQUIRED_LIBRARIES)
+ if (CMAKE_REQUIRED_INCLUDES)
+ set(CMAKE_SYMBOL_EXISTS_INCLUDES
+ "-DINCLUDE_DIRECTORIES:STRING=${CMAKE_REQUIRED_INCLUDES}")
+ else(CMAKE_REQUIRED_INCLUDES)
+ set(CMAKE_SYMBOL_EXISTS_INCLUDES)
+ endif(CMAKE_REQUIRED_INCLUDES)
+
+ foreach(_FILE ${_HEADER})
+ set(CHECK_PROTOTYPE_DEFINITION_HEADER
+ "${CHECK_PROTOTYPE_DEFINITION_HEADER}#include <${_FILE}>\n")
+ endforeach(_FILE)
+
+ set(CHECK_PROTOTYPE_DEFINITION_SYMBOL ${_FUNCTION})
+ set(CHECK_PROTOTYPE_DEFINITION_PROTO ${_PROTOTYPE})
+ set(CHECK_PROTOTYPE_DEFINITION_RETURN ${_RETURN})
+
+ configure_file("${PROJECT_SOURCE_DIR}/cmake/CheckPrototypeDefinition.c.in"
+ "${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckPrototypeDefinition.c" @ONLY)
+
+ file(READ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckPrototypeDefinition.c _SOURCE)
+
+ try_compile(${_VARIABLE}
+ ${CMAKE_BINARY_DIR}
+ ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/CheckPrototypeDefinition.c
+ COMPILE_DEFINITIONS ${CMAKE_REQUIRED_DEFINITIONS}
+ CMAKE_FLAGS -DCOMPILE_DEFINITIONS:STRING=${CHECK_PROTOTYPE_DEFINITION_FLAGS}
+ "${CHECK_PROTOTYPE_DEFINITION_LIBS}"
+ "${CMAKE_SYMBOL_EXISTS_INCLUDES}"
+ OUTPUT_VARIABLE OUTPUT)
+
+ if (${_VARIABLE})
+ set(${_VARIABLE} 1 CACHE INTERNAL "Have correct prototype for ${_FUNCTION}")
+ message(STATUS "Checking prototype ${_FUNCTION} for ${_VARIABLE} - True")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
+ "Determining if the prototype ${_FUNCTION} exists for ${_VARIABLE} passed with the following output:\n"
+ "${OUTPUT}\n\n")
+ else (${_VARIABLE})
+ message(STATUS "Checking prototype ${_FUNCTION} for ${_VARIABLE} - False")
+ set(${_VARIABLE} 0 CACHE INTERNAL "Have correct prototype for ${_FUNCTION}")
+ file(APPEND ${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
+ "Determining if the prototype ${_FUNCTION} exists for ${_VARIABLE} failed with the following output:\n"
+ "${OUTPUT}\n\n${_SOURCE}\n\n")
+ endif (${_VARIABLE})
+ endif()
+endfunction(CHECK_PROTOTYPE_DEFINITION)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CheckWorkingKqueue.cmake b/ipc/chromium/src/third_party/libevent/cmake/CheckWorkingKqueue.cmake
new file mode 100644
index 0000000000..f22f011b58
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CheckWorkingKqueue.cmake
@@ -0,0 +1,52 @@
+include(CheckCSourceRuns)
+
+check_c_source_runs(
+"
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/event.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+
+int
+main(int argc, char **argv)
+{
+ int kq;
+ int n;
+ int fd[2];
+ struct kevent ev;
+ struct timespec ts;
+ char buf[80000];
+
+ if (pipe(fd) == -1)
+ exit(1);
+ if (fcntl(fd[1], F_SETFL, O_NONBLOCK) == -1)
+ exit(1);
+
+ while ((n = write(fd[1], buf, sizeof(buf))) == sizeof(buf))
+ ;
+
+ if ((kq = kqueue()) == -1)
+ exit(1);
+
+ memset(&ev, 0, sizeof(ev));
+ ev.ident = fd[1];
+ ev.filter = EVFILT_WRITE;
+ ev.flags = EV_ADD | EV_ENABLE;
+ n = kevent(kq, &ev, 1, NULL, 0, NULL);
+ if (n == -1)
+ exit(1);
+
+ read(fd[0], buf, sizeof(buf));
+
+ ts.tv_sec = 0;
+ ts.tv_nsec = 0;
+ n = kevent(kq, NULL, 0, &ev, 1, &ts);
+ if (n == -1 || n == 0)
+ exit(1);
+
+ exit(0);
+}
+
+" EVENT__HAVE_WORKING_KQUEUE)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/CodeCoverage.cmake b/ipc/chromium/src/third_party/libevent/cmake/CodeCoverage.cmake
new file mode 100644
index 0000000000..eba85b3fb7
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/CodeCoverage.cmake
@@ -0,0 +1,165 @@
+#
+# Boost Software License - Version 1.0 - August 17th, 2003
+#
+# Permission is hereby granted, free of charge, to any person or organization
+# obtaining a copy of the software and accompanying documentation covered by
+# this license (the "Software") to use, reproduce, display, distribute,
+# execute, and transmit the Software, and to prepare derivative works of the
+# Software, and to permit third-parties to whom the Software is furnished to
+# do so, all subject to the following:
+#
+# The copyright notices in the Software and this entire statement, including
+# the above license grant, this restriction and the following disclaimer,
+# must be included in all copies of the Software, in whole or in part, and
+# all derivative works of the Software, unless such copies or derivative
+# works are solely in the form of machine-executable object code generated by
+# a source language processor.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+# SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+# FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+# DEALINGS IN THE SOFTWARE.
+#
+# 2012-01-31, Lars Bilke
+# - Enable Code Coverage
+#
+# 2013-09-17, Joakim Söderberg
+# - Added support for Clang.
+# - Some additional usage instructions.
+#
+# 2016-11-02, Azat Khuzhin
+# - Adopt for C compiler only (libevent)
+#
+# USAGE:
+# 1. Copy this file into your cmake modules path.
+#
+# 2. Add the following line to your CMakeLists.txt:
+# INCLUDE(CodeCoverage)
+#
+# 3. Set compiler flags to turn off optimization and enable coverage:
+# SET(CMAKE_CXX_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
+# SET(CMAKE_C_FLAGS "-g -O0 -fprofile-arcs -ftest-coverage")
+#
+# 3. Use the function SETUP_TARGET_FOR_COVERAGE to create a custom make target
+# which runs your test executable and produces a lcov code coverage report:
+# Example:
+# SETUP_TARGET_FOR_COVERAGE(
+# my_coverage_target # Name for custom target.
+# test_driver # Name of the test driver executable that runs the tests.
+# # NOTE! This should always have a ZERO as exit code
+# # otherwise the coverage generation will not complete.
+# coverage # Name of output directory.
+# )
+#
+# 4. Build a Debug build:
+# cmake -DCMAKE_BUILD_TYPE=Debug ..
+# make
+# make my_coverage_target
+#
+#
+
+# Check prereqs
+FIND_PROGRAM( GCOV_PATH gcov )
+FIND_PROGRAM( LCOV_PATH lcov )
+FIND_PROGRAM( GENHTML_PATH genhtml )
+FIND_PROGRAM( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/tests)
+
+IF(NOT GCOV_PATH)
+ MESSAGE(FATAL_ERROR "gcov not found! Aborting...")
+ENDIF() # NOT GCOV_PATH
+
+IF(NOT CMAKE_COMPILER_IS_GNUCC)
+ # Clang version 3.0.0 and greater now supports gcov as well.
+ MESSAGE(WARNING "Compiler is not GNU gcc! Clang Version 3.0.0 and greater supports gcov as well, but older versions don't.")
+
+ IF(NOT "${CMAKE_C_COMPILER_ID}" STREQUAL "Clang")
+ MESSAGE(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
+ ENDIF()
+ENDIF() # NOT CMAKE_COMPILER_IS_GNUCC
+
+IF ( NOT CMAKE_BUILD_TYPE STREQUAL "Debug" )
+ MESSAGE( WARNING "Code coverage results with an optimized (non-Debug) build may be misleading" )
+ENDIF() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"
+
+
+# Param _targetname The name of new the custom make target
+# Param _testrunner The name of the target which runs the tests.
+# MUST return ZERO always, even on errors.
+# If not, no coverage report will be created!
+# Param _outputname lcov output is generated as _outputname.info
+# HTML report is generated in _outputname/index.html
+# Optional fourth parameter is passed as arguments to _testrunner
+# Pass them in list form, e.g.: "-j;2" for -j 2
+FUNCTION(SETUP_TARGET_FOR_COVERAGE _targetname _testrunner _outputname)
+
+ IF(NOT LCOV_PATH)
+ MESSAGE(FATAL_ERROR "lcov not found! Aborting...")
+ ENDIF() # NOT LCOV_PATH
+
+ IF(NOT GENHTML_PATH)
+ MESSAGE(FATAL_ERROR "genhtml not found! Aborting...")
+ ENDIF() # NOT GENHTML_PATH
+
+ # Setup target
+ ADD_CUSTOM_TARGET(${_targetname}
+
+ # Cleanup lcov
+ ${LCOV_PATH} --directory . --zerocounters
+
+ # Run tests
+ COMMAND ${_testrunner} ${ARGV3}
+
+ # Capturing lcov counters and generating report
+ COMMAND ${LCOV_PATH} --directory . --capture --output-file ${_outputname}.info
+ COMMAND ${LCOV_PATH} --remove ${_outputname}.info 'tests/*' '/usr/*' --output-file ${_outputname}.info.cleaned
+ COMMAND ${GENHTML_PATH} -o ${_outputname} ${_outputname}.info.cleaned
+ COMMAND ${CMAKE_COMMAND} -E remove ${_outputname}.info ${_outputname}.info.cleaned
+
+ WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+ COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
+ )
+
+ # Show info where to find the report
+ ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
+ COMMAND ;
+ COMMENT "Open ./${_outputname}/index.html in your browser to view the coverage report."
+ )
+
+ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE
+
+# Param _targetname The name of new the custom make target
+# Param _testrunner The name of the target which runs the tests
+# Param _outputname cobertura output is generated as _outputname.xml
+# Optional fourth parameter is passed as arguments to _testrunner
+# Pass them in list form, e.g.: "-j;2" for -j 2
+FUNCTION(SETUP_TARGET_FOR_COVERAGE_COBERTURA _targetname _testrunner _outputname)
+
+ IF(NOT PYTHON_EXECUTABLE)
+ MESSAGE(FATAL_ERROR "Python not found! Aborting...")
+ ENDIF() # NOT PYTHON_EXECUTABLE
+
+ IF(NOT GCOVR_PATH)
+ MESSAGE(FATAL_ERROR "gcovr not found! Aborting...")
+ ENDIF() # NOT GCOVR_PATH
+
+ ADD_CUSTOM_TARGET(${_targetname}
+
+ # Run tests
+ ${_testrunner} ${ARGV3}
+
+ # Running gcovr
+ COMMAND ${GCOVR_PATH} -x -r ${CMAKE_SOURCE_DIR} -e '${CMAKE_SOURCE_DIR}/tests/' -o ${_outputname}.xml
+ WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+ COMMENT "Running gcovr to produce Cobertura code coverage report."
+ )
+
+ # Show info where to find the report
+ ADD_CUSTOM_COMMAND(TARGET ${_targetname} POST_BUILD
+ COMMAND ;
+ COMMENT "Cobertura code coverage report saved in ${_outputname}.xml."
+ )
+
+ENDFUNCTION() # SETUP_TARGET_FOR_COVERAGE_COBERTURA
diff --git a/ipc/chromium/src/third_party/libevent/cmake/Copyright.txt b/ipc/chromium/src/third_party/libevent/cmake/Copyright.txt
new file mode 100644
index 0000000000..813124f02e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/Copyright.txt
@@ -0,0 +1,57 @@
+CMake - Cross Platform Makefile Generator
+Copyright 2000-2013 Kitware, Inc.
+Copyright 2000-2011 Insight Software Consortium
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+* Neither the names of Kitware, Inc., the Insight Software Consortium,
+ nor the names of their contributors may be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+------------------------------------------------------------------------------
+
+The above copyright and license notice applies to distributions of
+CMake in source and binary form. Some source files contain additional
+notices of original copyright by their contributors; see each source
+for details. Third-party software packages supplied with CMake under
+compatible licenses provide their own copyright notices documented in
+corresponding subdirectories.
+
+------------------------------------------------------------------------------
+
+CMake was initially developed by Kitware with the following sponsorship:
+
+ * National Library of Medicine at the National Institutes of Health
+ as part of the Insight Segmentation and Registration Toolkit (ITK).
+
+ * US National Labs (Los Alamos, Livermore, Sandia) ASC Parallel
+ Visualization Initiative.
+
+ * National Alliance for Medical Image Computing (NAMIC) is funded by the
+ National Institutes of Health through the NIH Roadmap for Medical Research,
+ Grant U54 EB005149.
+
+ * Kitware, Inc. \ No newline at end of file
diff --git a/ipc/chromium/src/third_party/libevent/cmake/LibeventConfig.cmake.in b/ipc/chromium/src/third_party/libevent/cmake/LibeventConfig.cmake.in
new file mode 100644
index 0000000000..7b808c3245
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/LibeventConfig.cmake.in
@@ -0,0 +1,183 @@
+# - Config file for the Libevent package
+# It defines the following variables
+# LIBEVENT_FOUND - true if libevent and all required components found on the system
+# LIBEVENT_xxx_FOUND - true if component xxx(see available components) found on the system
+# LIBEVENT_VERSION - libevent version in format Major.Minor.Patch
+# LIBEVENT_INCLUDE_DIRS - directories where libevent header is located.
+# LIBEVENT_INCLUDE_DIR - same as DIRS
+# LIBEVENT_LIBRARIES - libevent library to link against.
+# LIBEVENT_LIBRARY - same as LIBRARIES
+#
+# These variables are deprecated, don't use them.
+# LIBEVENT_STATIC_LIBRARIES - libraries to link against (archive/static)
+# LIBEVENT_SHARED_LIBRARIES - libraries to link against (shared)
+#
+# When you try to locate the libevent libraries, you should specify which components you want to use.
+# The following table lists all available components. If none is given, all imported targets will used.
+# core - the core functons of libevent
+# extra - extra functions, contains http, dns and rpc
+# pthreads - multiple threads for libevent, not exists on Windows
+# openssl - openssl support for libevent
+#
+# By default, the shared libraries of libevent will be found. To find the static ones instead,
+# you must set the LIBEVENT_STATIC_LINK variable to TRUE before calling find_package(Libevent ...).
+# If no component provided, all components will be used.
+# example:
+# set(LIBEVENT_STATIC_LINK TRUE)
+# find_package(Libevent 2.2 REQUIRED COMPONENTS core)
+# include_directories(${LIBEVENT_INCLUDE_DIRS}) # Can be omitted
+# target_link_libraries(myapp ${LIBEVENT_LIBRARIES})
+# or target_link_libraries(myapp libevent::core)
+#
+# find_package() can handle dependencies automatically. For example, given the 'openssl' component,
+# all dependencies (libevent_core, libssl, libcrypto and openssl include directories) will be found.
+
+set(CONFIG_FOR_INSTALL_TREE @CONFIG_FOR_INSTALL_TREE@)
+
+set(LIBEVENT_VERSION @EVENT_PACKAGE_VERSION@)
+
+# IMPORTED targets from LibeventTargets.cmake
+set(LIBEVENT_STATIC_LIBRARIES "@LIBEVENT_STATIC_LIBRARIES@")
+set(LIBEVENT_SHARED_LIBRARIES "@LIBEVENT_SHARED_LIBRARIES@")
+
+# Default to the same type as libevent was built:
+if(NOT DEFINED LIBEVENT_STATIC_LINK)
+ set(LIBEVENT_STATIC_LINK NOT @EVENT_LIBRARY_SHARED@)
+endif()
+
+set(CMAKE_FIND_LIBRARY_SUFFIXES_SAVE "${CMAKE_FIND_LIBRARY_SUFFIXES}")
+if(${LIBEVENT_STATIC_LINK})
+ set(_LIB_TYPE static)
+ set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX})
+ set(_AVAILABLE_LIBS "${LIBEVENT_STATIC_LIBRARIES}")
+else()
+ set(_LIB_TYPE shared)
+ set(CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX})
+ set(_AVAILABLE_LIBS "${LIBEVENT_SHARED_LIBRARIES}")
+endif()
+
+# Get the path of the current file.
+get_filename_component(LIBEVENT_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
+get_filename_component(_INSTALL_PREFIX "${LIBEVENT_CMAKE_DIR}/../../.." ABSOLUTE)
+
+macro(message_if_needed _flag _msg)
+ if (NOT ${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY)
+ message(${_flag} "${_msg}")
+ endif()
+endmacro()
+
+macro(no_component_msg _comp)
+ if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED_${_comp})
+ set(pthreadlib)
+ if(NOT WIN32)
+ set(pthreadlib ", pthreads")
+ endif()
+ message(FATAL_ERROR "Your libevent library does not contain a ${_comp} component!\n"
+ "The valid components are core, extra${pthreadlib} and openssl.")
+ else()
+ message_if_needed(WARNING "Your libevent library does not contain a ${_comp} component!")
+ endif()
+endmacro()
+
+set(_EVENT_COMPONENTS)
+if(${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
+ list(REMOVE_DUPLICATES ${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS)
+ foreach(_comp ${${CMAKE_FIND_PACKAGE_NAME}_FIND_COMPONENTS})
+ list(FIND _AVAILABLE_LIBS ${_comp} _INDEX)
+ if(_INDEX GREATER -1)
+ list(APPEND _EVENT_COMPONENTS ${_comp})
+ else()
+ no_component_msg(${_comp})
+ endif()
+ endforeach()
+else()
+ set(_EVENT_COMPONENTS ${_AVAILABLE_LIBS})
+endif()
+
+set(_POSSIBLE_PKG_NAMES)
+list(APPEND _POSSIBLE_PKG_NAMES ${CMAKE_FIND_PACKAGE_NAME} LIBEVENT Libevent libevent)
+list(REMOVE_DUPLICATES _POSSIBLE_PKG_NAMES)
+
+macro(set_case_insensitive_found _comp)
+ foreach(name ${_POSSIBLE_PKG_NAMES})
+ if("${_comp}" STREQUAL "")
+ set(${name}_FOUND TRUE)
+ set(${name}_NOTFOUND FALSE)
+ else()
+ set(${name}_${_comp}_FOUND TRUE)
+ set(${name}_${_comp}_NOTFOUND FALSE)
+ endif()
+ endforeach()
+endmacro()
+
+if(CONFIG_FOR_INSTALL_TREE)
+ ## Config for install tree ----------------------------------------
+ # Find includes
+ unset(_event_h CACHE)
+ find_path(_event_h
+ NAMES event2/event.h
+ PATHS "${_INSTALL_PREFIX}/include"
+ NO_DEFAULT_PATH)
+ if(_event_h)
+ set(LIBEVENT_INCLUDE_DIRS "${_event_h}")
+ message_if_needed(STATUS "Found libevent include directory: ${_event_h}")
+ else()
+ message_if_needed(WARNING "Your libevent library does not contain header files!")
+ endif()
+
+ # Find libraries
+ macro(find_event_lib _comp)
+ unset(_event_lib CACHE)
+ find_library(_event_lib
+ NAMES "event_${_comp}"
+ PATHS "${_INSTALL_PREFIX}/lib"
+ NO_DEFAULT_PATH)
+ if(_event_lib)
+ list(APPEND LIBEVENT_LIBRARIES "libevent::${_comp}")
+ set_case_insensitive_found(${_comp})
+ message_if_needed(STATUS "Found libevent component: ${_event_lib}")
+ else()
+ no_component_msg(${_comp})
+ endif()
+ endmacro()
+
+ foreach(comp ${_EVENT_COMPONENTS})
+ find_event_lib(${comp})
+ endforeach()
+else()
+ ## Config for build tree ----------------------------------------
+ set(LIBEVENT_INCLUDE_DIRS "@EVENT__INCLUDE_DIRS@")
+ foreach(_comp ${_EVENT_COMPONENTS})
+ list(APPEND LIBEVENT_LIBRARIES "libevent::${_comp}")
+ set_case_insensitive_found(${_comp})
+ endforeach()
+endif()
+
+set(LIBEVENT_INCLUDE_DIR ${LIBEVENT_INCLUDE_DIRS})
+if(LIBEVENT_LIBRARIES)
+ set(LIBEVENT_LIBRARY ${LIBEVENT_LIBRARIES})
+ if(CONFIG_FOR_INSTALL_TREE)
+ message_if_needed(STATUS "Found libevent ${LIBEVENT_VERSION} in ${_INSTALL_PREFIX}")
+ else()
+ message_if_needed(STATUS "Found libevent ${LIBEVENT_VERSION} in ${LIBEVENT_CMAKE_DIR}")
+ endif()
+
+ # Avoid including targets more than one times
+ if(NOT TARGET event_core_${_LIB_TYPE})
+ # Include the project Targets file, this contains definitions for IMPORTED targets.
+ include(${LIBEVENT_CMAKE_DIR}/LibeventTargets-${_LIB_TYPE}.cmake)
+ endif()
+else()
+ if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED)
+ message(FATAL_ERROR "Can not find any libraries for libevent.")
+ else()
+ message_if_needed(WARNING "Can not find any libraries for libevent.")
+ endif()
+endif()
+
+set(CMAKE_FIND_LIBRARY_SUFFIXES "${CMAKE_FIND_LIBRARY_SUFFIXES_SAVE}")
+unset(_LIB_TYPE)
+unset(_AVAILABLE_LIBS)
+unset(_EVENT_COMPONENTS)
+unset(_POSSIBLE_PKG_NAMES)
+unset(_INSTALL_PREFIX)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/LibeventConfigVersion.cmake.in b/ipc/chromium/src/third_party/libevent/cmake/LibeventConfigVersion.cmake.in
new file mode 100644
index 0000000000..56371a8fee
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/LibeventConfigVersion.cmake.in
@@ -0,0 +1,11 @@
+set(PACKAGE_VERSION "@EVENT_PACKAGE_VERSION@")
+
+# Check whether the requested PACKAGE_FIND_VERSION is compatible
+if("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}")
+ set(PACKAGE_VERSION_COMPATIBLE FALSE)
+else()
+ set(PACKAGE_VERSION_COMPATIBLE TRUE)
+ if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}")
+ set(PACKAGE_VERSION_EXACT TRUE)
+ endif()
+endif()
diff --git a/ipc/chromium/src/third_party/libevent/cmake/Macros.cmake b/ipc/chromium/src/third_party/libevent/cmake/Macros.cmake
new file mode 100644
index 0000000000..e480bbfdca
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/Macros.cmake
@@ -0,0 +1,36 @@
+include(CheckSymbolExists)
+include(CheckIncludeFiles)
+
+# Check if each symbol in the symbol list exists,
+# and define PREFIX__HAVE_SYMNAME to 1 if yes.
+#
+# SYMLIST: list of symbols to check
+# HEADERS: header files to be included in check code
+# PREFIX: the prefix of definition
+macro(CHECK_SYMBOLS_EXIST SYMLIST HEADERS PREFIX)
+ foreach(SYMNAME ${SYMLIST})
+ string(TOUPPER "${SYMNAME}" SYMNAME_UPPER)
+ if ("${PREFIX}" STREQUAL "")
+ set(HAVE_SYM_DEF "HAVE_${SYMNAME_UPPER}")
+ else()
+ set(HAVE_SYM_DEF "${PREFIX}__HAVE_${SYMNAME_UPPER}")
+ endif()
+ CHECK_SYMBOL_EXISTS(${SYMNAME} "${HEADERS}" ${HAVE_SYM_DEF})
+ endforeach()
+endmacro()
+
+# Check if file exists, define PREFIX__HAVE_FILE to 1 if yes,
+# and collect file to EVENT_INCLUDES
+macro(CHECK_INCLUDE_FILE_CONCAT FILE PREFIX)
+ string(REGEX REPLACE "[./]" "_" FILE_UL ${FILE})
+ string(TOUPPER "${FILE_UL}" FILE_UL_UPPER)
+ if ("${PREFIX}" STREQUAL "")
+ set(HAVE_FILE_DEF "HAVE_${FILE_UL_UPPER}")
+ else()
+ set(HAVE_FILE_DEF "${PREFIX}__HAVE_${FILE_UL_UPPER}")
+ endif()
+ CHECK_INCLUDE_FILES("${EVENT_INCLUDES};${FILE}" ${HAVE_FILE_DEF})
+ if(${HAVE_FILE_DEF})
+ set(EVENT_INCLUDES ${EVENT_INCLUDES} ${FILE})
+ endif()
+endmacro()
diff --git a/ipc/chromium/src/third_party/libevent/cmake/Uninstall.cmake.in b/ipc/chromium/src/third_party/libevent/cmake/Uninstall.cmake.in
new file mode 100644
index 0000000000..c6dc09efe1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/Uninstall.cmake.in
@@ -0,0 +1,23 @@
+# https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake
+
+if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
+ message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt")
+endif(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
+
+file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files)
+string(REGEX REPLACE "\n" ";" files "${files}")
+foreach(file ${files})
+ message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
+ if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+ exec_program(
+ "@CMAKE_COMMAND@" ARGS "-E remove \"$ENV{DESTDIR}${file}\""
+ OUTPUT_VARIABLE rm_out
+ RETURN_VALUE rm_retval
+ )
+ if(NOT "${rm_retval}" STREQUAL 0)
+ message(FATAL_ERROR "Problem when removing $ENV{DESTDIR}${file}")
+ endif(NOT "${rm_retval}" STREQUAL 0)
+ else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+ message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
+ endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
+endforeach(file)
diff --git a/ipc/chromium/src/third_party/libevent/cmake/UseDoxygen.cmake b/ipc/chromium/src/third_party/libevent/cmake/UseDoxygen.cmake
new file mode 100644
index 0000000000..3b60d5a0f5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/UseDoxygen.cmake
@@ -0,0 +1,111 @@
+# Use FindDoxygen.cmake to generate documentation.
+
+option(DOXYGEN_GENERATE_HTML "Generate HTML" ON)
+option(DOXYGEN_GENERATE_MAN "Generate man pages" OFF)
+option(DOXYGEN_MAN_LINKS "Generate man links" ON)
+option(DOXYGEN_GENERATE_LATEX "Generate LaTeX" OFF)
+
+# If the case-insensitive value of the cmake option is one of
+# "off, no, false" or 0, it is equal to false, otherwise true.
+# And the values of the doxygen config does not exactly match it.
+# So we need to convert the cmake option to a doxygen config.
+macro(_convert_to_dx_cfg CMK_OPTION)
+ if (${CMK_OPTION})
+ set(${CMK_OPTION} YES)
+ else()
+ set(${CMK_OPTION} NO)
+ endif()
+endmacro()
+
+macro(UseDoxygen)
+ if (${CMAKE_VERSION} VERSION_LESS "3.9")
+ # Old versions of cmake have poor support for Doxygen generation.
+ message(FATAL_ERROR "Doxygen generation only enabled for cmake 3.9 and higher")
+ else()
+ find_package(Doxygen)
+ if (DOXYGEN_FOUND)
+ set(DOXYGEN_PROJECT_NAME ${PROJECT_NAME})
+ set(DOXYGEN_PROJECT_NUMBER ${EVENT_PACKAGE_VERSION})
+ set(DOXYGEN_PROJECT_BRIEF "Event notification library")
+ set(DOXYGEN_OUTPUT_DIRECTORY doxygen)
+ set(DOXYGEN_STRIP_FROM_PATH include)
+ set(DOXYGEN_JAVADOC_AUTOBRIEF YES)
+ set(DOXYGEN_OPTIMIZE_OUTPUT_FOR_C YES)
+ set(DOXYGEN_SORT_BRIEF_DOCS YES)
+ set(DOXYGEN_RECURSIVE NO)
+
+ _convert_to_dx_cfg(DOXYGEN_GENERATE_HTML)
+ _convert_to_dx_cfg(DOXYGEN_GENERATE_MAN)
+ _convert_to_dx_cfg(DOXYGEN_MAN_LINKS)
+ _convert_to_dx_cfg(DOXYGEN_GENERATE_LATEX)
+
+ set(DOXYGEN_LATEX_CMD_NAME latex)
+ set(DOXYGEN_PAPER_TYPE a4wide)
+ set(DOXYGEN_PDF_HYPERLINKS NO)
+
+ set(DOXYGEN_GENERATE_RTF NO)
+ set(DOXYGEN_GENERATE_XML NO)
+ set(DOXYGEN_GENERATE_CHI NO)
+
+ set(DOXYGEN_PREDEFINED TAILQ_ENTRY
+ RB_ENTRY
+ EVENT_DEFINED_TQENTRY_
+ EVENT_IN_DOXYGEN_
+ )
+
+ set(DOX_INPUT include/event2/buffer.h
+ include/event2/buffer_compat.h
+ include/event2/bufferevent.h
+ include/event2/bufferevent_compat.h
+ include/event2/bufferevent_ssl.h
+ include/event2/dns.h
+ include/event2/dns_compat.h
+ include/event2/event.h
+ include/event2/event_compat.h
+ include/event2/http.h
+ include/event2/http_compat.h
+ include/event2/listener.h
+ include/event2/rpc.h
+ include/event2/rpc_compat.h
+ include/event2/tag.h
+ include/event2/tag_compat.h
+ include/event2/thread.h
+ include/event2/util.h
+ )
+ # Add 'doxygen' target
+ doxygen_add_docs(doxygen
+ ${DOX_INPUT}
+ ALL
+ WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+ COMMENT "Generating doxygen documentation for ${PROJECT_NAME}..."
+ )
+
+ # Use 'make clean' to remove the generated directory
+ set_property(DIRECTORY
+ PROPERTY ADDITIONAL_MAKE_CLEAN_FILES
+ "${PROJECT_BINARY_DIR}/${DOXYGEN_OUTPUT_DIRECTORY}"
+ )
+
+ # Install html into <prefix>/share/doc/<project>
+ if ("${DOXYGEN_GENERATE_HTML}" STREQUAL "YES")
+ install(DIRECTORY
+ ${PROJECT_BINARY_DIR}/${DOXYGEN_OUTPUT_DIRECTORY}/html
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/share/doc/${PROJECT_NAME}
+ COMPONENT doc
+ )
+ endif()
+
+ # Install manual into <prefix>/share/man/man3
+ if ("${DOXYGEN_GENERATE_MAN}" STREQUAL "YES")
+ install(DIRECTORY
+ ${PROJECT_BINARY_DIR}/${DOXYGEN_OUTPUT_DIRECTORY}/man/man3
+ DESTINATION ${CMAKE_INSTALL_PREFIX}/share/man
+ COMPONENT doc
+ )
+ endif()
+
+ else(DOXYGEN_FOUND)
+ message(FATAL_ERROR "Doxygen command not found, set EVENT__DOXYGEN to disable")
+ endif (DOXYGEN_FOUND)
+ endif()
+endmacro()
diff --git a/ipc/chromium/src/third_party/libevent/cmake/VersionViaGit.cmake b/ipc/chromium/src/third_party/libevent/cmake/VersionViaGit.cmake
new file mode 100644
index 0000000000..24eb6af9b7
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/cmake/VersionViaGit.cmake
@@ -0,0 +1,66 @@
+# This module defines the following variables utilizing
+# git to determine the parent tag. And if found the macro
+# will attempt to parse them in the github tag fomat
+#
+# Useful for auto-versioning in our CMakeLists
+#
+# EVENT_GIT___VERSION_MAJOR - Major version.
+# EVENT_GIT___VERSION_MINOR - Minor version
+# EVENT_GIT___VERSION_STAGE - Stage version
+#
+# Example usage:
+#
+# event_fuzzy_version_from_git()
+# message("Libvent major=${EVENT_GIT___VERSION_MAJOR}")
+# message(" minor=${EVENT_GIT___VERSION_MINOR}")
+# message(" patch=${EVENT_GIT___VERSION_PATCH}")
+# message(" stage=${EVENT_GIT___VERSION_STAGE}")
+# endif()
+
+include(FindGit)
+
+macro(event_fuzzy_version_from_git)
+ # set our defaults.
+ set(EVENT_GIT___VERSION_MAJOR 2)
+ set(EVENT_GIT___VERSION_MINOR 1)
+ set(EVENT_GIT___VERSION_PATCH 12)
+ set(EVENT_GIT___VERSION_STAGE "stable")
+
+ find_package(Git)
+
+ if (GIT_FOUND)
+ execute_process(
+ COMMAND
+ ${GIT_EXECUTABLE} describe --abbrev=0 --always
+ WORKING_DIRECTORY
+ ${PROJECT_SOURCE_DIR}
+ RESULT_VARIABLE
+ GITRET
+ OUTPUT_VARIABLE
+ GITVERSION
+ OUTPUT_STRIP_TRAILING_WHITESPACE
+ )
+
+ string(REGEX REPLACE "[\\._-]" ";" VERSION_LIST "${GITVERSION}")
+ if(VERSION_LIST)
+ list(LENGTH VERSION_LIST VERSION_LIST_LENGTH)
+ endif()
+
+ if ((GITRET EQUAL 0) AND (VERSION_LIST_LENGTH EQUAL 5))
+ list(GET VERSION_LIST 1 _MAJOR)
+ list(GET VERSION_LIST 2 _MINOR)
+ list(GET VERSION_LIST 3 _PATCH)
+ list(GET VERSION_LIST 4 _STAGE)
+
+ set(_DEFAULT_VERSION "${EVENT_GIT___VERSION_MAJOR}.${EVENT_GIT___VERSION_MINOR}.${EVENT_GIT___VERSION_PATCH}-${EVENT_GIT___VERSION_STAGE}")
+ set(_GIT_VERSION "${_MAJOR}.${_MINOR}.${_PATCH}-${_STAGE}")
+
+ if (${_DEFAULT_VERSION} VERSION_LESS ${_GIT_VERSION})
+ set(EVENT_GIT___VERSION_MAJOR ${_MAJOR})
+ set(EVENT_GIT___VERSION_MINOR ${_MINOR})
+ set(EVENT_GIT___VERSION_PATCH ${_PATCH})
+ set(EVENT_GIT___VERSION_STAGE ${_STAGE})
+ endif()
+ endif()
+ endif()
+endmacro()
diff --git a/ipc/chromium/src/third_party/libevent/compat/sys/queue.h b/ipc/chromium/src/third_party/libevent/compat/sys/queue.h
new file mode 100644
index 0000000000..c387bdcf50
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/compat/sys/queue.h
@@ -0,0 +1,488 @@
+/* $OpenBSD: queue.h,v 1.16 2000/09/07 19:47:59 art Exp $ */
+/* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */
+
+/*
+ * Copyright (c) 1991, 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * @(#)queue.h 8.5 (Berkeley) 8/20/94
+ */
+
+#ifndef SYS_QUEUE_H__
+#define SYS_QUEUE_H__
+
+/*
+ * This file defines five types of data structures: singly-linked lists,
+ * lists, simple queues, tail queues, and circular queues.
+ *
+ *
+ * A singly-linked list is headed by a single forward pointer. The elements
+ * are singly linked for minimum space and pointer manipulation overhead at
+ * the expense of O(n) removal for arbitrary elements. New elements can be
+ * added to the list after an existing element or at the head of the list.
+ * Elements being removed from the head of the list should use the explicit
+ * macro for this purpose for optimum efficiency. A singly-linked list may
+ * only be traversed in the forward direction. Singly-linked lists are ideal
+ * for applications with large datasets and few or no removals or for
+ * implementing a LIFO queue.
+ *
+ * A list is headed by a single forward pointer (or an array of forward
+ * pointers for a hash table header). The elements are doubly linked
+ * so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before
+ * or after an existing element or at the head of the list. A list
+ * may only be traversed in the forward direction.
+ *
+ * A simple queue is headed by a pair of pointers, one the head of the
+ * list and the other to the tail of the list. The elements are singly
+ * linked to save space, so elements can only be removed from the
+ * head of the list. New elements can be added to the list before or after
+ * an existing element, at the head of the list, or at the end of the
+ * list. A simple queue may only be traversed in the forward direction.
+ *
+ * A tail queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or
+ * after an existing element, at the head of the list, or at the end of
+ * the list. A tail queue may be traversed in either direction.
+ *
+ * A circle queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or after
+ * an existing element, at the head of the list, or at the end of the list.
+ * A circle queue may be traversed in either direction, but has a more
+ * complex end of list detection.
+ *
+ * For details on the use of these macros, see the queue(3) manual page.
+ */
+
+/*
+ * Singly-linked List definitions.
+ */
+#define SLIST_HEAD(name, type) \
+struct name { \
+ struct type *slh_first; /* first element */ \
+}
+
+#define SLIST_HEAD_INITIALIZER(head) \
+ { NULL }
+
+#ifndef _WIN32
+#define SLIST_ENTRY(type) \
+struct { \
+ struct type *sle_next; /* next element */ \
+}
+#endif
+
+/*
+ * Singly-linked List access methods.
+ */
+#define SLIST_FIRST(head) ((head)->slh_first)
+#define SLIST_END(head) NULL
+#define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head))
+#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
+
+#define SLIST_FOREACH(var, head, field) \
+ for((var) = SLIST_FIRST(head); \
+ (var) != SLIST_END(head); \
+ (var) = SLIST_NEXT(var, field))
+
+/*
+ * Singly-linked List functions.
+ */
+#define SLIST_INIT(head) { \
+ SLIST_FIRST(head) = SLIST_END(head); \
+}
+
+#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
+ (elm)->field.sle_next = (slistelm)->field.sle_next; \
+ (slistelm)->field.sle_next = (elm); \
+} while (0)
+
+#define SLIST_INSERT_HEAD(head, elm, field) do { \
+ (elm)->field.sle_next = (head)->slh_first; \
+ (head)->slh_first = (elm); \
+} while (0)
+
+#define SLIST_REMOVE_HEAD(head, field) do { \
+ (head)->slh_first = (head)->slh_first->field.sle_next; \
+} while (0)
+
+/*
+ * List definitions.
+ */
+#define LIST_HEAD(name, type) \
+struct name { \
+ struct type *lh_first; /* first element */ \
+}
+
+#define LIST_HEAD_INITIALIZER(head) \
+ { NULL }
+
+#define LIST_ENTRY(type) \
+struct { \
+ struct type *le_next; /* next element */ \
+ struct type **le_prev; /* address of previous next element */ \
+}
+
+/*
+ * List access methods
+ */
+#define LIST_FIRST(head) ((head)->lh_first)
+#define LIST_END(head) NULL
+#define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head))
+#define LIST_NEXT(elm, field) ((elm)->field.le_next)
+
+#define LIST_FOREACH(var, head, field) \
+ for((var) = LIST_FIRST(head); \
+ (var)!= LIST_END(head); \
+ (var) = LIST_NEXT(var, field))
+
+/*
+ * List functions.
+ */
+#define LIST_INIT(head) do { \
+ LIST_FIRST(head) = LIST_END(head); \
+} while (0)
+
+#define LIST_INSERT_AFTER(listelm, elm, field) do { \
+ if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
+ (listelm)->field.le_next->field.le_prev = \
+ &(elm)->field.le_next; \
+ (listelm)->field.le_next = (elm); \
+ (elm)->field.le_prev = &(listelm)->field.le_next; \
+} while (0)
+
+#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
+ (elm)->field.le_prev = (listelm)->field.le_prev; \
+ (elm)->field.le_next = (listelm); \
+ *(listelm)->field.le_prev = (elm); \
+ (listelm)->field.le_prev = &(elm)->field.le_next; \
+} while (0)
+
+#define LIST_INSERT_HEAD(head, elm, field) do { \
+ if (((elm)->field.le_next = (head)->lh_first) != NULL) \
+ (head)->lh_first->field.le_prev = &(elm)->field.le_next;\
+ (head)->lh_first = (elm); \
+ (elm)->field.le_prev = &(head)->lh_first; \
+} while (0)
+
+#define LIST_REMOVE(elm, field) do { \
+ if ((elm)->field.le_next != NULL) \
+ (elm)->field.le_next->field.le_prev = \
+ (elm)->field.le_prev; \
+ *(elm)->field.le_prev = (elm)->field.le_next; \
+} while (0)
+
+#define LIST_REPLACE(elm, elm2, field) do { \
+ if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \
+ (elm2)->field.le_next->field.le_prev = \
+ &(elm2)->field.le_next; \
+ (elm2)->field.le_prev = (elm)->field.le_prev; \
+ *(elm2)->field.le_prev = (elm2); \
+} while (0)
+
+/*
+ * Simple queue definitions.
+ */
+#define SIMPLEQ_HEAD(name, type) \
+struct name { \
+ struct type *sqh_first; /* first element */ \
+ struct type **sqh_last; /* addr of last next element */ \
+}
+
+#define SIMPLEQ_HEAD_INITIALIZER(head) \
+ { NULL, &(head).sqh_first }
+
+#define SIMPLEQ_ENTRY(type) \
+struct { \
+ struct type *sqe_next; /* next element */ \
+}
+
+/*
+ * Simple queue access methods.
+ */
+#define SIMPLEQ_FIRST(head) ((head)->sqh_first)
+#define SIMPLEQ_END(head) NULL
+#define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))
+#define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next)
+
+#define SIMPLEQ_FOREACH(var, head, field) \
+ for((var) = SIMPLEQ_FIRST(head); \
+ (var) != SIMPLEQ_END(head); \
+ (var) = SIMPLEQ_NEXT(var, field))
+
+/*
+ * Simple queue functions.
+ */
+#define SIMPLEQ_INIT(head) do { \
+ (head)->sqh_first = NULL; \
+ (head)->sqh_last = &(head)->sqh_first; \
+} while (0)
+
+#define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \
+ if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \
+ (head)->sqh_last = &(elm)->field.sqe_next; \
+ (head)->sqh_first = (elm); \
+} while (0)
+
+#define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \
+ (elm)->field.sqe_next = NULL; \
+ *(head)->sqh_last = (elm); \
+ (head)->sqh_last = &(elm)->field.sqe_next; \
+} while (0)
+
+#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
+ if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\
+ (head)->sqh_last = &(elm)->field.sqe_next; \
+ (listelm)->field.sqe_next = (elm); \
+} while (0)
+
+#define SIMPLEQ_REMOVE_HEAD(head, elm, field) do { \
+ if (((head)->sqh_first = (elm)->field.sqe_next) == NULL) \
+ (head)->sqh_last = &(head)->sqh_first; \
+} while (0)
+
+/*
+ * Tail queue definitions.
+ */
+#define TAILQ_HEAD(name, type) \
+struct name { \
+ struct type *tqh_first; /* first element */ \
+ struct type **tqh_last; /* addr of last next element */ \
+}
+
+#define TAILQ_HEAD_INITIALIZER(head) \
+ { NULL, &(head).tqh_first }
+
+#define TAILQ_ENTRY(type) \
+struct { \
+ struct type *tqe_next; /* next element */ \
+ struct type **tqe_prev; /* address of previous next element */ \
+}
+
+/*
+ * tail queue access methods
+ */
+#define TAILQ_FIRST(head) ((head)->tqh_first)
+#define TAILQ_END(head) NULL
+#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
+#define TAILQ_LAST(head, headname) \
+ (*(((struct headname *)((head)->tqh_last))->tqh_last))
+/* XXX */
+#define TAILQ_PREV(elm, headname, field) \
+ (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
+#define TAILQ_EMPTY(head) \
+ (TAILQ_FIRST(head) == TAILQ_END(head))
+
+#define TAILQ_FOREACH(var, head, field) \
+ for((var) = TAILQ_FIRST(head); \
+ (var) != TAILQ_END(head); \
+ (var) = TAILQ_NEXT(var, field))
+
+#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
+ for((var) = TAILQ_LAST(head, headname); \
+ (var) != TAILQ_END(head); \
+ (var) = TAILQ_PREV(var, headname, field))
+
+/*
+ * Tail queue functions.
+ */
+#define TAILQ_INIT(head) do { \
+ (head)->tqh_first = NULL; \
+ (head)->tqh_last = &(head)->tqh_first; \
+} while (0)
+
+#define TAILQ_INSERT_HEAD(head, elm, field) do { \
+ if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \
+ (head)->tqh_first->field.tqe_prev = \
+ &(elm)->field.tqe_next; \
+ else \
+ (head)->tqh_last = &(elm)->field.tqe_next; \
+ (head)->tqh_first = (elm); \
+ (elm)->field.tqe_prev = &(head)->tqh_first; \
+} while (0)
+
+#define TAILQ_INSERT_TAIL(head, elm, field) do { \
+ (elm)->field.tqe_next = NULL; \
+ (elm)->field.tqe_prev = (head)->tqh_last; \
+ *(head)->tqh_last = (elm); \
+ (head)->tqh_last = &(elm)->field.tqe_next; \
+} while (0)
+
+#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
+ if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
+ (elm)->field.tqe_next->field.tqe_prev = \
+ &(elm)->field.tqe_next; \
+ else \
+ (head)->tqh_last = &(elm)->field.tqe_next; \
+ (listelm)->field.tqe_next = (elm); \
+ (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \
+} while (0)
+
+#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
+ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
+ (elm)->field.tqe_next = (listelm); \
+ *(listelm)->field.tqe_prev = (elm); \
+ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \
+} while (0)
+
+#define TAILQ_REMOVE(head, elm, field) do { \
+ if (((elm)->field.tqe_next) != NULL) \
+ (elm)->field.tqe_next->field.tqe_prev = \
+ (elm)->field.tqe_prev; \
+ else \
+ (head)->tqh_last = (elm)->field.tqe_prev; \
+ *(elm)->field.tqe_prev = (elm)->field.tqe_next; \
+} while (0)
+
+#define TAILQ_REPLACE(head, elm, elm2, field) do { \
+ if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \
+ (elm2)->field.tqe_next->field.tqe_prev = \
+ &(elm2)->field.tqe_next; \
+ else \
+ (head)->tqh_last = &(elm2)->field.tqe_next; \
+ (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \
+ *(elm2)->field.tqe_prev = (elm2); \
+} while (0)
+
+/*
+ * Circular queue definitions.
+ */
+#define CIRCLEQ_HEAD(name, type) \
+struct name { \
+ struct type *cqh_first; /* first element */ \
+ struct type *cqh_last; /* last element */ \
+}
+
+#define CIRCLEQ_HEAD_INITIALIZER(head) \
+ { CIRCLEQ_END(&head), CIRCLEQ_END(&head) }
+
+#define CIRCLEQ_ENTRY(type) \
+struct { \
+ struct type *cqe_next; /* next element */ \
+ struct type *cqe_prev; /* previous element */ \
+}
+
+/*
+ * Circular queue access methods
+ */
+#define CIRCLEQ_FIRST(head) ((head)->cqh_first)
+#define CIRCLEQ_LAST(head) ((head)->cqh_last)
+#define CIRCLEQ_END(head) ((void *)(head))
+#define CIRCLEQ_NEXT(elm, field) ((elm)->field.cqe_next)
+#define CIRCLEQ_PREV(elm, field) ((elm)->field.cqe_prev)
+#define CIRCLEQ_EMPTY(head) \
+ (CIRCLEQ_FIRST(head) == CIRCLEQ_END(head))
+
+#define CIRCLEQ_FOREACH(var, head, field) \
+ for((var) = CIRCLEQ_FIRST(head); \
+ (var) != CIRCLEQ_END(head); \
+ (var) = CIRCLEQ_NEXT(var, field))
+
+#define CIRCLEQ_FOREACH_REVERSE(var, head, field) \
+ for((var) = CIRCLEQ_LAST(head); \
+ (var) != CIRCLEQ_END(head); \
+ (var) = CIRCLEQ_PREV(var, field))
+
+/*
+ * Circular queue functions.
+ */
+#define CIRCLEQ_INIT(head) do { \
+ (head)->cqh_first = CIRCLEQ_END(head); \
+ (head)->cqh_last = CIRCLEQ_END(head); \
+} while (0)
+
+#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do { \
+ (elm)->field.cqe_next = (listelm)->field.cqe_next; \
+ (elm)->field.cqe_prev = (listelm); \
+ if ((listelm)->field.cqe_next == CIRCLEQ_END(head)) \
+ (head)->cqh_last = (elm); \
+ else \
+ (listelm)->field.cqe_next->field.cqe_prev = (elm); \
+ (listelm)->field.cqe_next = (elm); \
+} while (0)
+
+#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do { \
+ (elm)->field.cqe_next = (listelm); \
+ (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \
+ if ((listelm)->field.cqe_prev == CIRCLEQ_END(head)) \
+ (head)->cqh_first = (elm); \
+ else \
+ (listelm)->field.cqe_prev->field.cqe_next = (elm); \
+ (listelm)->field.cqe_prev = (elm); \
+} while (0)
+
+#define CIRCLEQ_INSERT_HEAD(head, elm, field) do { \
+ (elm)->field.cqe_next = (head)->cqh_first; \
+ (elm)->field.cqe_prev = CIRCLEQ_END(head); \
+ if ((head)->cqh_last == CIRCLEQ_END(head)) \
+ (head)->cqh_last = (elm); \
+ else \
+ (head)->cqh_first->field.cqe_prev = (elm); \
+ (head)->cqh_first = (elm); \
+} while (0)
+
+#define CIRCLEQ_INSERT_TAIL(head, elm, field) do { \
+ (elm)->field.cqe_next = CIRCLEQ_END(head); \
+ (elm)->field.cqe_prev = (head)->cqh_last; \
+ if ((head)->cqh_first == CIRCLEQ_END(head)) \
+ (head)->cqh_first = (elm); \
+ else \
+ (head)->cqh_last->field.cqe_next = (elm); \
+ (head)->cqh_last = (elm); \
+} while (0)
+
+#define CIRCLEQ_REMOVE(head, elm, field) do { \
+ if ((elm)->field.cqe_next == CIRCLEQ_END(head)) \
+ (head)->cqh_last = (elm)->field.cqe_prev; \
+ else \
+ (elm)->field.cqe_next->field.cqe_prev = \
+ (elm)->field.cqe_prev; \
+ if ((elm)->field.cqe_prev == CIRCLEQ_END(head)) \
+ (head)->cqh_first = (elm)->field.cqe_next; \
+ else \
+ (elm)->field.cqe_prev->field.cqe_next = \
+ (elm)->field.cqe_next; \
+} while (0)
+
+#define CIRCLEQ_REPLACE(head, elm, elm2, field) do { \
+ if (((elm2)->field.cqe_next = (elm)->field.cqe_next) == \
+ CIRCLEQ_END(head)) \
+ (head).cqh_last = (elm2); \
+ else \
+ (elm2)->field.cqe_next->field.cqe_prev = (elm2); \
+ if (((elm2)->field.cqe_prev = (elm)->field.cqe_prev) == \
+ CIRCLEQ_END(head)) \
+ (head).cqh_first = (elm2); \
+ else \
+ (elm2)->field.cqe_prev->field.cqe_next = (elm2); \
+} while (0)
+
+#endif /* !SYS_QUEUE_H__ */
diff --git a/ipc/chromium/src/third_party/libevent/configure.ac b/ipc/chromium/src/third_party/libevent/configure.ac
new file mode 100644
index 0000000000..d00e063a14
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/configure.ac
@@ -0,0 +1,1007 @@
+dnl Copyright 2000-2007 Niels Provos
+dnl Copyright 2007-2012 Niels Provos and Nick Mathewson
+dnl
+dnl See LICENSE for copying information.
+dnl
+dnl Original version Dug Song <dugsong@monkey.org>
+
+AC_INIT(libevent,2.1.12-stable)
+AC_PREREQ(2.67)
+AC_CONFIG_SRCDIR(event.c)
+
+AC_CONFIG_MACRO_DIR([m4])
+AC_CONFIG_AUX_DIR([build-aux])
+AM_INIT_AUTOMAKE
+dnl AM_SILENT_RULES req. automake 1.11. [no] defaults V=1
+AM_SILENT_RULES([yes])
+AC_CONFIG_HEADERS(config.h evconfig-private.h:evconfig-private.h.in)
+AC_DEFINE(NUMERIC_VERSION, 0x02010c00, [Numeric representation of the version])
+
+dnl Initialize prefix.
+AC_PREFIX_DEFAULT([/usr/local])
+
+dnl Try and get a full POSIX environment on obscure systems
+AC_USE_SYSTEM_EXTENSIONS
+
+AC_CANONICAL_BUILD
+AC_CANONICAL_HOST
+dnl the 'build' machine is where we run configure and compile
+dnl the 'host' machine is where the resulting stuff runs.
+
+#case "$host_os" in
+#
+# osf5*)
+# CFLAGS="$CFLAGS -D_OSF_SOURCE"
+# ;;
+#esac
+
+dnl Checks for programs.
+AM_PROG_CC_C_O
+AC_PROG_INSTALL
+AC_PROG_LN_S
+# AC_PROG_MKDIR_P - $(MKDIR_P) should be defined by AM_INIT_AUTOMAKE
+
+AC_PROG_SED
+
+AC_PROG_GCC_TRADITIONAL
+
+# We need to test for at least gcc 2.95 here, because older versions don't
+# have -fno-strict-aliasing
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 2) || (__GNUC__ == 2 && __GNUC_MINOR__ < 95)
+#error
+#endif])], have_gcc295=yes, have_gcc295=no)
+
+if test "$GCC" = "yes" ; then
+ # Enable many gcc warnings by default...
+ CFLAGS="$CFLAGS -Wall"
+ # And disable the strict-aliasing optimization, since it breaks
+ # our sockaddr-handling code in strange ways.
+ if test x$have_gcc295 = xyes; then
+ CFLAGS="$CFLAGS -fno-strict-aliasing"
+ fi
+fi
+
+# OS X Lion started deprecating the system openssl. Let's just disable
+# all deprecation warnings on OS X; but do so only for gcc...
+if test "$GCC" = "yes" ; then
+ case "$host_os" in
+ darwin*)
+ CFLAGS="$CFLAGS -Wno-deprecated-declarations"
+ ;;
+ esac
+fi
+
+AC_ARG_ENABLE(gcc-warnings,
+ AS_HELP_STRING(--disable-gcc-warnings, disable verbose warnings with GCC))
+
+AC_ARG_ENABLE(gcc-hardening,
+ AS_HELP_STRING(--enable-gcc-hardening, enable compiler security checks),
+[if test x$enableval = xyes; then
+ CFLAGS="$CFLAGS -D_FORTIFY_SOURCE=2 -fstack-protector-all"
+ CFLAGS="$CFLAGS -fwrapv -fPIE -Wstack-protector"
+ CFLAGS="$CFLAGS --param ssp-buffer-size=1"
+fi])
+
+AC_ARG_ENABLE(thread-support,
+ AS_HELP_STRING(--disable-thread-support, disable support for threading),
+ [], [enable_thread_support=yes])
+AC_ARG_ENABLE(malloc-replacement,
+ AS_HELP_STRING(--disable-malloc-replacement, disable support for replacing the memory mgt functions),
+ [], [enable_malloc_replacement=yes])
+AC_ARG_ENABLE(openssl,
+ AS_HELP_STRING(--disable-openssl, disable support for openssl encryption),
+ [], [enable_openssl=yes])
+AC_ARG_ENABLE(debug-mode,
+ AS_HELP_STRING(--disable-debug-mode, disable support for running in debug mode),
+ [], [enable_debug_mode=yes])
+AC_ARG_ENABLE([libevent-install],
+ AS_HELP_STRING([--disable-libevent-install, disable installation of libevent]),
+ [], [enable_libevent_install=yes])
+AC_ARG_ENABLE([libevent-regress],
+ AS_HELP_STRING([--disable-libevent-regress, skip regress in make check]),
+ [], [enable_libevent_regress=yes])
+AC_ARG_ENABLE([samples],
+ AS_HELP_STRING([--disable-samples, skip building of sample programs]),
+ [], [enable_samples=yes])
+AC_ARG_ENABLE([function-sections],
+ AS_HELP_STRING([--enable-function-sections, make static library allow smaller binaries with --gc-sections]),
+ [], [enable_function_sections=no])
+AC_ARG_ENABLE([verbose-debug],
+ AS_HELP_STRING([--enable-verbose-debug, verbose debug logging]),
+ [], [enable_verbose_debug=no])
+AC_ARG_ENABLE([clock-gettime],
+ AS_HELP_STRING(--disable-clock-gettime, do not use clock_gettime even if it is available),
+ [], [enable_clock_gettime=yes])
+
+
+LT_PREREQ([2.4.2])
+LT_INIT
+
+dnl Uncomment "AC_DISABLE_SHARED" to make shared libraries not get
+dnl built by default. You can also turn shared libs on and off from
+dnl the command line with --enable-shared and --disable-shared.
+dnl AC_DISABLE_SHARED
+AC_SUBST(LIBTOOL_DEPS)
+
+AM_CONDITIONAL([BUILD_SAMPLES], [test "$enable_samples" = "yes"])
+AM_CONDITIONAL([BUILD_REGRESS], [test "$enable_libevent_regress" = "yes"])
+
+dnl Checks for libraries.
+AC_SEARCH_LIBS([inet_ntoa], [nsl])
+AC_SEARCH_LIBS([socket], [socket])
+AC_SEARCH_LIBS([inet_aton], [resolv])
+if test "x$enable_clock_gettime" = "xyes"; then
+ AC_SEARCH_LIBS([clock_gettime], [rt])
+ AC_CHECK_FUNCS([clock_gettime])
+fi
+AC_SEARCH_LIBS([sendfile], [sendfile])
+
+dnl - check if the macro _WIN32 is defined on this compiler.
+dnl - (this is how we check for a windows compiler)
+AC_MSG_CHECKING(for WIN32)
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([],
+ [
+#ifndef _WIN32
+die horribly
+#endif
+ ]
+ )],
+ [bwin32=true; AC_MSG_RESULT(yes)],
+ [bwin32=false; AC_MSG_RESULT(no)]
+)
+
+dnl - check if the macro __midipix__ is defined on this compiler.
+dnl - (this is how we check for a midipix version of GCC)
+AC_MSG_CHECKING(for MIDIPIX)
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([],
+ [
+#ifndef __midipix__
+die horribly
+#endif
+ ]
+ )],
+ [midipix=true; AC_MSG_RESULT(yes)],
+ [midipix=false; AC_MSG_RESULT(no)]
+)
+
+dnl - check if the macro __CYGWIN__ is defined on this compiler.
+dnl - (this is how we check for a cygwin version of GCC)
+AC_MSG_CHECKING(for CYGWIN)
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([],
+ [
+#ifndef __CYGWIN__
+die horribly
+#endif
+ ]
+ )],
+ [cygwin=true; AC_MSG_RESULT(yes)],
+ [cygwin=false; AC_MSG_RESULT(no)]
+)
+
+AC_CHECK_HEADERS([zlib.h])
+
+if test "x$ac_cv_header_zlib_h" = "xyes"; then
+dnl Determine if we have zlib for regression tests
+dnl Don't put this one in LIBS
+save_LIBS="$LIBS"
+LIBS=""
+ZLIB_LIBS=""
+have_zlib=no
+AC_SEARCH_LIBS([inflateEnd], [z],
+ [have_zlib=yes
+ ZLIB_LIBS="$LIBS"
+ AC_DEFINE(HAVE_LIBZ, 1, [Define if the system has zlib])])
+LIBS="$save_LIBS"
+AC_SUBST(ZLIB_LIBS)
+fi
+AM_CONDITIONAL(ZLIB_REGRESS, [test "$have_zlib" = "yes"])
+
+dnl See if we have openssl. This doesn't go in LIBS either.
+if test "$bwin32" = true; then
+ EV_LIB_WS32=-lws2_32
+ EV_LIB_GDI=-lgdi32
+else
+ EV_LIB_WS32=
+ EV_LIB_GDI=
+fi
+AC_SUBST(EV_LIB_WS32)
+AC_SUBST(EV_LIB_GDI)
+AC_SUBST(OPENSSL_LIBADD)
+
+AC_SYS_LARGEFILE
+
+LIBEVENT_OPENSSL
+
+dnl Checks for header files.
+AC_CHECK_HEADERS([ \
+ arpa/inet.h \
+ fcntl.h \
+ ifaddrs.h \
+ mach/mach_time.h \
+ mach/mach.h \
+ netdb.h \
+ netinet/in.h \
+ netinet/in6.h \
+ netinet/tcp.h \
+ sys/un.h \
+ poll.h \
+ port.h \
+ stdarg.h \
+ stddef.h \
+ sys/devpoll.h \
+ sys/epoll.h \
+ sys/event.h \
+ sys/eventfd.h \
+ sys/ioctl.h \
+ sys/mman.h \
+ sys/param.h \
+ sys/queue.h \
+ sys/resource.h \
+ sys/select.h \
+ sys/sendfile.h \
+ sys/socket.h \
+ sys/stat.h \
+ sys/time.h \
+ sys/timerfd.h \
+ sys/uio.h \
+ sys/wait.h \
+ sys/random.h \
+ errno.h \
+ afunix.h \
+])
+
+case "${host_os}" in
+ linux*) ;;
+ *)
+ AC_CHECK_HEADERS(sys/sysctl.h, [], [], [
+ #ifdef HAVE_SYS_PARAM_H
+ #include <sys/param.h>
+ #endif
+ ])
+esac
+
+if test "x$ac_cv_header_sys_queue_h" = "xyes"; then
+ AC_MSG_CHECKING(for TAILQ_FOREACH in sys/queue.h)
+ AC_EGREP_CPP(yes,
+[
+#include <sys/queue.h>
+#ifdef TAILQ_FOREACH
+ yes
+#endif
+], [AC_MSG_RESULT(yes)
+ AC_DEFINE(HAVE_TAILQFOREACH, 1,
+ [Define if TAILQ_FOREACH is defined in <sys/queue.h>])],
+ AC_MSG_RESULT(no)
+ )
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+ AC_MSG_CHECKING(for timeradd in sys/time.h)
+ AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timeradd
+ yes
+#endif
+], [ AC_DEFINE(HAVE_TIMERADD, 1,
+ [Define if timeradd is defined in <sys/time.h>])
+ AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+ AC_MSG_CHECKING(for timercmp in sys/time.h)
+ AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timercmp
+ yes
+#endif
+], [ AC_DEFINE(HAVE_TIMERCMP, 1,
+ [Define if timercmp is defined in <sys/time.h>])
+ AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+ AC_MSG_CHECKING(for timerclear in sys/time.h)
+ AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timerclear
+ yes
+#endif
+], [ AC_DEFINE(HAVE_TIMERCLEAR, 1,
+ [Define if timerclear is defined in <sys/time.h>])
+ AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_time_h" = "xyes"; then
+ AC_MSG_CHECKING(for timerisset in sys/time.h)
+ AC_EGREP_CPP(yes,
+[
+#include <sys/time.h>
+#ifdef timerisset
+ yes
+#endif
+], [ AC_DEFINE(HAVE_TIMERISSET, 1,
+ [Define if timerisset is defined in <sys/time.h>])
+ AC_MSG_RESULT(yes)] ,AC_MSG_RESULT(no)
+)
+fi
+
+if test "x$ac_cv_header_sys_sysctl_h" = "xyes"; then
+ AC_CHECK_DECLS([CTL_KERN, KERN_ARND], [], [],
+ [[#include <sys/types.h>
+ #include <sys/sysctl.h>]]
+ )
+fi
+
+AM_CONDITIONAL(BUILD_WIN32, test x$bwin32 = xtrue)
+AM_CONDITIONAL(BUILD_CYGWIN, test x$cygwin = xtrue)
+AM_CONDITIONAL(BUILD_MIDIPIX, test x$midipix = xtrue)
+AM_CONDITIONAL(BUILD_WITH_NO_UNDEFINED, test x$bwin32 = xtrue || test x$cygwin = xtrue || test x$midipix = xtrue)
+
+if test x$bwin32 = xtrue; then
+ AC_HAVE_LIBRARY([ws2_32])
+fi
+
+dnl Checks for typedefs, structures, and compiler characteristics.
+AC_C_CONST
+AC_C_INLINE
+AC_HEADER_TIME
+
+dnl Checks for library functions.
+AC_CHECK_FUNCS([ \
+ accept4 \
+ arc4random \
+ arc4random_buf \
+ arc4random_addrandom \
+ eventfd \
+ epoll_create1 \
+ fcntl \
+ getegid \
+ geteuid \
+ getifaddrs \
+ gettimeofday \
+ issetugid \
+ mach_absolute_time \
+ mmap \
+ nanosleep \
+ pipe \
+ pipe2 \
+ putenv \
+ sendfile \
+ setenv \
+ setrlimit \
+ sigaction \
+ signal \
+ splice \
+ strlcpy \
+ strsep \
+ strtok_r \
+ strtoll \
+ sysctl \
+ timerfd_create \
+ umask \
+ unsetenv \
+ usleep \
+ vasprintf \
+ getrandom \
+])
+
+AS_IF([test x$bwin32 = xtrue],
+ AC_CHECK_FUNCS(_gmtime64_s, , [AC_CHECK_FUNCS(_gmtime64)])
+)
+
+AM_CONDITIONAL(STRLCPY_IMPL, [test x"$ac_cv_func_strlcpy" = xno])
+
+m4_define([funcstochk],
+ [getnameinfo
+ getprotobynumber
+ getservbyname
+ inet_ntop
+ inet_pton]
+)
+
+AS_IF([test x$bwin32 = xtrue],
+ [AX_CHECK_DECLS_EX([funcstochk getaddrinfo],
+ [#ifdef _WIN32
+ #include <winsock2.h>
+ #include <ws2tcpip.h>
+ #endif])],
+ [AC_CHECK_FUNCS(m4_normalize(funcstochk))]
+)
+
+m4_undefine([funcstochk])
+
+dnl check getaddrinfo and gethostbyname_r for non-windows
+AS_IF([test x$bwin32 = xfalse], [
+AC_CACHE_CHECK(
+ [for getaddrinfo],
+ [libevent_cv_getaddrinfo],
+ [AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM(
+ [[
+ #ifdef HAVE_NETDB_H
+ #include <netdb.h>
+ #endif
+ ]],
+ [[
+ getaddrinfo;
+ ]]
+ )],
+ [libevent_cv_getaddrinfo=yes],
+ [libevent_cv_getaddrinfo=no]
+ )]
+)
+if test "$libevent_cv_getaddrinfo" = "yes" ; then
+ AC_DEFINE([HAVE_GETADDRINFO], [1], [Do we have getaddrinfo()?])
+else
+
+# Check for gethostbyname_r in all its glorious incompatible versions.
+# (This is cut-and-pasted from Tor, which based its logic on
+# Python's configure.in.)
+AH_TEMPLATE(HAVE_GETHOSTBYNAME_R,
+ [Define this if you have any gethostbyname_r()])
+
+AC_CHECK_FUNC(gethostbyname_r, [
+ AC_MSG_CHECKING([how many arguments gethostbyname_r() wants])
+ OLD_CFLAGS=$CFLAGS
+ CFLAGS="$CFLAGS $MY_CPPFLAGS $MY_THREAD_CPPFLAGS $MY_CFLAGS"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+#include <netdb.h>
+ ], [[
+ char *cp1, *cp2;
+ struct hostent *h1, *h2;
+ int i1, i2;
+ (void)gethostbyname_r(cp1,h1,cp2,i1,&h2,&i2);
+ ]])],[
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R_6_ARG, 1,
+ [Define this if gethostbyname_r takes 6 arguments])
+ AC_MSG_RESULT(6)
+ ], [
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+#include <netdb.h>
+ ], [
+ char *cp1, *cp2;
+ struct hostent *h1;
+ int i1, i2;
+ (void)gethostbyname_r(cp1,h1,cp2,i1,&i2);
+ ])], [
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R_5_ARG, 1,
+ [Define this if gethostbyname_r takes 5 arguments])
+ AC_MSG_RESULT(5)
+ ], [
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
+#include <netdb.h>
+ ], [
+ char *cp1;
+ struct hostent *h1;
+ struct hostent_data hd;
+ (void) gethostbyname_r(cp1,h1,&hd);
+ ])], [
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R)
+ AC_DEFINE(HAVE_GETHOSTBYNAME_R_3_ARG, 1,
+ [Define this if gethostbyname_r takes 3 arguments])
+ AC_MSG_RESULT(3)
+ ], [
+ AC_MSG_RESULT(0)
+ ])
+ ])
+ ])
+ CFLAGS=$OLD_CFLAGS
+])
+
+fi
+]) dnl end of checking getaddrinfo and gethostbyname_r
+
+AC_MSG_CHECKING(for F_SETFD in fcntl.h)
+AC_EGREP_CPP(yes,
+[
+#define _GNU_SOURCE 1
+#include <fcntl.h>
+#ifdef F_SETFD
+yes
+#endif
+], [ AC_DEFINE(HAVE_SETFD, 1,
+ [Define if F_SETFD is defined in <fcntl.h>])
+ AC_MSG_RESULT(yes) ], AC_MSG_RESULT(no))
+
+needsignal=no
+haveselect=no
+if test x$bwin32 != xtrue; then
+ AC_CHECK_FUNCS(select, [haveselect=yes], )
+ if test "x$haveselect" = "xyes" ; then
+ needsignal=yes
+ fi
+fi
+AM_CONDITIONAL(SELECT_BACKEND, [test "x$haveselect" = "xyes"])
+
+havepoll=no
+AC_CHECK_FUNCS(poll, [havepoll=yes], )
+if test "x$havepoll" = "xyes" ; then
+ needsignal=yes
+fi
+AM_CONDITIONAL(POLL_BACKEND, [test "x$havepoll" = "xyes"])
+
+havedevpoll=no
+if test "x$ac_cv_header_sys_devpoll_h" = "xyes"; then
+ AC_DEFINE(HAVE_DEVPOLL, 1,
+ [Define if /dev/poll is available])
+fi
+AM_CONDITIONAL(DEVPOLL_BACKEND, [test "x$ac_cv_header_sys_devpoll_h" = "xyes"])
+
+havekqueue=no
+if test "x$ac_cv_header_sys_event_h" = "xyes"; then
+ AC_CHECK_FUNCS(kqueue, [havekqueue=yes], )
+ if test "x$havekqueue" = "xyes" ; then
+ AC_MSG_CHECKING(for working kqueue)
+ AC_RUN_IFELSE(
+ [AC_LANG_PROGRAM([
+#ifdef HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#ifdef HAVE_STRING_H
+#include <string.h>
+#endif
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/event.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <fcntl.h>
+ ], [[
+ int kq;
+ int n;
+ int fd[2];
+ struct kevent ev;
+ struct timespec ts;
+ char buf[80000];
+
+ if (pipe(fd) == -1)
+ return 1;
+ if (fcntl(fd[1], F_SETFL, O_NONBLOCK) == -1)
+ return 1;
+
+ while ((n = write(fd[1], buf, sizeof(buf))) == sizeof(buf))
+ ;
+
+ if ((kq = kqueue()) == -1)
+ return 1;
+
+ memset(&ev, 0, sizeof(ev));
+ ev.ident = fd[1];
+ ev.filter = EVFILT_WRITE;
+ ev.flags = EV_ADD | EV_ENABLE;
+ n = kevent(kq, &ev, 1, NULL, 0, NULL);
+ if (n == -1)
+ return 1;
+
+ read(fd[0], buf, sizeof(buf));
+
+ ts.tv_sec = 0;
+ ts.tv_nsec = 0;
+ n = kevent(kq, NULL, 0, &ev, 1, &ts);
+ if (n == -1 || n == 0)
+ return 1;
+
+ return 0;
+ ]]
+ )],
+ [AC_MSG_RESULT(yes)
+ AC_DEFINE(HAVE_WORKING_KQUEUE, 1,
+ [Define if kqueue works correctly with pipes])
+ havekqueue=yes
+ ], [AC_MSG_RESULT(no)], [AC_MSG_RESULT(no)]
+ )
+ fi
+fi
+AM_CONDITIONAL(KQUEUE_BACKEND, [test "x$havekqueue" = "xyes"])
+
+haveepollsyscall=no
+haveepoll=no
+AC_CHECK_FUNCS(epoll_ctl, [haveepoll=yes], )
+if test "x$haveepoll" = "xyes" ; then
+ AC_DEFINE(HAVE_EPOLL, 1,
+ [Define if your system supports the epoll system calls])
+ needsignal=yes
+fi
+if test "x$ac_cv_header_sys_epoll_h" = "xyes"; then
+ if test "x$haveepoll" = "xno" ; then
+ AC_MSG_CHECKING(for epoll system call)
+ AC_RUN_IFELSE(
+ [AC_LANG_PROGRAM([[
+#include <stdint.h>
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/epoll.h>
+#include <unistd.h>
+
+int
+epoll_create(int size)
+{
+ return (syscall(__NR_epoll_create, size));
+}
+ ]],[[
+ int epfd;
+
+ epfd = epoll_create(256);
+ return (epfd == -1 ? 1 : 0);
+ ]]
+ )],
+ [AC_MSG_RESULT(yes)
+ AC_DEFINE(HAVE_EPOLL, 1,
+ [Define if your system supports the epoll system calls])
+ needsignal=yes
+ have_epoll=yes
+ AC_LIBOBJ(epoll_sub)
+ ], [AC_MSG_RESULT(no)], [AC_MSG_RESULT(no)]
+ )
+ fi
+fi
+AM_CONDITIONAL(EPOLL_BACKEND, [test "x$haveepoll" = "xyes"])
+
+haveeventports=no
+AC_CHECK_FUNCS(port_create, [haveeventports=yes], )
+if test "x$haveeventports" = "xyes" ; then
+ AC_DEFINE(HAVE_EVENT_PORTS, 1,
+ [Define if your system supports event ports])
+ needsignal=yes
+fi
+AM_CONDITIONAL(EVPORT_BACKEND, [test "x$haveeventports" = "xyes"])
+
+if test "x$bwin32" = "xtrue"; then
+ needsignal=yes
+fi
+
+AM_CONDITIONAL(SIGNAL_SUPPORT, [test "x$needsignal" = "xyes"])
+
+AC_TYPE_PID_T
+AC_TYPE_SIZE_T
+AC_TYPE_SSIZE_T
+
+AC_CHECK_TYPES([uint64_t, uint32_t, uint16_t, uint8_t, uintptr_t], , ,
+[#ifdef HAVE_STDINT_H
+#include <stdint.h>
+#elif defined(HAVE_INTTYPES_H)
+#include <inttypes.h>
+#endif
+#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif])
+
+AC_CHECK_TYPES([fd_mask], , ,
+[#ifdef HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif])
+
+AC_CHECK_SIZEOF(long long)
+AC_CHECK_SIZEOF(long)
+AC_CHECK_SIZEOF(int)
+AC_CHECK_SIZEOF(short)
+AC_CHECK_SIZEOF(size_t)
+AC_CHECK_SIZEOF(void *)
+AC_CHECK_SIZEOF(off_t)
+AC_CHECK_SIZEOF(time_t)
+
+AC_CHECK_TYPES([struct in6_addr, struct sockaddr_in6, struct sockaddr_un, sa_family_t, struct addrinfo, struct sockaddr_storage], , ,
+[#define _GNU_SOURCE 1
+#include <sys/types.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#ifdef _WIN32
+#define WIN32_WINNT 0x400
+#define _WIN32_WINNT 0x400
+#define WIN32_LEAN_AND_MEAN
+#if defined(_MSC_VER) && (_MSC_VER < 1300)
+#include <winsock.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+])
+AC_CHECK_MEMBERS([struct in6_addr.s6_addr32, struct in6_addr.s6_addr16, struct sockaddr_in.sin_len, struct sockaddr_in6.sin6_len, struct sockaddr_storage.ss_family, struct sockaddr_storage.__ss_family], , ,
+[#include <sys/types.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef _WIN32
+#define WIN32_WINNT 0x400
+#define _WIN32_WINNT 0x400
+#define WIN32_LEAN_AND_MEAN
+#if defined(_MSC_VER) && (_MSC_VER < 1300)
+#include <winsock.h>
+#else
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+])
+
+AC_CHECK_TYPES([struct linger],,,
+[
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+])
+
+AC_MSG_CHECKING([for socklen_t])
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([
+ #include <sys/types.h>
+ #ifdef _WIN32
+ #include <ws2tcpip.h>
+ #else
+ #include <sys/socket.h>
+ #endif
+ ],[socklen_t x;]
+ )],
+ [AC_MSG_RESULT([yes])],
+ [AC_MSG_RESULT([no])
+ AC_DEFINE(socklen_t, unsigned int,
+ [Define to unsigned int if you dont have it])]
+)
+
+# __func__/__FUNCTION__ is not a macros in general
+AC_MSG_CHECKING([whether our compiler supports __func__])
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([],
+ [ const char *cp = __func__; ]
+ )],
+ [ AC_DEFINE(HAVE___func__, 1, [Define to 1 if compiler have __func__])
+ AC_MSG_RESULT([yes])
+ ],
+ [AC_MSG_RESULT([no])]
+)
+AC_MSG_CHECKING([whether our compiler supports __FUNCTION__])
+AC_COMPILE_IFELSE(
+ [AC_LANG_PROGRAM([],
+ [ const char *cp = __FUNCTION__; ]
+ )],
+ [ AC_DEFINE(HAVE___FUNCTION__, 1, [Define to 1 if compiler have __FUNCTION__])
+ AC_MSG_RESULT([yes])
+ ],
+ [AC_MSG_RESULT([no])]
+)
+
+# check if we can compile with pthreads
+have_pthreads=no
+if test x$bwin32 != xtrue && test "$enable_thread_support" != "no"; then
+ ACX_PTHREAD([
+ AC_DEFINE(HAVE_PTHREADS, 1,
+ [Define if we have pthreads on this system])
+ have_pthreads=yes])
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+ AC_CHECK_SIZEOF(pthread_t, ,
+ [AC_INCLUDES_DEFAULT()
+ #include <pthread.h> ]
+ )
+fi
+AM_CONDITIONAL(THREADS, [test "$enable_thread_support" != "no"])
+AM_CONDITIONAL(PTHREADS, [test "$have_pthreads" != "no" && test "$enable_thread_support" != "no"])
+
+# check if we should compile locking into the library
+if test x$enable_thread_support = xno; then
+ AC_DEFINE(DISABLE_THREAD_SUPPORT, 1,
+ [Define if libevent should not be compiled with thread support])
+fi
+
+# check if we should hard-code the mm functions.
+if test x$enable_malloc_replacement = xno; then
+ AC_DEFINE(DISABLE_MM_REPLACEMENT, 1,
+ [Define if libevent should not allow replacing the mm functions])
+fi
+
+# check if we should hard-code debugging out
+if test x$enable_debug_mode = xno; then
+ AC_DEFINE(DISABLE_DEBUG_MODE, 1,
+ [Define if libevent should build without support for a debug mode])
+fi
+
+# check if we should enable verbose debugging
+if test x$enable_verbose_debug = xyes; then
+ CFLAGS="$CFLAGS -DUSE_DEBUG"
+fi
+
+# check if we have and should use openssl
+AM_CONDITIONAL(OPENSSL, [test "$enable_openssl" != "no" && test "$have_openssl" = "yes"])
+
+# Add some more warnings which we use in development but not in the
+# released versions. (Some relevant gcc versions can't handle these.)
+if test x$enable_gcc_warnings != xno && test "$GCC" = "yes"; then
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4)
+#error
+#endif])], have_gcc4=yes, have_gcc4=no)
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 2)
+#error
+#endif])], have_gcc42=yes, have_gcc42=no)
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__GNUC__) || (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)
+#error
+#endif])], have_gcc45=yes, have_gcc45=no)
+
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([], [
+#if !defined(__clang__)
+#error
+#endif])], have_clang=yes, have_clang=no)
+
+ # -W is the same as -Wextra
+ CFLAGS="$CFLAGS -W -Wfloat-equal -Wundef -Wpointer-arith -Wstrict-prototypes -Wmissing-prototypes -Wwrite-strings -Wredundant-decls -Wmissing-declarations -Wnested-externs -Wbad-function-cast"
+ if test x$enable_gcc_warnings = xyes; then
+ CFLAGS="$CFLAGS -Werror"
+ fi
+
+ CFLAGS="$CFLAGS -Wno-unused-parameter -Wstrict-aliasing"
+
+ if test x$have_gcc4 = xyes ; then
+ # These warnings break gcc 3.3.5 and work on gcc 4.0.2
+ CFLAGS="$CFLAGS -Winit-self -Wmissing-field-initializers -Wdeclaration-after-statement"
+ #CFLAGS="$CFLAGS -Wold-style-definition"
+ fi
+
+ if test x$have_gcc42 = xyes ; then
+ # These warnings break gcc 4.0.2 and work on gcc 4.2
+ CFLAGS="$CFLAGS -Waddress"
+ fi
+
+ if test x$have_gcc42 = xyes && test x$have_clang = xno; then
+ # These warnings break gcc 4.0.2 and clang, but work on gcc 4.2
+ CFLAGS="$CFLAGS -Wnormalized=id -Woverride-init"
+ fi
+
+ if test x$have_gcc45 = xyes ; then
+ # These warnings work on gcc 4.5
+ CFLAGS="$CFLAGS -Wlogical-op"
+ fi
+
+ if test x$have_clang = xyes; then
+ # Disable the unused-function warnings, because these trigger
+ # for minheap-internal.h related code.
+ CFLAGS="$CFLAGS -Wno-unused-function"
+
+ # clang on macosx emits warnings for each directory specified which
+ # isn't "used" generating a lot of build noise (typically 3 warnings
+ # per file
+ case "$host_os" in
+ darwin*)
+ CFLAGS="$CFLAGS -Qunused-arguments"
+ ;;
+ esac
+ fi
+
+##This will break the world on some 64-bit architectures
+# CFLAGS="$CFLAGS -Winline"
+
+fi
+
+LIBEVENT_GC_SECTIONS=
+if test "$GCC" = yes && test "$enable_function_sections" = yes ; then
+ AC_CACHE_CHECK(
+ [if linker supports omitting unused code and data],
+ [libevent_cv_gc_sections_runs],
+ [
+ dnl NetBSD will link but likely not run with --gc-sections
+ dnl http://bugs.ntp.org/1844
+ dnl http://gnats.netbsd.org/40401
+ dnl --gc-sections causes attempt to load as linux elf, with
+ dnl wrong syscalls in place. Test a little gauntlet of
+ dnl simple stdio read code checking for errors, expecting
+ dnl enough syscall differences that the NetBSD code will
+ dnl fail even with Linux emulation working as designed.
+ dnl A shorter test could be refined by someone with access
+ dnl to a NetBSD host with Linux emulation working.
+ origCFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS -Wl,--gc-sections"
+ AC_LINK_IFELSE(
+ [AC_LANG_PROGRAM(
+ [[
+ #include <stdlib.h>
+ #include <stdio.h>
+ ]],
+ [[
+ FILE * fpC;
+ char buf[32];
+ size_t cch;
+ int read_success_once;
+
+ fpC = fopen("conftest.c", "r");
+ if (NULL == fpC)
+ exit(1);
+ do {
+ cch = fread(buf, sizeof(buf), 1, fpC);
+ read_success_once |= (0 != cch);
+ } while (0 != cch);
+ if (!read_success_once)
+ exit(2);
+ if (!feof(fpC))
+ exit(3);
+ if (0 != fclose(fpC))
+ exit(4);
+
+ exit(EXIT_SUCCESS);
+ ]]
+ )],
+ [
+ dnl We have to do this invocation manually so that we can
+ dnl get the output of conftest.err to make sure it doesn't
+ dnl mention gc-sections.
+ if test "X$cross_compiling" = "Xyes" || grep gc-sections conftest.err ; then
+ libevent_cv_gc_sections_runs=no
+ else
+ libevent_cv_gc_sections_runs=no
+ ./conftest >/dev/null 2>&1 && libevent_cv_gc_sections_runs=yes
+ fi
+ ],
+ [libevent_cv_gc_sections_runs=no]
+ )
+ CFLAGS="$origCFLAGS"
+ AS_UNSET([origCFLAGS])
+ ]
+ )
+ case "$libevent_cv_gc_sections_runs" in
+ yes)
+ CFLAGS="-ffunction-sections -fdata-sections $CFLAGS"
+ LIBEVENT_GC_SECTIONS="-Wl,--gc-sections"
+ ;;
+ esac
+fi
+AC_SUBST([LIBEVENT_GC_SECTIONS])
+
+AM_CONDITIONAL([INSTALL_LIBEVENT], [test "$enable_libevent_install" = "yes"])
+
+# Doxygen support
+DX_HTML_FEATURE(ON)
+DX_MAN_FEATURE(OFF)
+DX_RTF_FEATURE(OFF)
+DX_XML_FEATURE(OFF)
+DX_PDF_FEATURE(OFF)
+DX_PS_FEATURE(OFF)
+DX_CHM_FEATURE(OFF)
+DX_CHI_FEATURE(OFF)
+DX_INIT_DOXYGEN([libevent], [${top_srcdir}/Doxyfile], [doxygen])
+
+AM_CONDITIONAL([ENABLE_DOXYGEN], [test "$DX_FLAG_doc" = "1"])
+AM_CONDITIONAL([ENABLE_DOXYGEN_MAN], [test "$DX_FLAG_man" = "1"])
+
+AC_CONFIG_FILES( [libevent.pc libevent_openssl.pc libevent_pthreads.pc libevent_core.pc libevent_extra.pc] )
+AC_OUTPUT(Makefile)
diff --git a/ipc/chromium/src/third_party/libevent/defer-internal.h b/ipc/chromium/src/third_party/libevent/defer-internal.h
new file mode 100644
index 0000000000..d6f80a1180
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/defer-internal.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef DEFER_INTERNAL_H_INCLUDED_
+#define DEFER_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/queue.h>
+
+struct event_callback;
+typedef void (*deferred_cb_fn)(struct event_callback *, void *);
+
+/**
+ Initialize an empty, non-pending event_callback.
+
+ @param deferred The struct event_callback structure to initialize.
+ @param priority The priority that the callback should run at.
+ @param cb The function to run when the struct event_callback executes.
+ @param arg The function's second argument.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_deferred_cb_init_(struct event_callback *, ev_uint8_t, deferred_cb_fn, void *);
+/**
+ Change the priority of a non-pending event_callback.
+ */
+void event_deferred_cb_set_priority_(struct event_callback *, ev_uint8_t);
+/**
+ Cancel a struct event_callback if it is currently scheduled in an event_base.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_deferred_cb_cancel_(struct event_base *, struct event_callback *);
+/**
+ Activate a struct event_callback if it is not currently scheduled in an event_base.
+
+ Return true if it was not previously scheduled.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_deferred_cb_schedule_(struct event_base *, struct event_callback *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
+
diff --git a/ipc/chromium/src/third_party/libevent/devpoll.c b/ipc/chromium/src/third_party/libevent/devpoll.c
new file mode 100644
index 0000000000..3a2f86d6f1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/devpoll.c
@@ -0,0 +1,311 @@
+/*
+ * Copyright 2000-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_DEVPOLL
+
+#include <sys/types.h>
+#include <sys/resource.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/devpoll.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "evthread-internal.h"
+
+struct devpollop {
+ struct pollfd *events;
+ int nevents;
+ int dpfd;
+ struct pollfd *changes;
+ int nchanges;
+};
+
+static void *devpoll_init(struct event_base *);
+static int devpoll_add(struct event_base *, int fd, short old, short events, void *);
+static int devpoll_del(struct event_base *, int fd, short old, short events, void *);
+static int devpoll_dispatch(struct event_base *, struct timeval *);
+static void devpoll_dealloc(struct event_base *);
+
+const struct eventop devpollops = {
+ "devpoll",
+ devpoll_init,
+ devpoll_add,
+ devpoll_del,
+ devpoll_dispatch,
+ devpoll_dealloc,
+ 1, /* need reinit */
+ EV_FEATURE_FDS|EV_FEATURE_O1,
+ 0
+};
+
+#define NEVENT 32000
+
+static int
+devpoll_commit(struct devpollop *devpollop)
+{
+ /*
+ * Due to a bug in Solaris, we have to use pwrite with an offset of 0.
+ * Write is limited to 2GB of data, until it will fail.
+ */
+ if (pwrite(devpollop->dpfd, devpollop->changes,
+ sizeof(struct pollfd) * devpollop->nchanges, 0) == -1)
+ return (-1);
+
+ devpollop->nchanges = 0;
+ return (0);
+}
+
+static int
+devpoll_queue(struct devpollop *devpollop, int fd, int events) {
+ struct pollfd *pfd;
+
+ if (devpollop->nchanges >= devpollop->nevents) {
+ /*
+ * Change buffer is full, must commit it to /dev/poll before
+ * adding more
+ */
+ if (devpoll_commit(devpollop) != 0)
+ return (-1);
+ }
+
+ pfd = &devpollop->changes[devpollop->nchanges++];
+ pfd->fd = fd;
+ pfd->events = events;
+ pfd->revents = 0;
+
+ return (0);
+}
+
+static void *
+devpoll_init(struct event_base *base)
+{
+ int dpfd, nfiles = NEVENT;
+ struct rlimit rl;
+ struct devpollop *devpollop;
+
+ if (!(devpollop = mm_calloc(1, sizeof(struct devpollop))))
+ return (NULL);
+
+ if (getrlimit(RLIMIT_NOFILE, &rl) == 0 &&
+ rl.rlim_cur != RLIM_INFINITY)
+ nfiles = rl.rlim_cur;
+
+ /* Initialize the kernel queue */
+ if ((dpfd = evutil_open_closeonexec_("/dev/poll", O_RDWR, 0)) == -1) {
+ event_warn("open: /dev/poll");
+ mm_free(devpollop);
+ return (NULL);
+ }
+
+ devpollop->dpfd = dpfd;
+
+ /* Initialize fields */
+ /* FIXME: allocating 'nfiles' worth of space here can be
+ * expensive and unnecessary. See how epoll.c does it instead. */
+ devpollop->events = mm_calloc(nfiles, sizeof(struct pollfd));
+ if (devpollop->events == NULL) {
+ mm_free(devpollop);
+ close(dpfd);
+ return (NULL);
+ }
+ devpollop->nevents = nfiles;
+
+ devpollop->changes = mm_calloc(nfiles, sizeof(struct pollfd));
+ if (devpollop->changes == NULL) {
+ mm_free(devpollop->events);
+ mm_free(devpollop);
+ close(dpfd);
+ return (NULL);
+ }
+
+ evsig_init_(base);
+
+ return (devpollop);
+}
+
+static int
+devpoll_dispatch(struct event_base *base, struct timeval *tv)
+{
+ struct devpollop *devpollop = base->evbase;
+ struct pollfd *events = devpollop->events;
+ struct dvpoll dvp;
+ int i, res, timeout = -1;
+
+ if (devpollop->nchanges)
+ devpoll_commit(devpollop);
+
+ if (tv != NULL)
+ timeout = tv->tv_sec * 1000 + (tv->tv_usec + 999) / 1000;
+
+ dvp.dp_fds = devpollop->events;
+ dvp.dp_nfds = devpollop->nevents;
+ dvp.dp_timeout = timeout;
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = ioctl(devpollop->dpfd, DP_POLL, &dvp);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (res == -1) {
+ if (errno != EINTR) {
+ event_warn("ioctl: DP_POLL");
+ return (-1);
+ }
+
+ return (0);
+ }
+
+ event_debug(("%s: devpoll_wait reports %d", __func__, res));
+
+ for (i = 0; i < res; i++) {
+ int which = 0;
+ int what = events[i].revents;
+
+ if (what & POLLHUP)
+ what |= POLLIN | POLLOUT;
+ else if (what & POLLERR)
+ what |= POLLIN | POLLOUT;
+
+ if (what & POLLIN)
+ which |= EV_READ;
+ if (what & POLLOUT)
+ which |= EV_WRITE;
+
+ if (!which)
+ continue;
+
+ /* XXX(niels): not sure if this works for devpoll */
+ evmap_io_active_(base, events[i].fd, which);
+ }
+
+ return (0);
+}
+
+
+static int
+devpoll_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct devpollop *devpollop = base->evbase;
+ int res;
+ (void)p;
+
+ /*
+ * It's not necessary to OR the existing read/write events that we
+ * are currently interested in with the new event we are adding.
+ * The /dev/poll driver ORs any new events with the existing events
+ * that it has cached for the fd.
+ */
+
+ res = 0;
+ if (events & EV_READ)
+ res |= POLLIN;
+ if (events & EV_WRITE)
+ res |= POLLOUT;
+
+ if (devpoll_queue(devpollop, fd, res) != 0)
+ return (-1);
+
+ return (0);
+}
+
+static int
+devpoll_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct devpollop *devpollop = base->evbase;
+ int res;
+ (void)p;
+
+ res = 0;
+ if (events & EV_READ)
+ res |= POLLIN;
+ if (events & EV_WRITE)
+ res |= POLLOUT;
+
+ /*
+ * The only way to remove an fd from the /dev/poll monitored set is
+ * to use POLLREMOVE by itself. This removes ALL events for the fd
+ * provided so if we care about two events and are only removing one
+ * we must re-add the other event after POLLREMOVE.
+ */
+
+ if (devpoll_queue(devpollop, fd, POLLREMOVE) != 0)
+ return (-1);
+
+ if ((res & (POLLIN|POLLOUT)) != (POLLIN|POLLOUT)) {
+ /*
+ * We're not deleting all events, so we must resubmit the
+ * event that we are still interested in if one exists.
+ */
+
+ if ((res & POLLIN) && (old & EV_WRITE)) {
+ /* Deleting read, still care about write */
+ devpoll_queue(devpollop, fd, POLLOUT);
+ } else if ((res & POLLOUT) && (old & EV_READ)) {
+ /* Deleting write, still care about read */
+ devpoll_queue(devpollop, fd, POLLIN);
+ }
+ }
+
+ return (0);
+}
+
+static void
+devpoll_dealloc(struct event_base *base)
+{
+ struct devpollop *devpollop = base->evbase;
+
+ evsig_dealloc_(base);
+ if (devpollop->events)
+ mm_free(devpollop->events);
+ if (devpollop->changes)
+ mm_free(devpollop->changes);
+ if (devpollop->dpfd >= 0)
+ close(devpollop->dpfd);
+
+ memset(devpollop, 0, sizeof(struct devpollop));
+ mm_free(devpollop);
+}
+
+#endif /* EVENT__HAVE_DEVPOLL */
diff --git a/ipc/chromium/src/third_party/libevent/doxygen.am b/ipc/chromium/src/third_party/libevent/doxygen.am
new file mode 100644
index 0000000000..916d7c4079
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/doxygen.am
@@ -0,0 +1,55 @@
+# Doxygen documentation will not be generated with default configuration,
+# unless '--enable-doxygen-doc' is configured.
+# The following targets are all about doxygen:
+# make # 'make doxygen' would be auto executed
+# make doxygen # generating doxygen documentation
+# make doxygen-doc # same as 'make doxygen'
+# make clean # clean docs generated by doxygen
+# make install # install doxygen documentation
+# make uninstall # uninstall doxygen documentation
+
+if ENABLE_DOXYGEN
+
+# Add all needed rules defined in ax_prog_doxygen.m4
+@DX_RULES@
+
+# Use 'make clean' to clean docs generated by doxygen.
+clean-local:
+ -rm -rf $(DX_CLEANFILES)
+
+# integrate doxygen with automake targets
+man3_MANS = @DX_DOCDIR@/man/man3/*
+$(man3_MANS): doxygen-doc
+
+# Docs will be installed. It may be one or more docs supported
+# by doxygen, but does not include 'man'.
+docdirs = $(DX_INSTALL_DOCS)
+
+# Rules for installing docs generated by doxygen into $(htmldir),
+# The typical value of $(htmldir) is '/usr/local/share/doc/$(PACKAGE)'
+install-data-local:
+ @if ! test -d "$(DESTDIR)$(htmldir)"; then \
+ echo "$(mkinstalldirs) '$(DESTDIR)$(htmldir)'"; \
+ $(mkinstalldirs) '$(DESTDIR)$(htmldir)'; \
+ fi
+ @for d in $(docdirs); do \
+ echo "cp -pR $$d '$(DESTDIR)$(htmldir)/'"; \
+ cp -pR $$d '$(DESTDIR)$(htmldir)/'; \
+ done
+
+# Rules for uninstalling docs generated by doxygen from $(htmldir)
+uninstall-local:
+ @for d in $(docdirs); do \
+ d=`basename $$d`; \
+ echo "test ! -d '$(DESTDIR)$(htmldir)/'$$d || \
+ { find '$(DESTDIR)$(htmldir)/'$$d -type d ! -perm -200 -exec chmod u+w '{}' ';' && \
+ rm -rf '$(DESTDIR)$(htmldir)/'$$d; }"; \
+ test ! -d '$(DESTDIR)$(htmldir)/'$$d || \
+ { find '$(DESTDIR)$(htmldir)/'$$d -type d ! -perm -200 -exec chmod u+w '{}' ';' && \
+ rm -rf '$(DESTDIR)$(htmldir)/'$$d; }; \
+ done
+ rmdir "$(DESTDIR)$(htmldir)/" || true
+
+doxygen: doxygen-doc
+
+endif ENABLE_DOXYGEN
diff --git a/ipc/chromium/src/third_party/libevent/epoll.c b/ipc/chromium/src/third_party/libevent/epoll.c
new file mode 100644
index 0000000000..bdec2e4569
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/epoll.c
@@ -0,0 +1,545 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_EPOLL
+
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/resource.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/epoll.h>
+#include <signal.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIMERFD_H
+#include <sys/timerfd.h>
+#endif
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "changelist-internal.h"
+#include "time-internal.h"
+
+/* Since Linux 2.6.17, epoll is able to report about peer half-closed connection
+ using special EPOLLRDHUP flag on a read event.
+*/
+#if !defined(EPOLLRDHUP)
+#define EPOLLRDHUP 0
+#define EARLY_CLOSE_IF_HAVE_RDHUP 0
+#else
+#define EARLY_CLOSE_IF_HAVE_RDHUP EV_FEATURE_EARLY_CLOSE
+#endif
+
+#include "epolltable-internal.h"
+
+#if defined(EVENT__HAVE_SYS_TIMERFD_H) && \
+ defined(EVENT__HAVE_TIMERFD_CREATE) && \
+ defined(HAVE_POSIX_MONOTONIC) && defined(TFD_NONBLOCK) && \
+ defined(TFD_CLOEXEC)
+/* Note that we only use timerfd if TFD_NONBLOCK and TFD_CLOEXEC are available
+ and working. This means that we can't support it on 2.6.25 (where timerfd
+ was introduced) or 2.6.26, since 2.6.27 introduced those flags.
+ */
+#define USING_TIMERFD
+#endif
+
+struct epollop {
+ struct epoll_event *events;
+ int nevents;
+ int epfd;
+#ifdef USING_TIMERFD
+ int timerfd;
+#endif
+};
+
+static void *epoll_init(struct event_base *);
+static int epoll_dispatch(struct event_base *, struct timeval *);
+static void epoll_dealloc(struct event_base *);
+
+static const struct eventop epollops_changelist = {
+ "epoll (with changelist)",
+ epoll_init,
+ event_changelist_add_,
+ event_changelist_del_,
+ epoll_dispatch,
+ epoll_dealloc,
+ 1, /* need reinit */
+ EV_FEATURE_ET|EV_FEATURE_O1| EARLY_CLOSE_IF_HAVE_RDHUP,
+ EVENT_CHANGELIST_FDINFO_SIZE
+};
+
+
+static int epoll_nochangelist_add(struct event_base *base, evutil_socket_t fd,
+ short old, short events, void *p);
+static int epoll_nochangelist_del(struct event_base *base, evutil_socket_t fd,
+ short old, short events, void *p);
+
+const struct eventop epollops = {
+ "epoll",
+ epoll_init,
+ epoll_nochangelist_add,
+ epoll_nochangelist_del,
+ epoll_dispatch,
+ epoll_dealloc,
+ 1, /* need reinit */
+ EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_EARLY_CLOSE,
+ 0
+};
+
+#define INITIAL_NEVENT 32
+#define MAX_NEVENT 4096
+
+/* On Linux kernels at least up to 2.6.24.4, epoll can't handle timeout
+ * values bigger than (LONG_MAX - 999ULL)/HZ. HZ in the wild can be
+ * as big as 1000, and LONG_MAX can be as small as (1<<31)-1, so the
+ * largest number of msec we can support here is 2147482. Let's
+ * round that down by 47 seconds.
+ */
+#define MAX_EPOLL_TIMEOUT_MSEC (35*60*1000)
+
+static void *
+epoll_init(struct event_base *base)
+{
+ int epfd = -1;
+ struct epollop *epollop;
+
+#ifdef EVENT__HAVE_EPOLL_CREATE1
+ /* First, try the shiny new epoll_create1 interface, if we have it. */
+ epfd = epoll_create1(EPOLL_CLOEXEC);
+#endif
+ if (epfd == -1) {
+ /* Initialize the kernel queue using the old interface. (The
+ size field is ignored since 2.6.8.) */
+ if ((epfd = epoll_create(32000)) == -1) {
+ if (errno != ENOSYS)
+ event_warn("epoll_create");
+ return (NULL);
+ }
+ evutil_make_socket_closeonexec(epfd);
+ }
+
+ if (!(epollop = mm_calloc(1, sizeof(struct epollop)))) {
+ close(epfd);
+ return (NULL);
+ }
+
+ epollop->epfd = epfd;
+
+ /* Initialize fields */
+ epollop->events = mm_calloc(INITIAL_NEVENT, sizeof(struct epoll_event));
+ if (epollop->events == NULL) {
+ mm_free(epollop);
+ close(epfd);
+ return (NULL);
+ }
+ epollop->nevents = INITIAL_NEVENT;
+
+ if ((base->flags & EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST) != 0 ||
+ ((base->flags & EVENT_BASE_FLAG_IGNORE_ENV) == 0 &&
+ evutil_getenv_("EVENT_EPOLL_USE_CHANGELIST") != NULL)) {
+
+ base->evsel = &epollops_changelist;
+ }
+
+#ifdef USING_TIMERFD
+ /*
+ The epoll interface ordinarily gives us one-millisecond precision,
+ so on Linux it makes perfect sense to use the CLOCK_MONOTONIC_COARSE
+ timer. But when the user has set the new PRECISE_TIMER flag for an
+ event_base, we can try to use timerfd to give them finer granularity.
+ */
+ if ((base->flags & EVENT_BASE_FLAG_PRECISE_TIMER) &&
+ base->monotonic_timer.monotonic_clock == CLOCK_MONOTONIC) {
+ int fd;
+ fd = epollop->timerfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
+ if (epollop->timerfd >= 0) {
+ struct epoll_event epev;
+ memset(&epev, 0, sizeof(epev));
+ epev.data.fd = epollop->timerfd;
+ epev.events = EPOLLIN;
+ if (epoll_ctl(epollop->epfd, EPOLL_CTL_ADD, fd, &epev) < 0) {
+ event_warn("epoll_ctl(timerfd)");
+ close(fd);
+ epollop->timerfd = -1;
+ }
+ } else {
+ if (errno != EINVAL && errno != ENOSYS) {
+ /* These errors probably mean that we were
+ * compiled with timerfd/TFD_* support, but
+ * we're running on a kernel that lacks those.
+ */
+ event_warn("timerfd_create");
+ }
+ epollop->timerfd = -1;
+ }
+ } else {
+ epollop->timerfd = -1;
+ }
+#endif
+
+ evsig_init_(base);
+
+ return (epollop);
+}
+
+static const char *
+change_to_string(int change)
+{
+ change &= (EV_CHANGE_ADD|EV_CHANGE_DEL);
+ if (change == EV_CHANGE_ADD) {
+ return "add";
+ } else if (change == EV_CHANGE_DEL) {
+ return "del";
+ } else if (change == 0) {
+ return "none";
+ } else {
+ return "???";
+ }
+}
+
+static const char *
+epoll_op_to_string(int op)
+{
+ return op == EPOLL_CTL_ADD?"ADD":
+ op == EPOLL_CTL_DEL?"DEL":
+ op == EPOLL_CTL_MOD?"MOD":
+ "???";
+}
+
+#define PRINT_CHANGES(op, events, ch, status) \
+ "Epoll %s(%d) on fd %d " status ". " \
+ "Old events were %d; " \
+ "read change was %d (%s); " \
+ "write change was %d (%s); " \
+ "close change was %d (%s)", \
+ epoll_op_to_string(op), \
+ events, \
+ ch->fd, \
+ ch->old_events, \
+ ch->read_change, \
+ change_to_string(ch->read_change), \
+ ch->write_change, \
+ change_to_string(ch->write_change), \
+ ch->close_change, \
+ change_to_string(ch->close_change)
+
+static int
+epoll_apply_one_change(struct event_base *base,
+ struct epollop *epollop,
+ const struct event_change *ch)
+{
+ struct epoll_event epev;
+ int op, events = 0;
+ int idx;
+
+ idx = EPOLL_OP_TABLE_INDEX(ch);
+ op = epoll_op_table[idx].op;
+ events = epoll_op_table[idx].events;
+
+ if (!events) {
+ EVUTIL_ASSERT(op == 0);
+ return 0;
+ }
+
+ if ((ch->read_change|ch->write_change|ch->close_change) & EV_CHANGE_ET)
+ events |= EPOLLET;
+
+ memset(&epev, 0, sizeof(epev));
+ epev.data.fd = ch->fd;
+ epev.events = events;
+ if (epoll_ctl(epollop->epfd, op, ch->fd, &epev) == 0) {
+ event_debug((PRINT_CHANGES(op, epev.events, ch, "okay")));
+ return 0;
+ }
+
+ switch (op) {
+ case EPOLL_CTL_MOD:
+ if (errno == ENOENT) {
+ /* If a MOD operation fails with ENOENT, the
+ * fd was probably closed and re-opened. We
+ * should retry the operation as an ADD.
+ */
+ if (epoll_ctl(epollop->epfd, EPOLL_CTL_ADD, ch->fd, &epev) == -1) {
+ event_warn("Epoll MOD(%d) on %d retried as ADD; that failed too",
+ (int)epev.events, ch->fd);
+ return -1;
+ } else {
+ event_debug(("Epoll MOD(%d) on %d retried as ADD; succeeded.",
+ (int)epev.events,
+ ch->fd));
+ return 0;
+ }
+ }
+ break;
+ case EPOLL_CTL_ADD:
+ if (errno == EEXIST) {
+ /* If an ADD operation fails with EEXIST,
+ * either the operation was redundant (as with a
+ * precautionary add), or we ran into a fun
+ * kernel bug where using dup*() to duplicate the
+ * same file into the same fd gives you the same epitem
+ * rather than a fresh one. For the second case,
+ * we must retry with MOD. */
+ if (epoll_ctl(epollop->epfd, EPOLL_CTL_MOD, ch->fd, &epev) == -1) {
+ event_warn("Epoll ADD(%d) on %d retried as MOD; that failed too",
+ (int)epev.events, ch->fd);
+ return -1;
+ } else {
+ event_debug(("Epoll ADD(%d) on %d retried as MOD; succeeded.",
+ (int)epev.events,
+ ch->fd));
+ return 0;
+ }
+ }
+ break;
+ case EPOLL_CTL_DEL:
+ if (errno == ENOENT || errno == EBADF || errno == EPERM) {
+ /* If a delete fails with one of these errors,
+ * that's fine too: we closed the fd before we
+ * got around to calling epoll_dispatch. */
+ event_debug(("Epoll DEL(%d) on fd %d gave %s: DEL was unnecessary.",
+ (int)epev.events,
+ ch->fd,
+ strerror(errno)));
+ return 0;
+ }
+ break;
+ default:
+ break;
+ }
+
+ event_warn(PRINT_CHANGES(op, epev.events, ch, "failed"));
+ return -1;
+}
+
+static int
+epoll_apply_changes(struct event_base *base)
+{
+ struct event_changelist *changelist = &base->changelist;
+ struct epollop *epollop = base->evbase;
+ struct event_change *ch;
+
+ int r = 0;
+ int i;
+
+ for (i = 0; i < changelist->n_changes; ++i) {
+ ch = &changelist->changes[i];
+ if (epoll_apply_one_change(base, epollop, ch) < 0)
+ r = -1;
+ }
+
+ return (r);
+}
+
+static int
+epoll_nochangelist_add(struct event_base *base, evutil_socket_t fd,
+ short old, short events, void *p)
+{
+ struct event_change ch;
+ ch.fd = fd;
+ ch.old_events = old;
+ ch.read_change = ch.write_change = ch.close_change = 0;
+ if (events & EV_WRITE)
+ ch.write_change = EV_CHANGE_ADD |
+ (events & EV_ET);
+ if (events & EV_READ)
+ ch.read_change = EV_CHANGE_ADD |
+ (events & EV_ET);
+ if (events & EV_CLOSED)
+ ch.close_change = EV_CHANGE_ADD |
+ (events & EV_ET);
+
+ return epoll_apply_one_change(base, base->evbase, &ch);
+}
+
+static int
+epoll_nochangelist_del(struct event_base *base, evutil_socket_t fd,
+ short old, short events, void *p)
+{
+ struct event_change ch;
+ ch.fd = fd;
+ ch.old_events = old;
+ ch.read_change = ch.write_change = ch.close_change = 0;
+ if (events & EV_WRITE)
+ ch.write_change = EV_CHANGE_DEL |
+ (events & EV_ET);
+ if (events & EV_READ)
+ ch.read_change = EV_CHANGE_DEL |
+ (events & EV_ET);
+ if (events & EV_CLOSED)
+ ch.close_change = EV_CHANGE_DEL |
+ (events & EV_ET);
+
+ return epoll_apply_one_change(base, base->evbase, &ch);
+}
+
+static int
+epoll_dispatch(struct event_base *base, struct timeval *tv)
+{
+ struct epollop *epollop = base->evbase;
+ struct epoll_event *events = epollop->events;
+ int i, res;
+ long timeout = -1;
+
+#ifdef USING_TIMERFD
+ if (epollop->timerfd >= 0) {
+ struct itimerspec is;
+ is.it_interval.tv_sec = 0;
+ is.it_interval.tv_nsec = 0;
+ if (tv == NULL) {
+ /* No timeout; disarm the timer. */
+ is.it_value.tv_sec = 0;
+ is.it_value.tv_nsec = 0;
+ } else {
+ if (tv->tv_sec == 0 && tv->tv_usec == 0) {
+ /* we need to exit immediately; timerfd can't
+ * do that. */
+ timeout = 0;
+ }
+ is.it_value.tv_sec = tv->tv_sec;
+ is.it_value.tv_nsec = tv->tv_usec * 1000;
+ }
+ /* TODO: we could avoid unnecessary syscalls here by only
+ calling timerfd_settime when the top timeout changes, or
+ when we're called with a different timeval.
+ */
+ if (timerfd_settime(epollop->timerfd, 0, &is, NULL) < 0) {
+ event_warn("timerfd_settime");
+ }
+ } else
+#endif
+ if (tv != NULL) {
+ timeout = evutil_tv_to_msec_(tv);
+ if (timeout < 0 || timeout > MAX_EPOLL_TIMEOUT_MSEC) {
+ /* Linux kernels can wait forever if the timeout is
+ * too big; see comment on MAX_EPOLL_TIMEOUT_MSEC. */
+ timeout = MAX_EPOLL_TIMEOUT_MSEC;
+ }
+ }
+
+ epoll_apply_changes(base);
+ event_changelist_remove_all_(&base->changelist, base);
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = epoll_wait(epollop->epfd, events, epollop->nevents, timeout);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (res == -1) {
+ if (errno != EINTR) {
+ event_warn("epoll_wait");
+ return (-1);
+ }
+
+ return (0);
+ }
+
+ event_debug(("%s: epoll_wait reports %d", __func__, res));
+ EVUTIL_ASSERT(res <= epollop->nevents);
+
+ for (i = 0; i < res; i++) {
+ int what = events[i].events;
+ short ev = 0;
+#ifdef USING_TIMERFD
+ if (events[i].data.fd == epollop->timerfd)
+ continue;
+#endif
+
+ if (what & EPOLLERR) {
+ ev = EV_READ | EV_WRITE;
+ } else if ((what & EPOLLHUP) && !(what & EPOLLRDHUP)) {
+ ev = EV_READ | EV_WRITE;
+ } else {
+ if (what & EPOLLIN)
+ ev |= EV_READ;
+ if (what & EPOLLOUT)
+ ev |= EV_WRITE;
+ if (what & EPOLLRDHUP)
+ ev |= EV_CLOSED;
+ }
+
+ if (!ev)
+ continue;
+
+ evmap_io_active_(base, events[i].data.fd, ev | EV_ET);
+ }
+
+ if (res == epollop->nevents && epollop->nevents < MAX_NEVENT) {
+ /* We used all of the event space this time. We should
+ be ready for more events next time. */
+ int new_nevents = epollop->nevents * 2;
+ struct epoll_event *new_events;
+
+ new_events = mm_realloc(epollop->events,
+ new_nevents * sizeof(struct epoll_event));
+ if (new_events) {
+ epollop->events = new_events;
+ epollop->nevents = new_nevents;
+ }
+ }
+
+ return (0);
+}
+
+
+static void
+epoll_dealloc(struct event_base *base)
+{
+ struct epollop *epollop = base->evbase;
+
+ evsig_dealloc_(base);
+ if (epollop->events)
+ mm_free(epollop->events);
+ if (epollop->epfd >= 0)
+ close(epollop->epfd);
+#ifdef USING_TIMERFD
+ if (epollop->timerfd >= 0)
+ close(epollop->timerfd);
+#endif
+
+ memset(epollop, 0, sizeof(struct epollop));
+ mm_free(epollop);
+}
+
+#endif /* EVENT__HAVE_EPOLL */
diff --git a/ipc/chromium/src/third_party/libevent/epoll_sub.c b/ipc/chromium/src/third_party/libevent/epoll_sub.c
new file mode 100644
index 0000000000..3f01f6a699
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/epoll_sub.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2003-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "evconfig-private.h"
+#include <stdint.h>
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+#include <sys/epoll.h>
+#include <unistd.h>
+#include <errno.h>
+
+int
+epoll_create(int size)
+{
+#if !defined(__NR_epoll_create) && defined(__NR_epoll_create1)
+ if (size <= 0) {
+ errno = EINVAL;
+ return -1;
+ }
+ return (syscall(__NR_epoll_create1, 0));
+#else
+ return (syscall(__NR_epoll_create, size));
+#endif
+}
+
+int
+epoll_ctl(int epfd, int op, int fd, struct epoll_event *event)
+{
+
+ return (syscall(__NR_epoll_ctl, epfd, op, fd, event));
+}
+
+int
+epoll_wait(int epfd, struct epoll_event *events, int maxevents, int timeout)
+{
+#if !defined(__NR_epoll_wait) && defined(__NR_epoll_pwait)
+ return (syscall(__NR_epoll_pwait, epfd, events, maxevents, timeout, NULL, 0));
+#else
+ return (syscall(__NR_epoll_wait, epfd, events, maxevents, timeout));
+#endif
+}
diff --git a/ipc/chromium/src/third_party/libevent/epolltable-internal.h b/ipc/chromium/src/third_party/libevent/epolltable-internal.h
new file mode 100644
index 0000000000..73c2e3647e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/epolltable-internal.h
@@ -0,0 +1,1166 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EPOLLTABLE_INTERNAL_H_INCLUDED_
+#define EPOLLTABLE_INTERNAL_H_INCLUDED_
+
+/*
+ Here are the values we're masking off to decide what operations to do.
+ Note that since EV_READ|EV_WRITE.
+
+ Note also that this table is a little sparse, since ADD+DEL is
+ nonsensical ("xxx" in the list below.)
+
+ Note also that we are shifting old_events by only 5 bits, since
+ EV_READ is 2 and EV_WRITE is 4.
+
+ The table was auto-generated with a python script, according to this
+ pseudocode:[*0]
+
+ If either the read or the write change is add+del:
+ This is impossible; Set op==-1, events=0.
+ Else, if either the read or the write change is add:
+ Set events to 0.
+ If the read change is add, or
+ (the read change is not del, and ev_read is in old_events):
+ Add EPOLLIN to events.
+ If the write change is add, or
+ (the write change is not del, and ev_write is in old_events):
+ Add EPOLLOUT to events.
+
+ If old_events is set:
+ Set op to EPOLL_CTL_MOD [*1,*2]
+ Else:
+ Set op to EPOLL_CTL_ADD [*3]
+
+ Else, if the read or the write change is del:
+ Set op to EPOLL_CTL_DEL.
+ If the read change is del:
+ If the write change is del:
+ Set events to EPOLLIN|EPOLLOUT
+ Else if ev_write is in old_events:
+ Set events to EPOLLOUT
+ Set op to EPOLL_CTL_MOD
+ Else
+ Set events to EPOLLIN
+ Else:
+ {The write change is del.}
+ If ev_read is in old_events:
+ Set events to EPOLLIN
+ Set op to EPOLL_CTL_MOD
+ Else:
+ Set the events to EPOLLOUT
+
+ Else:
+ There is no read or write change; set op to 0 and events to 0.
+
+ The logic is a little tricky, since we had no events set on the fd before,
+ we need to set op="ADD" and set events=the events we want to add. If we
+ had any events set on the fd before, and we want any events to remain on
+ the fd, we need to say op="MOD" and set events=the events we want to
+ remain. But if we want to delete the last event, we say op="DEL" and
+ set events=(any non-null pointer).
+
+ [*0] Actually, the Python script has gotten a bit more complicated, to
+ support EPOLLRDHUP.
+
+ [*1] This MOD is only a guess. MOD might fail with ENOENT if the file was
+ closed and a new file was opened with the same fd. If so, we'll retry
+ with ADD.
+
+ [*2] We can't replace this with a no-op even if old_events is the same as
+ the new events: if the file was closed and reopened, we need to retry
+ with an ADD. (We do a MOD in this case since "no change" is more
+ common than "close and reopen", so we'll usually wind up doing 1
+ syscalls instead of 2.)
+
+ [*3] This ADD is only a guess. There is a fun Linux kernel issue where if
+ you have two fds for the same file (via dup) and you ADD one to an
+ epfd, then close it, then re-create it with the same fd (via dup2 or an
+ unlucky dup), then try to ADD it again, you'll get an EEXIST, since the
+ struct epitem is not actually removed from the struct eventpoll until
+ the file itself is closed.
+
+ EV_CHANGE_ADD==1
+ EV_CHANGE_DEL==2
+ EV_READ ==2
+ EV_WRITE ==4
+ EV_CLOSED ==0x80
+
+ Bit 0: close change is add
+ Bit 1: close change is del
+ Bit 2: read change is add
+ Bit 3: read change is del
+ Bit 4: write change is add
+ Bit 5: write change is del
+ Bit 6: old events had EV_READ
+ Bit 7: old events had EV_WRITE
+ Bit 8: old events had EV_CLOSED
+*/
+
+#define EPOLL_OP_TABLE_INDEX(c) \
+ ( (((c)->close_change&(EV_CHANGE_ADD|EV_CHANGE_DEL))) | \
+ (((c)->read_change&(EV_CHANGE_ADD|EV_CHANGE_DEL)) << 2) | \
+ (((c)->write_change&(EV_CHANGE_ADD|EV_CHANGE_DEL)) << 4) | \
+ (((c)->old_events&(EV_READ|EV_WRITE)) << 5) | \
+ (((c)->old_events&(EV_CLOSED)) << 1) \
+ )
+
+#if EV_READ != 2 || EV_WRITE != 4 || EV_CLOSED != 0x80 || EV_CHANGE_ADD != 1 || EV_CHANGE_DEL != 2
+#error "Libevent's internals changed! Regenerate the op_table in epolltable-internal.h"
+#endif
+
+static const struct operation {
+ int events;
+ int op;
+} epoll_op_table[] = {
+ /* old= 0, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= 0, write: 0, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write: 0, read: 0, close:del */
+ { EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= 0, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= 0, write: 0, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_ADD },
+ /* old= 0, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write: 0, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_ADD },
+ /* old= 0, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= 0, write: 0, read:del, close: 0 */
+ { EPOLLIN, EPOLL_CTL_DEL },
+ /* old= 0, write: 0, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write: 0, read:del, close:del */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= 0, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= 0, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= 0, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= 0, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= 0, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:add, read: 0, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:add, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_ADD },
+ /* old= 0, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= 0, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= 0, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:del, read: 0, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= 0, write:del, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:del, read: 0, close:del */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= 0, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:del, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_ADD },
+ /* old= 0, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_ADD },
+ /* old= 0, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:del, read:del, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= 0, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_ADD },
+ /* old= 0, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= 0, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= 0, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= 0, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= 0, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= 0, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= 0, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= r, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= r, write: 0, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= r, write: 0, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= r, write: 0, read:del, close: 0 */
+ { EPOLLIN, EPOLL_CTL_DEL },
+ /* old= r, write: 0, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write: 0, read:del, close:del */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= r, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= r, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= r, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= r, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= r, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= r, write:add, read: 0, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:add, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= r, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= r, write:add, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= r, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= r, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= r, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= r, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= r, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= r, write:del, read: 0, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write:del, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:del, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= r, write:del, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= r, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= r, write:del, read:del, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= r, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= r, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= r, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= r, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= r, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= r, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= r, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= r, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= r, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= r, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= r, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= r, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= r, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= r, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= r, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= r, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= r, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= r, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= r, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= r, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= r, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= r, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= r, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= w, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= w, write: 0, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= w, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= w, write: 0, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= w, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= w, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= w, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= w, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= w, write:add, read: 0, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:add, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= w, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= w, write:add, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= w, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= w, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= w, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= w, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= w, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= w, write:del, read: 0, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= w, write:del, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:del, read: 0, close:del */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= w, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= w, write:del, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= w, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= w, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= w, write:del, read:del, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= w, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= w, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= w, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= w, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= w, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= w, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= w, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= w, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= w, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= w, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= w, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= w, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= w, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= w, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= w, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= w, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= w, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= w, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= w, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= w, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= w, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= w, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= w, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= rw, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= rw, write: 0, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= rw, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= rw, write: 0, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= rw, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= rw, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= rw, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= rw, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:add, read: 0, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:add, read:del, close: 0 */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= rw, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= rw, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= rw, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:del, read: 0, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:del, read:add, close: 0 */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:del, read:del, close: 0 */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_DEL },
+ /* old= rw, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= rw, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= rw, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= rw, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= rw, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= rw, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= rw, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= rw, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= c, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= c, write: 0, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read: 0, close:del */
+ { EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= c, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= c, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= c, write: 0, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write: 0, read:del, close:del */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= c, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= c, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= c, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= c, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= c, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= c, write:add, read: 0, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= c, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= c, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= c, write:add, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= c, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= c, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= c, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= c, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= c, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= c, write:del, read: 0, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read: 0, close:del */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= c, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= c, write:del, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= c, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= c, write:del, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= c, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= c, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= c, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= c, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= c, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= c, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= c, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= c, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= c, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= c, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= c, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= c, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= c, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= c, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= c, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= c, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= c, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= c, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= c, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= c, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= c, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= c, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cr, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= cr, write: 0, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cr, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cr, write: 0, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write: 0, read:del, close:del */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= cr, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cr, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cr, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cr, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cr, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:add, read: 0, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:add, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cr, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cr, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cr, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:del, read: 0, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:del, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:del, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cr, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= cr, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cr, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cr, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= cr, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= cr, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cr, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cw, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old= cw, write: 0, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cw, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cw, write: 0, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cw, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cw, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cw, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cw, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:add, read: 0, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read: 0, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read: 0, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:add, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old= cw, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cw, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cw, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:del, read: 0, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read: 0, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read: 0, close:del */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= cw, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:del, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:del, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old= cw, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old= cw, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cw, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cw, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old= cw, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old= cw, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old= cw, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old=crw, write: 0, read: 0, close: 0 */
+ { 0, 0 },
+ /* old=crw, write: 0, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read: 0, close:xxx */
+ { 0, 255 },
+ /* old=crw, write: 0, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:add, close:xxx */
+ { 0, 255 },
+ /* old=crw, write: 0, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write: 0, read:del, close:xxx */
+ { 0, 255 },
+ /* old=crw, write: 0, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old=crw, write: 0, read:xxx, close:add */
+ { 0, 255 },
+ /* old=crw, write: 0, read:xxx, close:del */
+ { 0, 255 },
+ /* old=crw, write: 0, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:add, read: 0, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read: 0, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read: 0, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read: 0, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:add, read:add, close: 0 */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:add, close:add */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:add, close:del */
+ { EPOLLIN|EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:add, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:add, read:del, close: 0 */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:del, close:add */
+ { EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:del, close:del */
+ { EPOLLOUT, EPOLL_CTL_MOD },
+ /* old=crw, write:add, read:del, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:add, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:add, read:xxx, close:add */
+ { 0, 255 },
+ /* old=crw, write:add, read:xxx, close:del */
+ { 0, 255 },
+ /* old=crw, write:add, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:del, read: 0, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read: 0, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read: 0, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read: 0, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:del, read:add, close: 0 */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read:add, close:add */
+ { EPOLLIN|EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read:add, close:del */
+ { EPOLLIN, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read:add, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:del, read:del, close: 0 */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read:del, close:add */
+ { EPOLLRDHUP, EPOLL_CTL_MOD },
+ /* old=crw, write:del, read:del, close:del */
+ { EPOLLIN|EPOLLOUT|EPOLLRDHUP, EPOLL_CTL_DEL },
+ /* old=crw, write:del, read:del, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:del, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:del, read:xxx, close:add */
+ { 0, 255 },
+ /* old=crw, write:del, read:xxx, close:del */
+ { 0, 255 },
+ /* old=crw, write:del, read:xxx, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:xxx, read: 0, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:xxx, read: 0, close:add */
+ { 0, 255 },
+ /* old=crw, write:xxx, read: 0, close:del */
+ { 0, 255 },
+ /* old=crw, write:xxx, read: 0, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:add, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:add, close:add */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:add, close:del */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:add, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:del, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:del, close:add */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:del, close:del */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:del, close:xxx */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:xxx, close: 0 */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:xxx, close:add */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:xxx, close:del */
+ { 0, 255 },
+ /* old=crw, write:xxx, read:xxx, close:xxx */
+ { 0, 255 },
+};
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/evbuffer-internal.h b/ipc/chromium/src/third_party/libevent/evbuffer-internal.h
new file mode 100644
index 0000000000..d09b4f1ddd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evbuffer-internal.h
@@ -0,0 +1,351 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVBUFFER_INTERNAL_H_INCLUDED_
+#define EVBUFFER_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+#include "event2/util.h"
+#include "event2/event_struct.h"
+#include "util-internal.h"
+#include "defer-internal.h"
+
+/* Experimental cb flag: "never deferred." Implementation note:
+ * these callbacks may get an inaccurate view of n_del/n_added in their
+ * arguments. */
+#define EVBUFFER_CB_NODEFER 2
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+#include <sys/queue.h>
+
+/* Minimum allocation for a chain. We define this so that we're burning no
+ * more than 5% of each allocation on overhead. It would be nice to lose even
+ * less space, though. */
+#if EVENT__SIZEOF_VOID_P < 8
+#define MIN_BUFFER_SIZE 512
+#else
+#define MIN_BUFFER_SIZE 1024
+#endif
+
+/** A single evbuffer callback for an evbuffer. This function will be invoked
+ * when bytes are added to or removed from the evbuffer. */
+struct evbuffer_cb_entry {
+ /** Structures to implement a doubly-linked queue of callbacks */
+ LIST_ENTRY(evbuffer_cb_entry) next;
+ /** The callback function to invoke when this callback is called.
+ If EVBUFFER_CB_OBSOLETE is set in flags, the cb_obsolete field is
+ valid; otherwise, cb_func is valid. */
+ union {
+ evbuffer_cb_func cb_func;
+ evbuffer_cb cb_obsolete;
+ } cb;
+ /** Argument to pass to cb. */
+ void *cbarg;
+ /** Currently set flags on this callback. */
+ ev_uint32_t flags;
+};
+
+struct bufferevent;
+struct evbuffer_chain;
+struct evbuffer {
+ /** The first chain in this buffer's linked list of chains. */
+ struct evbuffer_chain *first;
+ /** The last chain in this buffer's linked list of chains. */
+ struct evbuffer_chain *last;
+
+ /** Pointer to the next pointer pointing at the 'last_with_data' chain.
+ *
+ * To unpack:
+ *
+ * The last_with_data chain is the last chain that has any data in it.
+ * If all chains in the buffer are empty, it is the first chain.
+ * If the buffer has no chains, it is NULL.
+ *
+ * The last_with_datap pointer points at _whatever 'next' pointer_
+ * pointing at the last_with_data chain. If the last_with_data chain
+ * is the first chain, or it is NULL, then the last_with_datap pointer
+ * is &buf->first.
+ */
+ struct evbuffer_chain **last_with_datap;
+
+ /** Total amount of bytes stored in all chains.*/
+ size_t total_len;
+
+ /** Number of bytes we have added to the buffer since we last tried to
+ * invoke callbacks. */
+ size_t n_add_for_cb;
+ /** Number of bytes we have removed from the buffer since we last
+ * tried to invoke callbacks. */
+ size_t n_del_for_cb;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ /** A lock used to mediate access to this buffer. */
+ void *lock;
+#endif
+ /** True iff we should free the lock field when we free this
+ * evbuffer. */
+ unsigned own_lock : 1;
+ /** True iff we should not allow changes to the front of the buffer
+ * (drains or prepends). */
+ unsigned freeze_start : 1;
+ /** True iff we should not allow changes to the end of the buffer
+ * (appends) */
+ unsigned freeze_end : 1;
+ /** True iff this evbuffer's callbacks are not invoked immediately
+ * upon a change in the buffer, but instead are deferred to be invoked
+ * from the event_base's loop. Useful for preventing enormous stack
+ * overflows when we have mutually recursive callbacks, and for
+ * serializing callbacks in a single thread. */
+ unsigned deferred_cbs : 1;
+#ifdef _WIN32
+ /** True iff this buffer is set up for overlapped IO. */
+ unsigned is_overlapped : 1;
+#endif
+ /** Zero or more EVBUFFER_FLAG_* bits */
+ ev_uint32_t flags;
+
+ /** Used to implement deferred callbacks. */
+ struct event_base *cb_queue;
+
+ /** A reference count on this evbuffer. When the reference count
+ * reaches 0, the buffer is destroyed. Manipulated with
+ * evbuffer_incref and evbuffer_decref_and_unlock and
+ * evbuffer_free. */
+ int refcnt;
+
+ /** A struct event_callback handle to make all of this buffer's callbacks
+ * invoked from the event loop. */
+ struct event_callback deferred;
+
+ /** A doubly-linked-list of callback functions */
+ LIST_HEAD(evbuffer_cb_queue, evbuffer_cb_entry) callbacks;
+
+ /** The parent bufferevent object this evbuffer belongs to.
+ * NULL if the evbuffer stands alone. */
+ struct bufferevent *parent;
+};
+
+#if EVENT__SIZEOF_OFF_T < EVENT__SIZEOF_SIZE_T
+typedef ev_ssize_t ev_misalign_t;
+#define EVBUFFER_CHAIN_MAX ((size_t)EV_SSIZE_MAX)
+#else
+typedef ev_off_t ev_misalign_t;
+#if EVENT__SIZEOF_OFF_T > EVENT__SIZEOF_SIZE_T
+#define EVBUFFER_CHAIN_MAX EV_SIZE_MAX
+#else
+#define EVBUFFER_CHAIN_MAX ((size_t)EV_SSIZE_MAX)
+#endif
+#endif
+
+/** A single item in an evbuffer. */
+struct evbuffer_chain {
+ /** points to next buffer in the chain */
+ struct evbuffer_chain *next;
+
+ /** total allocation available in the buffer field. */
+ size_t buffer_len;
+
+ /** unused space at the beginning of buffer or an offset into a
+ * file for sendfile buffers. */
+ ev_misalign_t misalign;
+
+ /** Offset into buffer + misalign at which to start writing.
+ * In other words, the total number of bytes actually stored
+ * in buffer. */
+ size_t off;
+
+ /** Set if special handling is required for this chain */
+ unsigned flags;
+#define EVBUFFER_FILESEGMENT 0x0001 /**< A chain used for a file segment */
+#define EVBUFFER_SENDFILE 0x0002 /**< a chain used with sendfile */
+#define EVBUFFER_REFERENCE 0x0004 /**< a chain with a mem reference */
+#define EVBUFFER_IMMUTABLE 0x0008 /**< read-only chain */
+ /** a chain that mustn't be reallocated or freed, or have its contents
+ * memmoved, until the chain is un-pinned. */
+#define EVBUFFER_MEM_PINNED_R 0x0010
+#define EVBUFFER_MEM_PINNED_W 0x0020
+#define EVBUFFER_MEM_PINNED_ANY (EVBUFFER_MEM_PINNED_R|EVBUFFER_MEM_PINNED_W)
+ /** a chain that should be freed, but can't be freed until it is
+ * un-pinned. */
+#define EVBUFFER_DANGLING 0x0040
+ /** a chain that is a referenced copy of another chain */
+#define EVBUFFER_MULTICAST 0x0080
+
+ /** number of references to this chain */
+ int refcnt;
+
+ /** Usually points to the read-write memory belonging to this
+ * buffer allocated as part of the evbuffer_chain allocation.
+ * For mmap, this can be a read-only buffer and
+ * EVBUFFER_IMMUTABLE will be set in flags. For sendfile, it
+ * may point to NULL.
+ */
+ unsigned char *buffer;
+};
+
+/** callback for a reference chain; lets us know what to do with it when
+ * we're done with it. Lives at the end of an evbuffer_chain with the
+ * EVBUFFER_REFERENCE flag set */
+struct evbuffer_chain_reference {
+ evbuffer_ref_cleanup_cb cleanupfn;
+ void *extra;
+};
+
+/** File segment for a file-segment chain. Lives at the end of an
+ * evbuffer_chain with the EVBUFFER_FILESEGMENT flag set. */
+struct evbuffer_chain_file_segment {
+ struct evbuffer_file_segment *segment;
+#ifdef _WIN32
+ /** If we're using CreateFileMapping, this is the handle to the view. */
+ HANDLE view_handle;
+#endif
+};
+
+/* Declared in event2/buffer.h; defined here. */
+struct evbuffer_file_segment {
+ void *lock; /**< lock prevent concurrent access to refcnt */
+ int refcnt; /**< Reference count for this file segment */
+ unsigned flags; /**< combination of EVBUF_FS_* flags */
+
+ /** What kind of file segment is this? */
+ unsigned can_sendfile : 1;
+ unsigned is_mapping : 1;
+
+ /** The fd that we read the data from. */
+ int fd;
+ /** If we're using mmap, this is the raw mapped memory. */
+ void *mapping;
+#ifdef _WIN32
+ /** If we're using CreateFileMapping, this is the mapping */
+ HANDLE mapping_handle;
+#endif
+ /** If we're using mmap or IO, this is the content of the file
+ * segment. */
+ char *contents;
+ /** Position of this segment within the file. */
+ ev_off_t file_offset;
+ /** If we're using mmap, this is the offset within 'mapping' where
+ * this data segment begins. */
+ ev_off_t mmap_offset;
+ /** The length of this segment. */
+ ev_off_t length;
+ /** Cleanup callback function */
+ evbuffer_file_segment_cleanup_cb cleanup_cb;
+ /** Argument to be pass to cleanup callback function */
+ void *cleanup_cb_arg;
+};
+
+/** Information about the multicast parent of a chain. Lives at the
+ * end of an evbuffer_chain with the EVBUFFER_MULTICAST flag set. */
+struct evbuffer_multicast_parent {
+ /** source buffer the multicast parent belongs to */
+ struct evbuffer *source;
+ /** multicast parent for this chain */
+ struct evbuffer_chain *parent;
+};
+
+#define EVBUFFER_CHAIN_SIZE sizeof(struct evbuffer_chain)
+/** Return a pointer to extra data allocated along with an evbuffer. */
+#define EVBUFFER_CHAIN_EXTRA(t, c) (t *)((struct evbuffer_chain *)(c) + 1)
+
+/** Assert that we are holding the lock on an evbuffer */
+#define ASSERT_EVBUFFER_LOCKED(buffer) \
+ EVLOCK_ASSERT_LOCKED((buffer)->lock)
+
+#define EVBUFFER_LOCK(buffer) \
+ do { \
+ EVLOCK_LOCK((buffer)->lock, 0); \
+ } while (0)
+#define EVBUFFER_UNLOCK(buffer) \
+ do { \
+ EVLOCK_UNLOCK((buffer)->lock, 0); \
+ } while (0)
+#define EVBUFFER_LOCK2(buffer1, buffer2) \
+ do { \
+ EVLOCK_LOCK2((buffer1)->lock, (buffer2)->lock, 0, 0); \
+ } while (0)
+#define EVBUFFER_UNLOCK2(buffer1, buffer2) \
+ do { \
+ EVLOCK_UNLOCK2((buffer1)->lock, (buffer2)->lock, 0, 0); \
+ } while (0)
+
+/** Increase the reference count of buf by one. */
+void evbuffer_incref_(struct evbuffer *buf);
+/** Increase the reference count of buf by one and acquire the lock. */
+void evbuffer_incref_and_lock_(struct evbuffer *buf);
+/** Pin a single buffer chain using a given flag. A pinned chunk may not be
+ * moved or freed until it is unpinned. */
+void evbuffer_chain_pin_(struct evbuffer_chain *chain, unsigned flag);
+/** Unpin a single buffer chain using a given flag. */
+void evbuffer_chain_unpin_(struct evbuffer_chain *chain, unsigned flag);
+/** As evbuffer_free, but requires that we hold a lock on the buffer, and
+ * releases the lock before freeing it and the buffer. */
+void evbuffer_decref_and_unlock_(struct evbuffer *buffer);
+
+/** As evbuffer_expand, but does not guarantee that the newly allocated memory
+ * is contiguous. Instead, it may be split across two or more chunks. */
+int evbuffer_expand_fast_(struct evbuffer *, size_t, int);
+
+/** Helper: prepares for a readv/WSARecv call by expanding the buffer to
+ * hold enough memory to read 'howmuch' bytes in possibly noncontiguous memory.
+ * Sets up the one or two iovecs in 'vecs' to point to the free memory and its
+ * extent, and *chainp to point to the first chain that we'll try to read into.
+ * Returns the number of vecs used.
+ */
+int evbuffer_read_setup_vecs_(struct evbuffer *buf, ev_ssize_t howmuch,
+ struct evbuffer_iovec *vecs, int n_vecs, struct evbuffer_chain ***chainp,
+ int exact);
+
+/* Helper macro: copies an evbuffer_iovec in ei to a win32 WSABUF in i. */
+#define WSABUF_FROM_EVBUFFER_IOV(i,ei) do { \
+ (i)->buf = (ei)->iov_base; \
+ (i)->len = (unsigned long)(ei)->iov_len; \
+ } while (0)
+/* XXXX the cast above is safe for now, but not if we allow mmaps on win64.
+ * See note in buffer_iocp's launch_write function */
+
+/** Set the parent bufferevent object for buf to bev */
+void evbuffer_set_parent_(struct evbuffer *buf, struct bufferevent *bev);
+
+void evbuffer_invoke_callbacks_(struct evbuffer *buf);
+
+
+int evbuffer_get_callbacks_(struct evbuffer *buffer,
+ struct event_callback **cbs,
+ int max_cbs);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVBUFFER_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/evconfig-private.h b/ipc/chromium/src/third_party/libevent/evconfig-private.h
new file mode 100644
index 0000000000..31e610040e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evconfig-private.h
@@ -0,0 +1,56 @@
+/* evconfig-private.h. Generated from evconfig-private.h.in by configure. */
+/* evconfig-private.h template - see "Configuration Header Templates" */
+/* in AC manual. Kevin Bowling <kevin.bowling@kev009.com */
+#ifndef EVCONFIG_PRIVATE_H_INCLUDED_
+#define EVCONFIG_PRIVATE_H_INCLUDED_
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+#ifndef _MINIX
+/* #undef _MINIX */
+#endif
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+#ifndef _POSIX_1_SOURCE
+/* #undef _POSIX_1_SOURCE */
+#endif
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#ifndef _POSIX_SOURCE
+/* #undef _POSIX_SOURCE */
+#endif
+
+/* Enable POSIX.2 extensions on QNX for getopt */
+#ifdef __QNX__
+# ifndef __EXT_POSIX2
+# define __EXT_POSIX2
+# endif
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/evconfig-private.h.cmake b/ipc/chromium/src/third_party/libevent/evconfig-private.h.cmake
new file mode 100644
index 0000000000..1adf9c03d1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evconfig-private.h.cmake
@@ -0,0 +1,40 @@
+
+#ifndef EVCONFIG_PRIVATE_H_INCLUDED_
+#define EVCONFIG_PRIVATE_H_INCLUDED_
+
+/* Enable extensions on AIX 3, Interix. */
+#cmakedefine _ALL_SOURCE
+
+/* Enable GNU extensions on systems that have them. */
+#cmakedefine _GNU_SOURCE 1
+
+/* Enable threading extensions on Solaris. */
+#cmakedefine _POSIX_PTHREAD_SEMANTICS 1
+
+/* Enable extensions on HP NonStop. */
+#cmakedefine _TANDEM_SOURCE 1
+
+/* Enable general extensions on Solaris. */
+#cmakedefine __EXTENSIONS__
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#cmakedefine _FILE_OFFSET_BITS 1
+/* Define for large files, on AIX-style hosts. */
+#cmakedefine _LARGE_FILES 1
+
+/* Define to 1 if on MINIX. */
+#cmakedefine _MINIX 1
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+#cmakedefine _POSIX_1_SOURCE 1
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#cmakedefine _POSIX_SOURCE 1
+
+/* Enable POSIX.2 extensions on QNX for getopt */
+#ifdef __QNX__
+#cmakedefine __EXT_POSIX2 1
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/evconfig-private.h.in b/ipc/chromium/src/third_party/libevent/evconfig-private.h.in
new file mode 100644
index 0000000000..8cd6478743
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evconfig-private.h.in
@@ -0,0 +1,55 @@
+/* evconfig-private.h template - see "Configuration Header Templates" */
+/* in AC manual. Kevin Bowling <kevin.bowling@kev009.com */
+#ifndef EVCONFIG_PRIVATE_H_INCLUDED_
+#define EVCONFIG_PRIVATE_H_INCLUDED_
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# undef _ALL_SOURCE
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# undef _GNU_SOURCE
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# undef _POSIX_PTHREAD_SEMANTICS
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# undef _TANDEM_SOURCE
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# undef __EXTENSIONS__
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#undef _FILE_OFFSET_BITS
+/* Define for large files, on AIX-style hosts. */
+#undef _LARGE_FILES
+
+/* Define to 1 if on MINIX. */
+#ifndef _MINIX
+#undef _MINIX
+#endif
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+#ifndef _POSIX_1_SOURCE
+#undef _POSIX_1_SOURCE
+#endif
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#ifndef _POSIX_SOURCE
+#undef _POSIX_SOURCE
+#endif
+
+/* Enable POSIX.2 extensions on QNX for getopt */
+#ifdef __QNX__
+# ifndef __EXT_POSIX2
+# define __EXT_POSIX2
+# endif
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/evdns.3 b/ipc/chromium/src/third_party/libevent/evdns.3
new file mode 100644
index 0000000000..10414fa2ef
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evdns.3
@@ -0,0 +1,322 @@
+.\"
+.\" Copyright (c) 2006 Niels Provos <provos@citi.umich.edu>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\" 3. The name of the author may not be used to endorse or promote products
+.\" derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+.\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+.\" AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+.\" THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+.\" EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+.\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+.\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+.\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+.\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd October 7, 2006
+.Dt EVDNS 3
+.Os
+.Sh NAME
+.Nm evdns_init
+.Nm evdns_shutdown
+.Nm evdns_err_to_string
+.Nm evdns_nameserver_add
+.Nm evdns_count_nameservers
+.Nm evdns_clear_nameservers_and_suspend
+.Nm evdns_resume
+.Nm evdns_nameserver_ip_add
+.Nm evdns_resolve_ipv4
+.Nm evdns_resolve_reverse
+.Nm evdns_resolv_conf_parse
+.Nm evdns_config_windows_nameservers
+.Nm evdns_search_clear
+.Nm evdns_search_add
+.Nm evdns_search_ndots_set
+.Nm evdns_set_log_fn
+.Nd asynchronous functions for DNS resolution.
+.Sh SYNOPSIS
+.Fd #include <sys/time.h>
+.Fd #include <event.h>
+.Fd #include <evdns.h>
+.Ft int
+.Fn evdns_init
+.Ft void
+.Fn evdns_shutdown "int fail_requests"
+.Ft "const char *"
+.Fn evdns_err_to_string "int err"
+.Ft int
+.Fn evdns_nameserver_add "unsigned long int address"
+.Ft int
+.Fn evdns_count_nameservers
+.Ft int
+.Fn evdns_clear_nameservers_and_suspend
+.Ft int
+.Fn evdns_resume
+.Ft int
+.Fn evdns_nameserver_ip_add(const char *ip_as_string);
+.Ft int
+.Fn evdns_resolve_ipv4 "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
+.Ft int
+.Fn evdns_resolve_reverse "struct in_addr *in" "int flags" "evdns_callback_type callback" "void *ptr"
+.Ft int
+.Fn evdns_resolv_conf_parse "int flags" "const char *"
+.Ft void
+.Fn evdns_search_clear
+.Ft void
+.Fn evdns_search_add "const char *domain"
+.Ft void
+.Fn evdns_search_ndots_set "const int ndots"
+.Ft void
+.Fn evdns_set_log_fn "evdns_debug_log_fn_type fn"
+.Ft int
+.Fn evdns_config_windows_nameservers
+.Sh DESCRIPTION
+Welcome, gentle reader
+.Pp
+Async DNS lookups are really a whole lot harder than they should be,
+mostly stemming from the fact that the libc resolver has never been
+very good at them. Before you use this library you should see if libc
+can do the job for you with the modern async call getaddrinfo_a
+(see http://www.imperialviolet.org/page25.html#e498). Otherwise,
+please continue.
+.Pp
+This code is based on libevent and you must call event_init before
+any of the APIs in this file. You must also seed the OpenSSL random
+source if you are using OpenSSL for ids (see below).
+.Pp
+This library is designed to be included and shipped with your source
+code. You statically link with it. You should also test for the
+existence of strtok_r and define HAVE_STRTOK_R if you have it.
+.Pp
+The DNS protocol requires a good source of id numbers and these
+numbers should be unpredictable for spoofing reasons. There are
+three methods for generating them here and you must define exactly
+one of them. In increasing order of preference:
+.Pp
+.Bl -tag -width "DNS_USE_GETTIMEOFDAY_FOR_ID" -compact -offset indent
+.It DNS_USE_GETTIMEOFDAY_FOR_ID
+Using the bottom 16 bits of the usec result from gettimeofday. This
+is a pretty poor solution but should work anywhere.
+.It DNS_USE_CPU_CLOCK_FOR_ID
+Using the bottom 16 bits of the nsec result from the CPU's time
+counter. This is better, but may not work everywhere. Requires
+POSIX realtime support and you'll need to link against -lrt on
+glibc systems at least.
+.It DNS_USE_OPENSSL_FOR_ID
+Uses the OpenSSL RAND_bytes call to generate the data. You must
+have seeded the pool before making any calls to this library.
+.El
+.Pp
+The library keeps track of the state of nameservers and will avoid
+them when they go down. Otherwise it will round robin between them.
+.Pp
+Quick start guide:
+ #include "evdns.h"
+ void callback(int result, char type, int count, int ttl,
+ void *addresses, void *arg);
+ evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
+ evdns_resolve("www.hostname.com", 0, callback, NULL);
+.Pp
+When the lookup is complete the callback function is called. The
+first argument will be one of the DNS_ERR_* defines in evdns.h.
+Hopefully it will be DNS_ERR_NONE, in which case type will be
+DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
+which the data can be cached for (in seconds), addresses will point
+to an array of uint32_t's and arg will be whatever you passed to
+evdns_resolve.
+.Pp
+Searching:
+.Pp
+In order for this library to be a good replacement for glibc's resolver it
+supports searching. This involves setting a list of default domains, in
+which names will be queried for. The number of dots in the query name
+determines the order in which this list is used.
+.Pp
+Searching appears to be a single lookup from the point of view of the API,
+although many DNS queries may be generated from a single call to
+evdns_resolve. Searching can also drastically slow down the resolution
+of names.
+.Pp
+To disable searching:
+.Bl -enum -compact -offset indent
+.It
+Never set it up. If you never call
+.Fn evdns_resolv_conf_parse,
+.Fn evdns_init,
+or
+.Fn evdns_search_add
+then no searching will occur.
+.It
+If you do call
+.Fn evdns_resolv_conf_parse
+then don't pass
+.Va DNS_OPTION_SEARCH
+(or
+.Va DNS_OPTIONS_ALL,
+which implies it).
+.It
+When calling
+.Fn evdns_resolve,
+pass the
+.Va DNS_QUERY_NO_SEARCH
+flag.
+.El
+.Pp
+The order of searches depends on the number of dots in the name. If the
+number is greater than the ndots setting then the names is first tried
+globally. Otherwise each search domain is appended in turn.
+.Pp
+The ndots setting can either be set from a resolv.conf, or by calling
+evdns_search_ndots_set.
+.Pp
+For example, with ndots set to 1 (the default) and a search domain list of
+["myhome.net"]:
+ Query: www
+ Order: www.myhome.net, www.
+.Pp
+ Query: www.abc
+ Order: www.abc., www.abc.myhome.net
+.Pp
+.Sh API reference
+.Pp
+.Bl -tag -width 0123456
+.It Ft int Fn evdns_init
+Initializes support for non-blocking name resolution by calling
+.Fn evdns_resolv_conf_parse
+on UNIX and
+.Fn evdns_config_windows_nameservers
+on Windows.
+.It Ft int Fn evdns_nameserver_add "unsigned long int address"
+Add a nameserver. The address should be an IP address in
+network byte order. The type of address is chosen so that
+it matches in_addr.s_addr.
+Returns non-zero on error.
+.It Ft int Fn evdns_nameserver_ip_add "const char *ip_as_string"
+This wraps the above function by parsing a string as an IP
+address and adds it as a nameserver.
+Returns non-zero on error
+.It Ft int Fn evdns_resolve "const char *name" "int flags" "evdns_callback_type callback" "void *ptr"
+Resolve a name. The name parameter should be a DNS name.
+The flags parameter should be 0, or DNS_QUERY_NO_SEARCH
+which disables searching for this query. (see defn of
+searching above).
+.Pp
+The callback argument is a function which is called when
+this query completes and ptr is an argument which is passed
+to that callback function.
+.Pp
+Returns non-zero on error
+.It Ft void Fn evdns_search_clear
+Clears the list of search domains
+.It Ft void Fn evdns_search_add "const char *domain"
+Add a domain to the list of search domains
+.It Ft void Fn evdns_search_ndots_set "int ndots"
+Set the number of dots which, when found in a name, causes
+the first query to be without any search domain.
+.It Ft int Fn evdns_count_nameservers "void"
+Return the number of configured nameservers (not necessarily the
+number of running nameservers). This is useful for double-checking
+whether our calls to the various nameserver configuration functions
+have been successful.
+.It Ft int Fn evdns_clear_nameservers_and_suspend "void"
+Remove all currently configured nameservers, and suspend all pending
+resolves. Resolves will not necessarily be re-attempted until
+evdns_resume() is called.
+.It Ft int Fn evdns_resume "void"
+Re-attempt resolves left in limbo after an earlier call to
+evdns_clear_nameservers_and_suspend().
+.It Ft int Fn evdns_config_windows_nameservers "void"
+Attempt to configure a set of nameservers based on platform settings on
+a win32 host. Preferentially tries to use GetNetworkParams; if that fails,
+looks in the registry. Returns 0 on success, nonzero on failure.
+.It Ft int Fn evdns_resolv_conf_parse "int flags" "const char *filename"
+Parse a resolv.conf like file from the given filename.
+.Pp
+See the man page for resolv.conf for the format of this file.
+The flags argument determines what information is parsed from
+this file:
+.Bl -tag -width "DNS_OPTION_NAMESERVERS" -offset indent -compact -nested
+.It DNS_OPTION_SEARCH
+domain, search and ndots options
+.It DNS_OPTION_NAMESERVERS
+nameserver lines
+.It DNS_OPTION_MISC
+timeout and attempts options
+.It DNS_OPTIONS_ALL
+all of the above
+.El
+.Pp
+The following directives are not parsed from the file:
+ sortlist, rotate, no-check-names, inet6, debug
+.Pp
+Returns non-zero on error:
+.Bl -tag -width "0" -offset indent -compact -nested
+.It 0
+no errors
+.It 1
+failed to open file
+.It 2
+failed to stat file
+.It 3
+file too large
+.It 4
+out of memory
+.It 5
+short read from file
+.El
+.El
+.Sh Internals:
+Requests are kept in two queues. The first is the inflight queue. In
+this queue requests have an allocated transaction id and nameserver.
+They will soon be transmitted if they haven't already been.
+.Pp
+The second is the waiting queue. The size of the inflight ring is
+limited and all other requests wait in waiting queue for space. This
+bounds the number of concurrent requests so that we don't flood the
+nameserver. Several algorithms require a full walk of the inflight
+queue and so bounding its size keeps thing going nicely under huge
+(many thousands of requests) loads.
+.Pp
+If a nameserver loses too many requests it is considered down and we
+try not to use it. After a while we send a probe to that nameserver
+(a lookup for google.com) and, if it replies, we consider it working
+again. If the nameserver fails a probe we wait longer to try again
+with the next probe.
+.Sh SEE ALSO
+.Xr event 3 ,
+.Xr gethostbyname 3 ,
+.Xr resolv.conf 5
+.Sh HISTORY
+The
+.Nm evdns
+API was developed by Adam Langley on top of the
+.Nm libevent
+API.
+The code was integrate into
+.Nm Tor
+by Nick Mathewson and finally put into
+.Nm libevent
+itself by Niels Provos.
+.Sh AUTHORS
+The
+.Nm evdns
+API and code was written by Adam Langley with significant
+contributions by Nick Mathewson.
+.Sh BUGS
+This documentation is neither complete nor authoritative.
+If you are in doubt about the usage of this API then
+check the source code to find out how it works, write
+up the missing piece of documentation and send it to
+me for inclusion in this man page.
diff --git a/ipc/chromium/src/third_party/libevent/evdns.c b/ipc/chromium/src/third_party/libevent/evdns.c
new file mode 100644
index 0000000000..a5b31a3c00
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evdns.c
@@ -0,0 +1,4847 @@
+/* Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Nick Mathewson and Niels Provos
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* Based on software by Adam Langly. Adam's original message:
+ *
+ * Async DNS Library
+ * Adam Langley <agl@imperialviolet.org>
+ * http://www.imperialviolet.org/eventdns.html
+ * Public Domain code
+ *
+ * This software is Public Domain. To view a copy of the public domain dedication,
+ * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
+ * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
+ *
+ * I ask and expect, but do not require, that all derivative works contain an
+ * attribution similar to:
+ * Parts developed by Adam Langley <agl@imperialviolet.org>
+ *
+ * You may wish to replace the word "Parts" with something else depending on
+ * the amount of original code.
+ *
+ * (Derivative works does not include programs which link against, run or include
+ * the source verbatim in their source distributions)
+ *
+ * Version: 0.1b
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifndef _FORTIFY_SOURCE
+#define _FORTIFY_SOURCE 3
+#endif
+
+#include <string.h>
+#include <fcntl.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+#include <sys/stat.h>
+#include <stdio.h>
+#include <stdarg.h>
+#ifdef _WIN32
+#include <winsock2.h>
+#include <winerror.h>
+#include <ws2tcpip.h>
+#ifndef _WIN32_IE
+#define _WIN32_IE 0x400
+#endif
+#include <shlobj.h>
+#endif
+
+#include "event2/dns.h"
+#include "event2/dns_struct.h"
+#include "event2/dns_compat.h"
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+
+#include "defer-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "strlcpy-internal.h"
+#include "ipv6-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+#ifdef _WIN32
+#include <ctype.h>
+#include <winsock2.h>
+#include <windows.h>
+#include <iphlpapi.h>
+#include <io.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#define EVDNS_LOG_DEBUG EVENT_LOG_DEBUG
+#define EVDNS_LOG_WARN EVENT_LOG_WARN
+#define EVDNS_LOG_MSG EVENT_LOG_MSG
+
+#ifndef HOST_NAME_MAX
+#define HOST_NAME_MAX 255
+#endif
+
+#include <stdio.h>
+
+#undef MIN
+#define MIN(a,b) ((a)<(b)?(a):(b))
+
+#define ASSERT_VALID_REQUEST(req) \
+ EVUTIL_ASSERT((req)->handle && (req)->handle->current_req == (req))
+
+#define u64 ev_uint64_t
+#define u32 ev_uint32_t
+#define u16 ev_uint16_t
+#define u8 ev_uint8_t
+
+/* maximum number of addresses from a single packet */
+/* that we bother recording */
+#define MAX_V4_ADDRS 32
+#define MAX_V6_ADDRS 32
+
+
+#define TYPE_A EVDNS_TYPE_A
+#define TYPE_CNAME 5
+#define TYPE_PTR EVDNS_TYPE_PTR
+#define TYPE_SOA EVDNS_TYPE_SOA
+#define TYPE_AAAA EVDNS_TYPE_AAAA
+
+#define CLASS_INET EVDNS_CLASS_INET
+
+/* Persistent handle. We keep this separate from 'struct request' since we
+ * need some object to last for as long as an evdns_request is outstanding so
+ * that it can be canceled, whereas a search request can lead to multiple
+ * 'struct request' instances being created over its lifetime. */
+struct evdns_request {
+ struct request *current_req;
+ struct evdns_base *base;
+
+ int pending_cb; /* Waiting for its callback to be invoked; not
+ * owned by event base any more. */
+
+ /* elements used by the searching code */
+ int search_index;
+ struct search_state *search_state;
+ char *search_origname; /* needs to be free()ed */
+ int search_flags;
+};
+
+struct request {
+ u8 *request; /* the dns packet data */
+ u8 request_type; /* TYPE_PTR or TYPE_A or TYPE_AAAA */
+ unsigned int request_len;
+ int reissue_count;
+ int tx_count; /* the number of times that this packet has been sent */
+ void *user_pointer; /* the pointer given to us for this request */
+ evdns_callback_type user_callback;
+ struct nameserver *ns; /* the server which we last sent it */
+
+ /* these objects are kept in a circular list */
+ /* XXX We could turn this into a CIRCLEQ. */
+ struct request *next, *prev;
+
+ struct event timeout_event;
+
+ u16 trans_id; /* the transaction id */
+ unsigned request_appended :1; /* true if the request pointer is data which follows this struct */
+ unsigned transmit_me :1; /* needs to be transmitted */
+
+ /* XXXX This is a horrible hack. */
+ char **put_cname_in_ptr; /* store the cname here if we get one. */
+
+ struct evdns_base *base;
+
+ struct evdns_request *handle;
+};
+
+struct reply {
+ unsigned int type;
+ unsigned int have_answer : 1;
+ union {
+ struct {
+ u32 addrcount;
+ u32 addresses[MAX_V4_ADDRS];
+ } a;
+ struct {
+ u32 addrcount;
+ struct in6_addr addresses[MAX_V6_ADDRS];
+ } aaaa;
+ struct {
+ char name[HOST_NAME_MAX];
+ } ptr;
+ } data;
+};
+
+struct nameserver {
+ evutil_socket_t socket; /* a connected UDP socket */
+ struct sockaddr_storage address;
+ ev_socklen_t addrlen;
+ int failed_times; /* number of times which we have given this server a chance */
+ int timedout; /* number of times in a row a request has timed out */
+ struct event event;
+ /* these objects are kept in a circular list */
+ struct nameserver *next, *prev;
+ struct event timeout_event; /* used to keep the timeout for */
+ /* when we next probe this server. */
+ /* Valid if state == 0 */
+ /* Outstanding probe request for this nameserver, if any */
+ struct evdns_request *probe_request;
+ char state; /* zero if we think that this server is down */
+ char choked; /* true if we have an EAGAIN from this server's socket */
+ char write_waiting; /* true if we are waiting for EV_WRITE events */
+ struct evdns_base *base;
+
+ /* Number of currently inflight requests: used
+ * to track when we should add/del the event. */
+ int requests_inflight;
+};
+
+
+/* Represents a local port where we're listening for DNS requests. Right now, */
+/* only UDP is supported. */
+struct evdns_server_port {
+ evutil_socket_t socket; /* socket we use to read queries and write replies. */
+ int refcnt; /* reference count. */
+ char choked; /* Are we currently blocked from writing? */
+ char closing; /* Are we trying to close this port, pending writes? */
+ evdns_request_callback_fn_type user_callback; /* Fn to handle requests */
+ void *user_data; /* Opaque pointer passed to user_callback */
+ struct event event; /* Read/write event */
+ /* circular list of replies that we want to write. */
+ struct server_request *pending_replies;
+ struct event_base *event_base;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ void *lock;
+#endif
+};
+
+/* Represents part of a reply being built. (That is, a single RR.) */
+struct server_reply_item {
+ struct server_reply_item *next; /* next item in sequence. */
+ char *name; /* name part of the RR */
+ u16 type; /* The RR type */
+ u16 class; /* The RR class (usually CLASS_INET) */
+ u32 ttl; /* The RR TTL */
+ char is_name; /* True iff data is a label */
+ u16 datalen; /* Length of data; -1 if data is a label */
+ void *data; /* The contents of the RR */
+};
+
+/* Represents a request that we've received as a DNS server, and holds */
+/* the components of the reply as we're constructing it. */
+struct server_request {
+ /* Pointers to the next and previous entries on the list of replies */
+ /* that we're waiting to write. Only set if we have tried to respond */
+ /* and gotten EAGAIN. */
+ struct server_request *next_pending;
+ struct server_request *prev_pending;
+
+ u16 trans_id; /* Transaction id. */
+ struct evdns_server_port *port; /* Which port received this request on? */
+ struct sockaddr_storage addr; /* Where to send the response */
+ ev_socklen_t addrlen; /* length of addr */
+
+ int n_answer; /* how many answer RRs have been set? */
+ int n_authority; /* how many authority RRs have been set? */
+ int n_additional; /* how many additional RRs have been set? */
+
+ struct server_reply_item *answer; /* linked list of answer RRs */
+ struct server_reply_item *authority; /* linked list of authority RRs */
+ struct server_reply_item *additional; /* linked list of additional RRs */
+
+ /* Constructed response. Only set once we're ready to send a reply. */
+ /* Once this is set, the RR fields are cleared, and no more should be set. */
+ char *response;
+ size_t response_len;
+
+ /* Caller-visible fields: flags, questions. */
+ struct evdns_server_request base;
+};
+
+struct evdns_base {
+ /* An array of n_req_heads circular lists for inflight requests.
+ * Each inflight request req is in req_heads[req->trans_id % n_req_heads].
+ */
+ struct request **req_heads;
+ /* A circular list of requests that we're waiting to send, but haven't
+ * sent yet because there are too many requests inflight */
+ struct request *req_waiting_head;
+ /* A circular list of nameservers. */
+ struct nameserver *server_head;
+ int n_req_heads;
+
+ struct event_base *event_base;
+
+ /* The number of good nameservers that we have */
+ int global_good_nameservers;
+
+ /* inflight requests are contained in the req_head list */
+ /* and are actually going out across the network */
+ int global_requests_inflight;
+ /* requests which aren't inflight are in the waiting list */
+ /* and are counted here */
+ int global_requests_waiting;
+
+ int global_max_requests_inflight;
+
+ struct timeval global_timeout; /* 5 seconds by default */
+ int global_max_reissues; /* a reissue occurs when we get some errors from the server */
+ int global_max_retransmits; /* number of times we'll retransmit a request which timed out */
+ /* number of timeouts in a row before we consider this server to be down */
+ int global_max_nameserver_timeout;
+ /* true iff we will use the 0x20 hack to prevent poisoning attacks. */
+ int global_randomize_case;
+
+ /* The first time that a nameserver fails, how long do we wait before
+ * probing to see if it has returned? */
+ struct timeval global_nameserver_probe_initial_timeout;
+
+ /** Port to bind to for outgoing DNS packets. */
+ struct sockaddr_storage global_outgoing_address;
+ /** ev_socklen_t for global_outgoing_address. 0 if it isn't set. */
+ ev_socklen_t global_outgoing_addrlen;
+
+ struct timeval global_getaddrinfo_allow_skew;
+
+ int so_rcvbuf;
+ int so_sndbuf;
+
+ int getaddrinfo_ipv4_timeouts;
+ int getaddrinfo_ipv6_timeouts;
+ int getaddrinfo_ipv4_answered;
+ int getaddrinfo_ipv6_answered;
+
+ struct search_state *global_search_state;
+
+ TAILQ_HEAD(hosts_list, hosts_entry) hostsdb;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ void *lock;
+#endif
+
+ int disable_when_inactive;
+};
+
+struct hosts_entry {
+ TAILQ_ENTRY(hosts_entry) next;
+ union {
+ struct sockaddr sa;
+ struct sockaddr_in sin;
+ struct sockaddr_in6 sin6;
+ } addr;
+ int addrlen;
+ char hostname[1];
+};
+
+static struct evdns_base *current_base = NULL;
+
+struct evdns_base *
+evdns_get_global_base(void)
+{
+ return current_base;
+}
+
+/* Given a pointer to an evdns_server_request, get the corresponding */
+/* server_request. */
+#define TO_SERVER_REQUEST(base_ptr) \
+ ((struct server_request*) \
+ (((char*)(base_ptr) - evutil_offsetof(struct server_request, base))))
+
+#define REQ_HEAD(base, id) ((base)->req_heads[id % (base)->n_req_heads])
+
+static struct nameserver *nameserver_pick(struct evdns_base *base);
+static void evdns_request_insert(struct request *req, struct request **head);
+static void evdns_request_remove(struct request *req, struct request **head);
+static void nameserver_ready_callback(evutil_socket_t fd, short events, void *arg);
+static int evdns_transmit(struct evdns_base *base);
+static int evdns_request_transmit(struct request *req);
+static void nameserver_send_probe(struct nameserver *const ns);
+static void search_request_finished(struct evdns_request *const);
+static int search_try_next(struct evdns_request *const req);
+static struct request *search_request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *const name, int flags, evdns_callback_type user_callback, void *user_arg);
+static void evdns_requests_pump_waiting_queue(struct evdns_base *base);
+static u16 transaction_id_pick(struct evdns_base *base);
+static struct request *request_new(struct evdns_base *base, struct evdns_request *handle, int type, const char *name, int flags, evdns_callback_type callback, void *ptr);
+static void request_submit(struct request *const req);
+
+static int server_request_free(struct server_request *req);
+static void server_request_free_answers(struct server_request *req);
+static void server_port_free(struct evdns_server_port *port);
+static void server_port_ready_callback(evutil_socket_t fd, short events, void *arg);
+static int evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename);
+static int evdns_base_set_option_impl(struct evdns_base *base,
+ const char *option, const char *val, int flags);
+static void evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests);
+static void evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg);
+
+static int strtoint(const char *const str);
+
+#ifdef EVENT__DISABLE_THREAD_SUPPORT
+#define EVDNS_LOCK(base) EVUTIL_NIL_STMT_
+#define EVDNS_UNLOCK(base) EVUTIL_NIL_STMT_
+#define ASSERT_LOCKED(base) EVUTIL_NIL_STMT_
+#else
+#define EVDNS_LOCK(base) \
+ EVLOCK_LOCK((base)->lock, 0)
+#define EVDNS_UNLOCK(base) \
+ EVLOCK_UNLOCK((base)->lock, 0)
+#define ASSERT_LOCKED(base) \
+ EVLOCK_ASSERT_LOCKED((base)->lock)
+#endif
+
+static evdns_debug_log_fn_type evdns_log_fn = NULL;
+
+void
+evdns_set_log_fn(evdns_debug_log_fn_type fn)
+{
+ evdns_log_fn = fn;
+}
+
+#ifdef __GNUC__
+#define EVDNS_LOG_CHECK __attribute__ ((format(printf, 2, 3)))
+#else
+#define EVDNS_LOG_CHECK
+#endif
+
+static void evdns_log_(int severity, const char *fmt, ...) EVDNS_LOG_CHECK;
+static void
+evdns_log_(int severity, const char *fmt, ...)
+{
+ va_list args;
+ va_start(args,fmt);
+ if (evdns_log_fn) {
+ char buf[512];
+ int is_warn = (severity == EVDNS_LOG_WARN);
+ evutil_vsnprintf(buf, sizeof(buf), fmt, args);
+ evdns_log_fn(is_warn, buf);
+ } else {
+ event_logv_(severity, NULL, fmt, args);
+ }
+ va_end(args);
+}
+
+#define log evdns_log_
+
+/* This walks the list of inflight requests to find the */
+/* one with a matching transaction id. Returns NULL on */
+/* failure */
+static struct request *
+request_find_from_trans_id(struct evdns_base *base, u16 trans_id) {
+ struct request *req = REQ_HEAD(base, trans_id);
+ struct request *const started_at = req;
+
+ ASSERT_LOCKED(base);
+
+ if (req) {
+ do {
+ if (req->trans_id == trans_id) return req;
+ req = req->next;
+ } while (req != started_at);
+ }
+
+ return NULL;
+}
+
+/* a libevent callback function which is called when a nameserver */
+/* has gone down and we want to test if it has came back to life yet */
+static void
+nameserver_prod_callback(evutil_socket_t fd, short events, void *arg) {
+ struct nameserver *const ns = (struct nameserver *) arg;
+ (void)fd;
+ (void)events;
+
+ EVDNS_LOCK(ns->base);
+ nameserver_send_probe(ns);
+ EVDNS_UNLOCK(ns->base);
+}
+
+/* a libevent callback which is called when a nameserver probe (to see if */
+/* it has come back to life) times out. We increment the count of failed_times */
+/* and wait longer to send the next probe packet. */
+static void
+nameserver_probe_failed(struct nameserver *const ns) {
+ struct timeval timeout;
+ int i;
+
+ ASSERT_LOCKED(ns->base);
+ (void) evtimer_del(&ns->timeout_event);
+ if (ns->state == 1) {
+ /* This can happen if the nameserver acts in a way which makes us mark */
+ /* it as bad and then starts sending good replies. */
+ return;
+ }
+
+#define MAX_PROBE_TIMEOUT 3600
+#define TIMEOUT_BACKOFF_FACTOR 3
+
+ memcpy(&timeout, &ns->base->global_nameserver_probe_initial_timeout,
+ sizeof(struct timeval));
+ for (i=ns->failed_times; i > 0 && timeout.tv_sec < MAX_PROBE_TIMEOUT; --i) {
+ timeout.tv_sec *= TIMEOUT_BACKOFF_FACTOR;
+ timeout.tv_usec *= TIMEOUT_BACKOFF_FACTOR;
+ if (timeout.tv_usec > 1000000) {
+ timeout.tv_sec += timeout.tv_usec / 1000000;
+ timeout.tv_usec %= 1000000;
+ }
+ }
+ if (timeout.tv_sec > MAX_PROBE_TIMEOUT) {
+ timeout.tv_sec = MAX_PROBE_TIMEOUT;
+ timeout.tv_usec = 0;
+ }
+
+ ns->failed_times++;
+
+ if (evtimer_add(&ns->timeout_event, &timeout) < 0) {
+ char addrbuf[128];
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer event for %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)));
+ }
+}
+
+static void
+request_swap_ns(struct request *req, struct nameserver *ns) {
+ if (ns && req->ns != ns) {
+ EVUTIL_ASSERT(req->ns->requests_inflight > 0);
+ req->ns->requests_inflight--;
+ ns->requests_inflight++;
+
+ req->ns = ns;
+ }
+}
+
+/* called when a nameserver has been deemed to have failed. For example, too */
+/* many packets have timed out etc */
+static void
+nameserver_failed(struct nameserver *const ns, const char *msg) {
+ struct request *req, *started_at;
+ struct evdns_base *base = ns->base;
+ int i;
+ char addrbuf[128];
+
+ ASSERT_LOCKED(base);
+ /* if this nameserver has already been marked as failed */
+ /* then don't do anything */
+ if (!ns->state) return;
+
+ log(EVDNS_LOG_MSG, "Nameserver %s has failed: %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)),
+ msg);
+
+ base->global_good_nameservers--;
+ EVUTIL_ASSERT(base->global_good_nameservers >= 0);
+ if (base->global_good_nameservers == 0) {
+ log(EVDNS_LOG_MSG, "All nameservers have failed");
+ }
+
+ ns->state = 0;
+ ns->failed_times = 1;
+
+ if (evtimer_add(&ns->timeout_event,
+ &base->global_nameserver_probe_initial_timeout) < 0) {
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer event for %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)));
+ /* ???? Do more? */
+ }
+
+ /* walk the list of inflight requests to see if any can be reassigned to */
+ /* a different server. Requests in the waiting queue don't have a */
+ /* nameserver assigned yet */
+
+ /* if we don't have *any* good nameservers then there's no point */
+ /* trying to reassign requests to one */
+ if (!base->global_good_nameservers) return;
+
+ for (i = 0; i < base->n_req_heads; ++i) {
+ req = started_at = base->req_heads[i];
+ if (req) {
+ do {
+ if (req->tx_count == 0 && req->ns == ns) {
+ /* still waiting to go out, can be moved */
+ /* to another server */
+ request_swap_ns(req, nameserver_pick(base));
+ }
+ req = req->next;
+ } while (req != started_at);
+ }
+ }
+}
+
+static void
+nameserver_up(struct nameserver *const ns)
+{
+ char addrbuf[128];
+ ASSERT_LOCKED(ns->base);
+ if (ns->state) return;
+ log(EVDNS_LOG_MSG, "Nameserver %s is back up",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)));
+ evtimer_del(&ns->timeout_event);
+ if (ns->probe_request) {
+ evdns_cancel_request(ns->base, ns->probe_request);
+ ns->probe_request = NULL;
+ }
+ ns->state = 1;
+ ns->failed_times = 0;
+ ns->timedout = 0;
+ ns->base->global_good_nameservers++;
+}
+
+static void
+request_trans_id_set(struct request *const req, const u16 trans_id) {
+ req->trans_id = trans_id;
+ *((u16 *) req->request) = htons(trans_id);
+}
+
+/* Called to remove a request from a list and dealloc it. */
+/* head is a pointer to the head of the list it should be */
+/* removed from or NULL if the request isn't in a list. */
+/* when free_handle is one, free the handle as well. */
+static void
+request_finished(struct request *const req, struct request **head, int free_handle) {
+ struct evdns_base *base = req->base;
+ int was_inflight = (head != &base->req_waiting_head);
+ EVDNS_LOCK(base);
+ ASSERT_VALID_REQUEST(req);
+
+ if (head)
+ evdns_request_remove(req, head);
+
+ log(EVDNS_LOG_DEBUG, "Removing timeout for request %p", req);
+ if (was_inflight) {
+ evtimer_del(&req->timeout_event);
+ base->global_requests_inflight--;
+ req->ns->requests_inflight--;
+ } else {
+ base->global_requests_waiting--;
+ }
+ /* it was initialized during request_new / evtimer_assign */
+ event_debug_unassign(&req->timeout_event);
+
+ if (req->ns &&
+ req->ns->requests_inflight == 0 &&
+ req->base->disable_when_inactive) {
+ event_del(&req->ns->event);
+ evtimer_del(&req->ns->timeout_event);
+ }
+
+ if (!req->request_appended) {
+ /* need to free the request data on it's own */
+ mm_free(req->request);
+ } else {
+ /* the request data is appended onto the header */
+ /* so everything gets free()ed when we: */
+ }
+
+ if (req->handle) {
+ EVUTIL_ASSERT(req->handle->current_req == req);
+
+ if (free_handle) {
+ search_request_finished(req->handle);
+ req->handle->current_req = NULL;
+ if (! req->handle->pending_cb) {
+ /* If we're planning to run the callback,
+ * don't free the handle until later. */
+ mm_free(req->handle);
+ }
+ req->handle = NULL; /* If we have a bug, let's crash
+ * early */
+ } else {
+ req->handle->current_req = NULL;
+ }
+ }
+
+ mm_free(req);
+
+ evdns_requests_pump_waiting_queue(base);
+ EVDNS_UNLOCK(base);
+}
+
+/* This is called when a server returns a funny error code. */
+/* We try the request again with another server. */
+/* */
+/* return: */
+/* 0 ok */
+/* 1 failed/reissue is pointless */
+static int
+request_reissue(struct request *req) {
+ const struct nameserver *const last_ns = req->ns;
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+ /* the last nameserver should have been marked as failing */
+ /* by the caller of this function, therefore pick will try */
+ /* not to return it */
+ request_swap_ns(req, nameserver_pick(req->base));
+ if (req->ns == last_ns) {
+ /* ... but pick did return it */
+ /* not a lot of point in trying again with the */
+ /* same server */
+ return 1;
+ }
+
+ req->reissue_count++;
+ req->tx_count = 0;
+ req->transmit_me = 1;
+
+ return 0;
+}
+
+/* this function looks for space on the inflight queue and promotes */
+/* requests from the waiting queue if it can. */
+/* */
+/* TODO: */
+/* add return code, see at nameserver_pick() and other functions. */
+static void
+evdns_requests_pump_waiting_queue(struct evdns_base *base) {
+ ASSERT_LOCKED(base);
+ while (base->global_requests_inflight < base->global_max_requests_inflight &&
+ base->global_requests_waiting) {
+ struct request *req;
+
+ EVUTIL_ASSERT(base->req_waiting_head);
+ req = base->req_waiting_head;
+
+ req->ns = nameserver_pick(base);
+ if (!req->ns)
+ return;
+
+ /* move a request from the waiting queue to the inflight queue */
+ req->ns->requests_inflight++;
+
+ evdns_request_remove(req, &base->req_waiting_head);
+
+ base->global_requests_waiting--;
+ base->global_requests_inflight++;
+
+ request_trans_id_set(req, transaction_id_pick(base));
+
+ evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
+ evdns_request_transmit(req);
+ evdns_transmit(base);
+ }
+}
+
+/* TODO(nickm) document */
+struct deferred_reply_callback {
+ struct event_callback deferred;
+ struct evdns_request *handle;
+ u8 request_type;
+ u8 have_reply;
+ u32 ttl;
+ u32 err;
+ evdns_callback_type user_callback;
+ struct reply reply;
+};
+
+static void
+reply_run_callback(struct event_callback *d, void *user_pointer)
+{
+ struct deferred_reply_callback *cb =
+ EVUTIL_UPCAST(d, struct deferred_reply_callback, deferred);
+
+ switch (cb->request_type) {
+ case TYPE_A:
+ if (cb->have_reply)
+ cb->user_callback(DNS_ERR_NONE, DNS_IPv4_A,
+ cb->reply.data.a.addrcount, cb->ttl,
+ cb->reply.data.a.addresses,
+ user_pointer);
+ else
+ cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+ break;
+ case TYPE_PTR:
+ if (cb->have_reply) {
+ char *name = cb->reply.data.ptr.name;
+ cb->user_callback(DNS_ERR_NONE, DNS_PTR, 1, cb->ttl,
+ &name, user_pointer);
+ } else {
+ cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+ }
+ break;
+ case TYPE_AAAA:
+ if (cb->have_reply)
+ cb->user_callback(DNS_ERR_NONE, DNS_IPv6_AAAA,
+ cb->reply.data.aaaa.addrcount, cb->ttl,
+ cb->reply.data.aaaa.addresses,
+ user_pointer);
+ else
+ cb->user_callback(cb->err, 0, 0, cb->ttl, NULL, user_pointer);
+ break;
+ default:
+ EVUTIL_ASSERT(0);
+ }
+
+ if (cb->handle && cb->handle->pending_cb) {
+ mm_free(cb->handle);
+ }
+
+ mm_free(cb);
+}
+
+static void
+reply_schedule_callback(struct request *const req, u32 ttl, u32 err, struct reply *reply)
+{
+ struct deferred_reply_callback *d = mm_calloc(1, sizeof(*d));
+
+ if (!d) {
+ event_warn("%s: Couldn't allocate space for deferred callback.",
+ __func__);
+ return;
+ }
+
+ ASSERT_LOCKED(req->base);
+
+ d->request_type = req->request_type;
+ d->user_callback = req->user_callback;
+ d->ttl = ttl;
+ d->err = err;
+ if (reply) {
+ d->have_reply = 1;
+ memcpy(&d->reply, reply, sizeof(struct reply));
+ }
+
+ if (req->handle) {
+ req->handle->pending_cb = 1;
+ d->handle = req->handle;
+ }
+
+ event_deferred_cb_init_(
+ &d->deferred,
+ event_get_priority(&req->timeout_event),
+ reply_run_callback,
+ req->user_pointer);
+ event_deferred_cb_schedule_(
+ req->base->event_base,
+ &d->deferred);
+}
+
+
+#define _QR_MASK 0x8000U
+#define _OP_MASK 0x7800U
+#define _AA_MASK 0x0400U
+#define _TC_MASK 0x0200U
+#define _RD_MASK 0x0100U
+#define _RA_MASK 0x0080U
+#define _Z_MASK 0x0040U
+#define _AD_MASK 0x0020U
+#define _CD_MASK 0x0010U
+#define _RCODE_MASK 0x000fU
+#define _Z_MASK_DEPRECATED 0x0070U
+
+/* this processes a parsed reply packet */
+static void
+reply_handle(struct request *const req, u16 flags, u32 ttl, struct reply *reply) {
+ int error;
+ char addrbuf[128];
+ static const int error_codes[] = {
+ DNS_ERR_FORMAT, DNS_ERR_SERVERFAILED, DNS_ERR_NOTEXIST,
+ DNS_ERR_NOTIMPL, DNS_ERR_REFUSED
+ };
+
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+
+ if (flags & (_RCODE_MASK | _TC_MASK) || !reply || !reply->have_answer) {
+ /* there was an error */
+ if (flags & _TC_MASK) {
+ error = DNS_ERR_TRUNCATED;
+ } else if (flags & _RCODE_MASK) {
+ u16 error_code = (flags & _RCODE_MASK) - 1;
+ if (error_code > 4) {
+ error = DNS_ERR_UNKNOWN;
+ } else {
+ error = error_codes[error_code];
+ }
+ } else if (reply && !reply->have_answer) {
+ error = DNS_ERR_NODATA;
+ } else {
+ error = DNS_ERR_UNKNOWN;
+ }
+
+ switch (error) {
+ case DNS_ERR_NOTIMPL:
+ case DNS_ERR_REFUSED:
+ /* we regard these errors as marking a bad nameserver */
+ if (req->reissue_count < req->base->global_max_reissues) {
+ char msg[64];
+ evutil_snprintf(msg, sizeof(msg), "Bad response %d (%s)",
+ error, evdns_err_to_string(error));
+ nameserver_failed(req->ns, msg);
+ if (!request_reissue(req)) return;
+ }
+ break;
+ case DNS_ERR_SERVERFAILED:
+ /* rcode 2 (servfailed) sometimes means "we
+ * are broken" and sometimes (with some binds)
+ * means "that request was very confusing."
+ * Treat this as a timeout, not a failure.
+ */
+ log(EVDNS_LOG_DEBUG, "Got a SERVERFAILED from nameserver"
+ "at %s; will allow the request to time out.",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&req->ns->address,
+ addrbuf, sizeof(addrbuf)));
+ /* Call the timeout function */
+ evdns_request_timeout_callback(0, 0, req);
+ return;
+ default:
+ /* we got a good reply from the nameserver: it is up. */
+ if (req->handle == req->ns->probe_request) {
+ /* Avoid double-free */
+ req->ns->probe_request = NULL;
+ }
+
+ nameserver_up(req->ns);
+ }
+
+ if (req->handle->search_state &&
+ req->request_type != TYPE_PTR) {
+ /* if we have a list of domains to search in,
+ * try the next one */
+ if (!search_try_next(req->handle)) {
+ /* a new request was issued so this
+ * request is finished and */
+ /* the user callback will be made when
+ * that request (or a */
+ /* child of it) finishes. */
+ return;
+ }
+ }
+
+ /* all else failed. Pass the failure up */
+ reply_schedule_callback(req, ttl, error, NULL);
+ request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+ } else {
+ /* all ok, tell the user */
+ reply_schedule_callback(req, ttl, 0, reply);
+ if (req->handle == req->ns->probe_request)
+ req->ns->probe_request = NULL; /* Avoid double-free */
+ nameserver_up(req->ns);
+ request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+ }
+}
+
+static int
+name_parse(u8 *packet, int length, int *idx, char *name_out, int name_out_len) {
+ int name_end = -1;
+ int j = *idx;
+ int ptr_count = 0;
+#define GET32(x) do { if (j + 4 > length) goto err; memcpy(&t32_, packet + j, 4); j += 4; x = ntohl(t32_); } while (0)
+#define GET16(x) do { if (j + 2 > length) goto err; memcpy(&t_, packet + j, 2); j += 2; x = ntohs(t_); } while (0)
+#define GET8(x) do { if (j >= length) goto err; x = packet[j++]; } while (0)
+
+ char *cp = name_out;
+ const char *const end = name_out + name_out_len;
+
+ /* Normally, names are a series of length prefixed strings terminated */
+ /* with a length of 0 (the lengths are u8's < 63). */
+ /* However, the length can start with a pair of 1 bits and that */
+ /* means that the next 14 bits are a pointer within the current */
+ /* packet. */
+
+ for (;;) {
+ u8 label_len;
+ GET8(label_len);
+ if (!label_len) break;
+ if (label_len & 0xc0) {
+ u8 ptr_low;
+ GET8(ptr_low);
+ if (name_end < 0) name_end = j;
+ j = (((int)label_len & 0x3f) << 8) + ptr_low;
+ /* Make sure that the target offset is in-bounds. */
+ if (j < 0 || j >= length) return -1;
+ /* If we've jumped more times than there are characters in the
+ * message, we must have a loop. */
+ if (++ptr_count > length) return -1;
+ continue;
+ }
+ if (label_len > 63) return -1;
+ if (cp != name_out) {
+ if (cp + 1 >= end) return -1;
+ *cp++ = '.';
+ }
+ if (cp + label_len >= end) return -1;
+ if (j + label_len > length) return -1;
+ memcpy(cp, packet + j, label_len);
+ cp += label_len;
+ j += label_len;
+ }
+ if (cp >= end) return -1;
+ *cp = '\0';
+ if (name_end < 0)
+ *idx = j;
+ else
+ *idx = name_end;
+ return 0;
+ err:
+ return -1;
+}
+
+/* parses a raw request from a nameserver */
+static int
+reply_parse(struct evdns_base *base, u8 *packet, int length) {
+ int j = 0, k = 0; /* index into packet */
+ u16 t_; /* used by the macros */
+ u32 t32_; /* used by the macros */
+ char tmp_name[256], cmp_name[256]; /* used by the macros */
+ int name_matches = 0;
+
+ u16 trans_id, questions, answers, authority, additional, datalength;
+ u16 flags = 0;
+ u32 ttl, ttl_r = 0xffffffff;
+ struct reply reply;
+ struct request *req = NULL;
+ unsigned int i;
+
+ ASSERT_LOCKED(base);
+
+ GET16(trans_id);
+ GET16(flags);
+ GET16(questions);
+ GET16(answers);
+ GET16(authority);
+ GET16(additional);
+ (void) authority; /* suppress "unused variable" warnings. */
+ (void) additional; /* suppress "unused variable" warnings. */
+
+ req = request_find_from_trans_id(base, trans_id);
+ if (!req) return -1;
+ EVUTIL_ASSERT(req->base == base);
+
+ memset(&reply, 0, sizeof(reply));
+
+ /* If it's not an answer, it doesn't correspond to any request. */
+ if (!(flags & _QR_MASK)) return -1; /* must be an answer */
+ if ((flags & (_RCODE_MASK|_TC_MASK)) && (flags & (_RCODE_MASK|_TC_MASK)) != DNS_ERR_NOTEXIST) {
+ /* there was an error and it's not NXDOMAIN */
+ goto err;
+ }
+ /* if (!answers) return; */ /* must have an answer of some form */
+
+ /* This macro skips a name in the DNS reply. */
+#define SKIP_NAME \
+ do { tmp_name[0] = '\0'; \
+ if (name_parse(packet, length, &j, tmp_name, \
+ sizeof(tmp_name))<0) \
+ goto err; \
+ } while (0)
+
+ reply.type = req->request_type;
+
+ /* skip over each question in the reply */
+ for (i = 0; i < questions; ++i) {
+ /* the question looks like
+ * <label:name><u16:type><u16:class>
+ */
+ tmp_name[0] = '\0';
+ cmp_name[0] = '\0';
+ k = j;
+ if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name)) < 0)
+ goto err;
+ if (name_parse(req->request, req->request_len, &k,
+ cmp_name, sizeof(cmp_name))<0)
+ goto err;
+ if (!base->global_randomize_case) {
+ if (strcmp(tmp_name, cmp_name) == 0)
+ name_matches = 1;
+ } else {
+ if (evutil_ascii_strcasecmp(tmp_name, cmp_name) == 0)
+ name_matches = 1;
+ }
+
+ j += 4;
+ if (j > length)
+ goto err;
+ }
+
+ if (!name_matches)
+ goto err;
+
+ /* now we have the answer section which looks like
+ * <label:name><u16:type><u16:class><u32:ttl><u16:len><data...>
+ */
+
+ for (i = 0; i < answers; ++i) {
+ u16 type, class;
+
+ SKIP_NAME;
+ GET16(type);
+ GET16(class);
+ GET32(ttl);
+ GET16(datalength);
+
+ if (type == TYPE_A && class == CLASS_INET) {
+ int addrcount, addrtocopy;
+ if (req->request_type != TYPE_A) {
+ j += datalength; continue;
+ }
+ if ((datalength & 3) != 0) /* not an even number of As. */
+ goto err;
+ addrcount = datalength >> 2;
+ addrtocopy = MIN(MAX_V4_ADDRS - reply.data.a.addrcount, (unsigned)addrcount);
+
+ ttl_r = MIN(ttl_r, ttl);
+ /* we only bother with the first four addresses. */
+ if (j + 4*addrtocopy > length) goto err;
+ memcpy(&reply.data.a.addresses[reply.data.a.addrcount],
+ packet + j, 4*addrtocopy);
+ j += 4*addrtocopy;
+ reply.data.a.addrcount += addrtocopy;
+ reply.have_answer = 1;
+ if (reply.data.a.addrcount == MAX_V4_ADDRS) break;
+ } else if (type == TYPE_PTR && class == CLASS_INET) {
+ if (req->request_type != TYPE_PTR) {
+ j += datalength; continue;
+ }
+ if (name_parse(packet, length, &j, reply.data.ptr.name,
+ sizeof(reply.data.ptr.name))<0)
+ goto err;
+ ttl_r = MIN(ttl_r, ttl);
+ reply.have_answer = 1;
+ break;
+ } else if (type == TYPE_CNAME) {
+ char cname[HOST_NAME_MAX];
+ if (!req->put_cname_in_ptr || *req->put_cname_in_ptr) {
+ j += datalength; continue;
+ }
+ if (name_parse(packet, length, &j, cname,
+ sizeof(cname))<0)
+ goto err;
+ *req->put_cname_in_ptr = mm_strdup(cname);
+ } else if (type == TYPE_AAAA && class == CLASS_INET) {
+ int addrcount, addrtocopy;
+ if (req->request_type != TYPE_AAAA) {
+ j += datalength; continue;
+ }
+ if ((datalength & 15) != 0) /* not an even number of AAAAs. */
+ goto err;
+ addrcount = datalength >> 4; /* each address is 16 bytes long */
+ addrtocopy = MIN(MAX_V6_ADDRS - reply.data.aaaa.addrcount, (unsigned)addrcount);
+ ttl_r = MIN(ttl_r, ttl);
+
+ /* we only bother with the first four addresses. */
+ if (j + 16*addrtocopy > length) goto err;
+ memcpy(&reply.data.aaaa.addresses[reply.data.aaaa.addrcount],
+ packet + j, 16*addrtocopy);
+ reply.data.aaaa.addrcount += addrtocopy;
+ j += 16*addrtocopy;
+ reply.have_answer = 1;
+ if (reply.data.aaaa.addrcount == MAX_V6_ADDRS) break;
+ } else {
+ /* skip over any other type of resource */
+ j += datalength;
+ }
+ }
+
+ if (!reply.have_answer) {
+ for (i = 0; i < authority; ++i) {
+ u16 type, class;
+ SKIP_NAME;
+ GET16(type);
+ GET16(class);
+ GET32(ttl);
+ GET16(datalength);
+ if (type == TYPE_SOA && class == CLASS_INET) {
+ u32 serial, refresh, retry, expire, minimum;
+ SKIP_NAME;
+ SKIP_NAME;
+ GET32(serial);
+ GET32(refresh);
+ GET32(retry);
+ GET32(expire);
+ GET32(minimum);
+ (void)expire;
+ (void)retry;
+ (void)refresh;
+ (void)serial;
+ ttl_r = MIN(ttl_r, ttl);
+ ttl_r = MIN(ttl_r, minimum);
+ } else {
+ /* skip over any other type of resource */
+ j += datalength;
+ }
+ }
+ }
+
+ if (ttl_r == 0xffffffff)
+ ttl_r = 0;
+
+ reply_handle(req, flags, ttl_r, &reply);
+ return 0;
+ err:
+ if (req)
+ reply_handle(req, flags, 0, NULL);
+ return -1;
+}
+
+/* Parse a raw request (packet,length) sent to a nameserver port (port) from */
+/* a DNS client (addr,addrlen), and if it's well-formed, call the corresponding */
+/* callback. */
+static int
+request_parse(u8 *packet, int length, struct evdns_server_port *port, struct sockaddr *addr, ev_socklen_t addrlen)
+{
+ int j = 0; /* index into packet */
+ u16 t_; /* used by the macros */
+ char tmp_name[256]; /* used by the macros */
+
+ int i;
+ u16 trans_id, flags, questions, answers, authority, additional;
+ struct server_request *server_req = NULL;
+
+ ASSERT_LOCKED(port);
+
+ /* Get the header fields */
+ GET16(trans_id);
+ GET16(flags);
+ GET16(questions);
+ GET16(answers);
+ GET16(authority);
+ GET16(additional);
+ (void)answers;
+ (void)additional;
+ (void)authority;
+
+ if (flags & _QR_MASK) return -1; /* Must not be an answer. */
+ flags &= (_RD_MASK|_CD_MASK); /* Only RD and CD get preserved. */
+
+ server_req = mm_malloc(sizeof(struct server_request));
+ if (server_req == NULL) return -1;
+ memset(server_req, 0, sizeof(struct server_request));
+
+ server_req->trans_id = trans_id;
+ memcpy(&server_req->addr, addr, addrlen);
+ server_req->addrlen = addrlen;
+
+ server_req->base.flags = flags;
+ server_req->base.nquestions = 0;
+ server_req->base.questions = mm_calloc(sizeof(struct evdns_server_question *), questions);
+ if (server_req->base.questions == NULL)
+ goto err;
+
+ for (i = 0; i < questions; ++i) {
+ u16 type, class;
+ struct evdns_server_question *q;
+ int namelen;
+ if (name_parse(packet, length, &j, tmp_name, sizeof(tmp_name))<0)
+ goto err;
+ GET16(type);
+ GET16(class);
+ namelen = (int)strlen(tmp_name);
+ q = mm_malloc(sizeof(struct evdns_server_question) + namelen);
+ if (!q)
+ goto err;
+ q->type = type;
+ q->dns_question_class = class;
+ memcpy(q->name, tmp_name, namelen+1);
+ server_req->base.questions[server_req->base.nquestions++] = q;
+ }
+
+ /* Ignore answers, authority, and additional. */
+
+ server_req->port = port;
+ port->refcnt++;
+
+ /* Only standard queries are supported. */
+ if (flags & _OP_MASK) {
+ evdns_server_request_respond(&(server_req->base), DNS_ERR_NOTIMPL);
+ return -1;
+ }
+
+ port->user_callback(&(server_req->base), port->user_data);
+
+ return 0;
+err:
+ if (server_req->base.questions) {
+ for (i = 0; i < server_req->base.nquestions; ++i)
+ mm_free(server_req->base.questions[i]);
+ mm_free(server_req->base.questions);
+ }
+ mm_free(server_req);
+ return -1;
+
+#undef SKIP_NAME
+#undef GET32
+#undef GET16
+#undef GET8
+}
+
+
+void
+evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void))
+{
+}
+
+void
+evdns_set_random_bytes_fn(void (*fn)(char *, size_t))
+{
+}
+
+/* Try to choose a strong transaction id which isn't already in flight */
+static u16
+transaction_id_pick(struct evdns_base *base) {
+ ASSERT_LOCKED(base);
+ for (;;) {
+ u16 trans_id;
+ evutil_secure_rng_get_bytes(&trans_id, sizeof(trans_id));
+
+ if (trans_id == 0xffff) continue;
+ /* now check to see if that id is already inflight */
+ if (request_find_from_trans_id(base, trans_id) == NULL)
+ return trans_id;
+ }
+}
+
+/* choose a namesever to use. This function will try to ignore */
+/* nameservers which we think are down and load balance across the rest */
+/* by updating the server_head global each time. */
+static struct nameserver *
+nameserver_pick(struct evdns_base *base) {
+ struct nameserver *started_at = base->server_head, *picked;
+ ASSERT_LOCKED(base);
+ if (!base->server_head) return NULL;
+
+ /* if we don't have any good nameservers then there's no */
+ /* point in trying to find one. */
+ if (!base->global_good_nameservers) {
+ base->server_head = base->server_head->next;
+ return base->server_head;
+ }
+
+ /* remember that nameservers are in a circular list */
+ for (;;) {
+ if (base->server_head->state) {
+ /* we think this server is currently good */
+ picked = base->server_head;
+ base->server_head = base->server_head->next;
+ return picked;
+ }
+
+ base->server_head = base->server_head->next;
+ if (base->server_head == started_at) {
+ /* all the nameservers seem to be down */
+ /* so we just return this one and hope for the */
+ /* best */
+ EVUTIL_ASSERT(base->global_good_nameservers == 0);
+ picked = base->server_head;
+ base->server_head = base->server_head->next;
+ return picked;
+ }
+ }
+}
+
+/* this is called when a namesever socket is ready for reading */
+static void
+nameserver_read(struct nameserver *ns) {
+ struct sockaddr_storage ss;
+ ev_socklen_t addrlen = sizeof(ss);
+ u8 packet[1500];
+ char addrbuf[128];
+ ASSERT_LOCKED(ns->base);
+
+ for (;;) {
+ const int r = recvfrom(ns->socket, (void*)packet,
+ sizeof(packet), 0,
+ (struct sockaddr*)&ss, &addrlen);
+ if (r < 0) {
+ int err = evutil_socket_geterror(ns->socket);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ return;
+ nameserver_failed(ns,
+ evutil_socket_error_to_string(err));
+ return;
+ }
+ if (evutil_sockaddr_cmp((struct sockaddr*)&ss,
+ (struct sockaddr*)&ns->address, 0)) {
+ log(EVDNS_LOG_WARN, "Address mismatch on received "
+ "DNS packet. Apparent source was %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ss,
+ addrbuf, sizeof(addrbuf)));
+ return;
+ }
+
+ ns->timedout = 0;
+ reply_parse(ns->base, packet, r);
+ }
+}
+
+/* Read a packet from a DNS client on a server port s, parse it, and */
+/* act accordingly. */
+static void
+server_port_read(struct evdns_server_port *s) {
+ u8 packet[1500];
+ struct sockaddr_storage addr;
+ ev_socklen_t addrlen;
+ int r;
+ ASSERT_LOCKED(s);
+
+ for (;;) {
+ addrlen = sizeof(struct sockaddr_storage);
+ r = recvfrom(s->socket, (void*)packet, sizeof(packet), 0,
+ (struct sockaddr*) &addr, &addrlen);
+ if (r < 0) {
+ int err = evutil_socket_geterror(s->socket);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ return;
+ log(EVDNS_LOG_WARN,
+ "Error %s (%d) while reading request.",
+ evutil_socket_error_to_string(err), err);
+ return;
+ }
+ request_parse(packet, r, s, (struct sockaddr*) &addr, addrlen);
+ }
+}
+
+/* Try to write all pending replies on a given DNS server port. */
+static void
+server_port_flush(struct evdns_server_port *port)
+{
+ struct server_request *req = port->pending_replies;
+ ASSERT_LOCKED(port);
+ while (req) {
+ int r = sendto(port->socket, req->response, (int)req->response_len, 0,
+ (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
+ if (r < 0) {
+ int err = evutil_socket_geterror(port->socket);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ return;
+ log(EVDNS_LOG_WARN, "Error %s (%d) while writing response to port; dropping", evutil_socket_error_to_string(err), err);
+ }
+ if (server_request_free(req)) {
+ /* we released the last reference to req->port. */
+ return;
+ } else {
+ EVUTIL_ASSERT(req != port->pending_replies);
+ req = port->pending_replies;
+ }
+ }
+
+ /* We have no more pending requests; stop listening for 'writeable' events. */
+ (void) event_del(&port->event);
+ event_assign(&port->event, port->event_base,
+ port->socket, EV_READ | EV_PERSIST,
+ server_port_ready_callback, port);
+
+ if (event_add(&port->event, NULL) < 0) {
+ log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server.");
+ /* ???? Do more? */
+ }
+}
+
+/* set if we are waiting for the ability to write to this server. */
+/* if waiting is true then we ask libevent for EV_WRITE events, otherwise */
+/* we stop these events. */
+static void
+nameserver_write_waiting(struct nameserver *ns, char waiting) {
+ ASSERT_LOCKED(ns->base);
+ if (ns->write_waiting == waiting) return;
+
+ ns->write_waiting = waiting;
+ (void) event_del(&ns->event);
+ event_assign(&ns->event, ns->base->event_base,
+ ns->socket, EV_READ | (waiting ? EV_WRITE : 0) | EV_PERSIST,
+ nameserver_ready_callback, ns);
+ if (event_add(&ns->event, NULL) < 0) {
+ char addrbuf[128];
+ log(EVDNS_LOG_WARN, "Error from libevent when adding event for %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)));
+ /* ???? Do more? */
+ }
+}
+
+/* a callback function. Called by libevent when the kernel says that */
+/* a nameserver socket is ready for writing or reading */
+static void
+nameserver_ready_callback(evutil_socket_t fd, short events, void *arg) {
+ struct nameserver *ns = (struct nameserver *) arg;
+ (void)fd;
+
+ EVDNS_LOCK(ns->base);
+ if (events & EV_WRITE) {
+ ns->choked = 0;
+ if (!evdns_transmit(ns->base)) {
+ nameserver_write_waiting(ns, 0);
+ }
+ }
+ if (events & EV_READ) {
+ nameserver_read(ns);
+ }
+ EVDNS_UNLOCK(ns->base);
+}
+
+/* a callback function. Called by libevent when the kernel says that */
+/* a server socket is ready for writing or reading. */
+static void
+server_port_ready_callback(evutil_socket_t fd, short events, void *arg) {
+ struct evdns_server_port *port = (struct evdns_server_port *) arg;
+ (void) fd;
+
+ EVDNS_LOCK(port);
+ if (events & EV_WRITE) {
+ port->choked = 0;
+ server_port_flush(port);
+ }
+ if (events & EV_READ) {
+ server_port_read(port);
+ }
+ EVDNS_UNLOCK(port);
+}
+
+/* This is an inefficient representation; only use it via the dnslabel_table_*
+ * functions, so that is can be safely replaced with something smarter later. */
+#define MAX_LABELS 128
+/* Structures used to implement name compression */
+struct dnslabel_entry { char *v; off_t pos; };
+struct dnslabel_table {
+ int n_labels; /* number of current entries */
+ /* map from name to position in message */
+ struct dnslabel_entry labels[MAX_LABELS];
+};
+
+/* Initialize dnslabel_table. */
+static void
+dnslabel_table_init(struct dnslabel_table *table)
+{
+ table->n_labels = 0;
+}
+
+/* Free all storage held by table, but not the table itself. */
+static void
+dnslabel_clear(struct dnslabel_table *table)
+{
+ int i;
+ for (i = 0; i < table->n_labels; ++i)
+ mm_free(table->labels[i].v);
+ table->n_labels = 0;
+}
+
+/* return the position of the label in the current message, or -1 if the label */
+/* hasn't been used yet. */
+static int
+dnslabel_table_get_pos(const struct dnslabel_table *table, const char *label)
+{
+ int i;
+ for (i = 0; i < table->n_labels; ++i) {
+ if (!strcmp(label, table->labels[i].v))
+ return table->labels[i].pos;
+ }
+ return -1;
+}
+
+/* remember that we've used the label at position pos */
+static int
+dnslabel_table_add(struct dnslabel_table *table, const char *label, off_t pos)
+{
+ char *v;
+ int p;
+ if (table->n_labels == MAX_LABELS)
+ return (-1);
+ v = mm_strdup(label);
+ if (v == NULL)
+ return (-1);
+ p = table->n_labels++;
+ table->labels[p].v = v;
+ table->labels[p].pos = pos;
+
+ return (0);
+}
+
+/* Converts a string to a length-prefixed set of DNS labels, starting */
+/* at buf[j]. name and buf must not overlap. name_len should be the length */
+/* of name. table is optional, and is used for compression. */
+/* */
+/* Input: abc.def */
+/* Output: <3>abc<3>def<0> */
+/* */
+/* Returns the first index after the encoded name, or negative on error. */
+/* -1 label was > 63 bytes */
+/* -2 name too long to fit in buffer. */
+/* */
+static off_t
+dnsname_to_labels(u8 *const buf, size_t buf_len, off_t j,
+ const char *name, const size_t name_len,
+ struct dnslabel_table *table) {
+ const char *end = name + name_len;
+ int ref = 0;
+ u16 t_;
+
+#define APPEND16(x) do { \
+ if (j + 2 > (off_t)buf_len) \
+ goto overflow; \
+ t_ = htons(x); \
+ memcpy(buf + j, &t_, 2); \
+ j += 2; \
+ } while (0)
+#define APPEND32(x) do { \
+ if (j + 4 > (off_t)buf_len) \
+ goto overflow; \
+ t32_ = htonl(x); \
+ memcpy(buf + j, &t32_, 4); \
+ j += 4; \
+ } while (0)
+
+ if (name_len > 255) return -2;
+
+ for (;;) {
+ const char *const start = name;
+ if (table && (ref = dnslabel_table_get_pos(table, name)) >= 0) {
+ APPEND16(ref | 0xc000);
+ return j;
+ }
+ name = strchr(name, '.');
+ if (!name) {
+ const size_t label_len = end - start;
+ if (label_len > 63) return -1;
+ if ((size_t)(j+label_len+1) > buf_len) return -2;
+ if (table) dnslabel_table_add(table, start, j);
+ buf[j++] = (ev_uint8_t)label_len;
+
+ memcpy(buf + j, start, label_len);
+ j += (int) label_len;
+ break;
+ } else {
+ /* append length of the label. */
+ const size_t label_len = name - start;
+ if (label_len > 63) return -1;
+ if ((size_t)(j+label_len+1) > buf_len) return -2;
+ if (table) dnslabel_table_add(table, start, j);
+ buf[j++] = (ev_uint8_t)label_len;
+
+ memcpy(buf + j, start, label_len);
+ j += (int) label_len;
+ /* hop over the '.' */
+ name++;
+ }
+ }
+
+ /* the labels must be terminated by a 0. */
+ /* It's possible that the name ended in a . */
+ /* in which case the zero is already there */
+ if (!j || buf[j-1]) buf[j++] = 0;
+ return j;
+ overflow:
+ return (-2);
+}
+
+/* Finds the length of a dns request for a DNS name of the given */
+/* length. The actual request may be smaller than the value returned */
+/* here */
+static size_t
+evdns_request_len(const size_t name_len) {
+ return 96 + /* length of the DNS standard header */
+ name_len + 2 +
+ 4; /* space for the resource type */
+}
+
+/* build a dns request packet into buf. buf should be at least as long */
+/* as evdns_request_len told you it should be. */
+/* */
+/* Returns the amount of space used. Negative on error. */
+static int
+evdns_request_data_build(const char *const name, const size_t name_len,
+ const u16 trans_id, const u16 type, const u16 class,
+ u8 *const buf, size_t buf_len) {
+ off_t j = 0; /* current offset into buf */
+ u16 t_; /* used by the macros */
+
+ APPEND16(trans_id);
+ APPEND16(0x0100); /* standard query, recusion needed */
+ APPEND16(1); /* one question */
+ APPEND16(0); /* no answers */
+ APPEND16(0); /* no authority */
+ APPEND16(0); /* no additional */
+
+ j = dnsname_to_labels(buf, buf_len, j, name, name_len, NULL);
+ if (j < 0) {
+ return (int)j;
+ }
+
+ APPEND16(type);
+ APPEND16(class);
+
+ return (int)j;
+ overflow:
+ return (-1);
+}
+
+/* exported function */
+struct evdns_server_port *
+evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
+{
+ struct evdns_server_port *port;
+ if (flags)
+ return NULL; /* flags not yet implemented */
+ if (!(port = mm_malloc(sizeof(struct evdns_server_port))))
+ return NULL;
+ memset(port, 0, sizeof(struct evdns_server_port));
+
+
+ port->socket = socket;
+ port->refcnt = 1;
+ port->choked = 0;
+ port->closing = 0;
+ port->user_callback = cb;
+ port->user_data = user_data;
+ port->pending_replies = NULL;
+ port->event_base = base;
+
+ event_assign(&port->event, port->event_base,
+ port->socket, EV_READ | EV_PERSIST,
+ server_port_ready_callback, port);
+ if (event_add(&port->event, NULL) < 0) {
+ mm_free(port);
+ return NULL;
+ }
+ EVTHREAD_ALLOC_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ return port;
+}
+
+struct evdns_server_port *
+evdns_add_server_port(evutil_socket_t socket, int flags, evdns_request_callback_fn_type cb, void *user_data)
+{
+ return evdns_add_server_port_with_base(NULL, socket, flags, cb, user_data);
+}
+
+/* exported function */
+void
+evdns_close_server_port(struct evdns_server_port *port)
+{
+ EVDNS_LOCK(port);
+ if (--port->refcnt == 0) {
+ EVDNS_UNLOCK(port);
+ server_port_free(port);
+ } else {
+ port->closing = 1;
+ EVDNS_UNLOCK(port);
+ }
+}
+
+/* exported function */
+int
+evdns_server_request_add_reply(struct evdns_server_request *req_, int section, const char *name, int type, int class, int ttl, int datalen, int is_name, const char *data)
+{
+ struct server_request *req = TO_SERVER_REQUEST(req_);
+ struct server_reply_item **itemp, *item;
+ int *countp;
+ int result = -1;
+
+ EVDNS_LOCK(req->port);
+ if (req->response) /* have we already answered? */
+ goto done;
+
+ switch (section) {
+ case EVDNS_ANSWER_SECTION:
+ itemp = &req->answer;
+ countp = &req->n_answer;
+ break;
+ case EVDNS_AUTHORITY_SECTION:
+ itemp = &req->authority;
+ countp = &req->n_authority;
+ break;
+ case EVDNS_ADDITIONAL_SECTION:
+ itemp = &req->additional;
+ countp = &req->n_additional;
+ break;
+ default:
+ goto done;
+ }
+ while (*itemp) {
+ itemp = &((*itemp)->next);
+ }
+ item = mm_malloc(sizeof(struct server_reply_item));
+ if (!item)
+ goto done;
+ item->next = NULL;
+ if (!(item->name = mm_strdup(name))) {
+ mm_free(item);
+ goto done;
+ }
+ item->type = type;
+ item->dns_question_class = class;
+ item->ttl = ttl;
+ item->is_name = is_name != 0;
+ item->datalen = 0;
+ item->data = NULL;
+ if (data) {
+ if (item->is_name) {
+ if (!(item->data = mm_strdup(data))) {
+ mm_free(item->name);
+ mm_free(item);
+ goto done;
+ }
+ item->datalen = (u16)-1;
+ } else {
+ if (!(item->data = mm_malloc(datalen))) {
+ mm_free(item->name);
+ mm_free(item);
+ goto done;
+ }
+ item->datalen = datalen;
+ memcpy(item->data, data, datalen);
+ }
+ }
+
+ *itemp = item;
+ ++(*countp);
+ result = 0;
+done:
+ EVDNS_UNLOCK(req->port);
+ return result;
+}
+
+/* exported function */
+int
+evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
+{
+ return evdns_server_request_add_reply(
+ req, EVDNS_ANSWER_SECTION, name, TYPE_A, CLASS_INET,
+ ttl, n*4, 0, addrs);
+}
+
+/* exported function */
+int
+evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl)
+{
+ return evdns_server_request_add_reply(
+ req, EVDNS_ANSWER_SECTION, name, TYPE_AAAA, CLASS_INET,
+ ttl, n*16, 0, addrs);
+}
+
+/* exported function */
+int
+evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl)
+{
+ u32 a;
+ char buf[32];
+ if (in && inaddr_name)
+ return -1;
+ else if (!in && !inaddr_name)
+ return -1;
+ if (in) {
+ a = ntohl(in->s_addr);
+ evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
+ (int)(u8)((a )&0xff),
+ (int)(u8)((a>>8 )&0xff),
+ (int)(u8)((a>>16)&0xff),
+ (int)(u8)((a>>24)&0xff));
+ inaddr_name = buf;
+ }
+ return evdns_server_request_add_reply(
+ req, EVDNS_ANSWER_SECTION, inaddr_name, TYPE_PTR, CLASS_INET,
+ ttl, -1, 1, hostname);
+}
+
+/* exported function */
+int
+evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl)
+{
+ return evdns_server_request_add_reply(
+ req, EVDNS_ANSWER_SECTION, name, TYPE_CNAME, CLASS_INET,
+ ttl, -1, 1, cname);
+}
+
+/* exported function */
+void
+evdns_server_request_set_flags(struct evdns_server_request *exreq, int flags)
+{
+ struct server_request *req = TO_SERVER_REQUEST(exreq);
+ req->base.flags &= ~(EVDNS_FLAGS_AA|EVDNS_FLAGS_RD);
+ req->base.flags |= flags;
+}
+
+static int
+evdns_server_request_format_response(struct server_request *req, int err)
+{
+ unsigned char buf[1500];
+ size_t buf_len = sizeof(buf);
+ off_t j = 0, r;
+ u16 t_;
+ u32 t32_;
+ int i;
+ u16 flags;
+ struct dnslabel_table table;
+
+ if (err < 0 || err > 15) return -1;
+
+ /* Set response bit and error code; copy OPCODE and RD fields from
+ * question; copy RA and AA if set by caller. */
+ flags = req->base.flags;
+ flags |= (_QR_MASK | err);
+
+ dnslabel_table_init(&table);
+ APPEND16(req->trans_id);
+ APPEND16(flags);
+ APPEND16(req->base.nquestions);
+ APPEND16(req->n_answer);
+ APPEND16(req->n_authority);
+ APPEND16(req->n_additional);
+
+ /* Add questions. */
+ for (i=0; i < req->base.nquestions; ++i) {
+ const char *s = req->base.questions[i]->name;
+ j = dnsname_to_labels(buf, buf_len, j, s, strlen(s), &table);
+ if (j < 0) {
+ dnslabel_clear(&table);
+ return (int) j;
+ }
+ APPEND16(req->base.questions[i]->type);
+ APPEND16(req->base.questions[i]->dns_question_class);
+ }
+
+ /* Add answer, authority, and additional sections. */
+ for (i=0; i<3; ++i) {
+ struct server_reply_item *item;
+ if (i==0)
+ item = req->answer;
+ else if (i==1)
+ item = req->authority;
+ else
+ item = req->additional;
+ while (item) {
+ r = dnsname_to_labels(buf, buf_len, j, item->name, strlen(item->name), &table);
+ if (r < 0)
+ goto overflow;
+ j = r;
+
+ APPEND16(item->type);
+ APPEND16(item->dns_question_class);
+ APPEND32(item->ttl);
+ if (item->is_name) {
+ off_t len_idx = j, name_start;
+ j += 2;
+ name_start = j;
+ r = dnsname_to_labels(buf, buf_len, j, item->data, strlen(item->data), &table);
+ if (r < 0)
+ goto overflow;
+ j = r;
+ t_ = htons( (short) (j-name_start) );
+ memcpy(buf+len_idx, &t_, 2);
+ } else {
+ APPEND16(item->datalen);
+ if (j+item->datalen > (off_t)buf_len)
+ goto overflow;
+ memcpy(buf+j, item->data, item->datalen);
+ j += item->datalen;
+ }
+ item = item->next;
+ }
+ }
+
+ if (j > 512) {
+overflow:
+ j = 512;
+ buf[2] |= 0x02; /* set the truncated bit. */
+ }
+
+ req->response_len = j;
+
+ if (!(req->response = mm_malloc(req->response_len))) {
+ server_request_free_answers(req);
+ dnslabel_clear(&table);
+ return (-1);
+ }
+ memcpy(req->response, buf, req->response_len);
+ server_request_free_answers(req);
+ dnslabel_clear(&table);
+ return (0);
+}
+
+/* exported function */
+int
+evdns_server_request_respond(struct evdns_server_request *req_, int err)
+{
+ struct server_request *req = TO_SERVER_REQUEST(req_);
+ struct evdns_server_port *port = req->port;
+ int r = -1;
+
+ EVDNS_LOCK(port);
+ if (!req->response) {
+ if ((r = evdns_server_request_format_response(req, err))<0)
+ goto done;
+ }
+
+ r = sendto(port->socket, req->response, (int)req->response_len, 0,
+ (struct sockaddr*) &req->addr, (ev_socklen_t)req->addrlen);
+ if (r<0) {
+ int sock_err = evutil_socket_geterror(port->socket);
+ if (EVUTIL_ERR_RW_RETRIABLE(sock_err))
+ goto done;
+
+ if (port->pending_replies) {
+ req->prev_pending = port->pending_replies->prev_pending;
+ req->next_pending = port->pending_replies;
+ req->prev_pending->next_pending =
+ req->next_pending->prev_pending = req;
+ } else {
+ req->prev_pending = req->next_pending = req;
+ port->pending_replies = req;
+ port->choked = 1;
+
+ (void) event_del(&port->event);
+ event_assign(&port->event, port->event_base, port->socket, (port->closing?0:EV_READ) | EV_WRITE | EV_PERSIST, server_port_ready_callback, port);
+
+ if (event_add(&port->event, NULL) < 0) {
+ log(EVDNS_LOG_WARN, "Error from libevent when adding event for DNS server");
+ }
+
+ }
+
+ r = 1;
+ goto done;
+ }
+ if (server_request_free(req)) {
+ r = 0;
+ goto done;
+ }
+
+ if (port->pending_replies)
+ server_port_flush(port);
+
+ r = 0;
+done:
+ EVDNS_UNLOCK(port);
+ return r;
+}
+
+/* Free all storage held by RRs in req. */
+static void
+server_request_free_answers(struct server_request *req)
+{
+ struct server_reply_item *victim, *next, **list;
+ int i;
+ for (i = 0; i < 3; ++i) {
+ if (i==0)
+ list = &req->answer;
+ else if (i==1)
+ list = &req->authority;
+ else
+ list = &req->additional;
+
+ victim = *list;
+ while (victim) {
+ next = victim->next;
+ mm_free(victim->name);
+ if (victim->data)
+ mm_free(victim->data);
+ mm_free(victim);
+ victim = next;
+ }
+ *list = NULL;
+ }
+}
+
+/* Free all storage held by req, and remove links to it. */
+/* return true iff we just wound up freeing the server_port. */
+static int
+server_request_free(struct server_request *req)
+{
+ int i, rc=1, lock=0;
+ if (req->base.questions) {
+ for (i = 0; i < req->base.nquestions; ++i)
+ mm_free(req->base.questions[i]);
+ mm_free(req->base.questions);
+ }
+
+ if (req->port) {
+ EVDNS_LOCK(req->port);
+ lock=1;
+ if (req->port->pending_replies == req) {
+ if (req->next_pending && req->next_pending != req)
+ req->port->pending_replies = req->next_pending;
+ else
+ req->port->pending_replies = NULL;
+ }
+ rc = --req->port->refcnt;
+ }
+
+ if (req->response) {
+ mm_free(req->response);
+ }
+
+ server_request_free_answers(req);
+
+ if (req->next_pending && req->next_pending != req) {
+ req->next_pending->prev_pending = req->prev_pending;
+ req->prev_pending->next_pending = req->next_pending;
+ }
+
+ if (rc == 0) {
+ EVDNS_UNLOCK(req->port); /* ????? nickm */
+ server_port_free(req->port);
+ mm_free(req);
+ return (1);
+ }
+ if (lock)
+ EVDNS_UNLOCK(req->port);
+ mm_free(req);
+ return (0);
+}
+
+/* Free all storage held by an evdns_server_port. Only called when */
+static void
+server_port_free(struct evdns_server_port *port)
+{
+ EVUTIL_ASSERT(port);
+ EVUTIL_ASSERT(!port->refcnt);
+ EVUTIL_ASSERT(!port->pending_replies);
+ if (port->socket > 0) {
+ evutil_closesocket(port->socket);
+ port->socket = -1;
+ }
+ (void) event_del(&port->event);
+ event_debug_unassign(&port->event);
+ EVTHREAD_FREE_LOCK(port->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ mm_free(port);
+}
+
+/* exported function */
+int
+evdns_server_request_drop(struct evdns_server_request *req_)
+{
+ struct server_request *req = TO_SERVER_REQUEST(req_);
+ server_request_free(req);
+ return 0;
+}
+
+/* exported function */
+int
+evdns_server_request_get_requesting_addr(struct evdns_server_request *req_, struct sockaddr *sa, int addr_len)
+{
+ struct server_request *req = TO_SERVER_REQUEST(req_);
+ if (addr_len < (int)req->addrlen)
+ return -1;
+ memcpy(sa, &(req->addr), req->addrlen);
+ return req->addrlen;
+}
+
+#undef APPEND16
+#undef APPEND32
+
+/* this is a libevent callback function which is called when a request */
+/* has timed out. */
+static void
+evdns_request_timeout_callback(evutil_socket_t fd, short events, void *arg) {
+ struct request *const req = (struct request *) arg;
+ struct evdns_base *base = req->base;
+
+ (void) fd;
+ (void) events;
+
+ log(EVDNS_LOG_DEBUG, "Request %p timed out", arg);
+ EVDNS_LOCK(base);
+
+ if (req->tx_count >= req->base->global_max_retransmits) {
+ struct nameserver *ns = req->ns;
+ /* this request has failed */
+ log(EVDNS_LOG_DEBUG, "Giving up on request %p; tx_count==%d",
+ arg, req->tx_count);
+ reply_schedule_callback(req, 0, DNS_ERR_TIMEOUT, NULL);
+
+ request_finished(req, &REQ_HEAD(req->base, req->trans_id), 1);
+ nameserver_failed(ns, "request timed out.");
+ } else {
+ /* retransmit it */
+ log(EVDNS_LOG_DEBUG, "Retransmitting request %p; tx_count==%d",
+ arg, req->tx_count);
+ (void) evtimer_del(&req->timeout_event);
+ request_swap_ns(req, nameserver_pick(base));
+ evdns_request_transmit(req);
+
+ req->ns->timedout++;
+ if (req->ns->timedout > req->base->global_max_nameserver_timeout) {
+ req->ns->timedout = 0;
+ nameserver_failed(req->ns, "request timed out.");
+ }
+ }
+
+ EVDNS_UNLOCK(base);
+}
+
+/* try to send a request to a given server. */
+/* */
+/* return: */
+/* 0 ok */
+/* 1 temporary failure */
+/* 2 other failure */
+static int
+evdns_request_transmit_to(struct request *req, struct nameserver *server) {
+ int r;
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+
+ if (server->requests_inflight == 1 &&
+ req->base->disable_when_inactive &&
+ event_add(&server->event, NULL) < 0) {
+ return 1;
+ }
+
+ r = sendto(server->socket, (void*)req->request, req->request_len, 0,
+ (struct sockaddr *)&server->address, server->addrlen);
+ if (r < 0) {
+ int err = evutil_socket_geterror(server->socket);
+ if (EVUTIL_ERR_RW_RETRIABLE(err))
+ return 1;
+ nameserver_failed(req->ns, evutil_socket_error_to_string(err));
+ return 2;
+ } else if (r != (int)req->request_len) {
+ return 1; /* short write */
+ } else {
+ return 0;
+ }
+}
+
+/* try to send a request, updating the fields of the request */
+/* as needed */
+/* */
+/* return: */
+/* 0 ok */
+/* 1 failed */
+static int
+evdns_request_transmit(struct request *req) {
+ int retcode = 0, r;
+
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+ /* if we fail to send this packet then this flag marks it */
+ /* for evdns_transmit */
+ req->transmit_me = 1;
+ EVUTIL_ASSERT(req->trans_id != 0xffff);
+
+ if (!req->ns)
+ {
+ /* unable to transmit request if no nameservers */
+ return 1;
+ }
+
+ if (req->ns->choked) {
+ /* don't bother trying to write to a socket */
+ /* which we have had EAGAIN from */
+ return 1;
+ }
+
+ r = evdns_request_transmit_to(req, req->ns);
+ switch (r) {
+ case 1:
+ /* temp failure */
+ req->ns->choked = 1;
+ nameserver_write_waiting(req->ns, 1);
+ return 1;
+ case 2:
+ /* failed to transmit the request entirely. we can fallthrough since
+ * we'll set a timeout, which will time out, and make us retransmit the
+ * request anyway. */
+ retcode = 1;
+ EVUTIL_FALLTHROUGH;
+ default:
+ /* all ok */
+ log(EVDNS_LOG_DEBUG,
+ "Setting timeout for request %p, sent to nameserver %p", req, req->ns);
+ if (evtimer_add(&req->timeout_event, &req->base->global_timeout) < 0) {
+ log(EVDNS_LOG_WARN,
+ "Error from libevent when adding timer for request %p",
+ req);
+ /* ???? Do more? */
+ }
+ req->tx_count++;
+ req->transmit_me = 0;
+ return retcode;
+ }
+}
+
+static void
+nameserver_probe_callback(int result, char type, int count, int ttl, void *addresses, void *arg) {
+ struct nameserver *const ns = (struct nameserver *) arg;
+ (void) type;
+ (void) count;
+ (void) ttl;
+ (void) addresses;
+
+ if (result == DNS_ERR_CANCEL) {
+ /* We canceled this request because the nameserver came up
+ * for some other reason. Do not change our opinion about
+ * the nameserver. */
+ return;
+ }
+
+ EVDNS_LOCK(ns->base);
+ ns->probe_request = NULL;
+ if (result == DNS_ERR_NONE || result == DNS_ERR_NOTEXIST) {
+ /* this is a good reply */
+ nameserver_up(ns);
+ } else {
+ nameserver_probe_failed(ns);
+ }
+ EVDNS_UNLOCK(ns->base);
+}
+
+static void
+nameserver_send_probe(struct nameserver *const ns) {
+ struct evdns_request *handle;
+ struct request *req;
+ char addrbuf[128];
+ /* here we need to send a probe to a given nameserver */
+ /* in the hope that it is up now. */
+
+ ASSERT_LOCKED(ns->base);
+ log(EVDNS_LOG_DEBUG, "Sending probe to %s",
+ evutil_format_sockaddr_port_(
+ (struct sockaddr *)&ns->address,
+ addrbuf, sizeof(addrbuf)));
+ handle = mm_calloc(1, sizeof(*handle));
+ if (!handle) return;
+ req = request_new(ns->base, handle, TYPE_A, "google.com", DNS_QUERY_NO_SEARCH, nameserver_probe_callback, ns);
+ if (!req) {
+ mm_free(handle);
+ return;
+ }
+ ns->probe_request = handle;
+ /* we force this into the inflight queue no matter what */
+ request_trans_id_set(req, transaction_id_pick(ns->base));
+ req->ns = ns;
+ request_submit(req);
+}
+
+/* returns: */
+/* 0 didn't try to transmit anything */
+/* 1 tried to transmit something */
+static int
+evdns_transmit(struct evdns_base *base) {
+ char did_try_to_transmit = 0;
+ int i;
+
+ ASSERT_LOCKED(base);
+ for (i = 0; i < base->n_req_heads; ++i) {
+ if (base->req_heads[i]) {
+ struct request *const started_at = base->req_heads[i], *req = started_at;
+ /* first transmit all the requests which are currently waiting */
+ do {
+ if (req->transmit_me) {
+ did_try_to_transmit = 1;
+ evdns_request_transmit(req);
+ }
+
+ req = req->next;
+ } while (req != started_at);
+ }
+ }
+
+ return did_try_to_transmit;
+}
+
+/* exported function */
+int
+evdns_base_count_nameservers(struct evdns_base *base)
+{
+ const struct nameserver *server;
+ int n = 0;
+
+ EVDNS_LOCK(base);
+ server = base->server_head;
+ if (!server)
+ goto done;
+ do {
+ ++n;
+ server = server->next;
+ } while (server != base->server_head);
+done:
+ EVDNS_UNLOCK(base);
+ return n;
+}
+
+int
+evdns_count_nameservers(void)
+{
+ return evdns_base_count_nameservers(current_base);
+}
+
+/* exported function */
+int
+evdns_base_clear_nameservers_and_suspend(struct evdns_base *base)
+{
+ struct nameserver *server, *started_at;
+ int i;
+
+ EVDNS_LOCK(base);
+ server = base->server_head;
+ started_at = base->server_head;
+ if (!server) {
+ EVDNS_UNLOCK(base);
+ return 0;
+ }
+ while (1) {
+ struct nameserver *next = server->next;
+ (void) event_del(&server->event);
+ if (evtimer_initialized(&server->timeout_event))
+ (void) evtimer_del(&server->timeout_event);
+ if (server->probe_request) {
+ evdns_cancel_request(server->base, server->probe_request);
+ server->probe_request = NULL;
+ }
+ if (server->socket >= 0)
+ evutil_closesocket(server->socket);
+ mm_free(server);
+ if (next == started_at)
+ break;
+ server = next;
+ }
+ base->server_head = NULL;
+ base->global_good_nameservers = 0;
+
+ for (i = 0; i < base->n_req_heads; ++i) {
+ struct request *req, *req_started_at;
+ req = req_started_at = base->req_heads[i];
+ while (req) {
+ struct request *next = req->next;
+ req->tx_count = req->reissue_count = 0;
+ req->ns = NULL;
+ /* ???? What to do about searches? */
+ (void) evtimer_del(&req->timeout_event);
+ req->trans_id = 0;
+ req->transmit_me = 0;
+
+ base->global_requests_waiting++;
+ evdns_request_insert(req, &base->req_waiting_head);
+ /* We want to insert these suspended elements at the front of
+ * the waiting queue, since they were pending before any of
+ * the waiting entries were added. This is a circular list,
+ * so we can just shift the start back by one.*/
+ base->req_waiting_head = base->req_waiting_head->prev;
+
+ if (next == req_started_at)
+ break;
+ req = next;
+ }
+ base->req_heads[i] = NULL;
+ }
+
+ base->global_requests_inflight = 0;
+
+ EVDNS_UNLOCK(base);
+ return 0;
+}
+
+int
+evdns_clear_nameservers_and_suspend(void)
+{
+ return evdns_base_clear_nameservers_and_suspend(current_base);
+}
+
+
+/* exported function */
+int
+evdns_base_resume(struct evdns_base *base)
+{
+ EVDNS_LOCK(base);
+ evdns_requests_pump_waiting_queue(base);
+ EVDNS_UNLOCK(base);
+
+ return 0;
+}
+
+int
+evdns_resume(void)
+{
+ return evdns_base_resume(current_base);
+}
+
+static int
+evdns_nameserver_add_impl_(struct evdns_base *base, const struct sockaddr *address, int addrlen) {
+ /* first check to see if we already have this nameserver */
+
+ const struct nameserver *server = base->server_head, *const started_at = base->server_head;
+ struct nameserver *ns;
+ int err = 0;
+ char addrbuf[128];
+
+ ASSERT_LOCKED(base);
+ if (server) {
+ do {
+ if (!evutil_sockaddr_cmp((struct sockaddr*)&server->address, address, 1)) return 3;
+ server = server->next;
+ } while (server != started_at);
+ }
+ if (addrlen > (int)sizeof(ns->address)) {
+ log(EVDNS_LOG_DEBUG, "Addrlen %d too long.", (int)addrlen);
+ return 2;
+ }
+
+ ns = (struct nameserver *) mm_malloc(sizeof(struct nameserver));
+ if (!ns) return -1;
+
+ memset(ns, 0, sizeof(struct nameserver));
+ ns->base = base;
+
+ evtimer_assign(&ns->timeout_event, ns->base->event_base, nameserver_prod_callback, ns);
+
+ ns->socket = evutil_socket_(address->sa_family,
+ SOCK_DGRAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
+ if (ns->socket < 0) { err = 1; goto out1; }
+
+ if (base->global_outgoing_addrlen &&
+ !evutil_sockaddr_is_loopback_(address)) {
+ if (bind(ns->socket,
+ (struct sockaddr*)&base->global_outgoing_address,
+ base->global_outgoing_addrlen) < 0) {
+ log(EVDNS_LOG_WARN,"Couldn't bind to outgoing address");
+ err = 2;
+ goto out2;
+ }
+ }
+
+ if (base->so_rcvbuf) {
+ if (setsockopt(ns->socket, SOL_SOCKET, SO_RCVBUF,
+ (void *)&base->so_rcvbuf, sizeof(base->so_rcvbuf))) {
+ log(EVDNS_LOG_WARN, "Couldn't set SO_RCVBUF to %i", base->so_rcvbuf);
+ err = -SO_RCVBUF;
+ goto out2;
+ }
+ }
+ if (base->so_sndbuf) {
+ if (setsockopt(ns->socket, SOL_SOCKET, SO_SNDBUF,
+ (void *)&base->so_sndbuf, sizeof(base->so_sndbuf))) {
+ log(EVDNS_LOG_WARN, "Couldn't set SO_SNDBUF to %i", base->so_sndbuf);
+ err = -SO_SNDBUF;
+ goto out2;
+ }
+ }
+
+ memcpy(&ns->address, address, addrlen);
+ ns->addrlen = addrlen;
+ ns->state = 1;
+ event_assign(&ns->event, ns->base->event_base, ns->socket,
+ EV_READ | EV_PERSIST, nameserver_ready_callback, ns);
+ if (!base->disable_when_inactive && event_add(&ns->event, NULL) < 0) {
+ err = 2;
+ goto out2;
+ }
+
+ log(EVDNS_LOG_DEBUG, "Added nameserver %s as %p",
+ evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), ns);
+
+ /* insert this nameserver into the list of them */
+ if (!base->server_head) {
+ ns->next = ns->prev = ns;
+ base->server_head = ns;
+ } else {
+ ns->next = base->server_head->next;
+ ns->prev = base->server_head;
+ base->server_head->next = ns;
+ ns->next->prev = ns;
+ }
+
+ base->global_good_nameservers++;
+
+ return 0;
+
+out2:
+ evutil_closesocket(ns->socket);
+out1:
+ event_debug_unassign(&ns->event);
+ mm_free(ns);
+ log(EVDNS_LOG_WARN, "Unable to add nameserver %s: error %d",
+ evutil_format_sockaddr_port_(address, addrbuf, sizeof(addrbuf)), err);
+ return err;
+}
+
+/* exported function */
+int
+evdns_base_nameserver_add(struct evdns_base *base, unsigned long int address)
+{
+ struct sockaddr_in sin;
+ int res;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_addr.s_addr = address;
+ sin.sin_port = htons(53);
+ sin.sin_family = AF_INET;
+ EVDNS_LOCK(base);
+ res = evdns_nameserver_add_impl_(base, (struct sockaddr*)&sin, sizeof(sin));
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+int
+evdns_nameserver_add(unsigned long int address) {
+ if (!current_base)
+ current_base = evdns_base_new(NULL, 0);
+ return evdns_base_nameserver_add(current_base, address);
+}
+
+static void
+sockaddr_setport(struct sockaddr *sa, ev_uint16_t port)
+{
+ if (sa->sa_family == AF_INET) {
+ ((struct sockaddr_in *)sa)->sin_port = htons(port);
+ } else if (sa->sa_family == AF_INET6) {
+ ((struct sockaddr_in6 *)sa)->sin6_port = htons(port);
+ }
+}
+
+static ev_uint16_t
+sockaddr_getport(struct sockaddr *sa)
+{
+ if (sa->sa_family == AF_INET) {
+ return ntohs(((struct sockaddr_in *)sa)->sin_port);
+ } else if (sa->sa_family == AF_INET6) {
+ return ntohs(((struct sockaddr_in6 *)sa)->sin6_port);
+ } else {
+ return 0;
+ }
+}
+
+/* exported function */
+int
+evdns_base_nameserver_ip_add(struct evdns_base *base, const char *ip_as_string) {
+ struct sockaddr_storage ss;
+ struct sockaddr *sa;
+ int len = sizeof(ss);
+ int res;
+ if (evutil_parse_sockaddr_port(ip_as_string, (struct sockaddr *)&ss,
+ &len)) {
+ log(EVDNS_LOG_WARN, "Unable to parse nameserver address %s",
+ ip_as_string);
+ return 4;
+ }
+ sa = (struct sockaddr *) &ss;
+ if (sockaddr_getport(sa) == 0)
+ sockaddr_setport(sa, 53);
+
+ EVDNS_LOCK(base);
+ res = evdns_nameserver_add_impl_(base, sa, len);
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+int
+evdns_nameserver_ip_add(const char *ip_as_string) {
+ if (!current_base)
+ current_base = evdns_base_new(NULL, 0);
+ return evdns_base_nameserver_ip_add(current_base, ip_as_string);
+}
+
+int
+evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
+ const struct sockaddr *sa, ev_socklen_t len, unsigned flags)
+{
+ int res;
+ EVUTIL_ASSERT(base);
+ EVDNS_LOCK(base);
+ res = evdns_nameserver_add_impl_(base, sa, len);
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+int
+evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
+ struct sockaddr *sa, ev_socklen_t len)
+{
+ int result = -1;
+ int i;
+ struct nameserver *server;
+ EVDNS_LOCK(base);
+ server = base->server_head;
+ for (i = 0; i < idx && server; ++i, server = server->next) {
+ if (server->next == base->server_head)
+ goto done;
+ }
+ if (! server)
+ goto done;
+
+ if (server->addrlen > len) {
+ result = (int) server->addrlen;
+ goto done;
+ }
+
+ memcpy(sa, &server->address, server->addrlen);
+ result = (int) server->addrlen;
+done:
+ EVDNS_UNLOCK(base);
+ return result;
+}
+
+/* remove from the queue */
+static void
+evdns_request_remove(struct request *req, struct request **head)
+{
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+
+#if 0
+ {
+ struct request *ptr;
+ int found = 0;
+ EVUTIL_ASSERT(*head != NULL);
+
+ ptr = *head;
+ do {
+ if (ptr == req) {
+ found = 1;
+ break;
+ }
+ ptr = ptr->next;
+ } while (ptr != *head);
+ EVUTIL_ASSERT(found);
+
+ EVUTIL_ASSERT(req->next);
+ }
+#endif
+
+ if (req->next == req) {
+ /* only item in the list */
+ *head = NULL;
+ } else {
+ req->next->prev = req->prev;
+ req->prev->next = req->next;
+ if (*head == req) *head = req->next;
+ }
+ req->next = req->prev = NULL;
+}
+
+/* insert into the tail of the queue */
+static void
+evdns_request_insert(struct request *req, struct request **head) {
+ ASSERT_LOCKED(req->base);
+ ASSERT_VALID_REQUEST(req);
+ if (!*head) {
+ *head = req;
+ req->next = req->prev = req;
+ return;
+ }
+
+ req->prev = (*head)->prev;
+ req->prev->next = req;
+ req->next = *head;
+ (*head)->prev = req;
+}
+
+static int
+string_num_dots(const char *s) {
+ int count = 0;
+ while ((s = strchr(s, '.'))) {
+ s++;
+ count++;
+ }
+ return count;
+}
+
+static struct request *
+request_new(struct evdns_base *base, struct evdns_request *handle, int type,
+ const char *name, int flags, evdns_callback_type callback,
+ void *user_ptr) {
+
+ const char issuing_now =
+ (base->global_requests_inflight < base->global_max_requests_inflight) ? 1 : 0;
+
+ const size_t name_len = strlen(name);
+ const size_t request_max_len = evdns_request_len(name_len);
+ const u16 trans_id = issuing_now ? transaction_id_pick(base) : 0xffff;
+ /* the request data is alloced in a single block with the header */
+ struct request *const req =
+ mm_malloc(sizeof(struct request) + request_max_len);
+ int rlen;
+ char namebuf[256];
+ (void) flags;
+
+ ASSERT_LOCKED(base);
+
+ if (!req) return NULL;
+
+ if (name_len >= sizeof(namebuf)) {
+ mm_free(req);
+ return NULL;
+ }
+
+ memset(req, 0, sizeof(struct request));
+ req->base = base;
+
+ evtimer_assign(&req->timeout_event, req->base->event_base, evdns_request_timeout_callback, req);
+
+ if (base->global_randomize_case) {
+ unsigned i;
+ char randbits[(sizeof(namebuf)+7)/8];
+ strlcpy(namebuf, name, sizeof(namebuf));
+ evutil_secure_rng_get_bytes(randbits, (name_len+7)/8);
+ for (i = 0; i < name_len; ++i) {
+ if (EVUTIL_ISALPHA_(namebuf[i])) {
+ if ((randbits[i >> 3] & (1<<(i & 7))))
+ namebuf[i] |= 0x20;
+ else
+ namebuf[i] &= ~0x20;
+ }
+ }
+ name = namebuf;
+ }
+
+ /* request data lives just after the header */
+ req->request = ((u8 *) req) + sizeof(struct request);
+ /* denotes that the request data shouldn't be free()ed */
+ req->request_appended = 1;
+ rlen = evdns_request_data_build(name, name_len, trans_id,
+ type, CLASS_INET, req->request, request_max_len);
+ if (rlen < 0)
+ goto err1;
+
+ req->request_len = rlen;
+ req->trans_id = trans_id;
+ req->tx_count = 0;
+ req->request_type = type;
+ req->user_pointer = user_ptr;
+ req->user_callback = callback;
+ req->ns = issuing_now ? nameserver_pick(base) : NULL;
+ req->next = req->prev = NULL;
+ req->handle = handle;
+ if (handle) {
+ handle->current_req = req;
+ handle->base = base;
+ }
+
+ return req;
+err1:
+ mm_free(req);
+ return NULL;
+}
+
+static void
+request_submit(struct request *const req) {
+ struct evdns_base *base = req->base;
+ ASSERT_LOCKED(base);
+ ASSERT_VALID_REQUEST(req);
+ if (req->ns) {
+ /* if it has a nameserver assigned then this is going */
+ /* straight into the inflight queue */
+ evdns_request_insert(req, &REQ_HEAD(base, req->trans_id));
+
+ base->global_requests_inflight++;
+ req->ns->requests_inflight++;
+
+ evdns_request_transmit(req);
+ } else {
+ evdns_request_insert(req, &base->req_waiting_head);
+ base->global_requests_waiting++;
+ }
+}
+
+/* exported function */
+void
+evdns_cancel_request(struct evdns_base *base, struct evdns_request *handle)
+{
+ struct request *req;
+
+ if (!handle->current_req)
+ return;
+
+ if (!base) {
+ /* This redundancy is silly; can we fix it? (Not for 2.0) XXXX */
+ base = handle->base;
+ if (!base)
+ base = handle->current_req->base;
+ }
+
+ EVDNS_LOCK(base);
+ if (handle->pending_cb) {
+ EVDNS_UNLOCK(base);
+ return;
+ }
+
+ req = handle->current_req;
+ ASSERT_VALID_REQUEST(req);
+
+ reply_schedule_callback(req, 0, DNS_ERR_CANCEL, NULL);
+ if (req->ns) {
+ /* remove from inflight queue */
+ request_finished(req, &REQ_HEAD(base, req->trans_id), 1);
+ } else {
+ /* remove from global_waiting head */
+ request_finished(req, &base->req_waiting_head, 1);
+ }
+ EVDNS_UNLOCK(base);
+}
+
+/* exported function */
+struct evdns_request *
+evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags,
+ evdns_callback_type callback, void *ptr) {
+ struct evdns_request *handle;
+ struct request *req;
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
+ handle = mm_calloc(1, sizeof(*handle));
+ if (handle == NULL)
+ return NULL;
+ EVDNS_LOCK(base);
+ if (flags & DNS_QUERY_NO_SEARCH) {
+ req =
+ request_new(base, handle, TYPE_A, name, flags,
+ callback, ptr);
+ if (req)
+ request_submit(req);
+ } else {
+ search_request_new(base, handle, TYPE_A, name, flags,
+ callback, ptr);
+ }
+ if (handle->current_req == NULL) {
+ mm_free(handle);
+ handle = NULL;
+ }
+ EVDNS_UNLOCK(base);
+ return handle;
+}
+
+int evdns_resolve_ipv4(const char *name, int flags,
+ evdns_callback_type callback, void *ptr)
+{
+ return evdns_base_resolve_ipv4(current_base, name, flags, callback, ptr)
+ ? 0 : -1;
+}
+
+
+/* exported function */
+struct evdns_request *
+evdns_base_resolve_ipv6(struct evdns_base *base,
+ const char *name, int flags,
+ evdns_callback_type callback, void *ptr)
+{
+ struct evdns_request *handle;
+ struct request *req;
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s", name);
+ handle = mm_calloc(1, sizeof(*handle));
+ if (handle == NULL)
+ return NULL;
+ EVDNS_LOCK(base);
+ if (flags & DNS_QUERY_NO_SEARCH) {
+ req = request_new(base, handle, TYPE_AAAA, name, flags,
+ callback, ptr);
+ if (req)
+ request_submit(req);
+ } else {
+ search_request_new(base, handle, TYPE_AAAA, name, flags,
+ callback, ptr);
+ }
+ if (handle->current_req == NULL) {
+ mm_free(handle);
+ handle = NULL;
+ }
+ EVDNS_UNLOCK(base);
+ return handle;
+}
+
+int evdns_resolve_ipv6(const char *name, int flags,
+ evdns_callback_type callback, void *ptr) {
+ return evdns_base_resolve_ipv6(current_base, name, flags, callback, ptr)
+ ? 0 : -1;
+}
+
+struct evdns_request *
+evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+ char buf[32];
+ struct evdns_request *handle;
+ struct request *req;
+ u32 a;
+ EVUTIL_ASSERT(in);
+ a = ntohl(in->s_addr);
+ evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d.in-addr.arpa",
+ (int)(u8)((a )&0xff),
+ (int)(u8)((a>>8 )&0xff),
+ (int)(u8)((a>>16)&0xff),
+ (int)(u8)((a>>24)&0xff));
+ handle = mm_calloc(1, sizeof(*handle));
+ if (handle == NULL)
+ return NULL;
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+ EVDNS_LOCK(base);
+ req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
+ if (req)
+ request_submit(req);
+ if (handle->current_req == NULL) {
+ mm_free(handle);
+ handle = NULL;
+ }
+ EVDNS_UNLOCK(base);
+ return (handle);
+}
+
+int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+ return evdns_base_resolve_reverse(current_base, in, flags, callback, ptr)
+ ? 0 : -1;
+}
+
+struct evdns_request *
+evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+ /* 32 nybbles, 32 periods, "ip6.arpa", NUL. */
+ char buf[73];
+ char *cp;
+ struct evdns_request *handle;
+ struct request *req;
+ int i;
+ EVUTIL_ASSERT(in);
+ cp = buf;
+ for (i=15; i >= 0; --i) {
+ u8 byte = in->s6_addr[i];
+ *cp++ = "0123456789abcdef"[byte & 0x0f];
+ *cp++ = '.';
+ *cp++ = "0123456789abcdef"[byte >> 4];
+ *cp++ = '.';
+ }
+ EVUTIL_ASSERT(cp + strlen("ip6.arpa") < buf+sizeof(buf));
+ memcpy(cp, "ip6.arpa", strlen("ip6.arpa")+1);
+ handle = mm_calloc(1, sizeof(*handle));
+ if (handle == NULL)
+ return NULL;
+ log(EVDNS_LOG_DEBUG, "Resolve requested for %s (reverse)", buf);
+ EVDNS_LOCK(base);
+ req = request_new(base, handle, TYPE_PTR, buf, flags, callback, ptr);
+ if (req)
+ request_submit(req);
+ if (handle->current_req == NULL) {
+ mm_free(handle);
+ handle = NULL;
+ }
+ EVDNS_UNLOCK(base);
+ return (handle);
+}
+
+int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr) {
+ return evdns_base_resolve_reverse_ipv6(current_base, in, flags, callback, ptr)
+ ? 0 : -1;
+}
+
+/* ================================================================= */
+/* Search support */
+/* */
+/* the libc resolver has support for searching a number of domains */
+/* to find a name. If nothing else then it takes the single domain */
+/* from the gethostname() call. */
+/* */
+/* It can also be configured via the domain and search options in a */
+/* resolv.conf. */
+/* */
+/* The ndots option controls how many dots it takes for the resolver */
+/* to decide that a name is non-local and so try a raw lookup first. */
+
+struct search_domain {
+ int len;
+ struct search_domain *next;
+ /* the text string is appended to this structure */
+};
+
+struct search_state {
+ int refcount;
+ int ndots;
+ int num_domains;
+ struct search_domain *head;
+};
+
+static void
+search_state_decref(struct search_state *const state) {
+ if (!state) return;
+ state->refcount--;
+ if (!state->refcount) {
+ struct search_domain *next, *dom;
+ for (dom = state->head; dom; dom = next) {
+ next = dom->next;
+ mm_free(dom);
+ }
+ mm_free(state);
+ }
+}
+
+static struct search_state *
+search_state_new(void) {
+ struct search_state *state = (struct search_state *) mm_malloc(sizeof(struct search_state));
+ if (!state) return NULL;
+ memset(state, 0, sizeof(struct search_state));
+ state->refcount = 1;
+ state->ndots = 1;
+
+ return state;
+}
+
+static void
+search_postfix_clear(struct evdns_base *base) {
+ search_state_decref(base->global_search_state);
+
+ base->global_search_state = search_state_new();
+}
+
+/* exported function */
+void
+evdns_base_search_clear(struct evdns_base *base)
+{
+ EVDNS_LOCK(base);
+ search_postfix_clear(base);
+ EVDNS_UNLOCK(base);
+}
+
+void
+evdns_search_clear(void) {
+ evdns_base_search_clear(current_base);
+}
+
+static void
+search_postfix_add(struct evdns_base *base, const char *domain) {
+ size_t domain_len;
+ struct search_domain *sdomain;
+ while (domain[0] == '.') domain++;
+ domain_len = strlen(domain);
+
+ ASSERT_LOCKED(base);
+ if (!base->global_search_state) base->global_search_state = search_state_new();
+ if (!base->global_search_state) return;
+ base->global_search_state->num_domains++;
+
+ sdomain = (struct search_domain *) mm_malloc(sizeof(struct search_domain) + domain_len);
+ if (!sdomain) return;
+ memcpy( ((u8 *) sdomain) + sizeof(struct search_domain), domain, domain_len);
+ sdomain->next = base->global_search_state->head;
+ sdomain->len = (int) domain_len;
+
+ base->global_search_state->head = sdomain;
+}
+
+/* reverse the order of members in the postfix list. This is needed because, */
+/* when parsing resolv.conf we push elements in the wrong order */
+static void
+search_reverse(struct evdns_base *base) {
+ struct search_domain *cur, *prev = NULL, *next;
+ ASSERT_LOCKED(base);
+ cur = base->global_search_state->head;
+ while (cur) {
+ next = cur->next;
+ cur->next = prev;
+ prev = cur;
+ cur = next;
+ }
+
+ base->global_search_state->head = prev;
+}
+
+/* exported function */
+void
+evdns_base_search_add(struct evdns_base *base, const char *domain) {
+ EVDNS_LOCK(base);
+ search_postfix_add(base, domain);
+ EVDNS_UNLOCK(base);
+}
+void
+evdns_search_add(const char *domain) {
+ evdns_base_search_add(current_base, domain);
+}
+
+/* exported function */
+void
+evdns_base_search_ndots_set(struct evdns_base *base, const int ndots) {
+ EVDNS_LOCK(base);
+ if (!base->global_search_state) base->global_search_state = search_state_new();
+ if (base->global_search_state)
+ base->global_search_state->ndots = ndots;
+ EVDNS_UNLOCK(base);
+}
+void
+evdns_search_ndots_set(const int ndots) {
+ evdns_base_search_ndots_set(current_base, ndots);
+}
+
+static void
+search_set_from_hostname(struct evdns_base *base) {
+ char hostname[HOST_NAME_MAX + 1], *domainname;
+
+ ASSERT_LOCKED(base);
+ search_postfix_clear(base);
+ if (gethostname(hostname, sizeof(hostname))) return;
+ domainname = strchr(hostname, '.');
+ if (!domainname) return;
+ search_postfix_add(base, domainname);
+}
+
+/* warning: returns malloced string */
+static char *
+search_make_new(const struct search_state *const state, int n, const char *const base_name) {
+ const size_t base_len = strlen(base_name);
+ char need_to_append_dot;
+ struct search_domain *dom;
+
+ if (!base_len) return NULL;
+ need_to_append_dot = base_name[base_len - 1] == '.' ? 0 : 1;
+
+ for (dom = state->head; dom; dom = dom->next) {
+ if (!n--) {
+ /* this is the postfix we want */
+ /* the actual postfix string is kept at the end of the structure */
+ const u8 *const postfix = ((u8 *) dom) + sizeof(struct search_domain);
+ const int postfix_len = dom->len;
+ char *const newname = (char *) mm_malloc(base_len + need_to_append_dot + postfix_len + 1);
+ if (!newname) return NULL;
+ memcpy(newname, base_name, base_len);
+ if (need_to_append_dot) newname[base_len] = '.';
+ memcpy(newname + base_len + need_to_append_dot, postfix, postfix_len);
+ newname[base_len + need_to_append_dot + postfix_len] = 0;
+ return newname;
+ }
+ }
+
+ /* we ran off the end of the list and still didn't find the requested string */
+ EVUTIL_ASSERT(0);
+ return NULL; /* unreachable; stops warnings in some compilers. */
+}
+
+static struct request *
+search_request_new(struct evdns_base *base, struct evdns_request *handle,
+ int type, const char *const name, int flags,
+ evdns_callback_type user_callback, void *user_arg) {
+ ASSERT_LOCKED(base);
+ EVUTIL_ASSERT(type == TYPE_A || type == TYPE_AAAA);
+ EVUTIL_ASSERT(handle->current_req == NULL);
+ if ( ((flags & DNS_QUERY_NO_SEARCH) == 0) &&
+ base->global_search_state &&
+ base->global_search_state->num_domains) {
+ /* we have some domains to search */
+ struct request *req;
+ if (string_num_dots(name) >= base->global_search_state->ndots) {
+ req = request_new(base, handle, type, name, flags, user_callback, user_arg);
+ if (!req) return NULL;
+ handle->search_index = -1;
+ } else {
+ char *const new_name = search_make_new(base->global_search_state, 0, name);
+ if (!new_name) return NULL;
+ req = request_new(base, handle, type, new_name, flags, user_callback, user_arg);
+ mm_free(new_name);
+ if (!req) return NULL;
+ handle->search_index = 0;
+ }
+ EVUTIL_ASSERT(handle->search_origname == NULL);
+ handle->search_origname = mm_strdup(name);
+ if (handle->search_origname == NULL) {
+ /* XXX Should we dealloc req? If yes, how? */
+ if (req)
+ mm_free(req);
+ return NULL;
+ }
+ handle->search_state = base->global_search_state;
+ handle->search_flags = flags;
+ base->global_search_state->refcount++;
+ request_submit(req);
+ return req;
+ } else {
+ struct request *const req = request_new(base, handle, type, name, flags, user_callback, user_arg);
+ if (!req) return NULL;
+ request_submit(req);
+ return req;
+ }
+}
+
+/* this is called when a request has failed to find a name. We need to check */
+/* if it is part of a search and, if so, try the next name in the list */
+/* returns: */
+/* 0 another request has been submitted */
+/* 1 no more requests needed */
+static int
+search_try_next(struct evdns_request *const handle) {
+ struct request *req = handle->current_req;
+ struct evdns_base *base = req->base;
+ struct request *newreq;
+ ASSERT_LOCKED(base);
+ if (handle->search_state) {
+ /* it is part of a search */
+ char *new_name;
+ handle->search_index++;
+ if (handle->search_index >= handle->search_state->num_domains) {
+ /* no more postfixes to try, however we may need to try */
+ /* this name without a postfix */
+ if (string_num_dots(handle->search_origname) < handle->search_state->ndots) {
+ /* yep, we need to try it raw */
+ newreq = request_new(base, NULL, req->request_type, handle->search_origname, handle->search_flags, req->user_callback, req->user_pointer);
+ log(EVDNS_LOG_DEBUG, "Search: trying raw query %s", handle->search_origname);
+ if (newreq) {
+ search_request_finished(handle);
+ goto submit_next;
+ }
+ }
+ return 1;
+ }
+
+ new_name = search_make_new(handle->search_state, handle->search_index, handle->search_origname);
+ if (!new_name) return 1;
+ log(EVDNS_LOG_DEBUG, "Search: now trying %s (%d)", new_name, handle->search_index);
+ newreq = request_new(base, NULL, req->request_type, new_name, handle->search_flags, req->user_callback, req->user_pointer);
+ mm_free(new_name);
+ if (!newreq) return 1;
+ goto submit_next;
+ }
+ return 1;
+
+submit_next:
+ request_finished(req, &REQ_HEAD(req->base, req->trans_id), 0);
+ handle->current_req = newreq;
+ newreq->handle = handle;
+ request_submit(newreq);
+ return 0;
+}
+
+static void
+search_request_finished(struct evdns_request *const handle) {
+ ASSERT_LOCKED(handle->current_req->base);
+ if (handle->search_state) {
+ search_state_decref(handle->search_state);
+ handle->search_state = NULL;
+ }
+ if (handle->search_origname) {
+ mm_free(handle->search_origname);
+ handle->search_origname = NULL;
+ }
+}
+
+/* ================================================================= */
+/* Parsing resolv.conf files */
+
+static void
+evdns_resolv_set_defaults(struct evdns_base *base, int flags) {
+ int add_default = flags & DNS_OPTION_NAMESERVERS;
+ if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
+ add_default = 0;
+
+ /* if the file isn't found then we assume a local resolver */
+ ASSERT_LOCKED(base);
+ if (flags & DNS_OPTION_SEARCH)
+ search_set_from_hostname(base);
+ if (add_default)
+ evdns_base_nameserver_ip_add(base, "127.0.0.1");
+}
+
+#ifndef EVENT__HAVE_STRTOK_R
+static char *
+strtok_r(char *s, const char *delim, char **state) {
+ char *cp, *start;
+ start = cp = s ? s : *state;
+ if (!cp)
+ return NULL;
+ while (*cp && !strchr(delim, *cp))
+ ++cp;
+ if (!*cp) {
+ if (cp == start)
+ return NULL;
+ *state = NULL;
+ return start;
+ } else {
+ *cp++ = '\0';
+ *state = cp;
+ return start;
+ }
+}
+#endif
+
+/* helper version of atoi which returns -1 on error */
+static int
+strtoint(const char *const str)
+{
+ char *endptr;
+ const int r = strtol(str, &endptr, 10);
+ if (*endptr) return -1;
+ return r;
+}
+
+/* Parse a number of seconds into a timeval; return -1 on error. */
+static int
+evdns_strtotimeval(const char *const str, struct timeval *out)
+{
+ double d;
+ char *endptr;
+ d = strtod(str, &endptr);
+ if (*endptr) return -1;
+ if (d < 0) return -1;
+ out->tv_sec = (int) d;
+ out->tv_usec = (int) ((d - (int) d)*1000000);
+ if (out->tv_sec == 0 && out->tv_usec < 1000) /* less than 1 msec */
+ return -1;
+ return 0;
+}
+
+/* helper version of atoi that returns -1 on error and clips to bounds. */
+static int
+strtoint_clipped(const char *const str, int min, int max)
+{
+ int r = strtoint(str);
+ if (r == -1)
+ return r;
+ else if (r<min)
+ return min;
+ else if (r>max)
+ return max;
+ else
+ return r;
+}
+
+static int
+evdns_base_set_max_requests_inflight(struct evdns_base *base, int maxinflight)
+{
+ int old_n_heads = base->n_req_heads, n_heads;
+ struct request **old_heads = base->req_heads, **new_heads, *req;
+ int i;
+
+ ASSERT_LOCKED(base);
+ if (maxinflight < 1)
+ maxinflight = 1;
+ n_heads = (maxinflight+4) / 5;
+ EVUTIL_ASSERT(n_heads > 0);
+ new_heads = mm_calloc(n_heads, sizeof(struct request*));
+ if (!new_heads)
+ return (-1);
+ if (old_heads) {
+ for (i = 0; i < old_n_heads; ++i) {
+ while (old_heads[i]) {
+ req = old_heads[i];
+ evdns_request_remove(req, &old_heads[i]);
+ evdns_request_insert(req, &new_heads[req->trans_id % n_heads]);
+ }
+ }
+ mm_free(old_heads);
+ }
+ base->req_heads = new_heads;
+ base->n_req_heads = n_heads;
+ base->global_max_requests_inflight = maxinflight;
+ return (0);
+}
+
+/* exported function */
+int
+evdns_base_set_option(struct evdns_base *base,
+ const char *option, const char *val)
+{
+ int res;
+ EVDNS_LOCK(base);
+ res = evdns_base_set_option_impl(base, option, val, DNS_OPTIONS_ALL);
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+static inline int
+str_matches_option(const char *s1, const char *optionname)
+{
+ /* Option names are given as "option:" We accept either 'option' in
+ * s1, or 'option:randomjunk'. The latter form is to implement the
+ * resolv.conf parser. */
+ size_t optlen = strlen(optionname);
+ size_t slen = strlen(s1);
+ if (slen == optlen || slen == optlen - 1)
+ return !strncmp(s1, optionname, slen);
+ else if (slen > optlen)
+ return !strncmp(s1, optionname, optlen);
+ else
+ return 0;
+}
+
+static int
+evdns_base_set_option_impl(struct evdns_base *base,
+ const char *option, const char *val, int flags)
+{
+ ASSERT_LOCKED(base);
+ if (str_matches_option(option, "ndots:")) {
+ const int ndots = strtoint(val);
+ if (ndots == -1) return -1;
+ if (!(flags & DNS_OPTION_SEARCH)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting ndots to %d", ndots);
+ if (!base->global_search_state) base->global_search_state = search_state_new();
+ if (!base->global_search_state) return -1;
+ base->global_search_state->ndots = ndots;
+ } else if (str_matches_option(option, "timeout:")) {
+ struct timeval tv;
+ if (evdns_strtotimeval(val, &tv) == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting timeout to %s", val);
+ memcpy(&base->global_timeout, &tv, sizeof(struct timeval));
+ } else if (str_matches_option(option, "getaddrinfo-allow-skew:")) {
+ struct timeval tv;
+ if (evdns_strtotimeval(val, &tv) == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting getaddrinfo-allow-skew to %s",
+ val);
+ memcpy(&base->global_getaddrinfo_allow_skew, &tv,
+ sizeof(struct timeval));
+ } else if (str_matches_option(option, "max-timeouts:")) {
+ const int maxtimeout = strtoint_clipped(val, 1, 255);
+ if (maxtimeout == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting maximum allowed timeouts to %d",
+ maxtimeout);
+ base->global_max_nameserver_timeout = maxtimeout;
+ } else if (str_matches_option(option, "max-inflight:")) {
+ const int maxinflight = strtoint_clipped(val, 1, 65000);
+ if (maxinflight == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting maximum inflight requests to %d",
+ maxinflight);
+ evdns_base_set_max_requests_inflight(base, maxinflight);
+ } else if (str_matches_option(option, "attempts:")) {
+ int retries = strtoint(val);
+ if (retries == -1) return -1;
+ if (retries > 255) retries = 255;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting retries to %d", retries);
+ base->global_max_retransmits = retries;
+ } else if (str_matches_option(option, "randomize-case:")) {
+ int randcase = strtoint(val);
+ if (randcase == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ base->global_randomize_case = randcase;
+ } else if (str_matches_option(option, "bind-to:")) {
+ /* XXX This only applies to successive nameservers, not
+ * to already-configured ones. We might want to fix that. */
+ int len = sizeof(base->global_outgoing_address);
+ if (!(flags & DNS_OPTION_NAMESERVERS)) return 0;
+ if (evutil_parse_sockaddr_port(val,
+ (struct sockaddr*)&base->global_outgoing_address, &len))
+ return -1;
+ base->global_outgoing_addrlen = len;
+ } else if (str_matches_option(option, "initial-probe-timeout:")) {
+ struct timeval tv;
+ if (evdns_strtotimeval(val, &tv) == -1) return -1;
+ if (tv.tv_sec > 3600)
+ tv.tv_sec = 3600;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting initial probe timeout to %s",
+ val);
+ memcpy(&base->global_nameserver_probe_initial_timeout, &tv,
+ sizeof(tv));
+ } else if (str_matches_option(option, "so-rcvbuf:")) {
+ int buf = strtoint(val);
+ if (buf == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting SO_RCVBUF to %s", val);
+ base->so_rcvbuf = buf;
+ } else if (str_matches_option(option, "so-sndbuf:")) {
+ int buf = strtoint(val);
+ if (buf == -1) return -1;
+ if (!(flags & DNS_OPTION_MISC)) return 0;
+ log(EVDNS_LOG_DEBUG, "Setting SO_SNDBUF to %s", val);
+ base->so_sndbuf = buf;
+ }
+ return 0;
+}
+
+int
+evdns_set_option(const char *option, const char *val, int flags)
+{
+ if (!current_base)
+ current_base = evdns_base_new(NULL, 0);
+ return evdns_base_set_option(current_base, option, val);
+}
+
+static void
+resolv_conf_parse_line(struct evdns_base *base, char *const start, int flags) {
+ char *strtok_state;
+ static const char *const delims = " \t";
+#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
+
+
+ char *const first_token = strtok_r(start, delims, &strtok_state);
+ ASSERT_LOCKED(base);
+ if (!first_token) return;
+
+ if (!strcmp(first_token, "nameserver") && (flags & DNS_OPTION_NAMESERVERS)) {
+ const char *const nameserver = NEXT_TOKEN;
+
+ if (nameserver)
+ evdns_base_nameserver_ip_add(base, nameserver);
+ } else if (!strcmp(first_token, "domain") && (flags & DNS_OPTION_SEARCH)) {
+ const char *const domain = NEXT_TOKEN;
+ if (domain) {
+ search_postfix_clear(base);
+ search_postfix_add(base, domain);
+ }
+ } else if (!strcmp(first_token, "search") && (flags & DNS_OPTION_SEARCH)) {
+ const char *domain;
+ search_postfix_clear(base);
+
+ while ((domain = NEXT_TOKEN)) {
+ search_postfix_add(base, domain);
+ }
+ search_reverse(base);
+ } else if (!strcmp(first_token, "options")) {
+ const char *option;
+ while ((option = NEXT_TOKEN)) {
+ const char *val = strchr(option, ':');
+ evdns_base_set_option_impl(base, option, val ? val+1 : "", flags);
+ }
+ }
+#undef NEXT_TOKEN
+}
+
+/* exported function */
+/* returns: */
+/* 0 no errors */
+/* 1 failed to open file */
+/* 2 failed to stat file */
+/* 3 file too large */
+/* 4 out of memory */
+/* 5 short read from file */
+int
+evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename) {
+ int res;
+ EVDNS_LOCK(base);
+ res = evdns_base_resolv_conf_parse_impl(base, flags, filename);
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+static char *
+evdns_get_default_hosts_filename(void)
+{
+#ifdef _WIN32
+ /* Windows is a little coy about where it puts its configuration
+ * files. Sure, they're _usually_ in C:\windows\system32, but
+ * there's no reason in principle they couldn't be in
+ * W:\hoboken chicken emergency\
+ */
+ char path[MAX_PATH+1];
+ static const char hostfile[] = "\\drivers\\etc\\hosts";
+ char *path_out;
+ size_t len_out;
+
+ if (! SHGetSpecialFolderPathA(NULL, path, CSIDL_SYSTEM, 0))
+ return NULL;
+ len_out = strlen(path)+strlen(hostfile)+1;
+ path_out = mm_malloc(len_out);
+ evutil_snprintf(path_out, len_out, "%s%s", path, hostfile);
+ return path_out;
+#else
+ return mm_strdup("/etc/hosts");
+#endif
+}
+
+static int
+evdns_base_resolv_conf_parse_impl(struct evdns_base *base, int flags, const char *const filename) {
+ size_t n;
+ char *resolv;
+ char *start;
+ int err = 0;
+ int add_default;
+
+ log(EVDNS_LOG_DEBUG, "Parsing resolv.conf file %s", filename);
+
+ add_default = flags & DNS_OPTION_NAMESERVERS;
+ if (flags & DNS_OPTION_NAMESERVERS_NO_DEFAULT)
+ add_default = 0;
+
+ if (flags & DNS_OPTION_HOSTSFILE) {
+ char *fname = evdns_get_default_hosts_filename();
+ evdns_base_load_hosts(base, fname);
+ if (fname)
+ mm_free(fname);
+ }
+
+ if (!filename) {
+ evdns_resolv_set_defaults(base, flags);
+ return 1;
+ }
+
+ if ((err = evutil_read_file_(filename, &resolv, &n, 0)) < 0) {
+ if (err == -1) {
+ /* No file. */
+ evdns_resolv_set_defaults(base, flags);
+ return 1;
+ } else {
+ return 2;
+ }
+ }
+
+ start = resolv;
+ for (;;) {
+ char *const newline = strchr(start, '\n');
+ if (!newline) {
+ resolv_conf_parse_line(base, start, flags);
+ break;
+ } else {
+ *newline = 0;
+ resolv_conf_parse_line(base, start, flags);
+ start = newline + 1;
+ }
+ }
+
+ if (!base->server_head && add_default) {
+ /* no nameservers were configured. */
+ evdns_base_nameserver_ip_add(base, "127.0.0.1");
+ err = 6;
+ }
+ if (flags & DNS_OPTION_SEARCH && (!base->global_search_state || base->global_search_state->num_domains == 0)) {
+ search_set_from_hostname(base);
+ }
+
+ mm_free(resolv);
+ return err;
+}
+
+int
+evdns_resolv_conf_parse(int flags, const char *const filename) {
+ if (!current_base)
+ current_base = evdns_base_new(NULL, 0);
+ return evdns_base_resolv_conf_parse(current_base, flags, filename);
+}
+
+
+#ifdef _WIN32
+/* Add multiple nameservers from a space-or-comma-separated list. */
+static int
+evdns_nameserver_ip_add_line(struct evdns_base *base, const char *ips) {
+ const char *addr;
+ char *buf;
+ int r;
+ ASSERT_LOCKED(base);
+ while (*ips) {
+ while (isspace(*ips) || *ips == ',' || *ips == '\t')
+ ++ips;
+ addr = ips;
+ while (isdigit(*ips) || *ips == '.' || *ips == ':' ||
+ *ips=='[' || *ips==']')
+ ++ips;
+ buf = mm_malloc(ips-addr+1);
+ if (!buf) return 4;
+ memcpy(buf, addr, ips-addr);
+ buf[ips-addr] = '\0';
+ r = evdns_base_nameserver_ip_add(base, buf);
+ mm_free(buf);
+ if (r) return r;
+ }
+ return 0;
+}
+
+typedef DWORD(WINAPI *GetNetworkParams_fn_t)(FIXED_INFO *, DWORD*);
+
+/* Use the windows GetNetworkParams interface in iphlpapi.dll to */
+/* figure out what our nameservers are. */
+static int
+load_nameservers_with_getnetworkparams(struct evdns_base *base)
+{
+ /* Based on MSDN examples and inspection of c-ares code. */
+ FIXED_INFO *fixed;
+ HMODULE handle = 0;
+ ULONG size = sizeof(FIXED_INFO);
+ void *buf = NULL;
+ int status = 0, r, added_any;
+ IP_ADDR_STRING *ns;
+ GetNetworkParams_fn_t fn;
+
+ ASSERT_LOCKED(base);
+ if (!(handle = evutil_load_windows_system_library_(
+ TEXT("iphlpapi.dll")))) {
+ log(EVDNS_LOG_WARN, "Could not open iphlpapi.dll");
+ status = -1;
+ goto done;
+ }
+ if (!(fn = (GetNetworkParams_fn_t) GetProcAddress(handle, "GetNetworkParams"))) {
+ log(EVDNS_LOG_WARN, "Could not get address of function.");
+ status = -1;
+ goto done;
+ }
+
+ buf = mm_malloc(size);
+ if (!buf) { status = 4; goto done; }
+ fixed = buf;
+ r = fn(fixed, &size);
+ if (r != ERROR_SUCCESS && r != ERROR_BUFFER_OVERFLOW) {
+ status = -1;
+ goto done;
+ }
+ if (r != ERROR_SUCCESS) {
+ mm_free(buf);
+ buf = mm_malloc(size);
+ if (!buf) { status = 4; goto done; }
+ fixed = buf;
+ r = fn(fixed, &size);
+ if (r != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG, "fn() failed.");
+ status = -1;
+ goto done;
+ }
+ }
+
+ EVUTIL_ASSERT(fixed);
+ added_any = 0;
+ ns = &(fixed->DnsServerList);
+ while (ns) {
+ r = evdns_nameserver_ip_add_line(base, ns->IpAddress.String);
+ if (r) {
+ log(EVDNS_LOG_DEBUG,"Could not add nameserver %s to list,error: %d",
+ (ns->IpAddress.String),(int)GetLastError());
+ status = r;
+ } else {
+ ++added_any;
+ log(EVDNS_LOG_DEBUG,"Successfully added %s as nameserver",ns->IpAddress.String);
+ }
+
+ ns = ns->Next;
+ }
+
+ if (!added_any) {
+ log(EVDNS_LOG_DEBUG, "No nameservers added.");
+ if (status == 0)
+ status = -1;
+ } else {
+ status = 0;
+ }
+
+ done:
+ if (buf)
+ mm_free(buf);
+ if (handle)
+ FreeLibrary(handle);
+ return status;
+}
+
+static int
+config_nameserver_from_reg_key(struct evdns_base *base, HKEY key, const TCHAR *subkey)
+{
+ char *buf;
+ DWORD bufsz = 0, type = 0;
+ int status = 0;
+
+ ASSERT_LOCKED(base);
+ if (RegQueryValueEx(key, subkey, 0, &type, NULL, &bufsz)
+ != ERROR_MORE_DATA)
+ return -1;
+ if (!(buf = mm_malloc(bufsz)))
+ return -1;
+
+ if (RegQueryValueEx(key, subkey, 0, &type, (LPBYTE)buf, &bufsz)
+ == ERROR_SUCCESS && bufsz > 1) {
+ status = evdns_nameserver_ip_add_line(base,buf);
+ }
+
+ mm_free(buf);
+ return status;
+}
+
+#define SERVICES_KEY TEXT("System\\CurrentControlSet\\Services\\")
+#define WIN_NS_9X_KEY SERVICES_KEY TEXT("VxD\\MSTCP")
+#define WIN_NS_NT_KEY SERVICES_KEY TEXT("Tcpip\\Parameters")
+
+static int
+load_nameservers_from_registry(struct evdns_base *base)
+{
+ int found = 0;
+ int r;
+#define TRY(k, name) \
+ if (!found && config_nameserver_from_reg_key(base,k,TEXT(name)) == 0) { \
+ log(EVDNS_LOG_DEBUG,"Found nameservers in %s/%s",#k,name); \
+ found = 1; \
+ } else if (!found) { \
+ log(EVDNS_LOG_DEBUG,"Didn't find nameservers in %s/%s", \
+ #k,#name); \
+ }
+
+ ASSERT_LOCKED(base);
+
+ if (((int)GetVersion()) > 0) { /* NT */
+ HKEY nt_key = 0, interfaces_key = 0;
+
+ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
+ KEY_READ, &nt_key) != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG,"Couldn't open nt key, %d",(int)GetLastError());
+ return -1;
+ }
+ r = RegOpenKeyEx(nt_key, TEXT("Interfaces"), 0,
+ KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS,
+ &interfaces_key);
+ if (r != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG,"Couldn't open interfaces key, %d",(int)GetLastError());
+ return -1;
+ }
+ TRY(nt_key, "NameServer");
+ TRY(nt_key, "DhcpNameServer");
+ TRY(interfaces_key, "NameServer");
+ TRY(interfaces_key, "DhcpNameServer");
+ RegCloseKey(interfaces_key);
+ RegCloseKey(nt_key);
+ } else {
+ HKEY win_key = 0;
+ if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X_KEY, 0,
+ KEY_READ, &win_key) != ERROR_SUCCESS) {
+ log(EVDNS_LOG_DEBUG, "Couldn't open registry key, %d", (int)GetLastError());
+ return -1;
+ }
+ TRY(win_key, "NameServer");
+ RegCloseKey(win_key);
+ }
+
+ if (found == 0) {
+ log(EVDNS_LOG_WARN,"Didn't find any nameservers.");
+ }
+
+ return found ? 0 : -1;
+#undef TRY
+}
+
+int
+evdns_base_config_windows_nameservers(struct evdns_base *base)
+{
+ int r;
+ char *fname;
+ if (base == NULL)
+ base = current_base;
+ if (base == NULL)
+ return -1;
+ EVDNS_LOCK(base);
+ fname = evdns_get_default_hosts_filename();
+ log(EVDNS_LOG_DEBUG, "Loading hosts entries from %s", fname);
+ evdns_base_load_hosts(base, fname);
+ if (fname)
+ mm_free(fname);
+
+ if (load_nameservers_with_getnetworkparams(base) == 0) {
+ EVDNS_UNLOCK(base);
+ return 0;
+ }
+ r = load_nameservers_from_registry(base);
+
+ EVDNS_UNLOCK(base);
+ return r;
+}
+
+int
+evdns_config_windows_nameservers(void)
+{
+ if (!current_base) {
+ current_base = evdns_base_new(NULL, 1);
+ return current_base == NULL ? -1 : 0;
+ } else {
+ return evdns_base_config_windows_nameservers(current_base);
+ }
+}
+#endif
+
+struct evdns_base *
+evdns_base_new(struct event_base *event_base, int flags)
+{
+ struct evdns_base *base;
+
+ if (evutil_secure_rng_init() < 0) {
+ log(EVDNS_LOG_WARN, "Unable to seed random number generator; "
+ "DNS can't run.");
+ return NULL;
+ }
+
+ /* Give the evutil library a hook into its evdns-enabled
+ * functionality. We can't just call evdns_getaddrinfo directly or
+ * else libevent-core will depend on libevent-extras. */
+ evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo);
+ evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel);
+
+ base = mm_malloc(sizeof(struct evdns_base));
+ if (base == NULL)
+ return (NULL);
+ memset(base, 0, sizeof(struct evdns_base));
+ base->req_waiting_head = NULL;
+
+ EVTHREAD_ALLOC_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ EVDNS_LOCK(base);
+
+ /* Set max requests inflight and allocate req_heads. */
+ base->req_heads = NULL;
+
+ evdns_base_set_max_requests_inflight(base, 64);
+
+ base->server_head = NULL;
+ base->event_base = event_base;
+ base->global_good_nameservers = base->global_requests_inflight =
+ base->global_requests_waiting = 0;
+
+ base->global_timeout.tv_sec = 5;
+ base->global_timeout.tv_usec = 0;
+ base->global_max_reissues = 1;
+ base->global_max_retransmits = 3;
+ base->global_max_nameserver_timeout = 3;
+ base->global_search_state = NULL;
+ base->global_randomize_case = 1;
+ base->global_getaddrinfo_allow_skew.tv_sec = 3;
+ base->global_getaddrinfo_allow_skew.tv_usec = 0;
+ base->global_nameserver_probe_initial_timeout.tv_sec = 10;
+ base->global_nameserver_probe_initial_timeout.tv_usec = 0;
+
+ TAILQ_INIT(&base->hostsdb);
+
+#define EVDNS_BASE_ALL_FLAGS ( \
+ EVDNS_BASE_INITIALIZE_NAMESERVERS | \
+ EVDNS_BASE_DISABLE_WHEN_INACTIVE | \
+ EVDNS_BASE_NAMESERVERS_NO_DEFAULT | \
+ 0)
+
+ if (flags & ~EVDNS_BASE_ALL_FLAGS) {
+ flags = EVDNS_BASE_INITIALIZE_NAMESERVERS;
+ log(EVDNS_LOG_WARN,
+ "Unrecognized flag passed to evdns_base_new(). Assuming "
+ "you meant EVDNS_BASE_INITIALIZE_NAMESERVERS.");
+ }
+#undef EVDNS_BASE_ALL_FLAGS
+
+ if (flags & EVDNS_BASE_INITIALIZE_NAMESERVERS) {
+ int r;
+ int opts = DNS_OPTIONS_ALL;
+ if (flags & EVDNS_BASE_NAMESERVERS_NO_DEFAULT) {
+ opts |= DNS_OPTION_NAMESERVERS_NO_DEFAULT;
+ }
+
+#ifdef _WIN32
+ r = evdns_base_config_windows_nameservers(base);
+#else
+ r = evdns_base_resolv_conf_parse(base, opts, "/etc/resolv.conf");
+#endif
+ if (r) {
+ evdns_base_free_and_unlock(base, 0);
+ return NULL;
+ }
+ }
+ if (flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE) {
+ base->disable_when_inactive = 1;
+ }
+
+ EVDNS_UNLOCK(base);
+ return base;
+}
+
+int
+evdns_init(void)
+{
+ struct evdns_base *base = evdns_base_new(NULL, 1);
+ if (base) {
+ current_base = base;
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+const char *
+evdns_err_to_string(int err)
+{
+ switch (err) {
+ case DNS_ERR_NONE: return "no error";
+ case DNS_ERR_FORMAT: return "misformatted query";
+ case DNS_ERR_SERVERFAILED: return "server failed";
+ case DNS_ERR_NOTEXIST: return "name does not exist";
+ case DNS_ERR_NOTIMPL: return "query not implemented";
+ case DNS_ERR_REFUSED: return "refused";
+
+ case DNS_ERR_TRUNCATED: return "reply truncated or ill-formed";
+ case DNS_ERR_UNKNOWN: return "unknown";
+ case DNS_ERR_TIMEOUT: return "request timed out";
+ case DNS_ERR_SHUTDOWN: return "dns subsystem shut down";
+ case DNS_ERR_CANCEL: return "dns request canceled";
+ case DNS_ERR_NODATA: return "no records in the reply";
+ default: return "[Unknown error code]";
+ }
+}
+
+static void
+evdns_nameserver_free(struct nameserver *server)
+{
+ if (server->socket >= 0)
+ evutil_closesocket(server->socket);
+ (void) event_del(&server->event);
+ event_debug_unassign(&server->event);
+ if (server->state == 0)
+ (void) event_del(&server->timeout_event);
+ if (server->probe_request) {
+ evdns_cancel_request(server->base, server->probe_request);
+ server->probe_request = NULL;
+ }
+ event_debug_unassign(&server->timeout_event);
+ mm_free(server);
+}
+
+static void
+evdns_base_free_and_unlock(struct evdns_base *base, int fail_requests)
+{
+ struct nameserver *server, *server_next;
+ struct search_domain *dom, *dom_next;
+ int i;
+
+ /* Requires that we hold the lock. */
+
+ /* TODO(nickm) we might need to refcount here. */
+
+ while (base->req_waiting_head) {
+ if (fail_requests)
+ reply_schedule_callback(base->req_waiting_head, 0, DNS_ERR_SHUTDOWN, NULL);
+ request_finished(base->req_waiting_head, &base->req_waiting_head, 1);
+ }
+ for (i = 0; i < base->n_req_heads; ++i) {
+ while (base->req_heads[i]) {
+ if (fail_requests)
+ reply_schedule_callback(base->req_heads[i], 0, DNS_ERR_SHUTDOWN, NULL);
+ request_finished(base->req_heads[i], &REQ_HEAD(base, base->req_heads[i]->trans_id), 1);
+ }
+ }
+ base->global_requests_inflight = base->global_requests_waiting = 0;
+
+ for (server = base->server_head; server; server = server_next) {
+ server_next = server->next;
+ /** already done something before */
+ server->probe_request = NULL;
+ evdns_nameserver_free(server);
+ if (server_next == base->server_head)
+ break;
+ }
+ base->server_head = NULL;
+ base->global_good_nameservers = 0;
+
+ if (base->global_search_state) {
+ for (dom = base->global_search_state->head; dom; dom = dom_next) {
+ dom_next = dom->next;
+ mm_free(dom);
+ }
+ mm_free(base->global_search_state);
+ base->global_search_state = NULL;
+ }
+
+ {
+ struct hosts_entry *victim;
+ while ((victim = TAILQ_FIRST(&base->hostsdb))) {
+ TAILQ_REMOVE(&base->hostsdb, victim, next);
+ mm_free(victim);
+ }
+ }
+
+ mm_free(base->req_heads);
+
+ EVDNS_UNLOCK(base);
+ EVTHREAD_FREE_LOCK(base->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+ mm_free(base);
+}
+
+void
+evdns_base_free(struct evdns_base *base, int fail_requests)
+{
+ EVDNS_LOCK(base);
+ evdns_base_free_and_unlock(base, fail_requests);
+}
+
+void
+evdns_base_clear_host_addresses(struct evdns_base *base)
+{
+ struct hosts_entry *victim;
+ EVDNS_LOCK(base);
+ while ((victim = TAILQ_FIRST(&base->hostsdb))) {
+ TAILQ_REMOVE(&base->hostsdb, victim, next);
+ mm_free(victim);
+ }
+ EVDNS_UNLOCK(base);
+}
+
+void
+evdns_shutdown(int fail_requests)
+{
+ if (current_base) {
+ struct evdns_base *b = current_base;
+ current_base = NULL;
+ evdns_base_free(b, fail_requests);
+ }
+ evdns_log_fn = NULL;
+}
+
+static int
+evdns_base_parse_hosts_line(struct evdns_base *base, char *line)
+{
+ char *strtok_state;
+ static const char *const delims = " \t";
+ char *const addr = strtok_r(line, delims, &strtok_state);
+ char *hostname, *hash;
+ struct sockaddr_storage ss;
+ int socklen = sizeof(ss);
+ ASSERT_LOCKED(base);
+
+#define NEXT_TOKEN strtok_r(NULL, delims, &strtok_state)
+
+ if (!addr || *addr == '#')
+ return 0;
+
+ memset(&ss, 0, sizeof(ss));
+ if (evutil_parse_sockaddr_port(addr, (struct sockaddr*)&ss, &socklen)<0)
+ return -1;
+ if (socklen > (int)sizeof(struct sockaddr_in6))
+ return -1;
+
+ if (sockaddr_getport((struct sockaddr*)&ss))
+ return -1;
+
+ while ((hostname = NEXT_TOKEN)) {
+ struct hosts_entry *he;
+ size_t namelen;
+ if ((hash = strchr(hostname, '#'))) {
+ if (hash == hostname)
+ return 0;
+ *hash = '\0';
+ }
+
+ namelen = strlen(hostname);
+
+ he = mm_calloc(1, sizeof(struct hosts_entry)+namelen);
+ if (!he)
+ return -1;
+ EVUTIL_ASSERT(socklen <= (int)sizeof(he->addr));
+ memcpy(&he->addr, &ss, socklen);
+ memcpy(he->hostname, hostname, namelen+1);
+ he->addrlen = socklen;
+
+ TAILQ_INSERT_TAIL(&base->hostsdb, he, next);
+
+ if (hash)
+ return 0;
+ }
+
+ return 0;
+#undef NEXT_TOKEN
+}
+
+static int
+evdns_base_load_hosts_impl(struct evdns_base *base, const char *hosts_fname)
+{
+ char *str=NULL, *cp, *eol;
+ size_t len;
+ int err=0;
+
+ ASSERT_LOCKED(base);
+
+ if (hosts_fname == NULL ||
+ (err = evutil_read_file_(hosts_fname, &str, &len, 0)) < 0) {
+ char tmp[64];
+ strlcpy(tmp, "127.0.0.1 localhost", sizeof(tmp));
+ evdns_base_parse_hosts_line(base, tmp);
+ strlcpy(tmp, "::1 localhost", sizeof(tmp));
+ evdns_base_parse_hosts_line(base, tmp);
+ return err ? -1 : 0;
+ }
+
+ /* This will break early if there is a NUL in the hosts file.
+ * Probably not a problem.*/
+ cp = str;
+ for (;;) {
+ eol = strchr(cp, '\n');
+
+ if (eol) {
+ *eol = '\0';
+ evdns_base_parse_hosts_line(base, cp);
+ cp = eol+1;
+ } else {
+ evdns_base_parse_hosts_line(base, cp);
+ break;
+ }
+ }
+
+ mm_free(str);
+ return 0;
+}
+
+int
+evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname)
+{
+ int res;
+ if (!base)
+ base = current_base;
+ EVDNS_LOCK(base);
+ res = evdns_base_load_hosts_impl(base, hosts_fname);
+ EVDNS_UNLOCK(base);
+ return res;
+}
+
+/* A single request for a getaddrinfo, either v4 or v6. */
+struct getaddrinfo_subrequest {
+ struct evdns_request *r;
+ ev_uint32_t type;
+};
+
+/* State data used to implement an in-progress getaddrinfo. */
+struct evdns_getaddrinfo_request {
+ struct evdns_base *evdns_base;
+ /* Copy of the modified 'hints' data that we'll use to build
+ * answers. */
+ struct evutil_addrinfo hints;
+ /* The callback to invoke when we're done */
+ evdns_getaddrinfo_cb user_cb;
+ /* User-supplied data to give to the callback. */
+ void *user_data;
+ /* The port to use when building sockaddrs. */
+ ev_uint16_t port;
+ /* The sub_request for an A record (if any) */
+ struct getaddrinfo_subrequest ipv4_request;
+ /* The sub_request for an AAAA record (if any) */
+ struct getaddrinfo_subrequest ipv6_request;
+
+ /* The cname result that we were told (if any) */
+ char *cname_result;
+
+ /* If we have one request answered and one request still inflight,
+ * then this field holds the answer from the first request... */
+ struct evutil_addrinfo *pending_result;
+ /* And this event is a timeout that will tell us to cancel the second
+ * request if it's taking a long time. */
+ struct event timeout;
+
+ /* And this field holds the error code from the first request... */
+ int pending_error;
+ /* If this is set, the user canceled this request. */
+ unsigned user_canceled : 1;
+ /* If this is set, the user can no longer cancel this request; we're
+ * just waiting for the free. */
+ unsigned request_done : 1;
+};
+
+/* Convert an evdns errors to the equivalent getaddrinfo error. */
+static int
+evdns_err_to_getaddrinfo_err(int e1)
+{
+ /* XXX Do this better! */
+ if (e1 == DNS_ERR_NONE)
+ return 0;
+ else if (e1 == DNS_ERR_NOTEXIST)
+ return EVUTIL_EAI_NONAME;
+ else
+ return EVUTIL_EAI_FAIL;
+}
+
+/* Return the more informative of two getaddrinfo errors. */
+static int
+getaddrinfo_merge_err(int e1, int e2)
+{
+ /* XXXX be cleverer here. */
+ if (e1 == 0)
+ return e2;
+ else
+ return e1;
+}
+
+static void
+free_getaddrinfo_request(struct evdns_getaddrinfo_request *data)
+{
+ /* DO NOT CALL this if either of the requests is pending. Only once
+ * both callbacks have been invoked is it safe to free the request */
+ if (data->pending_result)
+ evutil_freeaddrinfo(data->pending_result);
+ if (data->cname_result)
+ mm_free(data->cname_result);
+ event_del(&data->timeout);
+ mm_free(data);
+ return;
+}
+
+static void
+add_cname_to_reply(struct evdns_getaddrinfo_request *data,
+ struct evutil_addrinfo *ai)
+{
+ if (data->cname_result && ai) {
+ ai->ai_canonname = data->cname_result;
+ data->cname_result = NULL;
+ }
+}
+
+/* Callback: invoked when one request in a mixed-format A/AAAA getaddrinfo
+ * request has finished, but the other one took too long to answer. Pass
+ * along the answer we got, and cancel the other request.
+ */
+static void
+evdns_getaddrinfo_timeout_cb(evutil_socket_t fd, short what, void *ptr)
+{
+ int v4_timedout = 0, v6_timedout = 0;
+ struct evdns_getaddrinfo_request *data = ptr;
+
+ /* Cancel any pending requests, and note which one */
+ if (data->ipv4_request.r) {
+ /* XXXX This does nothing if the request's callback is already
+ * running (pending_cb is set). */
+ evdns_cancel_request(NULL, data->ipv4_request.r);
+ v4_timedout = 1;
+ EVDNS_LOCK(data->evdns_base);
+ ++data->evdns_base->getaddrinfo_ipv4_timeouts;
+ EVDNS_UNLOCK(data->evdns_base);
+ }
+ if (data->ipv6_request.r) {
+ /* XXXX This does nothing if the request's callback is already
+ * running (pending_cb is set). */
+ evdns_cancel_request(NULL, data->ipv6_request.r);
+ v6_timedout = 1;
+ EVDNS_LOCK(data->evdns_base);
+ ++data->evdns_base->getaddrinfo_ipv6_timeouts;
+ EVDNS_UNLOCK(data->evdns_base);
+ }
+
+ /* We only use this timeout callback when we have an answer for
+ * one address. */
+ EVUTIL_ASSERT(!v4_timedout || !v6_timedout);
+
+ /* Report the outcome of the other request that didn't time out. */
+ if (data->pending_result) {
+ add_cname_to_reply(data, data->pending_result);
+ data->user_cb(0, data->pending_result, data->user_data);
+ data->pending_result = NULL;
+ } else {
+ int e = data->pending_error;
+ if (!e)
+ e = EVUTIL_EAI_AGAIN;
+ data->user_cb(e, NULL, data->user_data);
+ }
+
+ data->user_cb = NULL; /* prevent double-call if evdns callbacks are
+ * in-progress. XXXX It would be better if this
+ * weren't necessary. */
+
+ if (!v4_timedout && !v6_timedout) {
+ /* should be impossible? XXXX */
+ free_getaddrinfo_request(data);
+ }
+}
+
+static int
+evdns_getaddrinfo_set_timeout(struct evdns_base *evdns_base,
+ struct evdns_getaddrinfo_request *data)
+{
+ return event_add(&data->timeout, &evdns_base->global_getaddrinfo_allow_skew);
+}
+
+static inline int
+evdns_result_is_answer(int result)
+{
+ return (result != DNS_ERR_NOTIMPL && result != DNS_ERR_REFUSED &&
+ result != DNS_ERR_SERVERFAILED && result != DNS_ERR_CANCEL);
+}
+
+static void
+evdns_getaddrinfo_gotresolve(int result, char type, int count,
+ int ttl, void *addresses, void *arg)
+{
+ int i;
+ struct getaddrinfo_subrequest *req = arg;
+ struct getaddrinfo_subrequest *other_req;
+ struct evdns_getaddrinfo_request *data;
+
+ struct evutil_addrinfo *res;
+
+ struct sockaddr_in sin;
+ struct sockaddr_in6 sin6;
+ struct sockaddr *sa;
+ int socklen, addrlen;
+ void *addrp;
+ int err;
+ int user_canceled;
+
+ EVUTIL_ASSERT(req->type == DNS_IPv4_A || req->type == DNS_IPv6_AAAA);
+ if (req->type == DNS_IPv4_A) {
+ data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv4_request);
+ other_req = &data->ipv6_request;
+ } else {
+ data = EVUTIL_UPCAST(req, struct evdns_getaddrinfo_request, ipv6_request);
+ other_req = &data->ipv4_request;
+ }
+
+ /** Called from evdns_base_free() with @fail_requests == 1 */
+ if (result != DNS_ERR_SHUTDOWN) {
+ EVDNS_LOCK(data->evdns_base);
+ if (evdns_result_is_answer(result)) {
+ if (req->type == DNS_IPv4_A)
+ ++data->evdns_base->getaddrinfo_ipv4_answered;
+ else
+ ++data->evdns_base->getaddrinfo_ipv6_answered;
+ }
+ user_canceled = data->user_canceled;
+ if (other_req->r == NULL)
+ data->request_done = 1;
+ EVDNS_UNLOCK(data->evdns_base);
+ } else {
+ data->evdns_base = NULL;
+ user_canceled = data->user_canceled;
+ }
+
+ req->r = NULL;
+
+ if (result == DNS_ERR_CANCEL && ! user_canceled) {
+ /* Internal cancel request from timeout or internal error.
+ * we already answered the user. */
+ if (other_req->r == NULL)
+ free_getaddrinfo_request(data);
+ return;
+ }
+
+ if (data->user_cb == NULL) {
+ /* We already answered. XXXX This shouldn't be needed; see
+ * comments in evdns_getaddrinfo_timeout_cb */
+ free_getaddrinfo_request(data);
+ return;
+ }
+
+ if (result == DNS_ERR_NONE) {
+ if (count == 0)
+ err = EVUTIL_EAI_NODATA;
+ else
+ err = 0;
+ } else {
+ err = evdns_err_to_getaddrinfo_err(result);
+ }
+
+ if (err) {
+ /* Looks like we got an error. */
+ if (other_req->r) {
+ /* The other request is still working; maybe it will
+ * succeed. */
+ /* XXXX handle failure from set_timeout */
+ if (result != DNS_ERR_SHUTDOWN) {
+ evdns_getaddrinfo_set_timeout(data->evdns_base, data);
+ }
+ data->pending_error = err;
+ return;
+ }
+
+ if (user_canceled) {
+ data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
+ } else if (data->pending_result) {
+ /* If we have an answer waiting, and we weren't
+ * canceled, ignore this error. */
+ add_cname_to_reply(data, data->pending_result);
+ data->user_cb(0, data->pending_result, data->user_data);
+ data->pending_result = NULL;
+ } else {
+ if (data->pending_error)
+ err = getaddrinfo_merge_err(err,
+ data->pending_error);
+ data->user_cb(err, NULL, data->user_data);
+ }
+ free_getaddrinfo_request(data);
+ return;
+ } else if (user_canceled) {
+ if (other_req->r) {
+ /* The other request is still working; let it hit this
+ * callback with EVUTIL_EAI_CANCEL callback and report
+ * the failure. */
+ return;
+ }
+ data->user_cb(EVUTIL_EAI_CANCEL, NULL, data->user_data);
+ free_getaddrinfo_request(data);
+ return;
+ }
+
+ /* Looks like we got some answers. We should turn them into addrinfos
+ * and then either queue those or return them all. */
+ EVUTIL_ASSERT(type == DNS_IPv4_A || type == DNS_IPv6_AAAA);
+
+ if (type == DNS_IPv4_A) {
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(data->port);
+
+ sa = (struct sockaddr *)&sin;
+ socklen = sizeof(sin);
+ addrlen = 4;
+ addrp = &sin.sin_addr.s_addr;
+ } else {
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(data->port);
+
+ sa = (struct sockaddr *)&sin6;
+ socklen = sizeof(sin6);
+ addrlen = 16;
+ addrp = &sin6.sin6_addr.s6_addr;
+ }
+
+ res = NULL;
+ for (i=0; i < count; ++i) {
+ struct evutil_addrinfo *ai;
+ memcpy(addrp, ((char*)addresses)+i*addrlen, addrlen);
+ ai = evutil_new_addrinfo_(sa, socklen, &data->hints);
+ if (!ai) {
+ if (other_req->r) {
+ evdns_cancel_request(NULL, other_req->r);
+ }
+ data->user_cb(EVUTIL_EAI_MEMORY, NULL, data->user_data);
+ if (res)
+ evutil_freeaddrinfo(res);
+
+ if (other_req->r == NULL)
+ free_getaddrinfo_request(data);
+ return;
+ }
+ res = evutil_addrinfo_append_(res, ai);
+ }
+
+ if (other_req->r) {
+ /* The other request is still in progress; wait for it */
+ /* XXXX handle failure from set_timeout */
+ evdns_getaddrinfo_set_timeout(data->evdns_base, data);
+ data->pending_result = res;
+ return;
+ } else {
+ /* The other request is done or never started; append its
+ * results (if any) and return them. */
+ if (data->pending_result) {
+ if (req->type == DNS_IPv4_A)
+ res = evutil_addrinfo_append_(res,
+ data->pending_result);
+ else
+ res = evutil_addrinfo_append_(
+ data->pending_result, res);
+ data->pending_result = NULL;
+ }
+
+ /* Call the user callback. */
+ add_cname_to_reply(data, res);
+ data->user_cb(0, res, data->user_data);
+
+ /* Free data. */
+ free_getaddrinfo_request(data);
+ }
+}
+
+static struct hosts_entry *
+find_hosts_entry(struct evdns_base *base, const char *hostname,
+ struct hosts_entry *find_after)
+{
+ struct hosts_entry *e;
+
+ if (find_after)
+ e = TAILQ_NEXT(find_after, next);
+ else
+ e = TAILQ_FIRST(&base->hostsdb);
+
+ for (; e; e = TAILQ_NEXT(e, next)) {
+ if (!evutil_ascii_strcasecmp(e->hostname, hostname))
+ return e;
+ }
+ return NULL;
+}
+
+static int
+evdns_getaddrinfo_fromhosts(struct evdns_base *base,
+ const char *nodename, struct evutil_addrinfo *hints, ev_uint16_t port,
+ struct evutil_addrinfo **res)
+{
+ int n_found = 0;
+ struct hosts_entry *e;
+ struct evutil_addrinfo *ai=NULL;
+ int f = hints->ai_family;
+
+ EVDNS_LOCK(base);
+ for (e = find_hosts_entry(base, nodename, NULL); e;
+ e = find_hosts_entry(base, nodename, e)) {
+ struct evutil_addrinfo *ai_new;
+ ++n_found;
+ if ((e->addr.sa.sa_family == AF_INET && f == PF_INET6) ||
+ (e->addr.sa.sa_family == AF_INET6 && f == PF_INET))
+ continue;
+ ai_new = evutil_new_addrinfo_(&e->addr.sa, e->addrlen, hints);
+ if (!ai_new) {
+ n_found = 0;
+ goto out;
+ }
+ sockaddr_setport(ai_new->ai_addr, port);
+ ai = evutil_addrinfo_append_(ai, ai_new);
+ }
+ EVDNS_UNLOCK(base);
+out:
+ if (n_found) {
+ /* Note that we return an empty answer if we found entries for
+ * this hostname but none were of the right address type. */
+ *res = ai;
+ return 0;
+ } else {
+ if (ai)
+ evutil_freeaddrinfo(ai);
+ return -1;
+ }
+}
+
+struct evdns_getaddrinfo_request *
+evdns_getaddrinfo(struct evdns_base *dns_base,
+ const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in,
+ evdns_getaddrinfo_cb cb, void *arg)
+{
+ struct evdns_getaddrinfo_request *data;
+ struct evutil_addrinfo hints;
+ struct evutil_addrinfo *res = NULL;
+ int err;
+ int port = 0;
+ int want_cname = 0;
+ int started = 0;
+
+ if (!dns_base) {
+ dns_base = current_base;
+ if (!dns_base) {
+ log(EVDNS_LOG_WARN,
+ "Call to getaddrinfo_async with no "
+ "evdns_base configured.");
+ cb(EVUTIL_EAI_FAIL, NULL, arg); /* ??? better error? */
+ return NULL;
+ }
+ }
+
+ /* If we _must_ answer this immediately, do so. */
+ if ((hints_in && (hints_in->ai_flags & EVUTIL_AI_NUMERICHOST))) {
+ res = NULL;
+ err = evutil_getaddrinfo(nodename, servname, hints_in, &res);
+ cb(err, res, arg);
+ return NULL;
+ }
+
+ if (hints_in) {
+ memcpy(&hints, hints_in, sizeof(hints));
+ } else {
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ }
+
+ evutil_adjust_hints_for_addrconfig_(&hints);
+
+ /* Now try to see if we _can_ answer immediately. */
+ /* (It would be nice to do this by calling getaddrinfo directly, with
+ * AI_NUMERICHOST, on plaforms that have it, but we can't: there isn't
+ * a reliable way to distinguish the "that wasn't a numeric host!" case
+ * from any other EAI_NONAME cases.) */
+ err = evutil_getaddrinfo_common_(nodename, servname, &hints, &res, &port);
+ if (err != EVUTIL_EAI_NEED_RESOLVE) {
+ cb(err, res, arg);
+ return NULL;
+ }
+
+ /* If there is an entry in the hosts file, we should give it now. */
+ if (!evdns_getaddrinfo_fromhosts(dns_base, nodename, &hints, port, &res)) {
+ cb(0, res, arg);
+ return NULL;
+ }
+
+ /* Okay, things are serious now. We're going to need to actually
+ * launch a request.
+ */
+ data = mm_calloc(1,sizeof(struct evdns_getaddrinfo_request));
+ if (!data) {
+ cb(EVUTIL_EAI_MEMORY, NULL, arg);
+ return NULL;
+ }
+
+ memcpy(&data->hints, &hints, sizeof(data->hints));
+ data->port = (ev_uint16_t)port;
+ data->ipv4_request.type = DNS_IPv4_A;
+ data->ipv6_request.type = DNS_IPv6_AAAA;
+ data->user_cb = cb;
+ data->user_data = arg;
+ data->evdns_base = dns_base;
+
+ want_cname = (hints.ai_flags & EVUTIL_AI_CANONNAME);
+
+ /* If we are asked for a PF_UNSPEC address, we launch two requests in
+ * parallel: one for an A address and one for an AAAA address. We
+ * can't send just one request, since many servers only answer one
+ * question per DNS request.
+ *
+ * Once we have the answer to one request, we allow for a short
+ * timeout before we report it, to see if the other one arrives. If
+ * they both show up in time, then we report both the answers.
+ *
+ * If too many addresses of one type time out or fail, we should stop
+ * launching those requests. (XXX we don't do that yet.)
+ */
+
+ EVDNS_LOCK(dns_base);
+
+ if (hints.ai_family != PF_INET6) {
+ log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv4 as %p",
+ nodename, &data->ipv4_request);
+
+ data->ipv4_request.r = evdns_base_resolve_ipv4(dns_base,
+ nodename, 0, evdns_getaddrinfo_gotresolve,
+ &data->ipv4_request);
+ if (want_cname && data->ipv4_request.r)
+ data->ipv4_request.r->current_req->put_cname_in_ptr =
+ &data->cname_result;
+ }
+ if (hints.ai_family != PF_INET) {
+ log(EVDNS_LOG_DEBUG, "Sending request for %s on ipv6 as %p",
+ nodename, &data->ipv6_request);
+
+ data->ipv6_request.r = evdns_base_resolve_ipv6(dns_base,
+ nodename, 0, evdns_getaddrinfo_gotresolve,
+ &data->ipv6_request);
+ if (want_cname && data->ipv6_request.r)
+ data->ipv6_request.r->current_req->put_cname_in_ptr =
+ &data->cname_result;
+ }
+
+ evtimer_assign(&data->timeout, dns_base->event_base,
+ evdns_getaddrinfo_timeout_cb, data);
+
+ started = (data->ipv4_request.r || data->ipv6_request.r);
+
+ EVDNS_UNLOCK(dns_base);
+
+ if (started) {
+ return data;
+ } else {
+ mm_free(data);
+ cb(EVUTIL_EAI_FAIL, NULL, arg);
+ return NULL;
+ }
+}
+
+void
+evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *data)
+{
+ EVDNS_LOCK(data->evdns_base);
+ if (data->request_done) {
+ EVDNS_UNLOCK(data->evdns_base);
+ return;
+ }
+ event_del(&data->timeout);
+ data->user_canceled = 1;
+ if (data->ipv4_request.r)
+ evdns_cancel_request(data->evdns_base, data->ipv4_request.r);
+ if (data->ipv6_request.r)
+ evdns_cancel_request(data->evdns_base, data->ipv6_request.r);
+ EVDNS_UNLOCK(data->evdns_base);
+}
diff --git a/ipc/chromium/src/third_party/libevent/event-config.h.cmake b/ipc/chromium/src/third_party/libevent/event-config.h.cmake
new file mode 100644
index 0000000000..fccf0cf059
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event-config.h.cmake
@@ -0,0 +1,513 @@
+/* event-config.h
+ *
+ * This file was generated by cmake when the makefiles were generated.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION @EVENT_NUMERIC_VERSION@
+#define EVENT__PACKAGE_VERSION "@EVENT_PACKAGE_VERSION@"
+
+#define EVENT__VERSION_MAJOR @EVENT_VERSION_MAJOR@
+#define EVENT__VERSION_MINOR @EVENT_VERSION_MINOR@
+#define EVENT__VERSION_PATCH @EVENT_VERSION_PATCH@
+
+/* Version number of package */
+#define EVENT__VERSION "@EVENT_VERSION@"
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME ""
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING ""
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME ""
+
+/* Define if libevent should build without support for a debug mode */
+#cmakedefine EVENT__DISABLE_DEBUG_MODE 1
+
+/* Define if libevent should not allow replacing the mm functions */
+#cmakedefine EVENT__DISABLE_MM_REPLACEMENT 1
+
+/* Define if libevent should not be compiled with thread support */
+#cmakedefine EVENT__DISABLE_THREAD_SUPPORT 1
+
+/* Define to 1 if you have the `accept4' function. */
+#cmakedefine EVENT__HAVE_ACCEPT4 1
+
+/* Define to 1 if you have the `arc4random' function. */
+#cmakedefine EVENT__HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the `arc4random_buf' function. */
+#cmakedefine EVENT__HAVE_ARC4RANDOM_BUF 1
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+#cmakedefine EVENT__HAVE_ARC4RANDOM_ADDRANDOM 1
+
+/* Define if clock_gettime is available in libc */
+#cmakedefine EVENT__DNS_USE_CPU_CLOCK_FOR_ID 1
+
+/* Define is no secure id variant is available */
+#cmakedefine EVENT__DNS_USE_GETTIMEOFDAY_FOR_ID 1
+#cmakedefine EVENT__DNS_USE_FTIME_FOR_ID 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#cmakedefine EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#cmakedefine EVENT__HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the declaration of `CTL_KERN'. */
+#define EVENT__HAVE_DECL_CTL_KERN @EVENT__HAVE_DECL_CTL_KERN@
+
+/* Define to 1 if you have the declaration of `KERN_ARND'. */
+#define EVENT__HAVE_DECL_KERN_ARND @EVENT__HAVE_DECL_KERN_ARND@
+
+/* Define to 1 if you have `getrandom' function. */
+#cmakedefine EVENT__HAVE_GETRANDOM 1
+
+/* Define if /dev/poll is available */
+#cmakedefine EVENT__HAVE_DEVPOLL 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#cmakedefine EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if fd_mask type is defined */
+#cmakedefine EVENT__HAVE_FD_MASK 1
+
+/* Define to 1 if the <sys/queue.h> header file defines TAILQ_FOREACH. */
+#cmakedefine EVENT__HAVE_TAILQFOREACH 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#cmakedefine EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+#cmakedefine EVENT__HAVE_EPOLL 1
+
+/* Define to 1 if you have the `epoll_create1' function. */
+#cmakedefine EVENT__HAVE_EPOLL_CREATE1 1
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+#cmakedefine EVENT__HAVE_EPOLL_CTL 1
+
+/* Define to 1 if you have the `eventfd' function. */
+#cmakedefine EVENT__HAVE_EVENTFD 1
+
+/* Define if your system supports event ports */
+#cmakedefine EVENT__HAVE_EVENT_PORTS 1
+
+/* Define to 1 if you have the `fcntl' function. */
+#cmakedefine EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#cmakedefine EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the `getaddrinfo' function. */
+#cmakedefine EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#cmakedefine EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#cmakedefine EVENT__HAVE_GETEUID 1
+
+/* TODO: Check for different gethostname argument counts. CheckPrototypeDefinition.cmake can be used. */
+/* Define this if you have any gethostbyname_r() */
+#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R 1
+
+/* Define this if gethostbyname_r takes 3 arguments */
+#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_3_ARG 1
+
+/* Define this if gethostbyname_r takes 5 arguments */
+#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_5_ARG 1
+
+/* Define this if gethostbyname_r takes 6 arguments */
+#cmakedefine EVENT__HAVE_GETHOSTBYNAME_R_6_ARG 1
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#cmakedefine EVENT__HAVE_GETIFADDRS 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#cmakedefine EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#cmakedefine EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getservbyname' function. */
+#cmakedefine EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#cmakedefine EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#cmakedefine EVENT__HAVE_IFADDRS_H 1
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#cmakedefine EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#cmakedefine EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#cmakedefine EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+#cmakedefine EVENT__HAVE_ISSETUGID 1
+
+/* Define to 1 if you have the `kqueue' function. */
+#cmakedefine EVENT__HAVE_KQUEUE 1
+
+/* Define if the system has zlib */
+#cmakedefine EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+#cmakedefine EVENT__HAVE_MACH_ABSOLUTE_TIME 1
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+#cmakedefine EVENT__HAVE_MACH_MACH_TIME_H 1
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+#cmakedefine EVENT__HAVE_MACH_MACH_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#cmakedefine EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#cmakedefine EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#cmakedefine EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the `usleep' function. */
+#cmakedefine EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+#cmakedefine EVENT__HAVE_NETINET_IN6_H 1
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#cmakedefine EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#cmakedefine EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <afunix.h> header file. */
+#cmakedefine EVENT__HAVE_AFUNIX_H 1
+
+/* Define if the system has openssl */
+#cmakedefine EVENT__HAVE_OPENSSL 1
+
+/* Define to 1 if you have the `pipe' function. */
+#cmakedefine EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#cmakedefine EVENT__HAVE_PIPE2 1
+
+/* Define to 1 if you have the `poll' function. */
+#cmakedefine EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#cmakedefine EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+#cmakedefine EVENT__HAVE_PORT_CREATE 1
+
+/* Define to 1 if you have the <port.h> header file. */
+#cmakedefine EVENT__HAVE_PORT_H 1
+
+/* Define if we have pthreads on this system */
+#cmakedefine EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#cmakedefine EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#cmakedefine EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#cmakedefine EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `setenv' function. */
+#cmakedefine EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#cmakedefine EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#cmakedefine EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#cmakedefine EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#cmakedefine EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+#cmakedefine EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+#cmakedefine EVENT__HAVE_SPLICE 1
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#cmakedefine EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#cmakedefine EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#cmakedefine EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#cmakedefine EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#cmakedefine EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+#cmakedefine EVENT__HAVE_STRLCPY 1
+
+/* Define to 1 if you have the `strsep' function. */
+#cmakedefine EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#cmakedefine EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#cmakedefine EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+#cmakedefine EVENT__HAVE__GMTIME64_S 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+#cmakedefine EVENT__HAVE__GMTIME64 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#cmakedefine EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is member of `struct in6_addr'. */
+#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+
+/* Define to 1 if `s6_addr32' is member of `struct in6_addr'. */
+#cmakedefine EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is member of `struct sockaddr_in6'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
+
+/* Define to 1 if `sin_len' is member of `struct sockaddr_in'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+#cmakedefine EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY 1
+
+/* Define to 1 if the system has the type `struct linger'. */
+#cmakedefine EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if you have the `sysctl' function. */
+#cmakedefine EVENT__HAVE_SYSCTL 1
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_EPOLL_H 1
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_EVENTFD_H 1
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_EVENT_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_SENDFILE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_RANDOM_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_SYSCTL_H 1
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_TIMERFD_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#cmakedefine EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#cmakedefine EVENT__HAVE_ERRNO_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#cmakedefine EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#cmakedefine EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#cmakedefine EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#cmakedefine EVENT__HAVE_TIMERCMP 1
+
+
+/* Define to 1 if you have the `timerfd_create' function. */
+#cmakedefine EVENT__HAVE_TIMERFD_CREATE 1
+
+/* Define if timerisset is defined in <sys/time.h> */
+#cmakedefine EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#cmakedefine EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#cmakedefine EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#cmakedefine EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#cmakedefine EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#cmakedefine EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#cmakedefine EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#cmakedefine EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#cmakedefine EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#cmakedefine EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+#cmakedefine EVENT__HAVE_WORKING_KQUEUE 1
+
+#ifdef __USE_UNUSED_DEFINITIONS__
+/* Define to necessary symbol if this constant uses a non-standard name on your system. */
+/* XXX: Hello, this isn't even used, nor is it defined anywhere... - Ellzey */
+#define EVENT__PTHREAD_CREATE_JOINABLE ${EVENT__PTHREAD_CREATE_JOINABLE}
+#endif
+
+/* The size of `pthread_t', as computed by sizeof. */
+#define EVENT__SIZEOF_PTHREAD_T @EVENT__SIZEOF_PTHREAD_T@
+
+/* The size of a `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT @EVENT__SIZEOF_INT@
+
+/* The size of a `long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG @EVENT__SIZEOF_LONG@
+
+/* The size of a `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG @EVENT__SIZEOF_LONG_LONG@
+
+/* The size of `off_t', as computed by sizeof. */
+#define EVENT__SIZEOF_OFF_T @EVENT__SIZEOF_OFF_T@
+
+#define EVENT__SIZEOF_SSIZE_T @EVENT__SIZEOF_SSIZE_T@
+
+
+/* The size of a `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT @EVENT__SIZEOF_SHORT@
+
+/* The size of `size_t', as computed by sizeof. */
+#define EVENT__SIZEOF_SIZE_T @EVENT__SIZEOF_SIZE_T@
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#cmakedefine EVENT__TIME_WITH_SYS_TIME 1
+
+/* The size of `socklen_t', as computed by sizeof. */
+#define EVENT__SIZEOF_SOCKLEN_T @EVENT__SIZEOF_SOCKLEN_T@
+
+/* The size of 'void *', as computer by sizeof */
+#define EVENT__SIZEOF_VOID_P @EVENT__SIZEOF_VOID_P@
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* why not c++?
+ *
+ * and are we really expected to use EVENT__inline everywhere,
+ * shouldn't we just do:
+ * ifdef EVENT__inline
+ * define inline EVENT__inline
+ *
+ * - Ellzey
+ */
+
+#define EVENT__inline @EVENT__inline@
+#endif
+
+#cmakedefine EVENT__HAVE___func__ 1
+#cmakedefine EVENT__HAVE___FUNCTION__ 1
+
+/* Define to `unsigned' if <sys/types.h> does not define. */
+#define EVENT__size_t @EVENT__size_t@
+
+/* Define to unsigned int if you dont have it */
+#define EVENT__socklen_t @EVENT__socklen_t@
+
+/* Define to `int' if <sys/types.h> does not define. */
+#define EVENT__ssize_t @EVENT__ssize_t@
+
+#endif /* \EVENT2_EVENT_CONFIG_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/event-internal.h b/ipc/chromium/src/third_party/libevent/event-internal.h
new file mode 100644
index 0000000000..9e5ff42447
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event-internal.h
@@ -0,0 +1,488 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT_INTERNAL_H_INCLUDED_
+#define EVENT_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <time.h>
+#include <sys/queue.h>
+#include "event2/event_struct.h"
+#include "minheap-internal.h"
+#include "evsignal-internal.h"
+#include "mm-internal.h"
+#include "defer-internal.h"
+
+/* map union members back */
+
+/* mutually exclusive */
+#define ev_signal_next ev_.ev_signal.ev_signal_next
+#define ev_io_next ev_.ev_io.ev_io_next
+#define ev_io_timeout ev_.ev_io.ev_timeout
+
+/* used only by signals */
+#define ev_ncalls ev_.ev_signal.ev_ncalls
+#define ev_pncalls ev_.ev_signal.ev_pncalls
+
+#define ev_pri ev_evcallback.evcb_pri
+#define ev_flags ev_evcallback.evcb_flags
+#define ev_closure ev_evcallback.evcb_closure
+#define ev_callback ev_evcallback.evcb_cb_union.evcb_callback
+#define ev_arg ev_evcallback.evcb_arg
+
+/** @name Event closure codes
+
+ Possible values for evcb_closure in struct event_callback
+
+ @{
+ */
+/** A regular event. Uses the evcb_callback callback */
+#define EV_CLOSURE_EVENT 0
+/** A signal event. Uses the evcb_callback callback */
+#define EV_CLOSURE_EVENT_SIGNAL 1
+/** A persistent non-signal event. Uses the evcb_callback callback */
+#define EV_CLOSURE_EVENT_PERSIST 2
+/** A simple callback. Uses the evcb_selfcb callback. */
+#define EV_CLOSURE_CB_SELF 3
+/** A finalizing callback. Uses the evcb_cbfinalize callback. */
+#define EV_CLOSURE_CB_FINALIZE 4
+/** A finalizing event. Uses the evcb_evfinalize callback. */
+#define EV_CLOSURE_EVENT_FINALIZE 5
+/** A finalizing event that should get freed after. Uses the evcb_evfinalize
+ * callback. */
+#define EV_CLOSURE_EVENT_FINALIZE_FREE 6
+/** @} */
+
+/** Structure to define the backend of a given event_base. */
+struct eventop {
+ /** The name of this backend. */
+ const char *name;
+ /** Function to set up an event_base to use this backend. It should
+ * create a new structure holding whatever information is needed to
+ * run the backend, and return it. The returned pointer will get
+ * stored by event_init into the event_base.evbase field. On failure,
+ * this function should return NULL. */
+ void *(*init)(struct event_base *);
+ /** Enable reading/writing on a given fd or signal. 'events' will be
+ * the events that we're trying to enable: one or more of EV_READ,
+ * EV_WRITE, EV_SIGNAL, and EV_ET. 'old' will be those events that
+ * were enabled on this fd previously. 'fdinfo' will be a structure
+ * associated with the fd by the evmap; its size is defined by the
+ * fdinfo field below. It will be set to 0 the first time the fd is
+ * added. The function should return 0 on success and -1 on error.
+ */
+ int (*add)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
+ /** As "add", except 'events' contains the events we mean to disable. */
+ int (*del)(struct event_base *, evutil_socket_t fd, short old, short events, void *fdinfo);
+ /** Function to implement the core of an event loop. It must see which
+ added events are ready, and cause event_active to be called for each
+ active event (usually via event_io_active or such). It should
+ return 0 on success and -1 on error.
+ */
+ int (*dispatch)(struct event_base *, struct timeval *);
+ /** Function to clean up and free our data from the event_base. */
+ void (*dealloc)(struct event_base *);
+ /** Flag: set if we need to reinitialize the event base after we fork.
+ */
+ int need_reinit;
+ /** Bit-array of supported event_method_features that this backend can
+ * provide. */
+ enum event_method_feature features;
+ /** Length of the extra information we should record for each fd that
+ has one or more active events. This information is recorded
+ as part of the evmap entry for each fd, and passed as an argument
+ to the add and del functions above.
+ */
+ size_t fdinfo_len;
+};
+
+#ifdef _WIN32
+/* If we're on win32, then file descriptors are not nice low densely packed
+ integers. Instead, they are pointer-like windows handles, and we want to
+ use a hashtable instead of an array to map fds to events.
+*/
+#define EVMAP_USE_HT
+#endif
+
+/* #define HT_CACHE_HASH_VALS */
+
+#ifdef EVMAP_USE_HT
+#define HT_NO_CACHE_HASH_VALUES
+#include "ht-internal.h"
+struct event_map_entry;
+HT_HEAD(event_io_map, event_map_entry);
+#else
+#define event_io_map event_signal_map
+#endif
+
+/* Used to map signal numbers to a list of events. If EVMAP_USE_HT is not
+ defined, this structure is also used as event_io_map, which maps fds to a
+ list of events.
+*/
+struct event_signal_map {
+ /* An array of evmap_io * or of evmap_signal *; empty entries are
+ * set to NULL. */
+ void **entries;
+ /* The number of entries available in entries */
+ int nentries;
+};
+
+/* A list of events waiting on a given 'common' timeout value. Ordinarily,
+ * events waiting for a timeout wait on a minheap. Sometimes, however, a
+ * queue can be faster.
+ **/
+struct common_timeout_list {
+ /* List of events currently waiting in the queue. */
+ struct event_list events;
+ /* 'magic' timeval used to indicate the duration of events in this
+ * queue. */
+ struct timeval duration;
+ /* Event that triggers whenever one of the events in the queue is
+ * ready to activate */
+ struct event timeout_event;
+ /* The event_base that this timeout list is part of */
+ struct event_base *base;
+};
+
+/** Mask used to get the real tv_usec value from a common timeout. */
+#define COMMON_TIMEOUT_MICROSECONDS_MASK 0x000fffff
+
+struct event_change;
+
+/* List of 'changes' since the last call to eventop.dispatch. Only maintained
+ * if the backend is using changesets. */
+struct event_changelist {
+ struct event_change *changes;
+ int n_changes;
+ int changes_size;
+};
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+/* Global internal flag: set to one if debug mode is on. */
+extern int event_debug_mode_on_;
+#define EVENT_DEBUG_MODE_IS_ON() (event_debug_mode_on_)
+#else
+#define EVENT_DEBUG_MODE_IS_ON() (0)
+#endif
+
+TAILQ_HEAD(evcallback_list, event_callback);
+
+/* Sets up an event for processing once */
+struct event_once {
+ LIST_ENTRY(event_once) next_once;
+ struct event ev;
+
+ void (*cb)(evutil_socket_t, short, void *);
+ void *arg;
+};
+
+struct event_base {
+ /** Function pointers and other data to describe this event_base's
+ * backend. */
+ const struct eventop *evsel;
+ /** Pointer to backend-specific data. */
+ void *evbase;
+
+ /** List of changes to tell backend about at next dispatch. Only used
+ * by the O(1) backends. */
+ struct event_changelist changelist;
+
+ /** Function pointers used to describe the backend that this event_base
+ * uses for signals */
+ const struct eventop *evsigsel;
+ /** Data to implement the common signal handler code. */
+ struct evsig_info sig;
+
+ /** Number of virtual events */
+ int virtual_event_count;
+ /** Maximum number of virtual events active */
+ int virtual_event_count_max;
+ /** Number of total events added to this event_base */
+ int event_count;
+ /** Maximum number of total events added to this event_base */
+ int event_count_max;
+ /** Number of total events active in this event_base */
+ int event_count_active;
+ /** Maximum number of total events active in this event_base */
+ int event_count_active_max;
+
+ /** Set if we should terminate the loop once we're done processing
+ * events. */
+ int event_gotterm;
+ /** Set if we should terminate the loop immediately */
+ int event_break;
+ /** Set if we should start a new instance of the loop immediately. */
+ int event_continue;
+
+ /** The currently running priority of events */
+ int event_running_priority;
+
+ /** Set if we're running the event_base_loop function, to prevent
+ * reentrant invocation. */
+ int running_loop;
+
+ /** Set to the number of deferred_cbs we've made 'active' in the
+ * loop. This is a hack to prevent starvation; it would be smarter
+ * to just use event_config_set_max_dispatch_interval's max_callbacks
+ * feature */
+ int n_deferreds_queued;
+
+ /* Active event management. */
+ /** An array of nactivequeues queues for active event_callbacks (ones
+ * that have triggered, and whose callbacks need to be called). Low
+ * priority numbers are more important, and stall higher ones.
+ */
+ struct evcallback_list *activequeues;
+ /** The length of the activequeues array */
+ int nactivequeues;
+ /** A list of event_callbacks that should become active the next time
+ * we process events, but not this time. */
+ struct evcallback_list active_later_queue;
+
+ /* common timeout logic */
+
+ /** An array of common_timeout_list* for all of the common timeout
+ * values we know. */
+ struct common_timeout_list **common_timeout_queues;
+ /** The number of entries used in common_timeout_queues */
+ int n_common_timeouts;
+ /** The total size of common_timeout_queues. */
+ int n_common_timeouts_allocated;
+
+ /** Mapping from file descriptors to enabled (added) events */
+ struct event_io_map io;
+
+ /** Mapping from signal numbers to enabled (added) events. */
+ struct event_signal_map sigmap;
+
+ /** Priority queue of events with timeouts. */
+ struct min_heap timeheap;
+
+ /** Stored timeval: used to avoid calling gettimeofday/clock_gettime
+ * too often. */
+ struct timeval tv_cache;
+
+ struct evutil_monotonic_timer monotonic_timer;
+
+ /** Difference between internal time (maybe from clock_gettime) and
+ * gettimeofday. */
+ struct timeval tv_clock_diff;
+ /** Second in which we last updated tv_clock_diff, in monotonic time. */
+ time_t last_updated_clock_diff;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ /* threading support */
+ /** The thread currently running the event_loop for this base */
+ unsigned long th_owner_id;
+ /** A lock to prevent conflicting accesses to this event_base */
+ void *th_base_lock;
+ /** A condition that gets signalled when we're done processing an
+ * event with waiters on it. */
+ void *current_event_cond;
+ /** Number of threads blocking on current_event_cond. */
+ int current_event_waiters;
+#endif
+ /** The event whose callback is executing right now */
+ struct event_callback *current_event;
+
+#ifdef _WIN32
+ /** IOCP support structure, if IOCP is enabled. */
+ struct event_iocp_port *iocp;
+#endif
+
+ /** Flags that this base was configured with */
+ enum event_base_config_flag flags;
+
+ struct timeval max_dispatch_time;
+ int max_dispatch_callbacks;
+ int limit_callbacks_after_prio;
+
+ /* Notify main thread to wake up break, etc. */
+ /** True if the base already has a pending notify, and we don't need
+ * to add any more. */
+ int is_notify_pending;
+ /** A socketpair used by some th_notify functions to wake up the main
+ * thread. */
+ evutil_socket_t th_notify_fd[2];
+ /** An event used by some th_notify functions to wake up the main
+ * thread. */
+ struct event th_notify;
+ /** A function used to wake up the main thread from another thread. */
+ int (*th_notify_fn)(struct event_base *base);
+
+ /** Saved seed for weak random number generator. Some backends use
+ * this to produce fairness among sockets. Protected by th_base_lock. */
+ struct evutil_weakrand_state weakrand_seed;
+
+ /** List of event_onces that have not yet fired. */
+ LIST_HEAD(once_event_list, event_once) once_events;
+
+};
+
+struct event_config_entry {
+ TAILQ_ENTRY(event_config_entry) next;
+
+ const char *avoid_method;
+};
+
+/** Internal structure: describes the configuration we want for an event_base
+ * that we're about to allocate. */
+struct event_config {
+ TAILQ_HEAD(event_configq, event_config_entry) entries;
+
+ int n_cpus_hint;
+ struct timeval max_dispatch_interval;
+ int max_dispatch_callbacks;
+ int limit_callbacks_after_prio;
+ enum event_method_feature require_features;
+ enum event_base_config_flag flags;
+};
+
+/* Internal use only: Functions that might be missing from <sys/queue.h> */
+#ifndef LIST_END
+#define LIST_END(head) NULL
+#endif
+
+#ifndef TAILQ_FIRST
+#define TAILQ_FIRST(head) ((head)->tqh_first)
+#endif
+#ifndef TAILQ_END
+#define TAILQ_END(head) NULL
+#endif
+#ifndef TAILQ_NEXT
+#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
+#endif
+
+#ifndef TAILQ_FOREACH
+#define TAILQ_FOREACH(var, head, field) \
+ for ((var) = TAILQ_FIRST(head); \
+ (var) != TAILQ_END(head); \
+ (var) = TAILQ_NEXT(var, field))
+#endif
+
+#ifndef TAILQ_INSERT_BEFORE
+#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
+ (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
+ (elm)->field.tqe_next = (listelm); \
+ *(listelm)->field.tqe_prev = (elm); \
+ (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \
+} while (0)
+#endif
+
+#define N_ACTIVE_CALLBACKS(base) \
+ ((base)->event_count_active)
+
+int evsig_set_handler_(struct event_base *base, int evsignal,
+ void (*fn)(int));
+int evsig_restore_handler_(struct event_base *base, int evsignal);
+
+int event_add_nolock_(struct event *ev,
+ const struct timeval *tv, int tv_is_absolute);
+/** Argument for event_del_nolock_. Tells event_del not to block on the event
+ * if it's running in another thread. */
+#define EVENT_DEL_NOBLOCK 0
+/** Argument for event_del_nolock_. Tells event_del to block on the event
+ * if it's running in another thread, regardless of its value for EV_FINALIZE
+ */
+#define EVENT_DEL_BLOCK 1
+/** Argument for event_del_nolock_. Tells event_del to block on the event
+ * if it is running in another thread and it doesn't have EV_FINALIZE set.
+ */
+#define EVENT_DEL_AUTOBLOCK 2
+/** Argument for event_del_nolock_. Tells event_del to proceed even if the
+ * event is set up for finalization rather for regular use.*/
+#define EVENT_DEL_EVEN_IF_FINALIZING 3
+int event_del_nolock_(struct event *ev, int blocking);
+int event_remove_timer_nolock_(struct event *ev);
+
+void event_active_nolock_(struct event *ev, int res, short count);
+EVENT2_EXPORT_SYMBOL
+int event_callback_activate_(struct event_base *, struct event_callback *);
+int event_callback_activate_nolock_(struct event_base *, struct event_callback *);
+int event_callback_cancel_(struct event_base *base,
+ struct event_callback *evcb);
+
+void event_callback_finalize_nolock_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *));
+EVENT2_EXPORT_SYMBOL
+void event_callback_finalize_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *));
+int event_callback_finalize_many_(struct event_base *base, int n_cbs, struct event_callback **evcb, void (*cb)(struct event_callback *, void *));
+
+
+EVENT2_EXPORT_SYMBOL
+void event_active_later_(struct event *ev, int res);
+void event_active_later_nolock_(struct event *ev, int res);
+int event_callback_activate_later_nolock_(struct event_base *base,
+ struct event_callback *evcb);
+int event_callback_cancel_nolock_(struct event_base *base,
+ struct event_callback *evcb, int even_if_finalizing);
+void event_callback_init_(struct event_base *base,
+ struct event_callback *cb);
+
+/* FIXME document. */
+EVENT2_EXPORT_SYMBOL
+void event_base_add_virtual_(struct event_base *base);
+void event_base_del_virtual_(struct event_base *base);
+
+/** For debugging: unless assertions are disabled, verify the referential
+ integrity of the internal data structures of 'base'. This operation can
+ be expensive.
+
+ Returns on success; aborts on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+void event_base_assert_ok_(struct event_base *base);
+void event_base_assert_ok_nolock_(struct event_base *base);
+
+
+/* Helper function: Call 'fn' exactly once every inserted or active event in
+ * the event_base 'base'.
+ *
+ * If fn returns 0, continue on to the next event. Otherwise, return the same
+ * value that fn returned.
+ *
+ * Requires that 'base' be locked.
+ */
+int event_base_foreach_event_nolock_(struct event_base *base,
+ event_base_foreach_event_cb cb, void *arg);
+
+/* Cleanup function to reset debug mode during shutdown.
+ *
+ * Calling this function doesn't mean it'll be possible to re-enable
+ * debug mode if any events were added.
+ */
+void event_disable_debug_mode(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/event.3 b/ipc/chromium/src/third_party/libevent/event.3
new file mode 100644
index 0000000000..655a823efe
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event.3
@@ -0,0 +1,624 @@
+.\" $OpenBSD: event.3,v 1.4 2002/07/12 18:50:48 provos Exp $
+.\"
+.\" Copyright (c) 2000 Artur Grabowski <art@openbsd.org>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\"
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\" 3. The name of the author may not be used to endorse or promote products
+.\" derived from this software without specific prior written permission.
+.\"
+.\" THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+.\" INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+.\" AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+.\" THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+.\" EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+.\" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+.\" OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+.\" WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+.\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+.\" ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+.\"
+.Dd August 8, 2000
+.Dt EVENT 3
+.Os
+.Sh NAME
+.Nm event_init ,
+.Nm event_dispatch ,
+.Nm event_loop ,
+.Nm event_loopexit ,
+.Nm event_loopbreak ,
+.Nm event_set ,
+.Nm event_base_dispatch ,
+.Nm event_base_loop ,
+.Nm event_base_loopexit ,
+.Nm event_base_loopbreak ,
+.Nm event_base_set ,
+.Nm event_base_free ,
+.Nm event_add ,
+.Nm event_del ,
+.Nm event_once ,
+.Nm event_base_once ,
+.Nm event_pending ,
+.Nm event_initialized ,
+.Nm event_priority_init ,
+.Nm event_priority_set ,
+.Nm evtimer_set ,
+.Nm evtimer_add ,
+.Nm evtimer_del ,
+.Nm evtimer_pending ,
+.Nm evtimer_initialized ,
+.Nm signal_set ,
+.Nm signal_add ,
+.Nm signal_del ,
+.Nm signal_pending ,
+.Nm signal_initialized ,
+.Nm bufferevent_new ,
+.Nm bufferevent_free ,
+.Nm bufferevent_write ,
+.Nm bufferevent_write_buffer ,
+.Nm bufferevent_read ,
+.Nm bufferevent_enable ,
+.Nm bufferevent_disable ,
+.Nm bufferevent_settimeout ,
+.Nm bufferevent_base_set ,
+.Nm evbuffer_new ,
+.Nm evbuffer_free ,
+.Nm evbuffer_add ,
+.Nm evbuffer_add_buffer ,
+.Nm evbuffer_add_printf ,
+.Nm evbuffer_add_vprintf ,
+.Nm evbuffer_drain ,
+.Nm evbuffer_write ,
+.Nm evbuffer_read ,
+.Nm evbuffer_find ,
+.Nm evbuffer_readline ,
+.Nm evhttp_new ,
+.Nm evhttp_bind_socket ,
+.Nm evhttp_free
+.Nd execute a function when a specific event occurs
+.Sh SYNOPSIS
+.Fd #include <sys/time.h>
+.Fd #include <event.h>
+.Ft "struct event_base *"
+.Fn "event_init" "void"
+.Ft int
+.Fn "event_dispatch" "void"
+.Ft int
+.Fn "event_loop" "int flags"
+.Ft int
+.Fn "event_loopexit" "struct timeval *tv"
+.Ft int
+.Fn "event_loopbreak" "void"
+.Ft void
+.Fn "event_set" "struct event *ev" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg"
+.Ft int
+.Fn "event_base_dispatch" "struct event_base *base"
+.Ft int
+.Fn "event_base_loop" "struct event_base *base" "int flags"
+.Ft int
+.Fn "event_base_loopexit" "struct event_base *base" "struct timeval *tv"
+.Ft int
+.Fn "event_base_loopbreak" "struct event_base *base"
+.Ft int
+.Fn "event_base_set" "struct event_base *base" "struct event *"
+.Ft void
+.Fn "event_base_free" "struct event_base *base"
+.Ft int
+.Fn "event_add" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "event_del" "struct event *ev"
+.Ft int
+.Fn "event_once" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
+.Ft int
+.Fn "event_base_once" "struct event_base *base" "int fd" "short event" "void (*fn)(int, short, void *)" "void *arg" "struct timeval *tv"
+.Ft int
+.Fn "event_pending" "struct event *ev" "short event" "struct timeval *tv"
+.Ft int
+.Fn "event_initialized" "struct event *ev"
+.Ft int
+.Fn "event_priority_init" "int npriorities"
+.Ft int
+.Fn "event_priority_set" "struct event *ev" "int priority"
+.Ft void
+.Fn "evtimer_set" "struct event *ev" "void (*fn)(int, short, void *)" "void *arg"
+.Ft void
+.Fn "evtimer_add" "struct event *ev" "struct timeval *"
+.Ft void
+.Fn "evtimer_del" "struct event *ev"
+.Ft int
+.Fn "evtimer_pending" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "evtimer_initialized" "struct event *ev"
+.Ft void
+.Fn "signal_set" "struct event *ev" "int signal" "void (*fn)(int, short, void *)" "void *arg"
+.Ft void
+.Fn "signal_add" "struct event *ev" "struct timeval *"
+.Ft void
+.Fn "signal_del" "struct event *ev"
+.Ft int
+.Fn "signal_pending" "struct event *ev" "struct timeval *tv"
+.Ft int
+.Fn "signal_initialized" "struct event *ev"
+.Ft "struct bufferevent *"
+.Fn "bufferevent_new" "int fd" "evbuffercb readcb" "evbuffercb writecb" "everrorcb" "void *cbarg"
+.Ft void
+.Fn "bufferevent_free" "struct bufferevent *bufev"
+.Ft int
+.Fn "bufferevent_write" "struct bufferevent *bufev" "void *data" "size_t size"
+.Ft int
+.Fn "bufferevent_write_buffer" "struct bufferevent *bufev" "struct evbuffer *buf"
+.Ft size_t
+.Fn "bufferevent_read" "struct bufferevent *bufev" "void *data" "size_t size"
+.Ft int
+.Fn "bufferevent_enable" "struct bufferevent *bufev" "short event"
+.Ft int
+.Fn "bufferevent_disable" "struct bufferevent *bufev" "short event"
+.Ft void
+.Fn "bufferevent_settimeout" "struct bufferevent *bufev" "int timeout_read" "int timeout_write"
+.Ft int
+.Fn "bufferevent_base_set" "struct event_base *base" "struct bufferevent *bufev"
+.Ft "struct evbuffer *"
+.Fn "evbuffer_new" "void"
+.Ft void
+.Fn "evbuffer_free" "struct evbuffer *buf"
+.Ft int
+.Fn "evbuffer_add" "struct evbuffer *buf" "const void *data" "size_t size"
+.Ft int
+.Fn "evbuffer_add_buffer" "struct evbuffer *dst" "struct evbuffer *src"
+.Ft int
+.Fn "evbuffer_add_printf" "struct evbuffer *buf" "const char *fmt" "..."
+.Ft int
+.Fn "evbuffer_add_vprintf" "struct evbuffer *buf" "const char *fmt" "va_list ap"
+.Ft void
+.Fn "evbuffer_drain" "struct evbuffer *buf" "size_t size"
+.Ft int
+.Fn "evbuffer_write" "struct evbuffer *buf" "int fd"
+.Ft int
+.Fn "evbuffer_read" "struct evbuffer *buf" "int fd" "int size"
+.Ft "unsigned char *"
+.Fn "evbuffer_find" "struct evbuffer *buf" "const unsigned char *data" "size_t size"
+.Ft "char *"
+.Fn "evbuffer_readline" "struct evbuffer *buf"
+.Ft "struct evhttp *"
+.Fn "evhttp_new" "struct event_base *base"
+.Ft int
+.Fn "evhttp_bind_socket" "struct evhttp *http" "const char *address" "unsigned short port"
+.Ft "void"
+.Fn "evhttp_free" "struct evhttp *http"
+.Ft int
+.Fa (*event_sigcb)(void) ;
+.Ft volatile sig_atomic_t
+.Fa event_gotsig ;
+.Sh DESCRIPTION
+The
+.Nm event
+API provides a mechanism to execute a function when a specific event
+on a file descriptor occurs or after a given time has passed.
+.Pp
+The
+.Nm event
+API needs to be initialized with
+.Fn event_init
+before it can be used.
+.Pp
+In order to process events, an application needs to call
+.Fn event_dispatch .
+This function only returns on error, and should replace the event core
+of the application program.
+.Pp
+The function
+.Fn event_set
+prepares the event structure
+.Fa ev
+to be used in future calls to
+.Fn event_add
+and
+.Fn event_del .
+The event will be prepared to call the function specified by the
+.Fa fn
+argument with an
+.Fa int
+argument indicating the file descriptor, a
+.Fa short
+argument indicating the type of event, and a
+.Fa void *
+argument given in the
+.Fa arg
+argument.
+The
+.Fa fd
+indicates the file descriptor that should be monitored for events.
+The events can be either
+.Va EV_READ ,
+.Va EV_WRITE ,
+or both,
+indicating that an application can read or write from the file descriptor
+respectively without blocking.
+.Pp
+The function
+.Fa fn
+will be called with the file descriptor that triggered the event and
+the type of event which will be either
+.Va EV_TIMEOUT ,
+.Va EV_SIGNAL ,
+.Va EV_READ ,
+or
+.Va EV_WRITE .
+Additionally, an event which has registered interest in more than one of the
+preceeding events, via bitwise-OR to
+.Fn event_set ,
+can provide its callback function with a bitwise-OR of more than one triggered
+event.
+The additional flag
+.Va EV_PERSIST
+makes an
+.Fn event_add
+persistent until
+.Fn event_del
+has been called.
+.Pp
+Once initialized, the
+.Fa ev
+structure can be used repeatedly with
+.Fn event_add
+and
+.Fn event_del
+and does not need to be reinitialized unless the function called and/or
+the argument to it are to be changed.
+However, when an
+.Fa ev
+structure has been added to libevent using
+.Fn event_add
+the structure must persist until the event occurs (assuming
+.Fa EV_PERSIST
+is not set) or is removed
+using
+.Fn event_del .
+You may not reuse the same
+.Fa ev
+structure for multiple monitored descriptors; each descriptor
+needs its own
+.Fa ev .
+.Pp
+The function
+.Fn event_add
+schedules the execution of the
+.Fa ev
+event when the event specified in
+.Fn event_set
+occurs or in at least the time specified in the
+.Fa tv .
+If
+.Fa tv
+is
+.Dv NULL ,
+no timeout occurs and the function will only be called
+if a matching event occurs on the file descriptor.
+The event in the
+.Fa ev
+argument must be already initialized by
+.Fn event_set
+and may not be used in calls to
+.Fn event_set
+until it has timed out or been removed with
+.Fn event_del .
+If the event in the
+.Fa ev
+argument already has a scheduled timeout, the old timeout will be
+replaced by the new one.
+.Pp
+The function
+.Fn event_del
+will cancel the event in the argument
+.Fa ev .
+If the event has already executed or has never been added
+the call will have no effect.
+.Pp
+The functions
+.Fn evtimer_set ,
+.Fn evtimer_add ,
+.Fn evtimer_del ,
+.Fn evtimer_initialized ,
+and
+.Fn evtimer_pending
+are abbreviations for common situations where only a timeout is required.
+The file descriptor passed will be \-1, and the event type will be
+.Va EV_TIMEOUT .
+.Pp
+The functions
+.Fn signal_set ,
+.Fn signal_add ,
+.Fn signal_del ,
+.Fn signal_initialized ,
+and
+.Fn signal_pending
+are abbreviations.
+The event type will be a persistent
+.Va EV_SIGNAL .
+That means
+.Fn signal_set
+adds
+.Va EV_PERSIST .
+.Pp
+In order to avoid races in signal handlers, the
+.Nm event
+API provides two variables:
+.Va event_sigcb
+and
+.Va event_gotsig .
+A signal handler
+sets
+.Va event_gotsig
+to indicate that a signal has been received.
+The application sets
+.Va event_sigcb
+to a callback function.
+After the signal handler sets
+.Va event_gotsig ,
+.Nm event_dispatch
+will execute the callback function to process received signals.
+The callback returns 1 when no events are registered any more.
+It can return \-1 to indicate an error to the
+.Nm event
+library, causing
+.Fn event_dispatch
+to terminate with
+.Va errno
+set to
+.Er EINTR .
+.Pp
+The function
+.Fn event_once
+is similar to
+.Fn event_set .
+However, it schedules a callback to be called exactly once and does not
+require the caller to prepare an
+.Fa event
+structure.
+This function supports
+.Fa EV_TIMEOUT ,
+.Fa EV_READ ,
+and
+.Fa EV_WRITE .
+.Pp
+The
+.Fn event_pending
+function can be used to check if the event specified by
+.Fa event
+is pending to run.
+If
+.Va EV_TIMEOUT
+was specified and
+.Fa tv
+is not
+.Dv NULL ,
+the expiration time of the event will be returned in
+.Fa tv .
+.Pp
+The
+.Fn event_initialized
+macro can be used to check if an event has been initialized.
+.Pp
+The
+.Nm event_loop
+function provides an interface for single pass execution of pending
+events.
+The flags
+.Va EVLOOP_ONCE
+and
+.Va EVLOOP_NONBLOCK
+are recognized.
+The
+.Nm event_loopexit
+function exits from the event loop. The next
+.Fn event_loop
+iteration after the
+given timer expires will complete normally (handling all queued events) then
+exit without blocking for events again. Subsequent invocations of
+.Fn event_loop
+will proceed normally.
+The
+.Nm event_loopbreak
+function exits from the event loop immediately.
+.Fn event_loop
+will abort after the next event is completed;
+.Fn event_loopbreak
+is typically invoked from this event's callback. This behavior is analogous
+to the "break;" statement. Subsequent invocations of
+.Fn event_loop
+will proceed normally.
+.Pp
+It is the responsibility of the caller to provide these functions with
+pre-allocated event structures.
+.Pp
+.Sh EVENT PRIORITIES
+By default
+.Nm libevent
+schedules all active events with the same priority.
+However, sometimes it is desirable to process some events with a higher
+priority than others.
+For that reason,
+.Nm libevent
+supports strict priority queues.
+Active events with a lower priority are always processed before events
+with a higher priority.
+.Pp
+The number of different priorities can be set initially with the
+.Fn event_priority_init
+function.
+This function should be called before the first call to
+.Fn event_dispatch .
+The
+.Fn event_priority_set
+function can be used to assign a priority to an event.
+By default,
+.Nm libevent
+assigns the middle priority to all events unless their priority
+is explicitly set.
+.Sh THREAD SAFE EVENTS
+.Nm Libevent
+has experimental support for thread-safe events.
+When initializing the library via
+.Fn event_init ,
+an event base is returned.
+This event base can be used in conjunction with calls to
+.Fn event_base_set ,
+.Fn event_base_dispatch ,
+.Fn event_base_loop ,
+.Fn event_base_loopexit ,
+.Fn bufferevent_base_set
+and
+.Fn event_base_free .
+.Fn event_base_set
+should be called after preparing an event with
+.Fn event_set ,
+as
+.Fn event_set
+assigns the provided event to the most recently created event base.
+.Fn bufferevent_base_set
+should be called after preparing a bufferevent with
+.Fn bufferevent_new .
+.Fn event_base_free
+should be used to free memory associated with the event base
+when it is no longer needed.
+.Sh BUFFERED EVENTS
+.Nm libevent
+provides an abstraction on top of the regular event callbacks.
+This abstraction is called a
+.Va "buffered event" .
+A buffered event provides input and output buffers that get filled
+and drained automatically.
+The user of a buffered event no longer deals directly with the IO,
+but instead is reading from input and writing to output buffers.
+.Pp
+A new bufferevent is created by
+.Fn bufferevent_new .
+The parameter
+.Fa fd
+specifies the file descriptor from which data is read and written to.
+This file descriptor is not allowed to be a
+.Xr pipe 2 .
+The next three parameters are callbacks.
+The read and write callback have the following form:
+.Ft void
+.Fn "(*cb)" "struct bufferevent *bufev" "void *arg" .
+The error callback has the following form:
+.Ft void
+.Fn "(*cb)" "struct bufferevent *bufev" "short what" "void *arg" .
+The argument is specified by the fourth parameter
+.Fa "cbarg" .
+A
+.Fa bufferevent struct
+pointer is returned on success, NULL on error.
+Both the read and the write callback may be NULL.
+The error callback has to be always provided.
+.Pp
+Once initialized, the bufferevent structure can be used repeatedly with
+bufferevent_enable() and bufferevent_disable().
+The flags parameter can be a combination of
+.Va EV_READ
+and
+.Va EV_WRITE .
+When read enabled the bufferevent will try to read from the file
+descriptor and call the read callback.
+The write callback is executed
+whenever the output buffer is drained below the write low watermark,
+which is
+.Va 0
+by default.
+.Pp
+The
+.Fn bufferevent_write
+function can be used to write data to the file descriptor.
+The data is appended to the output buffer and written to the descriptor
+automatically as it becomes available for writing.
+.Fn bufferevent_write
+returns 0 on success or \-1 on failure.
+The
+.Fn bufferevent_read
+function is used to read data from the input buffer,
+returning the amount of data read.
+.Pp
+If multiple bases are in use, bufferevent_base_set() must be called before
+enabling the bufferevent for the first time.
+.Sh NON-BLOCKING HTTP SUPPORT
+.Nm libevent
+provides a very thin HTTP layer that can be used both to host an HTTP
+server and also to make HTTP requests.
+An HTTP server can be created by calling
+.Fn evhttp_new .
+It can be bound to any port and address with the
+.Fn evhttp_bind_socket
+function.
+When the HTTP server is no longer used, it can be freed via
+.Fn evhttp_free .
+.Pp
+To be notified of HTTP requests, a user needs to register callbacks with the
+HTTP server.
+This can be done by calling
+.Fn evhttp_set_cb .
+The second argument is the URI for which a callback is being registered.
+The corresponding callback will receive an
+.Va struct evhttp_request
+object that contains all information about the request.
+.Pp
+This section does not document all the possible function calls; please
+check
+.Va event.h
+for the public interfaces.
+.Sh ADDITIONAL NOTES
+It is possible to disable support for
+.Va epoll , kqueue , devpoll , poll
+or
+.Va select
+by setting the environment variable
+.Va EVENT_NOEPOLL , EVENT_NOKQUEUE , EVENT_NODEVPOLL , EVENT_NOPOLL
+or
+.Va EVENT_NOSELECT ,
+respectively.
+By setting the environment variable
+.Va EVENT_SHOW_METHOD ,
+.Nm libevent
+displays the kernel notification method that it uses.
+.Sh RETURN VALUES
+Upon successful completion
+.Fn event_add
+and
+.Fn event_del
+return 0.
+Otherwise, \-1 is returned and the global variable errno is
+set to indicate the error.
+.Sh SEE ALSO
+.Xr kqueue 2 ,
+.Xr poll 2 ,
+.Xr select 2 ,
+.Xr evdns 3 ,
+.Xr timeout 9
+.Sh HISTORY
+The
+.Nm event
+API manpage is based on the
+.Xr timeout 9
+manpage by Artur Grabowski.
+The port of
+.Nm libevent
+to Windows is due to Michael A. Davis.
+Support for real-time signals is due to Taral.
+.Sh AUTHORS
+The
+.Nm event
+library was written by Niels Provos.
+.Sh BUGS
+This documentation is neither complete nor authoritative.
+If you are in doubt about the usage of this API then
+check the source code to find out how it works, write
+up the missing piece of documentation and send it to
+me for inclusion in this man page.
diff --git a/ipc/chromium/src/third_party/libevent/event.c b/ipc/chromium/src/third_party/libevent/event.c
new file mode 100644
index 0000000000..7a42b73191
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event.c
@@ -0,0 +1,4020 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#if !defined(_WIN32) && defined(EVENT__HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <ctype.h>
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+#include <time.h>
+#include <limits.h>
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event-internal.h"
+#include "defer-internal.h"
+#include "evthread-internal.h"
+#include "event2/thread.h"
+#include "event2/util.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "iocp-internal.h"
+#include "changelist-internal.h"
+#define HT_NO_CACHE_HASH_VALUES
+#include "ht-internal.h"
+#include "util-internal.h"
+
+
+#ifdef EVENT__HAVE_WORKING_KQUEUE
+#include "kqueue-internal.h"
+#endif
+
+#ifdef EVENT__HAVE_EVENT_PORTS
+extern const struct eventop evportops;
+#endif
+#ifdef EVENT__HAVE_SELECT
+extern const struct eventop selectops;
+#endif
+#ifdef EVENT__HAVE_POLL
+extern const struct eventop pollops;
+#endif
+#ifdef EVENT__HAVE_EPOLL
+extern const struct eventop epollops;
+#endif
+#ifdef EVENT__HAVE_WORKING_KQUEUE
+extern const struct eventop kqops;
+#endif
+#ifdef EVENT__HAVE_DEVPOLL
+extern const struct eventop devpollops;
+#endif
+#ifdef _WIN32
+extern const struct eventop win32ops;
+#endif
+
+/* Array of backends in order of preference. */
+static const struct eventop *eventops[] = {
+#ifdef EVENT__HAVE_EVENT_PORTS
+ &evportops,
+#endif
+#ifdef EVENT__HAVE_WORKING_KQUEUE
+ &kqops,
+#endif
+#ifdef EVENT__HAVE_EPOLL
+ &epollops,
+#endif
+#ifdef EVENT__HAVE_DEVPOLL
+ &devpollops,
+#endif
+#ifdef EVENT__HAVE_POLL
+ &pollops,
+#endif
+#ifdef EVENT__HAVE_SELECT
+ &selectops,
+#endif
+#ifdef _WIN32
+ &win32ops,
+#endif
+ NULL
+};
+
+/* Global state; deprecated */
+EVENT2_EXPORT_SYMBOL
+struct event_base *event_global_current_base_ = NULL;
+#define current_base event_global_current_base_
+
+/* Global state */
+
+static void *event_self_cbarg_ptr_ = NULL;
+
+/* Prototypes */
+static void event_queue_insert_active(struct event_base *, struct event_callback *);
+static void event_queue_insert_active_later(struct event_base *, struct event_callback *);
+static void event_queue_insert_timeout(struct event_base *, struct event *);
+static void event_queue_insert_inserted(struct event_base *, struct event *);
+static void event_queue_remove_active(struct event_base *, struct event_callback *);
+static void event_queue_remove_active_later(struct event_base *, struct event_callback *);
+static void event_queue_remove_timeout(struct event_base *, struct event *);
+static void event_queue_remove_inserted(struct event_base *, struct event *);
+static void event_queue_make_later_events_active(struct event_base *base);
+
+static int evthread_make_base_notifiable_nolock_(struct event_base *base);
+static int event_del_(struct event *ev, int blocking);
+
+#ifdef USE_REINSERT_TIMEOUT
+/* This code seems buggy; only turn it on if we find out what the trouble is. */
+static void event_queue_reinsert_timeout(struct event_base *,struct event *, int was_common, int is_common, int old_timeout_idx);
+#endif
+
+static int event_haveevents(struct event_base *);
+
+static int event_process_active(struct event_base *);
+
+static int timeout_next(struct event_base *, struct timeval **);
+static void timeout_process(struct event_base *);
+
+static inline void event_signal_closure(struct event_base *, struct event *ev);
+static inline void event_persist_closure(struct event_base *, struct event *ev);
+
+static int evthread_notify_base(struct event_base *base);
+
+static void insert_common_timeout_inorder(struct common_timeout_list *ctl,
+ struct event *ev);
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+/* These functions implement a hashtable of which 'struct event *' structures
+ * have been setup or added. We don't want to trust the content of the struct
+ * event itself, since we're trying to work through cases where an event gets
+ * clobbered or freed. Instead, we keep a hashtable indexed by the pointer.
+ */
+
+struct event_debug_entry {
+ HT_ENTRY(event_debug_entry) node;
+ const struct event *ptr;
+ unsigned added : 1;
+};
+
+static inline unsigned
+hash_debug_entry(const struct event_debug_entry *e)
+{
+ /* We need to do this silliness to convince compilers that we
+ * honestly mean to cast e->ptr to an integer, and discard any
+ * part of it that doesn't fit in an unsigned.
+ */
+ unsigned u = (unsigned) ((ev_uintptr_t) e->ptr);
+ /* Our hashtable implementation is pretty sensitive to low bits,
+ * and every struct event is over 64 bytes in size, so we can
+ * just say >>6. */
+ return (u >> 6);
+}
+
+static inline int
+eq_debug_entry(const struct event_debug_entry *a,
+ const struct event_debug_entry *b)
+{
+ return a->ptr == b->ptr;
+}
+
+int event_debug_mode_on_ = 0;
+
+
+#if !defined(EVENT__DISABLE_THREAD_SUPPORT) && !defined(EVENT__DISABLE_DEBUG_MODE)
+/**
+ * @brief debug mode variable which is set for any function/structure that needs
+ * to be shared across threads (if thread support is enabled).
+ *
+ * When and if evthreads are initialized, this variable will be evaluated,
+ * and if set to something other than zero, this means the evthread setup
+ * functions were called out of order.
+ *
+ * See: "Locks and threading" in the documentation.
+ */
+int event_debug_created_threadable_ctx_ = 0;
+#endif
+
+/* Set if it's too late to enable event_debug_mode. */
+static int event_debug_mode_too_late = 0;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+static void *event_debug_map_lock_ = NULL;
+#endif
+static HT_HEAD(event_debug_map, event_debug_entry) global_debug_map =
+ HT_INITIALIZER();
+
+HT_PROTOTYPE(event_debug_map, event_debug_entry, node, hash_debug_entry,
+ eq_debug_entry)
+HT_GENERATE(event_debug_map, event_debug_entry, node, hash_debug_entry,
+ eq_debug_entry, 0.5, mm_malloc, mm_realloc, mm_free)
+
+/* record that ev is now setup (that is, ready for an add) */
+static void event_debug_note_setup_(const struct event *ev)
+{
+ struct event_debug_entry *dent, find;
+
+ if (!event_debug_mode_on_)
+ goto out;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_FIND(event_debug_map, &global_debug_map, &find);
+ if (dent) {
+ dent->added = 0;
+ } else {
+ dent = mm_malloc(sizeof(*dent));
+ if (!dent)
+ event_err(1,
+ "Out of memory in debugging code");
+ dent->ptr = ev;
+ dent->added = 0;
+ HT_INSERT(event_debug_map, &global_debug_map, dent);
+ }
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+
+out:
+ event_debug_mode_too_late = 1;
+}
+/* record that ev is no longer setup */
+static void event_debug_note_teardown_(const struct event *ev)
+{
+ struct event_debug_entry *dent, find;
+
+ if (!event_debug_mode_on_)
+ goto out;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_REMOVE(event_debug_map, &global_debug_map, &find);
+ if (dent)
+ mm_free(dent);
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+
+out:
+ event_debug_mode_too_late = 1;
+}
+/* Macro: record that ev is now added */
+static void event_debug_note_add_(const struct event *ev)
+{
+ struct event_debug_entry *dent,find;
+
+ if (!event_debug_mode_on_)
+ goto out;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_FIND(event_debug_map, &global_debug_map, &find);
+ if (dent) {
+ dent->added = 1;
+ } else {
+ event_errx(EVENT_ERR_ABORT_,
+ "%s: noting an add on a non-setup event %p"
+ " (events: 0x%x, fd: "EV_SOCK_FMT
+ ", flags: 0x%x)",
+ __func__, ev, ev->ev_events,
+ EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
+ }
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+
+out:
+ event_debug_mode_too_late = 1;
+}
+/* record that ev is no longer added */
+static void event_debug_note_del_(const struct event *ev)
+{
+ struct event_debug_entry *dent, find;
+
+ if (!event_debug_mode_on_)
+ goto out;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_FIND(event_debug_map, &global_debug_map, &find);
+ if (dent) {
+ dent->added = 0;
+ } else {
+ event_errx(EVENT_ERR_ABORT_,
+ "%s: noting a del on a non-setup event %p"
+ " (events: 0x%x, fd: "EV_SOCK_FMT
+ ", flags: 0x%x)",
+ __func__, ev, ev->ev_events,
+ EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
+ }
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+
+out:
+ event_debug_mode_too_late = 1;
+}
+/* assert that ev is setup (i.e., okay to add or inspect) */
+static void event_debug_assert_is_setup_(const struct event *ev)
+{
+ struct event_debug_entry *dent, find;
+
+ if (!event_debug_mode_on_)
+ return;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_FIND(event_debug_map, &global_debug_map, &find);
+ if (!dent) {
+ event_errx(EVENT_ERR_ABORT_,
+ "%s called on a non-initialized event %p"
+ " (events: 0x%x, fd: "EV_SOCK_FMT
+ ", flags: 0x%x)",
+ __func__, ev, ev->ev_events,
+ EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
+ }
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+}
+/* assert that ev is not added (i.e., okay to tear down or set up again) */
+static void event_debug_assert_not_added_(const struct event *ev)
+{
+ struct event_debug_entry *dent, find;
+
+ if (!event_debug_mode_on_)
+ return;
+
+ find.ptr = ev;
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ dent = HT_FIND(event_debug_map, &global_debug_map, &find);
+ if (dent && dent->added) {
+ event_errx(EVENT_ERR_ABORT_,
+ "%s called on an already added event %p"
+ " (events: 0x%x, fd: "EV_SOCK_FMT", "
+ "flags: 0x%x)",
+ __func__, ev, ev->ev_events,
+ EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
+ }
+ EVLOCK_UNLOCK(event_debug_map_lock_, 0);
+}
+static void event_debug_assert_socket_nonblocking_(evutil_socket_t fd)
+{
+ if (!event_debug_mode_on_)
+ return;
+ if (fd < 0)
+ return;
+
+#ifndef _WIN32
+ {
+ int flags;
+ if ((flags = fcntl(fd, F_GETFL, NULL)) >= 0) {
+ EVUTIL_ASSERT(flags & O_NONBLOCK);
+ }
+ }
+#endif
+}
+#else
+static void event_debug_note_setup_(const struct event *ev) { (void)ev; }
+static void event_debug_note_teardown_(const struct event *ev) { (void)ev; }
+static void event_debug_note_add_(const struct event *ev) { (void)ev; }
+static void event_debug_note_del_(const struct event *ev) { (void)ev; }
+static void event_debug_assert_is_setup_(const struct event *ev) { (void)ev; }
+static void event_debug_assert_not_added_(const struct event *ev) { (void)ev; }
+static void event_debug_assert_socket_nonblocking_(evutil_socket_t fd) { (void)fd; }
+#endif
+
+#define EVENT_BASE_ASSERT_LOCKED(base) \
+ EVLOCK_ASSERT_LOCKED((base)->th_base_lock)
+
+/* How often (in seconds) do we check for changes in wall clock time relative
+ * to monotonic time? Set this to -1 for 'never.' */
+#define CLOCK_SYNC_INTERVAL 5
+
+/** Set 'tp' to the current time according to 'base'. We must hold the lock
+ * on 'base'. If there is a cached time, return it. Otherwise, use
+ * clock_gettime or gettimeofday as appropriate to find out the right time.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+gettime(struct event_base *base, struct timeval *tp)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (base->tv_cache.tv_sec) {
+ *tp = base->tv_cache;
+ return (0);
+ }
+
+ if (evutil_gettime_monotonic_(&base->monotonic_timer, tp) == -1) {
+ return -1;
+ }
+
+ if (base->last_updated_clock_diff + CLOCK_SYNC_INTERVAL
+ < tp->tv_sec) {
+ struct timeval tv;
+ evutil_gettimeofday(&tv,NULL);
+ evutil_timersub(&tv, tp, &base->tv_clock_diff);
+ base->last_updated_clock_diff = tp->tv_sec;
+ }
+
+ return 0;
+}
+
+int
+event_base_gettimeofday_cached(struct event_base *base, struct timeval *tv)
+{
+ int r;
+ if (!base) {
+ base = current_base;
+ if (!current_base)
+ return evutil_gettimeofday(tv, NULL);
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (base->tv_cache.tv_sec == 0) {
+ r = evutil_gettimeofday(tv, NULL);
+ } else {
+ evutil_timeradd(&base->tv_cache, &base->tv_clock_diff, tv);
+ r = 0;
+ }
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+/** Make 'base' have no current cached time. */
+static inline void
+clear_time_cache(struct event_base *base)
+{
+ base->tv_cache.tv_sec = 0;
+}
+
+/** Replace the cached time in 'base' with the current time. */
+static inline void
+update_time_cache(struct event_base *base)
+{
+ base->tv_cache.tv_sec = 0;
+ if (!(base->flags & EVENT_BASE_FLAG_NO_CACHE_TIME))
+ gettime(base, &base->tv_cache);
+}
+
+int
+event_base_update_cache_time(struct event_base *base)
+{
+
+ if (!base) {
+ base = current_base;
+ if (!current_base)
+ return -1;
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (base->running_loop)
+ update_time_cache(base);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return 0;
+}
+
+static inline struct event *
+event_callback_to_event(struct event_callback *evcb)
+{
+ EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_INIT));
+ return EVUTIL_UPCAST(evcb, struct event, ev_evcallback);
+}
+
+static inline struct event_callback *
+event_to_event_callback(struct event *ev)
+{
+ return &ev->ev_evcallback;
+}
+
+struct event_base *
+event_init(void)
+{
+ struct event_base *base = event_base_new_with_config(NULL);
+
+ if (base == NULL) {
+ event_errx(1, "%s: Unable to construct event_base", __func__);
+ return NULL;
+ }
+
+ current_base = base;
+
+ return (base);
+}
+
+struct event_base *
+event_base_new(void)
+{
+ struct event_base *base = NULL;
+ struct event_config *cfg = event_config_new();
+ if (cfg) {
+ base = event_base_new_with_config(cfg);
+ event_config_free(cfg);
+ }
+ return base;
+}
+
+/** Return true iff 'method' is the name of a method that 'cfg' tells us to
+ * avoid. */
+static int
+event_config_is_avoided_method(const struct event_config *cfg,
+ const char *method)
+{
+ struct event_config_entry *entry;
+
+ TAILQ_FOREACH(entry, &cfg->entries, next) {
+ if (entry->avoid_method != NULL &&
+ strcmp(entry->avoid_method, method) == 0)
+ return (1);
+ }
+
+ return (0);
+}
+
+/** Return true iff 'method' is disabled according to the environment. */
+static int
+event_is_method_disabled(const char *name)
+{
+ char environment[64];
+ int i;
+
+ evutil_snprintf(environment, sizeof(environment), "EVENT_NO%s", name);
+ for (i = 8; environment[i] != '\0'; ++i)
+ environment[i] = EVUTIL_TOUPPER_(environment[i]);
+ /* Note that evutil_getenv_() ignores the environment entirely if
+ * we're setuid */
+ return (evutil_getenv_(environment) != NULL);
+}
+
+int
+event_base_get_features(const struct event_base *base)
+{
+ return base->evsel->features;
+}
+
+void
+event_enable_debug_mode(void)
+{
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_mode_on_)
+ event_errx(1, "%s was called twice!", __func__);
+ if (event_debug_mode_too_late)
+ event_errx(1, "%s must be called *before* creating any events "
+ "or event_bases",__func__);
+
+ event_debug_mode_on_ = 1;
+
+ HT_INIT(event_debug_map, &global_debug_map);
+#endif
+}
+
+void
+event_disable_debug_mode(void)
+{
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ struct event_debug_entry **ent, *victim;
+
+ EVLOCK_LOCK(event_debug_map_lock_, 0);
+ for (ent = HT_START(event_debug_map, &global_debug_map); ent; ) {
+ victim = *ent;
+ ent = HT_NEXT_RMV(event_debug_map, &global_debug_map, ent);
+ mm_free(victim);
+ }
+ HT_CLEAR(event_debug_map, &global_debug_map);
+ EVLOCK_UNLOCK(event_debug_map_lock_ , 0);
+
+ event_debug_mode_on_ = 0;
+#endif
+}
+
+struct event_base *
+event_base_new_with_config(const struct event_config *cfg)
+{
+ int i;
+ struct event_base *base;
+ int should_check_environment;
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ event_debug_mode_too_late = 1;
+#endif
+
+ if ((base = mm_calloc(1, sizeof(struct event_base))) == NULL) {
+ event_warn("%s: calloc", __func__);
+ return NULL;
+ }
+
+ if (cfg)
+ base->flags = cfg->flags;
+
+ should_check_environment =
+ !(cfg && (cfg->flags & EVENT_BASE_FLAG_IGNORE_ENV));
+
+ {
+ struct timeval tmp;
+ int precise_time =
+ cfg && (cfg->flags & EVENT_BASE_FLAG_PRECISE_TIMER);
+ int flags;
+ if (should_check_environment && !precise_time) {
+ precise_time = evutil_getenv_("EVENT_PRECISE_TIMER") != NULL;
+ if (precise_time) {
+ base->flags |= EVENT_BASE_FLAG_PRECISE_TIMER;
+ }
+ }
+ flags = precise_time ? EV_MONOT_PRECISE : 0;
+ evutil_configure_monotonic_time_(&base->monotonic_timer, flags);
+
+ gettime(base, &tmp);
+ }
+
+ min_heap_ctor_(&base->timeheap);
+
+ base->sig.ev_signal_pair[0] = -1;
+ base->sig.ev_signal_pair[1] = -1;
+ base->th_notify_fd[0] = -1;
+ base->th_notify_fd[1] = -1;
+
+ TAILQ_INIT(&base->active_later_queue);
+
+ evmap_io_initmap_(&base->io);
+ evmap_signal_initmap_(&base->sigmap);
+ event_changelist_init_(&base->changelist);
+
+ base->evbase = NULL;
+
+ if (cfg) {
+ memcpy(&base->max_dispatch_time,
+ &cfg->max_dispatch_interval, sizeof(struct timeval));
+ base->limit_callbacks_after_prio =
+ cfg->limit_callbacks_after_prio;
+ } else {
+ base->max_dispatch_time.tv_sec = -1;
+ base->limit_callbacks_after_prio = 1;
+ }
+ if (cfg && cfg->max_dispatch_callbacks >= 0) {
+ base->max_dispatch_callbacks = cfg->max_dispatch_callbacks;
+ } else {
+ base->max_dispatch_callbacks = INT_MAX;
+ }
+ if (base->max_dispatch_callbacks == INT_MAX &&
+ base->max_dispatch_time.tv_sec == -1)
+ base->limit_callbacks_after_prio = INT_MAX;
+
+ for (i = 0; eventops[i] && !base->evbase; i++) {
+ if (cfg != NULL) {
+ /* determine if this backend should be avoided */
+ if (event_config_is_avoided_method(cfg,
+ eventops[i]->name))
+ continue;
+ if ((eventops[i]->features & cfg->require_features)
+ != cfg->require_features)
+ continue;
+ }
+
+ /* also obey the environment variables */
+ if (should_check_environment &&
+ event_is_method_disabled(eventops[i]->name))
+ continue;
+
+ base->evsel = eventops[i];
+
+ base->evbase = base->evsel->init(base);
+ }
+
+ if (base->evbase == NULL) {
+ event_warnx("%s: no event mechanism available",
+ __func__);
+ base->evsel = NULL;
+ event_base_free(base);
+ return NULL;
+ }
+
+ if (evutil_getenv_("EVENT_SHOW_METHOD"))
+ event_msgx("libevent using: %s", base->evsel->name);
+
+ /* allocate a single active event queue */
+ if (event_base_priority_init(base, 1) < 0) {
+ event_base_free(base);
+ return NULL;
+ }
+
+ /* prepare for threading */
+
+#if !defined(EVENT__DISABLE_THREAD_SUPPORT) && !defined(EVENT__DISABLE_DEBUG_MODE)
+ event_debug_created_threadable_ctx_ = 1;
+#endif
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (EVTHREAD_LOCKING_ENABLED() &&
+ (!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK))) {
+ int r;
+ EVTHREAD_ALLOC_LOCK(base->th_base_lock, 0);
+ EVTHREAD_ALLOC_COND(base->current_event_cond);
+ r = evthread_make_base_notifiable(base);
+ if (r<0) {
+ event_warnx("%s: Unable to make base notifiable.", __func__);
+ event_base_free(base);
+ return NULL;
+ }
+ }
+#endif
+
+#ifdef _WIN32
+ if (cfg && (cfg->flags & EVENT_BASE_FLAG_STARTUP_IOCP))
+ event_base_start_iocp_(base, cfg->n_cpus_hint);
+#endif
+
+ return (base);
+}
+
+int
+event_base_start_iocp_(struct event_base *base, int n_cpus)
+{
+#ifdef _WIN32
+ if (base->iocp)
+ return 0;
+ base->iocp = event_iocp_port_launch_(n_cpus);
+ if (!base->iocp) {
+ event_warnx("%s: Couldn't launch IOCP", __func__);
+ return -1;
+ }
+ return 0;
+#else
+ return -1;
+#endif
+}
+
+void
+event_base_stop_iocp_(struct event_base *base)
+{
+#ifdef _WIN32
+ int rv;
+
+ if (!base->iocp)
+ return;
+ rv = event_iocp_shutdown_(base->iocp, -1);
+ EVUTIL_ASSERT(rv >= 0);
+ base->iocp = NULL;
+#endif
+}
+
+static int
+event_base_cancel_single_callback_(struct event_base *base,
+ struct event_callback *evcb,
+ int run_finalizers)
+{
+ int result = 0;
+
+ if (evcb->evcb_flags & EVLIST_INIT) {
+ struct event *ev = event_callback_to_event(evcb);
+ if (!(ev->ev_flags & EVLIST_INTERNAL)) {
+ event_del_(ev, EVENT_DEL_EVEN_IF_FINALIZING);
+ result = 1;
+ }
+ } else {
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ event_callback_cancel_nolock_(base, evcb, 1);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ result = 1;
+ }
+
+ if (run_finalizers && (evcb->evcb_flags & EVLIST_FINALIZING)) {
+ switch (evcb->evcb_closure) {
+ case EV_CLOSURE_EVENT_FINALIZE:
+ case EV_CLOSURE_EVENT_FINALIZE_FREE: {
+ struct event *ev = event_callback_to_event(evcb);
+ ev->ev_evcallback.evcb_cb_union.evcb_evfinalize(ev, ev->ev_arg);
+ if (evcb->evcb_closure == EV_CLOSURE_EVENT_FINALIZE_FREE)
+ mm_free(ev);
+ break;
+ }
+ case EV_CLOSURE_CB_FINALIZE:
+ evcb->evcb_cb_union.evcb_cbfinalize(evcb, evcb->evcb_arg);
+ break;
+ default:
+ break;
+ }
+ }
+ return result;
+}
+
+static int event_base_free_queues_(struct event_base *base, int run_finalizers)
+{
+ int deleted = 0, i;
+
+ for (i = 0; i < base->nactivequeues; ++i) {
+ struct event_callback *evcb, *next;
+ for (evcb = TAILQ_FIRST(&base->activequeues[i]); evcb; ) {
+ next = TAILQ_NEXT(evcb, evcb_active_next);
+ deleted += event_base_cancel_single_callback_(base, evcb, run_finalizers);
+ evcb = next;
+ }
+ }
+
+ {
+ struct event_callback *evcb;
+ while ((evcb = TAILQ_FIRST(&base->active_later_queue))) {
+ deleted += event_base_cancel_single_callback_(base, evcb, run_finalizers);
+ }
+ }
+
+ return deleted;
+}
+
+static void
+event_base_free_(struct event_base *base, int run_finalizers)
+{
+ int i, n_deleted=0;
+ struct event *ev;
+ /* XXXX grab the lock? If there is contention when one thread frees
+ * the base, then the contending thread will be very sad soon. */
+
+ /* event_base_free(NULL) is how to free the current_base if we
+ * made it with event_init and forgot to hold a reference to it. */
+ if (base == NULL && current_base)
+ base = current_base;
+ /* Don't actually free NULL. */
+ if (base == NULL) {
+ event_warnx("%s: no base to free", __func__);
+ return;
+ }
+ /* XXX(niels) - check for internal events first */
+
+#ifdef _WIN32
+ event_base_stop_iocp_(base);
+#endif
+
+ /* threading fds if we have them */
+ if (base->th_notify_fd[0] != -1) {
+ event_del(&base->th_notify);
+ EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
+ if (base->th_notify_fd[1] != -1)
+ EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
+ base->th_notify_fd[0] = -1;
+ base->th_notify_fd[1] = -1;
+ event_debug_unassign(&base->th_notify);
+ }
+
+ /* Delete all non-internal events. */
+ evmap_delete_all_(base);
+
+ while ((ev = min_heap_top_(&base->timeheap)) != NULL) {
+ event_del(ev);
+ ++n_deleted;
+ }
+ for (i = 0; i < base->n_common_timeouts; ++i) {
+ struct common_timeout_list *ctl =
+ base->common_timeout_queues[i];
+ event_del(&ctl->timeout_event); /* Internal; doesn't count */
+ event_debug_unassign(&ctl->timeout_event);
+ for (ev = TAILQ_FIRST(&ctl->events); ev; ) {
+ struct event *next = TAILQ_NEXT(ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+ if (!(ev->ev_flags & EVLIST_INTERNAL)) {
+ event_del(ev);
+ ++n_deleted;
+ }
+ ev = next;
+ }
+ mm_free(ctl);
+ }
+ if (base->common_timeout_queues)
+ mm_free(base->common_timeout_queues);
+
+ for (;;) {
+ /* For finalizers we can register yet another finalizer out from
+ * finalizer, and iff finalizer will be in active_later_queue we can
+ * add finalizer to activequeues, and we will have events in
+ * activequeues after this function returns, which is not what we want
+ * (we even have an assertion for this).
+ *
+ * A simple case is bufferevent with underlying (i.e. filters).
+ */
+ int i = event_base_free_queues_(base, run_finalizers);
+ event_debug(("%s: %d events freed", __func__, i));
+ if (!i) {
+ break;
+ }
+ n_deleted += i;
+ }
+
+ if (n_deleted)
+ event_debug(("%s: %d events were still set in base",
+ __func__, n_deleted));
+
+ while (LIST_FIRST(&base->once_events)) {
+ struct event_once *eonce = LIST_FIRST(&base->once_events);
+ LIST_REMOVE(eonce, next_once);
+ mm_free(eonce);
+ }
+
+ if (base->evsel != NULL && base->evsel->dealloc != NULL)
+ base->evsel->dealloc(base);
+
+ for (i = 0; i < base->nactivequeues; ++i)
+ EVUTIL_ASSERT(TAILQ_EMPTY(&base->activequeues[i]));
+
+ EVUTIL_ASSERT(min_heap_empty_(&base->timeheap));
+ min_heap_dtor_(&base->timeheap);
+
+ mm_free(base->activequeues);
+
+ evmap_io_clear_(&base->io);
+ evmap_signal_clear_(&base->sigmap);
+ event_changelist_freemem_(&base->changelist);
+
+ EVTHREAD_FREE_LOCK(base->th_base_lock, 0);
+ EVTHREAD_FREE_COND(base->current_event_cond);
+
+ /* If we're freeing current_base, there won't be a current_base. */
+ if (base == current_base)
+ current_base = NULL;
+ mm_free(base);
+}
+
+void
+event_base_free_nofinalize(struct event_base *base)
+{
+ event_base_free_(base, 0);
+}
+
+void
+event_base_free(struct event_base *base)
+{
+ event_base_free_(base, 1);
+}
+
+/* Fake eventop; used to disable the backend temporarily inside event_reinit
+ * so that we can call event_del() on an event without telling the backend.
+ */
+static int
+nil_backend_del(struct event_base *b, evutil_socket_t fd, short old,
+ short events, void *fdinfo)
+{
+ return 0;
+}
+const struct eventop nil_eventop = {
+ "nil",
+ NULL, /* init: unused. */
+ NULL, /* add: unused. */
+ nil_backend_del, /* del: used, so needs to be killed. */
+ NULL, /* dispatch: unused. */
+ NULL, /* dealloc: unused. */
+ 0, 0, 0
+};
+
+/* reinitialize the event base after a fork */
+int
+event_reinit(struct event_base *base)
+{
+ const struct eventop *evsel;
+ int res = 0;
+ int was_notifiable = 0;
+ int had_signal_added = 0;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ evsel = base->evsel;
+
+ /* check if this event mechanism requires reinit on the backend */
+ if (evsel->need_reinit) {
+ /* We're going to call event_del() on our notify events (the
+ * ones that tell about signals and wakeup events). But we
+ * don't actually want to tell the backend to change its
+ * state, since it might still share some resource (a kqueue,
+ * an epoll fd) with the parent process, and we don't want to
+ * delete the fds from _that_ backend, we temporarily stub out
+ * the evsel with a replacement.
+ */
+ base->evsel = &nil_eventop;
+ }
+
+ /* We need to re-create a new signal-notification fd and a new
+ * thread-notification fd. Otherwise, we'll still share those with
+ * the parent process, which would make any notification sent to them
+ * get received by one or both of the event loops, more or less at
+ * random.
+ */
+ if (base->sig.ev_signal_added) {
+ event_del_nolock_(&base->sig.ev_signal, EVENT_DEL_AUTOBLOCK);
+ event_debug_unassign(&base->sig.ev_signal);
+ memset(&base->sig.ev_signal, 0, sizeof(base->sig.ev_signal));
+ had_signal_added = 1;
+ base->sig.ev_signal_added = 0;
+ }
+ if (base->sig.ev_signal_pair[0] != -1)
+ EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[0]);
+ if (base->sig.ev_signal_pair[1] != -1)
+ EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[1]);
+ if (base->th_notify_fn != NULL) {
+ was_notifiable = 1;
+ base->th_notify_fn = NULL;
+ }
+ if (base->th_notify_fd[0] != -1) {
+ event_del_nolock_(&base->th_notify, EVENT_DEL_AUTOBLOCK);
+ EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
+ if (base->th_notify_fd[1] != -1)
+ EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
+ base->th_notify_fd[0] = -1;
+ base->th_notify_fd[1] = -1;
+ event_debug_unassign(&base->th_notify);
+ }
+
+ /* Replace the original evsel. */
+ base->evsel = evsel;
+
+ if (evsel->need_reinit) {
+ /* Reconstruct the backend through brute-force, so that we do
+ * not share any structures with the parent process. For some
+ * backends, this is necessary: epoll and kqueue, for
+ * instance, have events associated with a kernel
+ * structure. If didn't reinitialize, we'd share that
+ * structure with the parent process, and any changes made by
+ * the parent would affect our backend's behavior (and vice
+ * versa).
+ */
+ if (base->evsel->dealloc != NULL)
+ base->evsel->dealloc(base);
+ base->evbase = evsel->init(base);
+ if (base->evbase == NULL) {
+ event_errx(1,
+ "%s: could not reinitialize event mechanism",
+ __func__);
+ res = -1;
+ goto done;
+ }
+
+ /* Empty out the changelist (if any): we are starting from a
+ * blank slate. */
+ event_changelist_freemem_(&base->changelist);
+
+ /* Tell the event maps to re-inform the backend about all
+ * pending events. This will make the signal notification
+ * event get re-created if necessary. */
+ if (evmap_reinit_(base) < 0)
+ res = -1;
+ } else {
+ res = evsig_init_(base);
+ if (res == 0 && had_signal_added) {
+ res = event_add_nolock_(&base->sig.ev_signal, NULL, 0);
+ if (res == 0)
+ base->sig.ev_signal_added = 1;
+ }
+ }
+
+ /* If we were notifiable before, and nothing just exploded, become
+ * notifiable again. */
+ if (was_notifiable && res == 0)
+ res = evthread_make_base_notifiable_nolock_(base);
+
+done:
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return (res);
+}
+
+/* Get the monotonic time for this event_base' timer */
+int
+event_gettime_monotonic(struct event_base *base, struct timeval *tv)
+{
+ int rv = -1;
+
+ if (base && tv) {
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ rv = evutil_gettime_monotonic_(&(base->monotonic_timer), tv);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ }
+
+ return rv;
+}
+
+const char **
+event_get_supported_methods(void)
+{
+ static const char **methods = NULL;
+ const struct eventop **method;
+ const char **tmp;
+ int i = 0, k;
+
+ /* count all methods */
+ for (method = &eventops[0]; *method != NULL; ++method) {
+ ++i;
+ }
+
+ /* allocate one more than we need for the NULL pointer */
+ tmp = mm_calloc((i + 1), sizeof(char *));
+ if (tmp == NULL)
+ return (NULL);
+
+ /* populate the array with the supported methods */
+ for (k = 0, i = 0; eventops[k] != NULL; ++k) {
+ tmp[i++] = eventops[k]->name;
+ }
+ tmp[i] = NULL;
+
+ if (methods != NULL)
+ mm_free((char**)methods);
+
+ methods = tmp;
+
+ return (methods);
+}
+
+struct event_config *
+event_config_new(void)
+{
+ struct event_config *cfg = mm_calloc(1, sizeof(*cfg));
+
+ if (cfg == NULL)
+ return (NULL);
+
+ TAILQ_INIT(&cfg->entries);
+ cfg->max_dispatch_interval.tv_sec = -1;
+ cfg->max_dispatch_callbacks = INT_MAX;
+ cfg->limit_callbacks_after_prio = 1;
+
+ return (cfg);
+}
+
+static void
+event_config_entry_free(struct event_config_entry *entry)
+{
+ if (entry->avoid_method != NULL)
+ mm_free((char *)entry->avoid_method);
+ mm_free(entry);
+}
+
+void
+event_config_free(struct event_config *cfg)
+{
+ struct event_config_entry *entry;
+
+ while ((entry = TAILQ_FIRST(&cfg->entries)) != NULL) {
+ TAILQ_REMOVE(&cfg->entries, entry, next);
+ event_config_entry_free(entry);
+ }
+ mm_free(cfg);
+}
+
+int
+event_config_set_flag(struct event_config *cfg, int flag)
+{
+ if (!cfg)
+ return -1;
+ cfg->flags |= flag;
+ return 0;
+}
+
+int
+event_config_avoid_method(struct event_config *cfg, const char *method)
+{
+ struct event_config_entry *entry = mm_malloc(sizeof(*entry));
+ if (entry == NULL)
+ return (-1);
+
+ if ((entry->avoid_method = mm_strdup(method)) == NULL) {
+ mm_free(entry);
+ return (-1);
+ }
+
+ TAILQ_INSERT_TAIL(&cfg->entries, entry, next);
+
+ return (0);
+}
+
+int
+event_config_require_features(struct event_config *cfg,
+ int features)
+{
+ if (!cfg)
+ return (-1);
+ cfg->require_features = features;
+ return (0);
+}
+
+int
+event_config_set_num_cpus_hint(struct event_config *cfg, int cpus)
+{
+ if (!cfg)
+ return (-1);
+ cfg->n_cpus_hint = cpus;
+ return (0);
+}
+
+int
+event_config_set_max_dispatch_interval(struct event_config *cfg,
+ const struct timeval *max_interval, int max_callbacks, int min_priority)
+{
+ if (max_interval)
+ memcpy(&cfg->max_dispatch_interval, max_interval,
+ sizeof(struct timeval));
+ else
+ cfg->max_dispatch_interval.tv_sec = -1;
+ cfg->max_dispatch_callbacks =
+ max_callbacks >= 0 ? max_callbacks : INT_MAX;
+ if (min_priority < 0)
+ min_priority = 0;
+ cfg->limit_callbacks_after_prio = min_priority;
+ return (0);
+}
+
+int
+event_priority_init(int npriorities)
+{
+ return event_base_priority_init(current_base, npriorities);
+}
+
+int
+event_base_priority_init(struct event_base *base, int npriorities)
+{
+ int i, r;
+ r = -1;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (N_ACTIVE_CALLBACKS(base) || npriorities < 1
+ || npriorities >= EVENT_MAX_PRIORITIES)
+ goto err;
+
+ if (npriorities == base->nactivequeues)
+ goto ok;
+
+ if (base->nactivequeues) {
+ mm_free(base->activequeues);
+ base->nactivequeues = 0;
+ }
+
+ /* Allocate our priority queues */
+ base->activequeues = (struct evcallback_list *)
+ mm_calloc(npriorities, sizeof(struct evcallback_list));
+ if (base->activequeues == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto err;
+ }
+ base->nactivequeues = npriorities;
+
+ for (i = 0; i < base->nactivequeues; ++i) {
+ TAILQ_INIT(&base->activequeues[i]);
+ }
+
+ok:
+ r = 0;
+err:
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return (r);
+}
+
+int
+event_base_get_npriorities(struct event_base *base)
+{
+
+ int n;
+ if (base == NULL)
+ base = current_base;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ n = base->nactivequeues;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return (n);
+}
+
+int
+event_base_get_num_events(struct event_base *base, unsigned int type)
+{
+ int r = 0;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (type & EVENT_BASE_COUNT_ACTIVE)
+ r += base->event_count_active;
+
+ if (type & EVENT_BASE_COUNT_VIRTUAL)
+ r += base->virtual_event_count;
+
+ if (type & EVENT_BASE_COUNT_ADDED)
+ r += base->event_count;
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ return r;
+}
+
+int
+event_base_get_max_events(struct event_base *base, unsigned int type, int clear)
+{
+ int r = 0;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (type & EVENT_BASE_COUNT_ACTIVE) {
+ r += base->event_count_active_max;
+ if (clear)
+ base->event_count_active_max = 0;
+ }
+
+ if (type & EVENT_BASE_COUNT_VIRTUAL) {
+ r += base->virtual_event_count_max;
+ if (clear)
+ base->virtual_event_count_max = 0;
+ }
+
+ if (type & EVENT_BASE_COUNT_ADDED) {
+ r += base->event_count_max;
+ if (clear)
+ base->event_count_max = 0;
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ return r;
+}
+
+/* Returns true iff we're currently watching any events. */
+static int
+event_haveevents(struct event_base *base)
+{
+ /* Caller must hold th_base_lock */
+ return (base->virtual_event_count > 0 || base->event_count > 0);
+}
+
+/* "closure" function called when processing active signal events */
+static inline void
+event_signal_closure(struct event_base *base, struct event *ev)
+{
+ short ncalls;
+ int should_break;
+
+ /* Allows deletes to work */
+ ncalls = ev->ev_ncalls;
+ if (ncalls != 0)
+ ev->ev_pncalls = &ncalls;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ while (ncalls) {
+ ncalls--;
+ ev->ev_ncalls = ncalls;
+ if (ncalls == 0)
+ ev->ev_pncalls = NULL;
+ (*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ should_break = base->event_break;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ if (should_break) {
+ if (ncalls != 0)
+ ev->ev_pncalls = NULL;
+ return;
+ }
+ }
+}
+
+/* Common timeouts are special timeouts that are handled as queues rather than
+ * in the minheap. This is more efficient than the minheap if we happen to
+ * know that we're going to get several thousands of timeout events all with
+ * the same timeout value.
+ *
+ * Since all our timeout handling code assumes timevals can be copied,
+ * assigned, etc, we can't use "magic pointer" to encode these common
+ * timeouts. Searching through a list to see if every timeout is common could
+ * also get inefficient. Instead, we take advantage of the fact that tv_usec
+ * is 32 bits long, but only uses 20 of those bits (since it can never be over
+ * 999999.) We use the top bits to encode 4 bites of magic number, and 8 bits
+ * of index into the event_base's aray of common timeouts.
+ */
+
+#define MICROSECONDS_MASK COMMON_TIMEOUT_MICROSECONDS_MASK
+#define COMMON_TIMEOUT_IDX_MASK 0x0ff00000
+#define COMMON_TIMEOUT_IDX_SHIFT 20
+#define COMMON_TIMEOUT_MASK 0xf0000000
+#define COMMON_TIMEOUT_MAGIC 0x50000000
+
+#define COMMON_TIMEOUT_IDX(tv) \
+ (((tv)->tv_usec & COMMON_TIMEOUT_IDX_MASK)>>COMMON_TIMEOUT_IDX_SHIFT)
+
+/** Return true iff if 'tv' is a common timeout in 'base' */
+static inline int
+is_common_timeout(const struct timeval *tv,
+ const struct event_base *base)
+{
+ int idx;
+ if ((tv->tv_usec & COMMON_TIMEOUT_MASK) != COMMON_TIMEOUT_MAGIC)
+ return 0;
+ idx = COMMON_TIMEOUT_IDX(tv);
+ return idx < base->n_common_timeouts;
+}
+
+/* True iff tv1 and tv2 have the same common-timeout index, or if neither
+ * one is a common timeout. */
+static inline int
+is_same_common_timeout(const struct timeval *tv1, const struct timeval *tv2)
+{
+ return (tv1->tv_usec & ~MICROSECONDS_MASK) ==
+ (tv2->tv_usec & ~MICROSECONDS_MASK);
+}
+
+/** Requires that 'tv' is a common timeout. Return the corresponding
+ * common_timeout_list. */
+static inline struct common_timeout_list *
+get_common_timeout_list(struct event_base *base, const struct timeval *tv)
+{
+ return base->common_timeout_queues[COMMON_TIMEOUT_IDX(tv)];
+}
+
+#if 0
+static inline int
+common_timeout_ok(const struct timeval *tv,
+ struct event_base *base)
+{
+ const struct timeval *expect =
+ &get_common_timeout_list(base, tv)->duration;
+ return tv->tv_sec == expect->tv_sec &&
+ tv->tv_usec == expect->tv_usec;
+}
+#endif
+
+/* Add the timeout for the first event in given common timeout list to the
+ * event_base's minheap. */
+static void
+common_timeout_schedule(struct common_timeout_list *ctl,
+ const struct timeval *now, struct event *head)
+{
+ struct timeval timeout = head->ev_timeout;
+ timeout.tv_usec &= MICROSECONDS_MASK;
+ event_add_nolock_(&ctl->timeout_event, &timeout, 1);
+}
+
+/* Callback: invoked when the timeout for a common timeout queue triggers.
+ * This means that (at least) the first event in that queue should be run,
+ * and the timeout should be rescheduled if there are more events. */
+static void
+common_timeout_callback(evutil_socket_t fd, short what, void *arg)
+{
+ struct timeval now;
+ struct common_timeout_list *ctl = arg;
+ struct event_base *base = ctl->base;
+ struct event *ev = NULL;
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ gettime(base, &now);
+ while (1) {
+ ev = TAILQ_FIRST(&ctl->events);
+ if (!ev || ev->ev_timeout.tv_sec > now.tv_sec ||
+ (ev->ev_timeout.tv_sec == now.tv_sec &&
+ (ev->ev_timeout.tv_usec&MICROSECONDS_MASK) > now.tv_usec))
+ break;
+ event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
+ event_active_nolock_(ev, EV_TIMEOUT, 1);
+ }
+ if (ev)
+ common_timeout_schedule(ctl, &now, ev);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+#define MAX_COMMON_TIMEOUTS 256
+
+const struct timeval *
+event_base_init_common_timeout(struct event_base *base,
+ const struct timeval *duration)
+{
+ int i;
+ struct timeval tv;
+ const struct timeval *result=NULL;
+ struct common_timeout_list *new_ctl;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (duration->tv_usec > 1000000) {
+ memcpy(&tv, duration, sizeof(struct timeval));
+ if (is_common_timeout(duration, base))
+ tv.tv_usec &= MICROSECONDS_MASK;
+ tv.tv_sec += tv.tv_usec / 1000000;
+ tv.tv_usec %= 1000000;
+ duration = &tv;
+ }
+ for (i = 0; i < base->n_common_timeouts; ++i) {
+ const struct common_timeout_list *ctl =
+ base->common_timeout_queues[i];
+ if (duration->tv_sec == ctl->duration.tv_sec &&
+ duration->tv_usec ==
+ (ctl->duration.tv_usec & MICROSECONDS_MASK)) {
+ EVUTIL_ASSERT(is_common_timeout(&ctl->duration, base));
+ result = &ctl->duration;
+ goto done;
+ }
+ }
+ if (base->n_common_timeouts == MAX_COMMON_TIMEOUTS) {
+ event_warnx("%s: Too many common timeouts already in use; "
+ "we only support %d per event_base", __func__,
+ MAX_COMMON_TIMEOUTS);
+ goto done;
+ }
+ if (base->n_common_timeouts_allocated == base->n_common_timeouts) {
+ int n = base->n_common_timeouts < 16 ? 16 :
+ base->n_common_timeouts*2;
+ struct common_timeout_list **newqueues =
+ mm_realloc(base->common_timeout_queues,
+ n*sizeof(struct common_timeout_queue *));
+ if (!newqueues) {
+ event_warn("%s: realloc",__func__);
+ goto done;
+ }
+ base->n_common_timeouts_allocated = n;
+ base->common_timeout_queues = newqueues;
+ }
+ new_ctl = mm_calloc(1, sizeof(struct common_timeout_list));
+ if (!new_ctl) {
+ event_warn("%s: calloc",__func__);
+ goto done;
+ }
+ TAILQ_INIT(&new_ctl->events);
+ new_ctl->duration.tv_sec = duration->tv_sec;
+ new_ctl->duration.tv_usec =
+ duration->tv_usec | COMMON_TIMEOUT_MAGIC |
+ (base->n_common_timeouts << COMMON_TIMEOUT_IDX_SHIFT);
+ evtimer_assign(&new_ctl->timeout_event, base,
+ common_timeout_callback, new_ctl);
+ new_ctl->timeout_event.ev_flags |= EVLIST_INTERNAL;
+ event_priority_set(&new_ctl->timeout_event, 0);
+ new_ctl->base = base;
+ base->common_timeout_queues[base->n_common_timeouts++] = new_ctl;
+ result = &new_ctl->duration;
+
+done:
+ if (result)
+ EVUTIL_ASSERT(is_common_timeout(result, base));
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return result;
+}
+
+/* Closure function invoked when we're activating a persistent event. */
+static inline void
+event_persist_closure(struct event_base *base, struct event *ev)
+{
+ void (*evcb_callback)(evutil_socket_t, short, void *);
+
+ // Other fields of *ev that must be stored before executing
+ evutil_socket_t evcb_fd;
+ short evcb_res;
+ void *evcb_arg;
+
+ /* reschedule the persistent event if we have a timeout. */
+ if (ev->ev_io_timeout.tv_sec || ev->ev_io_timeout.tv_usec) {
+ /* If there was a timeout, we want it to run at an interval of
+ * ev_io_timeout after the last time it was _scheduled_ for,
+ * not ev_io_timeout after _now_. If it fired for another
+ * reason, though, the timeout ought to start ticking _now_. */
+ struct timeval run_at, relative_to, delay, now;
+ ev_uint32_t usec_mask = 0;
+ EVUTIL_ASSERT(is_same_common_timeout(&ev->ev_timeout,
+ &ev->ev_io_timeout));
+ gettime(base, &now);
+ if (is_common_timeout(&ev->ev_timeout, base)) {
+ delay = ev->ev_io_timeout;
+ usec_mask = delay.tv_usec & ~MICROSECONDS_MASK;
+ delay.tv_usec &= MICROSECONDS_MASK;
+ if (ev->ev_res & EV_TIMEOUT) {
+ relative_to = ev->ev_timeout;
+ relative_to.tv_usec &= MICROSECONDS_MASK;
+ } else {
+ relative_to = now;
+ }
+ } else {
+ delay = ev->ev_io_timeout;
+ if (ev->ev_res & EV_TIMEOUT) {
+ relative_to = ev->ev_timeout;
+ } else {
+ relative_to = now;
+ }
+ }
+ evutil_timeradd(&relative_to, &delay, &run_at);
+ if (evutil_timercmp(&run_at, &now, <)) {
+ /* Looks like we missed at least one invocation due to
+ * a clock jump, not running the event loop for a
+ * while, really slow callbacks, or
+ * something. Reschedule relative to now.
+ */
+ evutil_timeradd(&now, &delay, &run_at);
+ }
+ run_at.tv_usec |= usec_mask;
+ event_add_nolock_(ev, &run_at, 1);
+ }
+
+ // Save our callback before we release the lock
+ evcb_callback = ev->ev_callback;
+ evcb_fd = ev->ev_fd;
+ evcb_res = ev->ev_res;
+ evcb_arg = ev->ev_arg;
+
+ // Release the lock
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ // Execute the callback
+ (evcb_callback)(evcb_fd, evcb_res, evcb_arg);
+}
+
+/*
+ Helper for event_process_active to process all the events in a single queue,
+ releasing the lock as we go. This function requires that the lock be held
+ when it's invoked. Returns -1 if we get a signal or an event_break that
+ means we should stop processing any active events now. Otherwise returns
+ the number of non-internal event_callbacks that we processed.
+*/
+static int
+event_process_active_single_queue(struct event_base *base,
+ struct evcallback_list *activeq,
+ int max_to_process, const struct timeval *endtime)
+{
+ struct event_callback *evcb;
+ int count = 0;
+
+ EVUTIL_ASSERT(activeq != NULL);
+
+ for (evcb = TAILQ_FIRST(activeq); evcb; evcb = TAILQ_FIRST(activeq)) {
+ struct event *ev=NULL;
+ if (evcb->evcb_flags & EVLIST_INIT) {
+ ev = event_callback_to_event(evcb);
+
+ if (ev->ev_events & EV_PERSIST || ev->ev_flags & EVLIST_FINALIZING)
+ event_queue_remove_active(base, evcb);
+ else
+ event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
+ event_debug((
+ "event_process_active: event: %p, %s%s%scall %p",
+ ev,
+ ev->ev_res & EV_READ ? "EV_READ " : " ",
+ ev->ev_res & EV_WRITE ? "EV_WRITE " : " ",
+ ev->ev_res & EV_CLOSED ? "EV_CLOSED " : " ",
+ ev->ev_callback));
+ } else {
+ event_queue_remove_active(base, evcb);
+ event_debug(("event_process_active: event_callback %p, "
+ "closure %d, call %p",
+ evcb, evcb->evcb_closure, evcb->evcb_cb_union.evcb_callback));
+ }
+
+ if (!(evcb->evcb_flags & EVLIST_INTERNAL))
+ ++count;
+
+
+ base->current_event = evcb;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ base->current_event_waiters = 0;
+#endif
+
+ switch (evcb->evcb_closure) {
+ case EV_CLOSURE_EVENT_SIGNAL:
+ EVUTIL_ASSERT(ev != NULL);
+ event_signal_closure(base, ev);
+ break;
+ case EV_CLOSURE_EVENT_PERSIST:
+ EVUTIL_ASSERT(ev != NULL);
+ event_persist_closure(base, ev);
+ break;
+ case EV_CLOSURE_EVENT: {
+ void (*evcb_callback)(evutil_socket_t, short, void *);
+ short res;
+ EVUTIL_ASSERT(ev != NULL);
+ evcb_callback = *ev->ev_callback;
+ res = ev->ev_res;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ evcb_callback(ev->ev_fd, res, ev->ev_arg);
+ }
+ break;
+ case EV_CLOSURE_CB_SELF: {
+ void (*evcb_selfcb)(struct event_callback *, void *) = evcb->evcb_cb_union.evcb_selfcb;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ evcb_selfcb(evcb, evcb->evcb_arg);
+ }
+ break;
+ case EV_CLOSURE_EVENT_FINALIZE:
+ case EV_CLOSURE_EVENT_FINALIZE_FREE: {
+ void (*evcb_evfinalize)(struct event *, void *);
+ int evcb_closure = evcb->evcb_closure;
+ EVUTIL_ASSERT(ev != NULL);
+ base->current_event = NULL;
+ evcb_evfinalize = ev->ev_evcallback.evcb_cb_union.evcb_evfinalize;
+ EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_FINALIZING));
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ event_debug_note_teardown_(ev);
+ evcb_evfinalize(ev, ev->ev_arg);
+ if (evcb_closure == EV_CLOSURE_EVENT_FINALIZE_FREE)
+ mm_free(ev);
+ }
+ break;
+ case EV_CLOSURE_CB_FINALIZE: {
+ void (*evcb_cbfinalize)(struct event_callback *, void *) = evcb->evcb_cb_union.evcb_cbfinalize;
+ base->current_event = NULL;
+ EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_FINALIZING));
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ evcb_cbfinalize(evcb, evcb->evcb_arg);
+ }
+ break;
+ default:
+ EVUTIL_ASSERT(0);
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ base->current_event = NULL;
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (base->current_event_waiters) {
+ base->current_event_waiters = 0;
+ EVTHREAD_COND_BROADCAST(base->current_event_cond);
+ }
+#endif
+
+ if (base->event_break)
+ return -1;
+ if (count >= max_to_process)
+ return count;
+ if (count && endtime) {
+ struct timeval now;
+ update_time_cache(base);
+ gettime(base, &now);
+ if (evutil_timercmp(&now, endtime, >=))
+ return count;
+ }
+ if (base->event_continue)
+ break;
+ }
+ return count;
+}
+
+/*
+ * Active events are stored in priority queues. Lower priorities are always
+ * process before higher priorities. Low priority events can starve high
+ * priority ones.
+ */
+
+static int
+event_process_active(struct event_base *base)
+{
+ /* Caller must hold th_base_lock */
+ struct evcallback_list *activeq = NULL;
+ int i, c = 0;
+ const struct timeval *endtime;
+ struct timeval tv;
+ const int maxcb = base->max_dispatch_callbacks;
+ const int limit_after_prio = base->limit_callbacks_after_prio;
+ if (base->max_dispatch_time.tv_sec >= 0) {
+ update_time_cache(base);
+ gettime(base, &tv);
+ evutil_timeradd(&base->max_dispatch_time, &tv, &tv);
+ endtime = &tv;
+ } else {
+ endtime = NULL;
+ }
+
+ for (i = 0; i < base->nactivequeues; ++i) {
+ if (TAILQ_FIRST(&base->activequeues[i]) != NULL) {
+ base->event_running_priority = i;
+ activeq = &base->activequeues[i];
+ if (i < limit_after_prio)
+ c = event_process_active_single_queue(base, activeq,
+ INT_MAX, NULL);
+ else
+ c = event_process_active_single_queue(base, activeq,
+ maxcb, endtime);
+ if (c < 0) {
+ goto done;
+ } else if (c > 0)
+ break; /* Processed a real event; do not
+ * consider lower-priority events */
+ /* If we get here, all of the events we processed
+ * were internal. Continue. */
+ }
+ }
+
+done:
+ base->event_running_priority = -1;
+
+ return c;
+}
+
+/*
+ * Wait continuously for events. We exit only if no events are left.
+ */
+
+int
+event_dispatch(void)
+{
+ return (event_loop(0));
+}
+
+int
+event_base_dispatch(struct event_base *event_base)
+{
+ return (event_base_loop(event_base, 0));
+}
+
+const char *
+event_base_get_method(const struct event_base *base)
+{
+ EVUTIL_ASSERT(base);
+ return (base->evsel->name);
+}
+
+/** Callback: used to implement event_base_loopexit by telling the event_base
+ * that it's time to exit its loop. */
+static void
+event_loopexit_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct event_base *base = arg;
+ base->event_gotterm = 1;
+}
+
+int
+event_loopexit(const struct timeval *tv)
+{
+ return (event_once(-1, EV_TIMEOUT, event_loopexit_cb,
+ current_base, tv));
+}
+
+int
+event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
+{
+ return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
+ event_base, tv));
+}
+
+int
+event_loopbreak(void)
+{
+ return (event_base_loopbreak(current_base));
+}
+
+int
+event_base_loopbreak(struct event_base *event_base)
+{
+ int r = 0;
+ if (event_base == NULL)
+ return (-1);
+
+ EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+ event_base->event_break = 1;
+
+ if (EVBASE_NEED_NOTIFY(event_base)) {
+ r = evthread_notify_base(event_base);
+ } else {
+ r = (0);
+ }
+ EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+ return r;
+}
+
+int
+event_base_loopcontinue(struct event_base *event_base)
+{
+ int r = 0;
+ if (event_base == NULL)
+ return (-1);
+
+ EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+ event_base->event_continue = 1;
+
+ if (EVBASE_NEED_NOTIFY(event_base)) {
+ r = evthread_notify_base(event_base);
+ } else {
+ r = (0);
+ }
+ EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+ return r;
+}
+
+int
+event_base_got_break(struct event_base *event_base)
+{
+ int res;
+ EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+ res = event_base->event_break;
+ EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+ return res;
+}
+
+int
+event_base_got_exit(struct event_base *event_base)
+{
+ int res;
+ EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
+ res = event_base->event_gotterm;
+ EVBASE_RELEASE_LOCK(event_base, th_base_lock);
+ return res;
+}
+
+/* not thread safe */
+
+int
+event_loop(int flags)
+{
+ return event_base_loop(current_base, flags);
+}
+
+int
+event_base_loop(struct event_base *base, int flags)
+{
+ const struct eventop *evsel = base->evsel;
+ struct timeval tv;
+ struct timeval *tv_p;
+ int res, done, retval = 0;
+
+ /* Grab the lock. We will release it inside evsel.dispatch, and again
+ * as we invoke user callbacks. */
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (base->running_loop) {
+ event_warnx("%s: reentrant invocation. Only one event_base_loop"
+ " can run on each event_base at once.", __func__);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return -1;
+ }
+
+ base->running_loop = 1;
+
+ clear_time_cache(base);
+
+ if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)
+ evsig_set_base_(base);
+
+ done = 0;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ base->th_owner_id = EVTHREAD_GET_ID();
+#endif
+
+ base->event_gotterm = base->event_break = 0;
+
+ while (!done) {
+ base->event_continue = 0;
+ base->n_deferreds_queued = 0;
+
+ /* Terminate the loop if we have been asked to */
+ if (base->event_gotterm) {
+ break;
+ }
+
+ if (base->event_break) {
+ break;
+ }
+
+ tv_p = &tv;
+ if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {
+ timeout_next(base, &tv_p);
+ } else {
+ /*
+ * if we have active events, we just poll new events
+ * without waiting.
+ */
+ evutil_timerclear(&tv);
+ }
+
+ /* If we have no events, we just exit */
+ if (0==(flags&EVLOOP_NO_EXIT_ON_EMPTY) &&
+ !event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
+ event_debug(("%s: no events registered.", __func__));
+ retval = 1;
+ goto done;
+ }
+
+ event_queue_make_later_events_active(base);
+
+ clear_time_cache(base);
+
+ res = evsel->dispatch(base, tv_p);
+
+ if (res == -1) {
+ event_debug(("%s: dispatch returned unsuccessfully.",
+ __func__));
+ retval = -1;
+ goto done;
+ }
+
+ update_time_cache(base);
+
+ timeout_process(base);
+
+ if (N_ACTIVE_CALLBACKS(base)) {
+ int n = event_process_active(base);
+ if ((flags & EVLOOP_ONCE)
+ && N_ACTIVE_CALLBACKS(base) == 0
+ && n != 0)
+ done = 1;
+ } else if (flags & EVLOOP_NONBLOCK)
+ done = 1;
+ }
+ event_debug(("%s: asked to terminate loop.", __func__));
+
+done:
+ clear_time_cache(base);
+ base->running_loop = 0;
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ return (retval);
+}
+
+/* One-time callback to implement event_base_once: invokes the user callback,
+ * then deletes the allocated storage */
+static void
+event_once_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct event_once *eonce = arg;
+
+ (*eonce->cb)(fd, events, eonce->arg);
+ EVBASE_ACQUIRE_LOCK(eonce->ev.ev_base, th_base_lock);
+ LIST_REMOVE(eonce, next_once);
+ EVBASE_RELEASE_LOCK(eonce->ev.ev_base, th_base_lock);
+ event_debug_unassign(&eonce->ev);
+ mm_free(eonce);
+}
+
+/* not threadsafe, event scheduled once. */
+int
+event_once(evutil_socket_t fd, short events,
+ void (*callback)(evutil_socket_t, short, void *),
+ void *arg, const struct timeval *tv)
+{
+ return event_base_once(current_base, fd, events, callback, arg, tv);
+}
+
+/* Schedules an event once */
+int
+event_base_once(struct event_base *base, evutil_socket_t fd, short events,
+ void (*callback)(evutil_socket_t, short, void *),
+ void *arg, const struct timeval *tv)
+{
+ struct event_once *eonce;
+ int res = 0;
+ int activate = 0;
+
+ if (!base)
+ return (-1);
+
+ /* We cannot support signals that just fire once, or persistent
+ * events. */
+ if (events & (EV_SIGNAL|EV_PERSIST))
+ return (-1);
+
+ if ((eonce = mm_calloc(1, sizeof(struct event_once))) == NULL)
+ return (-1);
+
+ eonce->cb = callback;
+ eonce->arg = arg;
+
+ if ((events & (EV_TIMEOUT|EV_SIGNAL|EV_READ|EV_WRITE|EV_CLOSED)) == EV_TIMEOUT) {
+ evtimer_assign(&eonce->ev, base, event_once_cb, eonce);
+
+ if (tv == NULL || ! evutil_timerisset(tv)) {
+ /* If the event is going to become active immediately,
+ * don't put it on the timeout queue. This is one
+ * idiom for scheduling a callback, so let's make
+ * it fast (and order-preserving). */
+ activate = 1;
+ }
+ } else if (events & (EV_READ|EV_WRITE|EV_CLOSED)) {
+ events &= EV_READ|EV_WRITE|EV_CLOSED;
+
+ event_assign(&eonce->ev, base, fd, events, event_once_cb, eonce);
+ } else {
+ /* Bad event combination */
+ mm_free(eonce);
+ return (-1);
+ }
+
+ if (res == 0) {
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (activate)
+ event_active_nolock_(&eonce->ev, EV_TIMEOUT, 1);
+ else
+ res = event_add_nolock_(&eonce->ev, tv, 0);
+
+ if (res != 0) {
+ mm_free(eonce);
+ return (res);
+ } else {
+ LIST_INSERT_HEAD(&base->once_events, eonce, next_once);
+ }
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ }
+
+ return (0);
+}
+
+int
+event_assign(struct event *ev, struct event_base *base, evutil_socket_t fd, short events, void (*callback)(evutil_socket_t, short, void *), void *arg)
+{
+ if (!base)
+ base = current_base;
+ if (arg == &event_self_cbarg_ptr_)
+ arg = ev;
+
+ if (!(events & EV_SIGNAL))
+ event_debug_assert_socket_nonblocking_(fd);
+ event_debug_assert_not_added_(ev);
+
+ ev->ev_base = base;
+
+ ev->ev_callback = callback;
+ ev->ev_arg = arg;
+ ev->ev_fd = fd;
+ ev->ev_events = events;
+ ev->ev_res = 0;
+ ev->ev_flags = EVLIST_INIT;
+ ev->ev_ncalls = 0;
+ ev->ev_pncalls = NULL;
+
+ if (events & EV_SIGNAL) {
+ if ((events & (EV_READ|EV_WRITE|EV_CLOSED)) != 0) {
+ event_warnx("%s: EV_SIGNAL is not compatible with "
+ "EV_READ, EV_WRITE or EV_CLOSED", __func__);
+ return -1;
+ }
+ ev->ev_closure = EV_CLOSURE_EVENT_SIGNAL;
+ } else {
+ if (events & EV_PERSIST) {
+ evutil_timerclear(&ev->ev_io_timeout);
+ ev->ev_closure = EV_CLOSURE_EVENT_PERSIST;
+ } else {
+ ev->ev_closure = EV_CLOSURE_EVENT;
+ }
+ }
+
+ min_heap_elem_init_(ev);
+
+ if (base != NULL) {
+ /* by default, we put new events into the middle priority */
+ ev->ev_pri = base->nactivequeues / 2;
+ }
+
+ event_debug_note_setup_(ev);
+
+ return 0;
+}
+
+int
+event_base_set(struct event_base *base, struct event *ev)
+{
+ /* Only innocent events may be assigned to a different base */
+ if (ev->ev_flags != EVLIST_INIT)
+ return (-1);
+
+ event_debug_assert_is_setup_(ev);
+
+ ev->ev_base = base;
+ ev->ev_pri = base->nactivequeues/2;
+
+ return (0);
+}
+
+void
+event_set(struct event *ev, evutil_socket_t fd, short events,
+ void (*callback)(evutil_socket_t, short, void *), void *arg)
+{
+ int r;
+ r = event_assign(ev, current_base, fd, events, callback, arg);
+ EVUTIL_ASSERT(r == 0);
+}
+
+void *
+event_self_cbarg(void)
+{
+ return &event_self_cbarg_ptr_;
+}
+
+struct event *
+event_base_get_running_event(struct event_base *base)
+{
+ struct event *ev = NULL;
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (EVBASE_IN_THREAD(base)) {
+ struct event_callback *evcb = base->current_event;
+ if (evcb->evcb_flags & EVLIST_INIT)
+ ev = event_callback_to_event(evcb);
+ }
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return ev;
+}
+
+struct event *
+event_new(struct event_base *base, evutil_socket_t fd, short events, void (*cb)(evutil_socket_t, short, void *), void *arg)
+{
+ struct event *ev;
+ ev = mm_malloc(sizeof(struct event));
+ if (ev == NULL)
+ return (NULL);
+ if (event_assign(ev, base, fd, events, cb, arg) < 0) {
+ mm_free(ev);
+ return (NULL);
+ }
+
+ return (ev);
+}
+
+void
+event_free(struct event *ev)
+{
+ /* This is disabled, so that events which have been finalized be a
+ * valid target for event_free(). That's */
+ // event_debug_assert_is_setup_(ev);
+
+ /* make sure that this event won't be coming back to haunt us. */
+ event_del(ev);
+ event_debug_note_teardown_(ev);
+ mm_free(ev);
+
+}
+
+void
+event_debug_unassign(struct event *ev)
+{
+ event_debug_assert_not_added_(ev);
+ event_debug_note_teardown_(ev);
+
+ ev->ev_flags &= ~EVLIST_INIT;
+}
+
+#define EVENT_FINALIZE_FREE_ 0x10000
+static int
+event_finalize_nolock_(struct event_base *base, unsigned flags, struct event *ev, event_finalize_callback_fn cb)
+{
+ ev_uint8_t closure = (flags & EVENT_FINALIZE_FREE_) ?
+ EV_CLOSURE_EVENT_FINALIZE_FREE : EV_CLOSURE_EVENT_FINALIZE;
+
+ event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
+ ev->ev_closure = closure;
+ ev->ev_evcallback.evcb_cb_union.evcb_evfinalize = cb;
+ event_active_nolock_(ev, EV_FINALIZE, 1);
+ ev->ev_flags |= EVLIST_FINALIZING;
+ return 0;
+}
+
+static int
+event_finalize_impl_(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
+{
+ int r;
+ struct event_base *base = ev->ev_base;
+ if (EVUTIL_FAILURE_CHECK(!base)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return -1;
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ r = event_finalize_nolock_(base, flags, ev, cb);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+int
+event_finalize(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
+{
+ return event_finalize_impl_(flags, ev, cb);
+}
+
+int
+event_free_finalize(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
+{
+ return event_finalize_impl_(flags|EVENT_FINALIZE_FREE_, ev, cb);
+}
+
+void
+event_callback_finalize_nolock_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *))
+{
+ struct event *ev = NULL;
+ if (evcb->evcb_flags & EVLIST_INIT) {
+ ev = event_callback_to_event(evcb);
+ event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
+ } else {
+ event_callback_cancel_nolock_(base, evcb, 0); /*XXX can this fail?*/
+ }
+
+ evcb->evcb_closure = EV_CLOSURE_CB_FINALIZE;
+ evcb->evcb_cb_union.evcb_cbfinalize = cb;
+ event_callback_activate_nolock_(base, evcb); /* XXX can this really fail?*/
+ evcb->evcb_flags |= EVLIST_FINALIZING;
+}
+
+void
+event_callback_finalize_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *))
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ event_callback_finalize_nolock_(base, flags, evcb, cb);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+/** Internal: Finalize all of the n_cbs callbacks in evcbs. The provided
+ * callback will be invoked on *one of them*, after they have *all* been
+ * finalized. */
+int
+event_callback_finalize_many_(struct event_base *base, int n_cbs, struct event_callback **evcbs, void (*cb)(struct event_callback *, void *))
+{
+ int n_pending = 0, i;
+
+ if (base == NULL)
+ base = current_base;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ event_debug(("%s: %d events finalizing", __func__, n_cbs));
+
+ /* At most one can be currently executing; the rest we just
+ * cancel... But we always make sure that the finalize callback
+ * runs. */
+ for (i = 0; i < n_cbs; ++i) {
+ struct event_callback *evcb = evcbs[i];
+ if (evcb == base->current_event) {
+ event_callback_finalize_nolock_(base, 0, evcb, cb);
+ ++n_pending;
+ } else {
+ event_callback_cancel_nolock_(base, evcb, 0);
+ }
+ }
+
+ if (n_pending == 0) {
+ /* Just do the first one. */
+ event_callback_finalize_nolock_(base, 0, evcbs[0], cb);
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return 0;
+}
+
+/*
+ * Set's the priority of an event - if an event is already scheduled
+ * changing the priority is going to fail.
+ */
+
+int
+event_priority_set(struct event *ev, int pri)
+{
+ event_debug_assert_is_setup_(ev);
+
+ if (ev->ev_flags & EVLIST_ACTIVE)
+ return (-1);
+ if (pri < 0 || pri >= ev->ev_base->nactivequeues)
+ return (-1);
+
+ ev->ev_pri = pri;
+
+ return (0);
+}
+
+/*
+ * Checks if a specific event is pending or scheduled.
+ */
+
+int
+event_pending(const struct event *ev, short event, struct timeval *tv)
+{
+ int flags = 0;
+
+ if (EVUTIL_FAILURE_CHECK(ev->ev_base == NULL)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return 0;
+ }
+
+ EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+ event_debug_assert_is_setup_(ev);
+
+ if (ev->ev_flags & EVLIST_INSERTED)
+ flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL));
+ if (ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))
+ flags |= ev->ev_res;
+ if (ev->ev_flags & EVLIST_TIMEOUT)
+ flags |= EV_TIMEOUT;
+
+ event &= (EV_TIMEOUT|EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL);
+
+ /* See if there is a timeout that we should report */
+ if (tv != NULL && (flags & event & EV_TIMEOUT)) {
+ struct timeval tmp = ev->ev_timeout;
+ tmp.tv_usec &= MICROSECONDS_MASK;
+ /* correctly remamp to real time */
+ evutil_timeradd(&ev->ev_base->tv_clock_diff, &tmp, tv);
+ }
+
+ EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+
+ return (flags & event);
+}
+
+int
+event_initialized(const struct event *ev)
+{
+ if (!(ev->ev_flags & EVLIST_INIT))
+ return 0;
+
+ return 1;
+}
+
+void
+event_get_assignment(const struct event *event, struct event_base **base_out, evutil_socket_t *fd_out, short *events_out, event_callback_fn *callback_out, void **arg_out)
+{
+ event_debug_assert_is_setup_(event);
+
+ if (base_out)
+ *base_out = event->ev_base;
+ if (fd_out)
+ *fd_out = event->ev_fd;
+ if (events_out)
+ *events_out = event->ev_events;
+ if (callback_out)
+ *callback_out = event->ev_callback;
+ if (arg_out)
+ *arg_out = event->ev_arg;
+}
+
+size_t
+event_get_struct_event_size(void)
+{
+ return sizeof(struct event);
+}
+
+evutil_socket_t
+event_get_fd(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_fd;
+}
+
+struct event_base *
+event_get_base(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_base;
+}
+
+short
+event_get_events(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_events;
+}
+
+event_callback_fn
+event_get_callback(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_callback;
+}
+
+void *
+event_get_callback_arg(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_arg;
+}
+
+int
+event_get_priority(const struct event *ev)
+{
+ event_debug_assert_is_setup_(ev);
+ return ev->ev_pri;
+}
+
+int
+event_add(struct event *ev, const struct timeval *tv)
+{
+ int res;
+
+ if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return -1;
+ }
+
+ EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+ res = event_add_nolock_(ev, tv, 0);
+
+ EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+
+ return (res);
+}
+
+/* Helper callback: wake an event_base from another thread. This version
+ * works by writing a byte to one end of a socketpair, so that the event_base
+ * listening on the other end will wake up as the corresponding event
+ * triggers */
+static int
+evthread_notify_base_default(struct event_base *base)
+{
+ char buf[1];
+ int r;
+ buf[0] = (char) 0;
+#ifdef _WIN32
+ r = send(base->th_notify_fd[1], buf, 1, 0);
+#else
+ r = write(base->th_notify_fd[1], buf, 1);
+#endif
+ return (r < 0 && ! EVUTIL_ERR_IS_EAGAIN(errno)) ? -1 : 0;
+}
+
+#ifdef EVENT__HAVE_EVENTFD
+/* Helper callback: wake an event_base from another thread. This version
+ * assumes that you have a working eventfd() implementation. */
+static int
+evthread_notify_base_eventfd(struct event_base *base)
+{
+ ev_uint64_t msg = 1;
+ int r;
+ do {
+ r = write(base->th_notify_fd[0], (void*) &msg, sizeof(msg));
+ } while (r < 0 && errno == EAGAIN);
+
+ return (r < 0) ? -1 : 0;
+}
+#endif
+
+
+/** Tell the thread currently running the event_loop for base (if any) that it
+ * needs to stop waiting in its dispatch function (if it is) and process all
+ * active callbacks. */
+static int
+evthread_notify_base(struct event_base *base)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (!base->th_notify_fn)
+ return -1;
+ if (base->is_notify_pending)
+ return 0;
+ base->is_notify_pending = 1;
+ return base->th_notify_fn(base);
+}
+
+/* Implementation function to remove a timeout on a currently pending event.
+ */
+int
+event_remove_timer_nolock_(struct event *ev)
+{
+ struct event_base *base = ev->ev_base;
+
+ EVENT_BASE_ASSERT_LOCKED(base);
+ event_debug_assert_is_setup_(ev);
+
+ event_debug(("event_remove_timer_nolock: event: %p", ev));
+
+ /* If it's not pending on a timeout, we don't need to do anything. */
+ if (ev->ev_flags & EVLIST_TIMEOUT) {
+ event_queue_remove_timeout(base, ev);
+ evutil_timerclear(&ev->ev_.ev_io.ev_timeout);
+ }
+
+ return (0);
+}
+
+int
+event_remove_timer(struct event *ev)
+{
+ int res;
+
+ if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return -1;
+ }
+
+ EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+ res = event_remove_timer_nolock_(ev);
+
+ EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+
+ return (res);
+}
+
+/* Implementation function to add an event. Works just like event_add,
+ * except: 1) it requires that we have the lock. 2) if tv_is_absolute is set,
+ * we treat tv as an absolute time, not as an interval to add to the current
+ * time */
+int
+event_add_nolock_(struct event *ev, const struct timeval *tv,
+ int tv_is_absolute)
+{
+ struct event_base *base = ev->ev_base;
+ int res = 0;
+ int notify = 0;
+
+ EVENT_BASE_ASSERT_LOCKED(base);
+ event_debug_assert_is_setup_(ev);
+
+ event_debug((
+ "event_add: event: %p (fd "EV_SOCK_FMT"), %s%s%s%scall %p",
+ ev,
+ EV_SOCK_ARG(ev->ev_fd),
+ ev->ev_events & EV_READ ? "EV_READ " : " ",
+ ev->ev_events & EV_WRITE ? "EV_WRITE " : " ",
+ ev->ev_events & EV_CLOSED ? "EV_CLOSED " : " ",
+ tv ? "EV_TIMEOUT " : " ",
+ ev->ev_callback));
+
+ EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
+
+ if (ev->ev_flags & EVLIST_FINALIZING) {
+ /* XXXX debug */
+ return (-1);
+ }
+
+ /*
+ * prepare for timeout insertion further below, if we get a
+ * failure on any step, we should not change any state.
+ */
+ if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
+ if (min_heap_reserve_(&base->timeheap,
+ 1 + min_heap_size_(&base->timeheap)) == -1)
+ return (-1); /* ENOMEM == errno */
+ }
+
+ /* If the main thread is currently executing a signal event's
+ * callback, and we are not the main thread, then we want to wait
+ * until the callback is done before we mess with the event, or else
+ * we can race on ev_ncalls and ev_pncalls below. */
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (base->current_event == event_to_event_callback(ev) &&
+ (ev->ev_events & EV_SIGNAL)
+ && !EVBASE_IN_THREAD(base)) {
+ ++base->current_event_waiters;
+ EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+ }
+#endif
+
+ if ((ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL)) &&
+ !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
+ if (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED))
+ res = evmap_io_add_(base, ev->ev_fd, ev);
+ else if (ev->ev_events & EV_SIGNAL)
+ res = evmap_signal_add_(base, (int)ev->ev_fd, ev);
+ if (res != -1)
+ event_queue_insert_inserted(base, ev);
+ if (res == 1) {
+ /* evmap says we need to notify the main thread. */
+ notify = 1;
+ res = 0;
+ }
+ }
+
+ /*
+ * we should change the timeout state only if the previous event
+ * addition succeeded.
+ */
+ if (res != -1 && tv != NULL) {
+ struct timeval now;
+ int common_timeout;
+#ifdef USE_REINSERT_TIMEOUT
+ int was_common;
+ int old_timeout_idx;
+#endif
+
+ /*
+ * for persistent timeout events, we remember the
+ * timeout value and re-add the event.
+ *
+ * If tv_is_absolute, this was already set.
+ */
+ if (ev->ev_closure == EV_CLOSURE_EVENT_PERSIST && !tv_is_absolute)
+ ev->ev_io_timeout = *tv;
+
+#ifndef USE_REINSERT_TIMEOUT
+ if (ev->ev_flags & EVLIST_TIMEOUT) {
+ event_queue_remove_timeout(base, ev);
+ }
+#endif
+
+ /* Check if it is active due to a timeout. Rescheduling
+ * this timeout before the callback can be executed
+ * removes it from the active list. */
+ if ((ev->ev_flags & EVLIST_ACTIVE) &&
+ (ev->ev_res & EV_TIMEOUT)) {
+ if (ev->ev_events & EV_SIGNAL) {
+ /* See if we are just active executing
+ * this event in a loop
+ */
+ if (ev->ev_ncalls && ev->ev_pncalls) {
+ /* Abort loop */
+ *ev->ev_pncalls = 0;
+ }
+ }
+
+ event_queue_remove_active(base, event_to_event_callback(ev));
+ }
+
+ gettime(base, &now);
+
+ common_timeout = is_common_timeout(tv, base);
+#ifdef USE_REINSERT_TIMEOUT
+ was_common = is_common_timeout(&ev->ev_timeout, base);
+ old_timeout_idx = COMMON_TIMEOUT_IDX(&ev->ev_timeout);
+#endif
+
+ if (tv_is_absolute) {
+ ev->ev_timeout = *tv;
+ } else if (common_timeout) {
+ struct timeval tmp = *tv;
+ tmp.tv_usec &= MICROSECONDS_MASK;
+ evutil_timeradd(&now, &tmp, &ev->ev_timeout);
+ ev->ev_timeout.tv_usec |=
+ (tv->tv_usec & ~MICROSECONDS_MASK);
+ } else {
+ evutil_timeradd(&now, tv, &ev->ev_timeout);
+ }
+
+ event_debug((
+ "event_add: event %p, timeout in %d seconds %d useconds, call %p",
+ ev, (int)tv->tv_sec, (int)tv->tv_usec, ev->ev_callback));
+
+#ifdef USE_REINSERT_TIMEOUT
+ event_queue_reinsert_timeout(base, ev, was_common, common_timeout, old_timeout_idx);
+#else
+ event_queue_insert_timeout(base, ev);
+#endif
+
+ if (common_timeout) {
+ struct common_timeout_list *ctl =
+ get_common_timeout_list(base, &ev->ev_timeout);
+ if (ev == TAILQ_FIRST(&ctl->events)) {
+ common_timeout_schedule(ctl, &now, ev);
+ }
+ } else {
+ struct event* top = NULL;
+ /* See if the earliest timeout is now earlier than it
+ * was before: if so, we will need to tell the main
+ * thread to wake up earlier than it would otherwise.
+ * We double check the timeout of the top element to
+ * handle time distortions due to system suspension.
+ */
+ if (min_heap_elt_is_top_(ev))
+ notify = 1;
+ else if ((top = min_heap_top_(&base->timeheap)) != NULL &&
+ evutil_timercmp(&top->ev_timeout, &now, <))
+ notify = 1;
+ }
+ }
+
+ /* if we are not in the right thread, we need to wake up the loop */
+ if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
+ evthread_notify_base(base);
+
+ event_debug_note_add_(ev);
+
+ return (res);
+}
+
+static int
+event_del_(struct event *ev, int blocking)
+{
+ int res;
+ struct event_base *base = ev->ev_base;
+
+ if (EVUTIL_FAILURE_CHECK(!base)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return -1;
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ res = event_del_nolock_(ev, blocking);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ return (res);
+}
+
+int
+event_del(struct event *ev)
+{
+ return event_del_(ev, EVENT_DEL_AUTOBLOCK);
+}
+
+int
+event_del_block(struct event *ev)
+{
+ return event_del_(ev, EVENT_DEL_BLOCK);
+}
+
+int
+event_del_noblock(struct event *ev)
+{
+ return event_del_(ev, EVENT_DEL_NOBLOCK);
+}
+
+/** Helper for event_del: always called with th_base_lock held.
+ *
+ * "blocking" must be one of the EVENT_DEL_{BLOCK, NOBLOCK, AUTOBLOCK,
+ * EVEN_IF_FINALIZING} values. See those for more information.
+ */
+int
+event_del_nolock_(struct event *ev, int blocking)
+{
+ struct event_base *base;
+ int res = 0, notify = 0;
+
+ event_debug(("event_del: %p (fd "EV_SOCK_FMT"), callback %p",
+ ev, EV_SOCK_ARG(ev->ev_fd), ev->ev_callback));
+
+ /* An event without a base has not been added */
+ if (ev->ev_base == NULL)
+ return (-1);
+
+ EVENT_BASE_ASSERT_LOCKED(ev->ev_base);
+
+ if (blocking != EVENT_DEL_EVEN_IF_FINALIZING) {
+ if (ev->ev_flags & EVLIST_FINALIZING) {
+ /* XXXX Debug */
+ return 0;
+ }
+ }
+
+ base = ev->ev_base;
+
+ EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
+
+ /* See if we are just active executing this event in a loop */
+ if (ev->ev_events & EV_SIGNAL) {
+ if (ev->ev_ncalls && ev->ev_pncalls) {
+ /* Abort loop */
+ *ev->ev_pncalls = 0;
+ }
+ }
+
+ if (ev->ev_flags & EVLIST_TIMEOUT) {
+ /* NOTE: We never need to notify the main thread because of a
+ * deleted timeout event: all that could happen if we don't is
+ * that the dispatch loop might wake up too early. But the
+ * point of notifying the main thread _is_ to wake up the
+ * dispatch loop early anyway, so we wouldn't gain anything by
+ * doing it.
+ */
+ event_queue_remove_timeout(base, ev);
+ }
+
+ if (ev->ev_flags & EVLIST_ACTIVE)
+ event_queue_remove_active(base, event_to_event_callback(ev));
+ else if (ev->ev_flags & EVLIST_ACTIVE_LATER)
+ event_queue_remove_active_later(base, event_to_event_callback(ev));
+
+ if (ev->ev_flags & EVLIST_INSERTED) {
+ event_queue_remove_inserted(base, ev);
+ if (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED))
+ res = evmap_io_del_(base, ev->ev_fd, ev);
+ else
+ res = evmap_signal_del_(base, (int)ev->ev_fd, ev);
+ if (res == 1) {
+ /* evmap says we need to notify the main thread. */
+ notify = 1;
+ res = 0;
+ }
+ /* If we do not have events, let's notify event base so it can
+ * exit without waiting */
+ if (!event_haveevents(base) && !N_ACTIVE_CALLBACKS(base))
+ notify = 1;
+ }
+
+ /* if we are not in the right thread, we need to wake up the loop */
+ if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
+ evthread_notify_base(base);
+
+ event_debug_note_del_(ev);
+
+ /* If the main thread is currently executing this event's callback,
+ * and we are not the main thread, then we want to wait until the
+ * callback is done before returning. That way, when this function
+ * returns, it will be safe to free the user-supplied argument.
+ */
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (blocking != EVENT_DEL_NOBLOCK &&
+ base->current_event == event_to_event_callback(ev) &&
+ !EVBASE_IN_THREAD(base) &&
+ (blocking == EVENT_DEL_BLOCK || !(ev->ev_events & EV_FINALIZE))) {
+ ++base->current_event_waiters;
+ EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+ }
+#endif
+
+ return (res);
+}
+
+void
+event_active(struct event *ev, int res, short ncalls)
+{
+ if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
+ event_warnx("%s: event has no event_base set.", __func__);
+ return;
+ }
+
+ EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+
+ event_debug_assert_is_setup_(ev);
+
+ event_active_nolock_(ev, res, ncalls);
+
+ EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+}
+
+
+void
+event_active_nolock_(struct event *ev, int res, short ncalls)
+{
+ struct event_base *base;
+
+ event_debug(("event_active: %p (fd "EV_SOCK_FMT"), res %d, callback %p",
+ ev, EV_SOCK_ARG(ev->ev_fd), (int)res, ev->ev_callback));
+
+ base = ev->ev_base;
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (ev->ev_flags & EVLIST_FINALIZING) {
+ /* XXXX debug */
+ return;
+ }
+
+ switch ((ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
+ default:
+ case EVLIST_ACTIVE|EVLIST_ACTIVE_LATER:
+ EVUTIL_ASSERT(0);
+ break;
+ case EVLIST_ACTIVE:
+ /* We get different kinds of events, add them together */
+ ev->ev_res |= res;
+ return;
+ case EVLIST_ACTIVE_LATER:
+ ev->ev_res |= res;
+ break;
+ case 0:
+ ev->ev_res = res;
+ break;
+ }
+
+ if (ev->ev_pri < base->event_running_priority)
+ base->event_continue = 1;
+
+ if (ev->ev_events & EV_SIGNAL) {
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (base->current_event == event_to_event_callback(ev) &&
+ !EVBASE_IN_THREAD(base)) {
+ ++base->current_event_waiters;
+ EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
+ }
+#endif
+ ev->ev_ncalls = ncalls;
+ ev->ev_pncalls = NULL;
+ }
+
+ event_callback_activate_nolock_(base, event_to_event_callback(ev));
+}
+
+void
+event_active_later_(struct event *ev, int res)
+{
+ EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
+ event_active_later_nolock_(ev, res);
+ EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
+}
+
+void
+event_active_later_nolock_(struct event *ev, int res)
+{
+ struct event_base *base = ev->ev_base;
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) {
+ /* We get different kinds of events, add them together */
+ ev->ev_res |= res;
+ return;
+ }
+
+ ev->ev_res = res;
+
+ event_callback_activate_later_nolock_(base, event_to_event_callback(ev));
+}
+
+int
+event_callback_activate_(struct event_base *base,
+ struct event_callback *evcb)
+{
+ int r;
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ r = event_callback_activate_nolock_(base, evcb);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+int
+event_callback_activate_nolock_(struct event_base *base,
+ struct event_callback *evcb)
+{
+ int r = 1;
+
+ if (evcb->evcb_flags & EVLIST_FINALIZING)
+ return 0;
+
+ switch (evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) {
+ default:
+ EVUTIL_ASSERT(0);
+ EVUTIL_FALLTHROUGH;
+ case EVLIST_ACTIVE_LATER:
+ event_queue_remove_active_later(base, evcb);
+ r = 0;
+ break;
+ case EVLIST_ACTIVE:
+ return 0;
+ case 0:
+ break;
+ }
+
+ event_queue_insert_active(base, evcb);
+
+ if (EVBASE_NEED_NOTIFY(base))
+ evthread_notify_base(base);
+
+ return r;
+}
+
+int
+event_callback_activate_later_nolock_(struct event_base *base,
+ struct event_callback *evcb)
+{
+ if (evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))
+ return 0;
+
+ event_queue_insert_active_later(base, evcb);
+ if (EVBASE_NEED_NOTIFY(base))
+ evthread_notify_base(base);
+ return 1;
+}
+
+void
+event_callback_init_(struct event_base *base,
+ struct event_callback *cb)
+{
+ memset(cb, 0, sizeof(*cb));
+ cb->evcb_pri = base->nactivequeues - 1;
+}
+
+int
+event_callback_cancel_(struct event_base *base,
+ struct event_callback *evcb)
+{
+ int r;
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ r = event_callback_cancel_nolock_(base, evcb, 0);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+int
+event_callback_cancel_nolock_(struct event_base *base,
+ struct event_callback *evcb, int even_if_finalizing)
+{
+ if ((evcb->evcb_flags & EVLIST_FINALIZING) && !even_if_finalizing)
+ return 0;
+
+ if (evcb->evcb_flags & EVLIST_INIT)
+ return event_del_nolock_(event_callback_to_event(evcb),
+ even_if_finalizing ? EVENT_DEL_EVEN_IF_FINALIZING : EVENT_DEL_AUTOBLOCK);
+
+ switch ((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
+ default:
+ case EVLIST_ACTIVE|EVLIST_ACTIVE_LATER:
+ EVUTIL_ASSERT(0);
+ break;
+ case EVLIST_ACTIVE:
+ /* We get different kinds of events, add them together */
+ event_queue_remove_active(base, evcb);
+ return 0;
+ case EVLIST_ACTIVE_LATER:
+ event_queue_remove_active_later(base, evcb);
+ break;
+ case 0:
+ break;
+ }
+
+ return 0;
+}
+
+void
+event_deferred_cb_init_(struct event_callback *cb, ev_uint8_t priority, deferred_cb_fn fn, void *arg)
+{
+ memset(cb, 0, sizeof(*cb));
+ cb->evcb_cb_union.evcb_selfcb = fn;
+ cb->evcb_arg = arg;
+ cb->evcb_pri = priority;
+ cb->evcb_closure = EV_CLOSURE_CB_SELF;
+}
+
+void
+event_deferred_cb_set_priority_(struct event_callback *cb, ev_uint8_t priority)
+{
+ cb->evcb_pri = priority;
+}
+
+void
+event_deferred_cb_cancel_(struct event_base *base, struct event_callback *cb)
+{
+ if (!base)
+ base = current_base;
+ event_callback_cancel_(base, cb);
+}
+
+#define MAX_DEFERREDS_QUEUED 32
+int
+event_deferred_cb_schedule_(struct event_base *base, struct event_callback *cb)
+{
+ int r = 1;
+ if (!base)
+ base = current_base;
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ if (base->n_deferreds_queued > MAX_DEFERREDS_QUEUED) {
+ r = event_callback_activate_later_nolock_(base, cb);
+ } else {
+ r = event_callback_activate_nolock_(base, cb);
+ if (r) {
+ ++base->n_deferreds_queued;
+ }
+ }
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+static int
+timeout_next(struct event_base *base, struct timeval **tv_p)
+{
+ /* Caller must hold th_base_lock */
+ struct timeval now;
+ struct event *ev;
+ struct timeval *tv = *tv_p;
+ int res = 0;
+
+ ev = min_heap_top_(&base->timeheap);
+
+ if (ev == NULL) {
+ /* if no time-based events are active wait for I/O */
+ *tv_p = NULL;
+ goto out;
+ }
+
+ if (gettime(base, &now) == -1) {
+ res = -1;
+ goto out;
+ }
+
+ if (evutil_timercmp(&ev->ev_timeout, &now, <=)) {
+ evutil_timerclear(tv);
+ goto out;
+ }
+
+ evutil_timersub(&ev->ev_timeout, &now, tv);
+
+ EVUTIL_ASSERT(tv->tv_sec >= 0);
+ EVUTIL_ASSERT(tv->tv_usec >= 0);
+ event_debug(("timeout_next: event: %p, in %d seconds, %d useconds", ev, (int)tv->tv_sec, (int)tv->tv_usec));
+
+out:
+ return (res);
+}
+
+/* Activate every event whose timeout has elapsed. */
+static void
+timeout_process(struct event_base *base)
+{
+ /* Caller must hold lock. */
+ struct timeval now;
+ struct event *ev;
+
+ if (min_heap_empty_(&base->timeheap)) {
+ return;
+ }
+
+ gettime(base, &now);
+
+ while ((ev = min_heap_top_(&base->timeheap))) {
+ if (evutil_timercmp(&ev->ev_timeout, &now, >))
+ break;
+
+ /* delete this event from the I/O queues */
+ event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
+
+ event_debug(("timeout_process: event: %p, call %p",
+ ev, ev->ev_callback));
+ event_active_nolock_(ev, EV_TIMEOUT, 1);
+ }
+}
+
+#ifndef MAX
+#define MAX(a,b) (((a)>(b))?(a):(b))
+#endif
+
+#define MAX_EVENT_COUNT(var, v) var = MAX(var, v)
+
+/* These are a fancy way to spell
+ if (~flags & EVLIST_INTERNAL)
+ base->event_count--/++;
+*/
+#define DECR_EVENT_COUNT(base,flags) \
+ ((base)->event_count -= !((flags) & EVLIST_INTERNAL))
+#define INCR_EVENT_COUNT(base,flags) do { \
+ ((base)->event_count += !((flags) & EVLIST_INTERNAL)); \
+ MAX_EVENT_COUNT((base)->event_count_max, (base)->event_count); \
+} while (0)
+
+static void
+event_queue_remove_inserted(struct event_base *base, struct event *ev)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (EVUTIL_FAILURE_CHECK(!(ev->ev_flags & EVLIST_INSERTED))) {
+ event_errx(1, "%s: %p(fd "EV_SOCK_FMT") not on queue %x", __func__,
+ ev, EV_SOCK_ARG(ev->ev_fd), EVLIST_INSERTED);
+ return;
+ }
+ DECR_EVENT_COUNT(base, ev->ev_flags);
+ ev->ev_flags &= ~EVLIST_INSERTED;
+}
+static void
+event_queue_remove_active(struct event_base *base, struct event_callback *evcb)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (EVUTIL_FAILURE_CHECK(!(evcb->evcb_flags & EVLIST_ACTIVE))) {
+ event_errx(1, "%s: %p not on queue %x", __func__,
+ evcb, EVLIST_ACTIVE);
+ return;
+ }
+ DECR_EVENT_COUNT(base, evcb->evcb_flags);
+ evcb->evcb_flags &= ~EVLIST_ACTIVE;
+ base->event_count_active--;
+
+ TAILQ_REMOVE(&base->activequeues[evcb->evcb_pri],
+ evcb, evcb_active_next);
+}
+static void
+event_queue_remove_active_later(struct event_base *base, struct event_callback *evcb)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (EVUTIL_FAILURE_CHECK(!(evcb->evcb_flags & EVLIST_ACTIVE_LATER))) {
+ event_errx(1, "%s: %p not on queue %x", __func__,
+ evcb, EVLIST_ACTIVE_LATER);
+ return;
+ }
+ DECR_EVENT_COUNT(base, evcb->evcb_flags);
+ evcb->evcb_flags &= ~EVLIST_ACTIVE_LATER;
+ base->event_count_active--;
+
+ TAILQ_REMOVE(&base->active_later_queue, evcb, evcb_active_next);
+}
+static void
+event_queue_remove_timeout(struct event_base *base, struct event *ev)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (EVUTIL_FAILURE_CHECK(!(ev->ev_flags & EVLIST_TIMEOUT))) {
+ event_errx(1, "%s: %p(fd "EV_SOCK_FMT") not on queue %x", __func__,
+ ev, EV_SOCK_ARG(ev->ev_fd), EVLIST_TIMEOUT);
+ return;
+ }
+ DECR_EVENT_COUNT(base, ev->ev_flags);
+ ev->ev_flags &= ~EVLIST_TIMEOUT;
+
+ if (is_common_timeout(&ev->ev_timeout, base)) {
+ struct common_timeout_list *ctl =
+ get_common_timeout_list(base, &ev->ev_timeout);
+ TAILQ_REMOVE(&ctl->events, ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+ } else {
+ min_heap_erase_(&base->timeheap, ev);
+ }
+}
+
+#ifdef USE_REINSERT_TIMEOUT
+/* Remove and reinsert 'ev' into the timeout queue. */
+static void
+event_queue_reinsert_timeout(struct event_base *base, struct event *ev,
+ int was_common, int is_common, int old_timeout_idx)
+{
+ struct common_timeout_list *ctl;
+ if (!(ev->ev_flags & EVLIST_TIMEOUT)) {
+ event_queue_insert_timeout(base, ev);
+ return;
+ }
+
+ switch ((was_common<<1) | is_common) {
+ case 3: /* Changing from one common timeout to another */
+ ctl = base->common_timeout_queues[old_timeout_idx];
+ TAILQ_REMOVE(&ctl->events, ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+ ctl = get_common_timeout_list(base, &ev->ev_timeout);
+ insert_common_timeout_inorder(ctl, ev);
+ break;
+ case 2: /* Was common; is no longer common */
+ ctl = base->common_timeout_queues[old_timeout_idx];
+ TAILQ_REMOVE(&ctl->events, ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+ min_heap_push_(&base->timeheap, ev);
+ break;
+ case 1: /* Wasn't common; has become common. */
+ min_heap_erase_(&base->timeheap, ev);
+ ctl = get_common_timeout_list(base, &ev->ev_timeout);
+ insert_common_timeout_inorder(ctl, ev);
+ break;
+ case 0: /* was in heap; is still on heap. */
+ min_heap_adjust_(&base->timeheap, ev);
+ break;
+ default:
+ EVUTIL_ASSERT(0); /* unreachable */
+ break;
+ }
+}
+#endif
+
+/* Add 'ev' to the common timeout list in 'ev'. */
+static void
+insert_common_timeout_inorder(struct common_timeout_list *ctl,
+ struct event *ev)
+{
+ struct event *e;
+ /* By all logic, we should just be able to append 'ev' to the end of
+ * ctl->events, since the timeout on each 'ev' is set to {the common
+ * timeout} + {the time when we add the event}, and so the events
+ * should arrive in order of their timeeouts. But just in case
+ * there's some wacky threading issue going on, we do a search from
+ * the end of 'ev' to find the right insertion point.
+ */
+ TAILQ_FOREACH_REVERSE(e, &ctl->events,
+ event_list, ev_timeout_pos.ev_next_with_common_timeout) {
+ /* This timercmp is a little sneaky, since both ev and e have
+ * magic values in tv_usec. Fortunately, they ought to have
+ * the _same_ magic values in tv_usec. Let's assert for that.
+ */
+ EVUTIL_ASSERT(
+ is_same_common_timeout(&e->ev_timeout, &ev->ev_timeout));
+ if (evutil_timercmp(&ev->ev_timeout, &e->ev_timeout, >=)) {
+ TAILQ_INSERT_AFTER(&ctl->events, e, ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+ return;
+ }
+ }
+ TAILQ_INSERT_HEAD(&ctl->events, ev,
+ ev_timeout_pos.ev_next_with_common_timeout);
+}
+
+static void
+event_queue_insert_inserted(struct event_base *base, struct event *ev)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (EVUTIL_FAILURE_CHECK(ev->ev_flags & EVLIST_INSERTED)) {
+ event_errx(1, "%s: %p(fd "EV_SOCK_FMT") already inserted", __func__,
+ ev, EV_SOCK_ARG(ev->ev_fd));
+ return;
+ }
+
+ INCR_EVENT_COUNT(base, ev->ev_flags);
+
+ ev->ev_flags |= EVLIST_INSERTED;
+}
+
+static void
+event_queue_insert_active(struct event_base *base, struct event_callback *evcb)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (evcb->evcb_flags & EVLIST_ACTIVE) {
+ /* Double insertion is possible for active events */
+ return;
+ }
+
+ INCR_EVENT_COUNT(base, evcb->evcb_flags);
+
+ evcb->evcb_flags |= EVLIST_ACTIVE;
+
+ base->event_count_active++;
+ MAX_EVENT_COUNT(base->event_count_active_max, base->event_count_active);
+ EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
+ TAILQ_INSERT_TAIL(&base->activequeues[evcb->evcb_pri],
+ evcb, evcb_active_next);
+}
+
+static void
+event_queue_insert_active_later(struct event_base *base, struct event_callback *evcb)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+ if (evcb->evcb_flags & (EVLIST_ACTIVE_LATER|EVLIST_ACTIVE)) {
+ /* Double insertion is possible */
+ return;
+ }
+
+ INCR_EVENT_COUNT(base, evcb->evcb_flags);
+ evcb->evcb_flags |= EVLIST_ACTIVE_LATER;
+ base->event_count_active++;
+ MAX_EVENT_COUNT(base->event_count_active_max, base->event_count_active);
+ EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
+ TAILQ_INSERT_TAIL(&base->active_later_queue, evcb, evcb_active_next);
+}
+
+static void
+event_queue_insert_timeout(struct event_base *base, struct event *ev)
+{
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ if (EVUTIL_FAILURE_CHECK(ev->ev_flags & EVLIST_TIMEOUT)) {
+ event_errx(1, "%s: %p(fd "EV_SOCK_FMT") already on timeout", __func__,
+ ev, EV_SOCK_ARG(ev->ev_fd));
+ return;
+ }
+
+ INCR_EVENT_COUNT(base, ev->ev_flags);
+
+ ev->ev_flags |= EVLIST_TIMEOUT;
+
+ if (is_common_timeout(&ev->ev_timeout, base)) {
+ struct common_timeout_list *ctl =
+ get_common_timeout_list(base, &ev->ev_timeout);
+ insert_common_timeout_inorder(ctl, ev);
+ } else {
+ min_heap_push_(&base->timeheap, ev);
+ }
+}
+
+static void
+event_queue_make_later_events_active(struct event_base *base)
+{
+ struct event_callback *evcb;
+ EVENT_BASE_ASSERT_LOCKED(base);
+
+ while ((evcb = TAILQ_FIRST(&base->active_later_queue))) {
+ TAILQ_REMOVE(&base->active_later_queue, evcb, evcb_active_next);
+ evcb->evcb_flags = (evcb->evcb_flags & ~EVLIST_ACTIVE_LATER) | EVLIST_ACTIVE;
+ EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
+ TAILQ_INSERT_TAIL(&base->activequeues[evcb->evcb_pri], evcb, evcb_active_next);
+ base->n_deferreds_queued += (evcb->evcb_closure == EV_CLOSURE_CB_SELF);
+ }
+}
+
+/* Functions for debugging */
+
+const char *
+event_get_version(void)
+{
+ return (EVENT__VERSION);
+}
+
+ev_uint32_t
+event_get_version_number(void)
+{
+ return (EVENT__NUMERIC_VERSION);
+}
+
+/*
+ * No thread-safe interface needed - the information should be the same
+ * for all threads.
+ */
+
+const char *
+event_get_method(void)
+{
+ return (current_base->evsel->name);
+}
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+static void *(*mm_malloc_fn_)(size_t sz) = NULL;
+static void *(*mm_realloc_fn_)(void *p, size_t sz) = NULL;
+static void (*mm_free_fn_)(void *p) = NULL;
+
+void *
+event_mm_malloc_(size_t sz)
+{
+ if (sz == 0)
+ return NULL;
+
+ if (mm_malloc_fn_)
+ return mm_malloc_fn_(sz);
+ else
+ return malloc(sz);
+}
+
+void *
+event_mm_calloc_(size_t count, size_t size)
+{
+ if (count == 0 || size == 0)
+ return NULL;
+
+ if (mm_malloc_fn_) {
+ size_t sz = count * size;
+ void *p = NULL;
+ if (count > EV_SIZE_MAX / size)
+ goto error;
+ p = mm_malloc_fn_(sz);
+ if (p)
+ return memset(p, 0, sz);
+ } else {
+ void *p = calloc(count, size);
+#ifdef _WIN32
+ /* Windows calloc doesn't reliably set ENOMEM */
+ if (p == NULL)
+ goto error;
+#endif
+ return p;
+ }
+
+error:
+ errno = ENOMEM;
+ return NULL;
+}
+
+char *
+event_mm_strdup_(const char *str)
+{
+ if (!str) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if (mm_malloc_fn_) {
+ size_t ln = strlen(str);
+ void *p = NULL;
+ if (ln == EV_SIZE_MAX)
+ goto error;
+ p = mm_malloc_fn_(ln+1);
+ if (p)
+ return memcpy(p, str, ln+1);
+ } else
+#ifdef _WIN32
+ return _strdup(str);
+#else
+ return strdup(str);
+#endif
+
+error:
+ errno = ENOMEM;
+ return NULL;
+}
+
+void *
+event_mm_realloc_(void *ptr, size_t sz)
+{
+ if (mm_realloc_fn_)
+ return mm_realloc_fn_(ptr, sz);
+ else
+ return realloc(ptr, sz);
+}
+
+void
+event_mm_free_(void *ptr)
+{
+ if (mm_free_fn_)
+ mm_free_fn_(ptr);
+ else
+ free(ptr);
+}
+
+void
+event_set_mem_functions(void *(*malloc_fn)(size_t sz),
+ void *(*realloc_fn)(void *ptr, size_t sz),
+ void (*free_fn)(void *ptr))
+{
+ mm_malloc_fn_ = malloc_fn;
+ mm_realloc_fn_ = realloc_fn;
+ mm_free_fn_ = free_fn;
+}
+#endif
+
+#ifdef EVENT__HAVE_EVENTFD
+static void
+evthread_notify_drain_eventfd(evutil_socket_t fd, short what, void *arg)
+{
+ ev_uint64_t msg;
+ ev_ssize_t r;
+ struct event_base *base = arg;
+
+ r = read(fd, (void*) &msg, sizeof(msg));
+ if (r<0 && errno != EAGAIN) {
+ event_sock_warn(fd, "Error reading from eventfd");
+ }
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ base->is_notify_pending = 0;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+#endif
+
+static void
+evthread_notify_drain_default(evutil_socket_t fd, short what, void *arg)
+{
+ unsigned char buf[1024];
+ struct event_base *base = arg;
+#ifdef _WIN32
+ while (recv(fd, (char*)buf, sizeof(buf), 0) > 0)
+ ;
+#else
+ while (read(fd, (char*)buf, sizeof(buf)) > 0)
+ ;
+#endif
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ base->is_notify_pending = 0;
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+int
+evthread_make_base_notifiable(struct event_base *base)
+{
+ int r;
+ if (!base)
+ return -1;
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ r = evthread_make_base_notifiable_nolock_(base);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+static int
+evthread_make_base_notifiable_nolock_(struct event_base *base)
+{
+ void (*cb)(evutil_socket_t, short, void *);
+ int (*notify)(struct event_base *);
+
+ if (base->th_notify_fn != NULL) {
+ /* The base is already notifiable: we're doing fine. */
+ return 0;
+ }
+
+#if defined(EVENT__HAVE_WORKING_KQUEUE)
+ if (base->evsel == &kqops && event_kq_add_notify_event_(base) == 0) {
+ base->th_notify_fn = event_kq_notify_base_;
+ /* No need to add an event here; the backend can wake
+ * itself up just fine. */
+ return 0;
+ }
+#endif
+
+#ifdef EVENT__HAVE_EVENTFD
+ base->th_notify_fd[0] = evutil_eventfd_(0,
+ EVUTIL_EFD_CLOEXEC|EVUTIL_EFD_NONBLOCK);
+ if (base->th_notify_fd[0] >= 0) {
+ base->th_notify_fd[1] = -1;
+ notify = evthread_notify_base_eventfd;
+ cb = evthread_notify_drain_eventfd;
+ } else
+#endif
+ if (evutil_make_internal_pipe_(base->th_notify_fd) == 0) {
+ notify = evthread_notify_base_default;
+ cb = evthread_notify_drain_default;
+ } else {
+ return -1;
+ }
+
+ base->th_notify_fn = notify;
+
+ /* prepare an event that we can use for wakeup */
+ event_assign(&base->th_notify, base, base->th_notify_fd[0],
+ EV_READ|EV_PERSIST, cb, base);
+
+ /* we need to mark this as internal event */
+ base->th_notify.ev_flags |= EVLIST_INTERNAL;
+ event_priority_set(&base->th_notify, 0);
+
+ return event_add_nolock_(&base->th_notify, NULL, 0);
+}
+
+int
+event_base_foreach_event_nolock_(struct event_base *base,
+ event_base_foreach_event_cb fn, void *arg)
+{
+ int r, i;
+ unsigned u;
+ struct event *ev;
+
+ /* Start out with all the EVLIST_INSERTED events. */
+ if ((r = evmap_foreach_event_(base, fn, arg)))
+ return r;
+
+ /* Okay, now we deal with those events that have timeouts and are in
+ * the min-heap. */
+ for (u = 0; u < base->timeheap.n; ++u) {
+ ev = base->timeheap.p[u];
+ if (ev->ev_flags & EVLIST_INSERTED) {
+ /* we already processed this one */
+ continue;
+ }
+ if ((r = fn(base, ev, arg)))
+ return r;
+ }
+
+ /* Now for the events in one of the timeout queues.
+ * the min-heap. */
+ for (i = 0; i < base->n_common_timeouts; ++i) {
+ struct common_timeout_list *ctl =
+ base->common_timeout_queues[i];
+ TAILQ_FOREACH(ev, &ctl->events,
+ ev_timeout_pos.ev_next_with_common_timeout) {
+ if (ev->ev_flags & EVLIST_INSERTED) {
+ /* we already processed this one */
+ continue;
+ }
+ if ((r = fn(base, ev, arg)))
+ return r;
+ }
+ }
+
+ /* Finally, we deal wit all the active events that we haven't touched
+ * yet. */
+ for (i = 0; i < base->nactivequeues; ++i) {
+ struct event_callback *evcb;
+ TAILQ_FOREACH(evcb, &base->activequeues[i], evcb_active_next) {
+ if ((evcb->evcb_flags & (EVLIST_INIT|EVLIST_INSERTED|EVLIST_TIMEOUT)) != EVLIST_INIT) {
+ /* This isn't an event (evlist_init clear), or
+ * we already processed it. (inserted or
+ * timeout set */
+ continue;
+ }
+ ev = event_callback_to_event(evcb);
+ if ((r = fn(base, ev, arg)))
+ return r;
+ }
+ }
+
+ return 0;
+}
+
+/* Helper for event_base_dump_events: called on each event in the event base;
+ * dumps only the inserted events. */
+static int
+dump_inserted_event_fn(const struct event_base *base, const struct event *e, void *arg)
+{
+ FILE *output = arg;
+ const char *gloss = (e->ev_events & EV_SIGNAL) ?
+ "sig" : "fd ";
+
+ if (! (e->ev_flags & (EVLIST_INSERTED|EVLIST_TIMEOUT)))
+ return 0;
+
+ fprintf(output, " %p [%s "EV_SOCK_FMT"]%s%s%s%s%s%s%s",
+ (void*)e, gloss, EV_SOCK_ARG(e->ev_fd),
+ (e->ev_events&EV_READ)?" Read":"",
+ (e->ev_events&EV_WRITE)?" Write":"",
+ (e->ev_events&EV_CLOSED)?" EOF":"",
+ (e->ev_events&EV_SIGNAL)?" Signal":"",
+ (e->ev_events&EV_PERSIST)?" Persist":"",
+ (e->ev_events&EV_ET)?" ET":"",
+ (e->ev_flags&EVLIST_INTERNAL)?" Internal":"");
+ if (e->ev_flags & EVLIST_TIMEOUT) {
+ struct timeval tv;
+ tv.tv_sec = e->ev_timeout.tv_sec;
+ tv.tv_usec = e->ev_timeout.tv_usec & MICROSECONDS_MASK;
+ evutil_timeradd(&tv, &base->tv_clock_diff, &tv);
+ fprintf(output, " Timeout=%ld.%06d",
+ (long)tv.tv_sec, (int)(tv.tv_usec & MICROSECONDS_MASK));
+ }
+ fputc('\n', output);
+
+ return 0;
+}
+
+/* Helper for event_base_dump_events: called on each event in the event base;
+ * dumps only the active events. */
+static int
+dump_active_event_fn(const struct event_base *base, const struct event *e, void *arg)
+{
+ FILE *output = arg;
+ const char *gloss = (e->ev_events & EV_SIGNAL) ?
+ "sig" : "fd ";
+
+ if (! (e->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)))
+ return 0;
+
+ fprintf(output, " %p [%s "EV_SOCK_FMT", priority=%d]%s%s%s%s%s active%s%s\n",
+ (void*)e, gloss, EV_SOCK_ARG(e->ev_fd), e->ev_pri,
+ (e->ev_res&EV_READ)?" Read":"",
+ (e->ev_res&EV_WRITE)?" Write":"",
+ (e->ev_res&EV_CLOSED)?" EOF":"",
+ (e->ev_res&EV_SIGNAL)?" Signal":"",
+ (e->ev_res&EV_TIMEOUT)?" Timeout":"",
+ (e->ev_flags&EVLIST_INTERNAL)?" [Internal]":"",
+ (e->ev_flags&EVLIST_ACTIVE_LATER)?" [NextTime]":"");
+
+ return 0;
+}
+
+int
+event_base_foreach_event(struct event_base *base,
+ event_base_foreach_event_cb fn, void *arg)
+{
+ int r;
+ if ((!fn) || (!base)) {
+ return -1;
+ }
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ r = event_base_foreach_event_nolock_(base, fn, arg);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+ return r;
+}
+
+
+void
+event_base_dump_events(struct event_base *base, FILE *output)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ fprintf(output, "Inserted events:\n");
+ event_base_foreach_event_nolock_(base, dump_inserted_event_fn, output);
+
+ fprintf(output, "Active events:\n");
+ event_base_foreach_event_nolock_(base, dump_active_event_fn, output);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+void
+event_base_active_by_fd(struct event_base *base, evutil_socket_t fd, short events)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ /* Activate any non timer events */
+ if (!(events & EV_TIMEOUT)) {
+ evmap_io_active_(base, fd, events & (EV_READ|EV_WRITE|EV_CLOSED));
+ } else {
+ /* If we want to activate timer events, loop and activate each event with
+ * the same fd in both the timeheap and common timeouts list */
+ int i;
+ unsigned u;
+ struct event *ev;
+
+ for (u = 0; u < base->timeheap.n; ++u) {
+ ev = base->timeheap.p[u];
+ if (ev->ev_fd == fd) {
+ event_active_nolock_(ev, EV_TIMEOUT, 1);
+ }
+ }
+
+ for (i = 0; i < base->n_common_timeouts; ++i) {
+ struct common_timeout_list *ctl = base->common_timeout_queues[i];
+ TAILQ_FOREACH(ev, &ctl->events,
+ ev_timeout_pos.ev_next_with_common_timeout) {
+ if (ev->ev_fd == fd) {
+ event_active_nolock_(ev, EV_TIMEOUT, 1);
+ }
+ }
+ }
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+void
+event_base_active_by_signal(struct event_base *base, int sig)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ evmap_signal_active_(base, sig, 1);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+
+void
+event_base_add_virtual_(struct event_base *base)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ base->virtual_event_count++;
+ MAX_EVENT_COUNT(base->virtual_event_count_max, base->virtual_event_count);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+void
+event_base_del_virtual_(struct event_base *base)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ EVUTIL_ASSERT(base->virtual_event_count > 0);
+ base->virtual_event_count--;
+ if (base->virtual_event_count == 0 && EVBASE_NEED_NOTIFY(base))
+ evthread_notify_base(base);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+static void
+event_free_debug_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_map_lock_ != NULL) {
+ EVTHREAD_FREE_LOCK(event_debug_map_lock_, 0);
+ event_debug_map_lock_ = NULL;
+ evthreadimpl_disable_lock_debugging_();
+ }
+#endif /* EVENT__DISABLE_DEBUG_MODE */
+#endif /* EVENT__DISABLE_THREAD_SUPPORT */
+ return;
+}
+
+static void
+event_free_debug_globals(void)
+{
+ event_free_debug_globals_locks();
+}
+
+static void
+event_free_evsig_globals(void)
+{
+ evsig_free_globals_();
+}
+
+static void
+event_free_evutil_globals(void)
+{
+ evutil_free_globals_();
+}
+
+static void
+event_free_globals(void)
+{
+ event_free_debug_globals();
+ event_free_evsig_globals();
+ event_free_evutil_globals();
+}
+
+void
+libevent_global_shutdown(void)
+{
+ event_disable_debug_mode();
+ event_free_globals();
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+event_global_setup_locks_(const int enable_locks)
+{
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ EVTHREAD_SETUP_GLOBAL_LOCK(event_debug_map_lock_, 0);
+#endif
+ if (evsig_global_setup_locks_(enable_locks) < 0)
+ return -1;
+ if (evutil_global_setup_locks_(enable_locks) < 0)
+ return -1;
+ if (evutil_secure_rng_global_setup_locks_(enable_locks) < 0)
+ return -1;
+ return 0;
+}
+#endif
+
+void
+event_base_assert_ok_(struct event_base *base)
+{
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ event_base_assert_ok_nolock_(base);
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+void
+event_base_assert_ok_nolock_(struct event_base *base)
+{
+ int i;
+ int count;
+
+ /* First do checks on the per-fd and per-signal lists */
+ evmap_check_integrity_(base);
+
+ /* Check the heap property */
+ for (i = 1; i < (int)base->timeheap.n; ++i) {
+ int parent = (i - 1) / 2;
+ struct event *ev, *p_ev;
+ ev = base->timeheap.p[i];
+ p_ev = base->timeheap.p[parent];
+ EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
+ EVUTIL_ASSERT(evutil_timercmp(&p_ev->ev_timeout, &ev->ev_timeout, <=));
+ EVUTIL_ASSERT(ev->ev_timeout_pos.min_heap_idx == i);
+ }
+
+ /* Check that the common timeouts are fine */
+ for (i = 0; i < base->n_common_timeouts; ++i) {
+ struct common_timeout_list *ctl = base->common_timeout_queues[i];
+ struct event *last=NULL, *ev;
+
+ EVUTIL_ASSERT_TAILQ_OK(&ctl->events, event, ev_timeout_pos.ev_next_with_common_timeout);
+
+ TAILQ_FOREACH(ev, &ctl->events, ev_timeout_pos.ev_next_with_common_timeout) {
+ if (last)
+ EVUTIL_ASSERT(evutil_timercmp(&last->ev_timeout, &ev->ev_timeout, <=));
+ EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
+ EVUTIL_ASSERT(is_common_timeout(&ev->ev_timeout,base));
+ EVUTIL_ASSERT(COMMON_TIMEOUT_IDX(&ev->ev_timeout) == i);
+ last = ev;
+ }
+ }
+
+ /* Check the active queues. */
+ count = 0;
+ for (i = 0; i < base->nactivequeues; ++i) {
+ struct event_callback *evcb;
+ EVUTIL_ASSERT_TAILQ_OK(&base->activequeues[i], event_callback, evcb_active_next);
+ TAILQ_FOREACH(evcb, &base->activequeues[i], evcb_active_next) {
+ EVUTIL_ASSERT((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) == EVLIST_ACTIVE);
+ EVUTIL_ASSERT(evcb->evcb_pri == i);
+ ++count;
+ }
+ }
+
+ {
+ struct event_callback *evcb;
+ TAILQ_FOREACH(evcb, &base->active_later_queue, evcb_active_next) {
+ EVUTIL_ASSERT((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) == EVLIST_ACTIVE_LATER);
+ ++count;
+ }
+ }
+ EVUTIL_ASSERT(count == base->event_count_active);
+}
diff --git a/ipc/chromium/src/third_party/libevent/event_iocp.c b/ipc/chromium/src/third_party/libevent/event_iocp.c
new file mode 100644
index 0000000000..6b2a2e15ef
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event_iocp.c
@@ -0,0 +1,294 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "evconfig-private.h"
+
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#include <windows.h>
+#include <process.h>
+#include <stdio.h>
+#include <mswsock.h>
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "iocp-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "event-internal.h"
+#include "evthread-internal.h"
+
+#define NOTIFICATION_KEY ((ULONG_PTR)-1)
+
+void
+event_overlapped_init_(struct event_overlapped *o, iocp_callback cb)
+{
+ memset(o, 0, sizeof(struct event_overlapped));
+ o->cb = cb;
+}
+
+static void
+handle_entry(OVERLAPPED *o, ULONG_PTR completion_key, DWORD nBytes, int ok)
+{
+ struct event_overlapped *eo =
+ EVUTIL_UPCAST(o, struct event_overlapped, overlapped);
+ eo->cb(eo, completion_key, nBytes, ok);
+}
+
+static void
+loop(void *port_)
+{
+ struct event_iocp_port *port = port_;
+ long ms = port->ms;
+ HANDLE p = port->port;
+
+ if (ms <= 0)
+ ms = INFINITE;
+
+ while (1) {
+ OVERLAPPED *overlapped=NULL;
+ ULONG_PTR key=0;
+ DWORD bytes=0;
+ int ok = GetQueuedCompletionStatus(p, &bytes, &key,
+ &overlapped, ms);
+ EnterCriticalSection(&port->lock);
+ if (port->shutdown) {
+ if (--port->n_live_threads == 0)
+ ReleaseSemaphore(port->shutdownSemaphore, 1,
+ NULL);
+ LeaveCriticalSection(&port->lock);
+ return;
+ }
+ LeaveCriticalSection(&port->lock);
+
+ if (key != NOTIFICATION_KEY && overlapped)
+ handle_entry(overlapped, key, bytes, ok);
+ else if (!overlapped)
+ break;
+ }
+ event_warnx("GetQueuedCompletionStatus exited with no event.");
+ EnterCriticalSection(&port->lock);
+ if (--port->n_live_threads == 0)
+ ReleaseSemaphore(port->shutdownSemaphore, 1, NULL);
+ LeaveCriticalSection(&port->lock);
+}
+
+int
+event_iocp_port_associate_(struct event_iocp_port *port, evutil_socket_t fd,
+ ev_uintptr_t key)
+{
+ HANDLE h;
+ h = CreateIoCompletionPort((HANDLE)fd, port->port, key, port->n_threads);
+ if (!h)
+ return -1;
+ return 0;
+}
+
+static void *
+get_extension_function(SOCKET s, const GUID *which_fn)
+{
+ void *ptr = NULL;
+ DWORD bytes=0;
+ WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER,
+ (GUID*)which_fn, sizeof(*which_fn),
+ &ptr, sizeof(ptr),
+ &bytes, NULL, NULL);
+
+ /* No need to detect errors here: if ptr is set, then we have a good
+ function pointer. Otherwise, we should behave as if we had no
+ function pointer.
+ */
+ return ptr;
+}
+
+/* Mingw doesn't have these in its mswsock.h. The values are copied from
+ wine.h. Perhaps if we copy them exactly, the cargo will come again.
+*/
+#ifndef WSAID_ACCEPTEX
+#define WSAID_ACCEPTEX \
+ {0xb5367df1,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
+#endif
+#ifndef WSAID_CONNECTEX
+#define WSAID_CONNECTEX \
+ {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}}
+#endif
+#ifndef WSAID_GETACCEPTEXSOCKADDRS
+#define WSAID_GETACCEPTEXSOCKADDRS \
+ {0xb5367df2,0xcbac,0x11cf,{0x95,0xca,0x00,0x80,0x5f,0x48,0xa1,0x92}}
+#endif
+
+static int extension_fns_initialized = 0;
+
+static void
+init_extension_functions(struct win32_extension_fns *ext)
+{
+ const GUID acceptex = WSAID_ACCEPTEX;
+ const GUID connectex = WSAID_CONNECTEX;
+ const GUID getacceptexsockaddrs = WSAID_GETACCEPTEXSOCKADDRS;
+ SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
+ if (s == EVUTIL_INVALID_SOCKET)
+ return;
+ ext->AcceptEx = get_extension_function(s, &acceptex);
+ ext->ConnectEx = get_extension_function(s, &connectex);
+ ext->GetAcceptExSockaddrs = get_extension_function(s,
+ &getacceptexsockaddrs);
+ closesocket(s);
+
+ extension_fns_initialized = 1;
+}
+
+static struct win32_extension_fns the_extension_fns;
+
+const struct win32_extension_fns *
+event_get_win32_extension_fns_(void)
+{
+ return &the_extension_fns;
+}
+
+#define N_CPUS_DEFAULT 2
+
+struct event_iocp_port *
+event_iocp_port_launch_(int n_cpus)
+{
+ struct event_iocp_port *port;
+ int i;
+
+ if (!extension_fns_initialized)
+ init_extension_functions(&the_extension_fns);
+
+ if (!(port = mm_calloc(1, sizeof(struct event_iocp_port))))
+ return NULL;
+
+ if (n_cpus <= 0)
+ n_cpus = N_CPUS_DEFAULT;
+ port->n_threads = n_cpus * 2;
+ port->threads = mm_calloc(port->n_threads, sizeof(HANDLE));
+ if (!port->threads)
+ goto err;
+
+ port->port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0,
+ n_cpus);
+ port->ms = -1;
+ if (!port->port)
+ goto err;
+
+ port->shutdownSemaphore = CreateSemaphore(NULL, 0, 1, NULL);
+ if (!port->shutdownSemaphore)
+ goto err;
+
+ for (i=0; i<port->n_threads; ++i) {
+ ev_uintptr_t th = _beginthread(loop, 0, port);
+ if (th == (ev_uintptr_t)-1)
+ goto err;
+ port->threads[i] = (HANDLE)th;
+ ++port->n_live_threads;
+ }
+
+ InitializeCriticalSectionAndSpinCount(&port->lock, 1000);
+
+ return port;
+err:
+ if (port->port)
+ CloseHandle(port->port);
+ if (port->threads)
+ mm_free(port->threads);
+ if (port->shutdownSemaphore)
+ CloseHandle(port->shutdownSemaphore);
+ mm_free(port);
+ return NULL;
+}
+
+static void
+event_iocp_port_unlock_and_free_(struct event_iocp_port *port)
+{
+ DeleteCriticalSection(&port->lock);
+ CloseHandle(port->port);
+ CloseHandle(port->shutdownSemaphore);
+ mm_free(port->threads);
+ mm_free(port);
+}
+
+static int
+event_iocp_notify_all(struct event_iocp_port *port)
+{
+ int i, r, ok=1;
+ for (i=0; i<port->n_threads; ++i) {
+ r = PostQueuedCompletionStatus(port->port, 0, NOTIFICATION_KEY,
+ NULL);
+ if (!r)
+ ok = 0;
+ }
+ return ok ? 0 : -1;
+}
+
+int
+event_iocp_shutdown_(struct event_iocp_port *port, long waitMsec)
+{
+ DWORD ms = INFINITE;
+ int n;
+
+ EnterCriticalSection(&port->lock);
+ port->shutdown = 1;
+ LeaveCriticalSection(&port->lock);
+ event_iocp_notify_all(port);
+
+ if (waitMsec >= 0)
+ ms = waitMsec;
+
+ WaitForSingleObject(port->shutdownSemaphore, ms);
+ EnterCriticalSection(&port->lock);
+ n = port->n_live_threads;
+ LeaveCriticalSection(&port->lock);
+ if (n == 0) {
+ event_iocp_port_unlock_and_free_(port);
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+int
+event_iocp_activate_overlapped_(
+ struct event_iocp_port *port, struct event_overlapped *o,
+ ev_uintptr_t key, ev_uint32_t n)
+{
+ BOOL r;
+
+ r = PostQueuedCompletionStatus(port->port, n, key, &o->overlapped);
+ return (r==0) ? -1 : 0;
+}
+
+struct event_iocp_port *
+event_base_get_iocp_(struct event_base *base)
+{
+#ifdef _WIN32
+ return base->iocp;
+#else
+ return NULL;
+#endif
+}
diff --git a/ipc/chromium/src/third_party/libevent/event_rpcgen.py b/ipc/chromium/src/third_party/libevent/event_rpcgen.py
new file mode 100755
index 0000000000..0bae3b0fe6
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event_rpcgen.py
@@ -0,0 +1,1925 @@
+#!/usr/bin/env python
+#
+# Copyright (c) 2005-2007 Niels Provos <provos@citi.umich.edu>
+# Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+# All rights reserved.
+#
+# Generates marshaling code based on libevent.
+
+# pylint: disable=too-many-lines
+# pylint: disable=too-many-branches
+# pylint: disable=too-many-public-methods
+# pylint: disable=too-many-statements
+# pylint: disable=global-statement
+
+# TODO:
+# 1) propagate the arguments/options parsed by argparse down to the
+# instantiated factory objects.
+# 2) move the globals into a class that manages execution, including the
+# progress outputs that go to stderr at the moment.
+# 3) emit other languages.
+
+import argparse
+import re
+import sys
+
+_NAME = "event_rpcgen.py"
+_VERSION = "0.1"
+
+# Globals
+LINE_COUNT = 0
+
+CPPCOMMENT_RE = re.compile(r"\/\/.*$")
+NONIDENT_RE = re.compile(r"\W")
+PREPROCESSOR_DEF_RE = re.compile(r"^#define")
+STRUCT_REF_RE = re.compile(r"^struct\[(?P<name>[a-zA-Z_][a-zA-Z0-9_]*)\]$")
+STRUCT_DEF_RE = re.compile(r"^struct +[a-zA-Z_][a-zA-Z0-9_]* *{$")
+WHITESPACE_RE = re.compile(r"\s+")
+
+HEADER_DIRECT = []
+CPP_DIRECT = []
+
+QUIETLY = False
+
+
+def declare(s):
+ if not QUIETLY:
+ print(s)
+
+
+def TranslateList(mylist, mydict):
+ return [x % mydict for x in mylist]
+
+
+class RpcGenError(Exception):
+ """An Exception class for parse errors."""
+
+ def __init__(self, why): # pylint: disable=super-init-not-called
+ self.why = why
+
+ def __str__(self):
+ return str(self.why)
+
+
+# Holds everything that makes a struct
+class Struct(object):
+ def __init__(self, name):
+ self._name = name
+ self._entries = []
+ self._tags = {}
+ declare(" Created struct: %s" % name)
+
+ def AddEntry(self, entry):
+ if entry.Tag() in self._tags:
+ raise RpcGenError(
+ 'Entry "%s" duplicates tag number %d from "%s" '
+ "around line %d"
+ % (entry.Name(), entry.Tag(), self._tags[entry.Tag()], LINE_COUNT)
+ )
+ self._entries.append(entry)
+ self._tags[entry.Tag()] = entry.Name()
+ declare(" Added entry: %s" % entry.Name())
+
+ def Name(self):
+ return self._name
+
+ def EntryTagName(self, entry):
+ """Creates the name inside an enumeration for distinguishing data
+ types."""
+ name = "%s_%s" % (self._name, entry.Name())
+ return name.upper()
+
+ @staticmethod
+ def PrintIndented(filep, ident, code):
+ """Takes an array, add indentation to each entry and prints it."""
+ for entry in code:
+ filep.write("%s%s\n" % (ident, entry))
+
+
+class StructCCode(Struct):
+ """ Knows how to generate C code for a struct """
+
+ def __init__(self, name):
+ Struct.__init__(self, name)
+
+ def PrintTags(self, filep):
+ """Prints the tag definitions for a structure."""
+ filep.write("/* Tag definition for %s */\n" % self._name)
+ filep.write("enum %s_ {\n" % self._name.lower())
+ for entry in self._entries:
+ filep.write(" %s=%d,\n" % (self.EntryTagName(entry), entry.Tag()))
+ filep.write(" %s_MAX_TAGS\n" % (self._name.upper()))
+ filep.write("};\n\n")
+
+ def PrintForwardDeclaration(self, filep):
+ filep.write("struct %s;\n" % self._name)
+
+ def PrintDeclaration(self, filep):
+ filep.write("/* Structure declaration for %s */\n" % self._name)
+ filep.write("struct %s_access_ {\n" % self._name)
+ for entry in self._entries:
+ dcl = entry.AssignDeclaration("(*%s_assign)" % entry.Name())
+ dcl.extend(entry.GetDeclaration("(*%s_get)" % entry.Name()))
+ if entry.Array():
+ dcl.extend(entry.AddDeclaration("(*%s_add)" % entry.Name()))
+ self.PrintIndented(filep, " ", dcl)
+ filep.write("};\n\n")
+
+ filep.write("struct %s {\n" % self._name)
+ filep.write(" struct %s_access_ *base;\n\n" % self._name)
+ for entry in self._entries:
+ dcl = entry.Declaration()
+ self.PrintIndented(filep, " ", dcl)
+ filep.write("\n")
+ for entry in self._entries:
+ filep.write(" ev_uint8_t %s_set;\n" % entry.Name())
+ filep.write("};\n\n")
+
+ filep.write(
+ """struct %(name)s *%(name)s_new(void);
+struct %(name)s *%(name)s_new_with_arg(void *);
+void %(name)s_free(struct %(name)s *);
+void %(name)s_clear(struct %(name)s *);
+void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);
+int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);
+int %(name)s_complete(struct %(name)s *);
+void evtag_marshal_%(name)s(struct evbuffer *, ev_uint32_t,
+ const struct %(name)s *);
+int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
+ struct %(name)s *);\n"""
+ % {"name": self._name}
+ )
+
+ # Write a setting function of every variable
+ for entry in self._entries:
+ self.PrintIndented(
+ filep, "", entry.AssignDeclaration(entry.AssignFuncName())
+ )
+ self.PrintIndented(filep, "", entry.GetDeclaration(entry.GetFuncName()))
+ if entry.Array():
+ self.PrintIndented(filep, "", entry.AddDeclaration(entry.AddFuncName()))
+
+ filep.write("/* --- %s done --- */\n\n" % self._name)
+
+ def PrintCode(self, filep):
+ filep.write(
+ """/*
+ * Implementation of %s
+ */
+"""
+ % (self._name)
+ )
+
+ filep.write(
+ """
+static struct %(name)s_access_ %(name)s_base__ = {
+"""
+ % {"name": self._name}
+ )
+ for entry in self._entries:
+ self.PrintIndented(filep, " ", entry.CodeBase())
+ filep.write("};\n\n")
+
+ # Creation
+ filep.write(
+ """struct %(name)s *
+%(name)s_new(void)
+{
+ return %(name)s_new_with_arg(NULL);
+}
+
+struct %(name)s *
+%(name)s_new_with_arg(void *unused)
+{
+ struct %(name)s *tmp;
+ if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {
+ event_warn("%%s: malloc", __func__);
+ return (NULL);
+ }
+ tmp->base = &%(name)s_base__;
+
+"""
+ % {"name": self._name}
+ )
+
+ for entry in self._entries:
+ self.PrintIndented(filep, " ", entry.CodeInitialize("tmp"))
+ filep.write(" tmp->%s_set = 0;\n\n" % entry.Name())
+
+ filep.write(
+ """ return (tmp);
+}
+
+"""
+ )
+
+ # Adding
+ for entry in self._entries:
+ if entry.Array():
+ self.PrintIndented(filep, "", entry.CodeAdd())
+ filep.write("\n")
+
+ # Assigning
+ for entry in self._entries:
+ self.PrintIndented(filep, "", entry.CodeAssign())
+ filep.write("\n")
+
+ # Getting
+ for entry in self._entries:
+ self.PrintIndented(filep, "", entry.CodeGet())
+ filep.write("\n")
+
+ # Clearing
+ filep.write(
+ """void
+%(name)s_clear(struct %(name)s *tmp)
+{
+"""
+ % {"name": self._name}
+ )
+ for entry in self._entries:
+ self.PrintIndented(filep, " ", entry.CodeClear("tmp"))
+
+ filep.write("}\n\n")
+
+ # Freeing
+ filep.write(
+ """void
+%(name)s_free(struct %(name)s *tmp)
+{
+"""
+ % {"name": self._name}
+ )
+
+ for entry in self._entries:
+ self.PrintIndented(filep, " ", entry.CodeFree("tmp"))
+
+ filep.write(
+ """ free(tmp);
+}
+
+"""
+ )
+
+ # Marshaling
+ filep.write(
+ """void
+%(name)s_marshal(struct evbuffer *evbuf, const struct %(name)s *tmp) {
+"""
+ % {"name": self._name}
+ )
+ for entry in self._entries:
+ indent = " "
+ # Optional entries do not have to be set
+ if entry.Optional():
+ indent += " "
+ filep.write(" if (tmp->%s_set) {\n" % entry.Name())
+ self.PrintIndented(
+ filep,
+ indent,
+ entry.CodeMarshal(
+ "evbuf",
+ self.EntryTagName(entry),
+ entry.GetVarName("tmp"),
+ entry.GetVarLen("tmp"),
+ ),
+ )
+ if entry.Optional():
+ filep.write(" }\n")
+
+ filep.write("}\n\n")
+
+ # Unmarshaling
+ filep.write(
+ """int
+%(name)s_unmarshal(struct %(name)s *tmp, struct evbuffer *evbuf)
+{
+ ev_uint32_t tag;
+ while (evbuffer_get_length(evbuf) > 0) {
+ if (evtag_peek(evbuf, &tag) == -1)
+ return (-1);
+ switch (tag) {
+
+"""
+ % {"name": self._name}
+ )
+ for entry in self._entries:
+ filep.write(" case %s:\n" % (self.EntryTagName(entry)))
+ if not entry.Array():
+ filep.write(
+ """ if (tmp->%s_set)
+ return (-1);
+"""
+ % (entry.Name())
+ )
+
+ self.PrintIndented(
+ filep,
+ " ",
+ entry.CodeUnmarshal(
+ "evbuf",
+ self.EntryTagName(entry),
+ entry.GetVarName("tmp"),
+ entry.GetVarLen("tmp"),
+ ),
+ )
+
+ filep.write(
+ """ tmp->%s_set = 1;
+ break;
+"""
+ % (entry.Name())
+ )
+ filep.write(
+ """ default:
+ return -1;
+ }
+ }
+
+"""
+ )
+ # Check if it was decoded completely
+ filep.write(
+ """ if (%(name)s_complete(tmp) == -1)
+ return (-1);
+ return (0);
+}
+"""
+ % {"name": self._name}
+ )
+
+ # Checking if a structure has all the required data
+ filep.write(
+ """
+int
+%(name)s_complete(struct %(name)s *msg)
+{
+"""
+ % {"name": self._name}
+ )
+ for entry in self._entries:
+ if not entry.Optional():
+ code = [
+ """if (!msg->%(name)s_set)
+ return (-1);"""
+ ]
+ code = TranslateList(code, entry.GetTranslation())
+ self.PrintIndented(filep, " ", code)
+
+ self.PrintIndented(
+ filep, " ", entry.CodeComplete("msg", entry.GetVarName("msg"))
+ )
+ filep.write(
+ """ return (0);
+}
+"""
+ )
+
+ # Complete message unmarshaling
+ filep.write(
+ """
+int
+evtag_unmarshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ struct %(name)s *msg)
+{
+ ev_uint32_t tag;
+ int res = -1;
+
+ struct evbuffer *tmp = evbuffer_new();
+
+ if (evtag_unmarshal(evbuf, &tag, tmp) == -1 || tag != need_tag)
+ goto error;
+
+ if (%(name)s_unmarshal(msg, tmp) == -1)
+ goto error;
+
+ res = 0;
+
+ error:
+ evbuffer_free(tmp);
+ return (res);
+}
+"""
+ % {"name": self._name}
+ )
+
+ # Complete message marshaling
+ filep.write(
+ """
+void
+evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag,
+ const struct %(name)s *msg)
+{
+ struct evbuffer *buf_ = evbuffer_new();
+ assert(buf_ != NULL);
+ %(name)s_marshal(buf_, msg);
+ evtag_marshal_buffer(evbuf, tag, buf_);
+ evbuffer_free(buf_);
+}
+
+"""
+ % {"name": self._name}
+ )
+
+
+class Entry(object):
+ def __init__(self, ent_type, name, tag):
+ self._type = ent_type
+ self._name = name
+ self._tag = int(tag)
+ self._ctype = ent_type
+ self._optional = False
+ self._can_be_array = False
+ self._array = False
+ self._line_count = -1
+ self._struct = None
+ self._refname = None
+
+ self._optpointer = True
+ self._optaddarg = True
+
+ @staticmethod
+ def GetInitializer():
+ raise NotImplementedError("Entry does not provide an initializer")
+
+ def SetStruct(self, struct):
+ self._struct = struct
+
+ def LineCount(self):
+ assert self._line_count != -1
+ return self._line_count
+
+ def SetLineCount(self, number):
+ self._line_count = number
+
+ def Array(self):
+ return self._array
+
+ def Optional(self):
+ return self._optional
+
+ def Tag(self):
+ return self._tag
+
+ def Name(self):
+ return self._name
+
+ def Type(self):
+ return self._type
+
+ def MakeArray(self):
+ self._array = True
+
+ def MakeOptional(self):
+ self._optional = True
+
+ def Verify(self):
+ if self.Array() and not self._can_be_array:
+ raise RpcGenError(
+ 'Entry "%s" cannot be created as an array '
+ "around line %d" % (self._name, self.LineCount())
+ )
+ if not self._struct:
+ raise RpcGenError(
+ 'Entry "%s" does not know which struct it belongs to '
+ "around line %d" % (self._name, self.LineCount())
+ )
+ if self._optional and self._array:
+ raise RpcGenError(
+ 'Entry "%s" has illegal combination of optional and array '
+ "around line %d" % (self._name, self.LineCount())
+ )
+
+ def GetTranslation(self, extradict=None):
+ if extradict is None:
+ extradict = {}
+ mapping = {
+ "parent_name": self._struct.Name(),
+ "name": self._name,
+ "ctype": self._ctype,
+ "refname": self._refname,
+ "optpointer": self._optpointer and "*" or "",
+ "optreference": self._optpointer and "&" or "",
+ "optaddarg": self._optaddarg and ", const %s value" % self._ctype or "",
+ }
+ for (k, v) in list(extradict.items()):
+ mapping[k] = v
+
+ return mapping
+
+ def GetVarName(self, var):
+ return "%(var)s->%(name)s_data" % self.GetTranslation({"var": var})
+
+ def GetVarLen(self, _var):
+ return "sizeof(%s)" % self._ctype
+
+ def GetFuncName(self):
+ return "%s_%s_get" % (self._struct.Name(), self._name)
+
+ def GetDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, %s *);" % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def CodeGet(self):
+ code = """int
+%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, %(ctype)s *value)
+{
+ if (msg->%(name)s_set != 1)
+ return (-1);
+ *value = msg->%(name)s_data;
+ return (0);
+}"""
+ code = code % self.GetTranslation()
+ return code.split("\n")
+
+ def AssignFuncName(self):
+ return "%s_%s_assign" % (self._struct.Name(), self._name)
+
+ def AddFuncName(self):
+ return "%s_%s_add" % (self._struct.Name(), self._name)
+
+ def AssignDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, const %s);"
+ % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def CodeAssign(self):
+ code = [
+ "int",
+ "%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,"
+ " const %(ctype)s value)",
+ "{",
+ " msg->%(name)s_set = 1;",
+ " msg->%(name)s_data = value;",
+ " return (0);",
+ "}",
+ ]
+ code = "\n".join(code)
+ code = code % self.GetTranslation()
+ return code.split("\n")
+
+ def CodeClear(self, structname):
+ code = ["%s->%s_set = 0;" % (structname, self.Name())]
+
+ return code
+
+ @staticmethod
+ def CodeComplete(_structname, _var_name):
+ return []
+
+ @staticmethod
+ def CodeFree(_name):
+ return []
+
+ def CodeBase(self):
+ code = ["%(parent_name)s_%(name)s_assign,", "%(parent_name)s_%(name)s_get,"]
+ if self.Array():
+ code.append("%(parent_name)s_%(name)s_add,")
+
+ code = "\n".join(code)
+ code = code % self.GetTranslation()
+ return code.split("\n")
+
+
+class EntryBytes(Entry):
+ def __init__(self, ent_type, name, tag, length):
+ # Init base class
+ super(EntryBytes, self).__init__(ent_type, name, tag)
+
+ self._length = length
+ self._ctype = "ev_uint8_t"
+
+ @staticmethod
+ def GetInitializer():
+ return "NULL"
+
+ def GetVarLen(self, _var):
+ return "(%s)" % self._length
+
+ @staticmethod
+ def CodeArrayAdd(varname, _value):
+ # XXX: copy here
+ return ["%(varname)s = NULL;" % {"varname": varname}]
+
+ def GetDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, %s **);" % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def AssignDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, const %s *);"
+ % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def Declaration(self):
+ dcl = ["ev_uint8_t %s_data[%s];" % (self._name, self._length)]
+
+ return dcl
+
+ def CodeGet(self):
+ name = self._name
+ code = [
+ "int",
+ "%s_%s_get(struct %s *msg, %s **value)"
+ % (self._struct.Name(), name, self._struct.Name(), self._ctype),
+ "{",
+ " if (msg->%s_set != 1)" % name,
+ " return (-1);",
+ " *value = msg->%s_data;" % name,
+ " return (0);",
+ "}",
+ ]
+ return code
+
+ def CodeAssign(self):
+ name = self._name
+ code = [
+ "int",
+ "%s_%s_assign(struct %s *msg, const %s *value)"
+ % (self._struct.Name(), name, self._struct.Name(), self._ctype),
+ "{",
+ " msg->%s_set = 1;" % name,
+ " memcpy(msg->%s_data, value, %s);" % (name, self._length),
+ " return (0);",
+ "}",
+ ]
+ return code
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+ code = [
+ "if (evtag_unmarshal_fixed(%(buf)s, %(tag)s, "
+ "%(var)s, %(varlen)s) == -1) {",
+ ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+ " return (-1);",
+ "}",
+ ]
+ return TranslateList(
+ code,
+ self.GetTranslation(
+ {"var": var_name, "varlen": var_len, "buf": buf, "tag": tag_name}
+ ),
+ )
+
+ @staticmethod
+ def CodeMarshal(buf, tag_name, var_name, var_len):
+ code = ["evtag_marshal(%s, %s, %s, %s);" % (buf, tag_name, var_name, var_len)]
+ return code
+
+ def CodeClear(self, structname):
+ code = [
+ "%s->%s_set = 0;" % (structname, self.Name()),
+ "memset(%s->%s_data, 0, sizeof(%s->%s_data));"
+ % (structname, self._name, structname, self._name),
+ ]
+
+ return code
+
+ def CodeInitialize(self, name):
+ code = [
+ "memset(%s->%s_data, 0, sizeof(%s->%s_data));"
+ % (name, self._name, name, self._name)
+ ]
+ return code
+
+ def Verify(self):
+ if not self._length:
+ raise RpcGenError(
+ 'Entry "%s" needs a length '
+ "around line %d" % (self._name, self.LineCount())
+ )
+
+ super(EntryBytes, self).Verify()
+
+
+class EntryInt(Entry):
+ def __init__(self, ent_type, name, tag, bits=32):
+ # Init base class
+ super(EntryInt, self).__init__(ent_type, name, tag)
+
+ self._can_be_array = True
+ if bits == 32:
+ self._ctype = "ev_uint32_t"
+ self._marshal_type = "int"
+ if bits == 64:
+ self._ctype = "ev_uint64_t"
+ self._marshal_type = "int64"
+
+ @staticmethod
+ def GetInitializer():
+ return "0"
+
+ @staticmethod
+ def CodeArrayFree(_var):
+ return []
+
+ @staticmethod
+ def CodeArrayAssign(varname, srcvar):
+ return ["%(varname)s = %(srcvar)s;" % {"varname": varname, "srcvar": srcvar}]
+
+ @staticmethod
+ def CodeArrayAdd(varname, value):
+ """Returns a new entry of this type."""
+ return ["%(varname)s = %(value)s;" % {"varname": varname, "value": value}]
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, _var_len):
+ code = [
+ "if (evtag_unmarshal_%(ma)s(%(buf)s, %(tag)s, &%(var)s) == -1) {",
+ ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+ " return (-1);",
+ "}",
+ ]
+ code = "\n".join(code) % self.GetTranslation(
+ {"ma": self._marshal_type, "buf": buf, "tag": tag_name, "var": var_name}
+ )
+ return code.split("\n")
+
+ def CodeMarshal(self, buf, tag_name, var_name, _var_len):
+ code = [
+ "evtag_marshal_%s(%s, %s, %s);"
+ % (self._marshal_type, buf, tag_name, var_name)
+ ]
+ return code
+
+ def Declaration(self):
+ dcl = ["%s %s_data;" % (self._ctype, self._name)]
+
+ return dcl
+
+ def CodeInitialize(self, name):
+ code = ["%s->%s_data = 0;" % (name, self._name)]
+ return code
+
+
+class EntryString(Entry):
+ def __init__(self, ent_type, name, tag):
+ # Init base class
+ super(EntryString, self).__init__(ent_type, name, tag)
+
+ self._can_be_array = True
+ self._ctype = "char *"
+
+ @staticmethod
+ def GetInitializer():
+ return "NULL"
+
+ @staticmethod
+ def CodeArrayFree(varname):
+ code = ["if (%(var)s != NULL) free(%(var)s);"]
+
+ return TranslateList(code, {"var": varname})
+
+ @staticmethod
+ def CodeArrayAssign(varname, srcvar):
+ code = [
+ "if (%(var)s != NULL)",
+ " free(%(var)s);",
+ "%(var)s = strdup(%(srcvar)s);",
+ "if (%(var)s == NULL) {",
+ ' event_warnx("%%s: strdup", __func__);',
+ " return (-1);",
+ "}",
+ ]
+
+ return TranslateList(code, {"var": varname, "srcvar": srcvar})
+
+ @staticmethod
+ def CodeArrayAdd(varname, value):
+ code = [
+ "if (%(value)s != NULL) {",
+ " %(var)s = strdup(%(value)s);",
+ " if (%(var)s == NULL) {",
+ " goto error;",
+ " }",
+ "} else {",
+ " %(var)s = NULL;",
+ "}",
+ ]
+
+ return TranslateList(code, {"var": varname, "value": value})
+
+ def GetVarLen(self, var):
+ return "strlen(%s)" % self.GetVarName(var)
+
+ @staticmethod
+ def CodeMakeInitalize(varname):
+ return "%(varname)s = NULL;" % {"varname": varname}
+
+ def CodeAssign(self):
+ code = """int
+%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
+ const %(ctype)s value)
+{
+ if (msg->%(name)s_data != NULL)
+ free(msg->%(name)s_data);
+ if ((msg->%(name)s_data = strdup(value)) == NULL)
+ return (-1);
+ msg->%(name)s_set = 1;
+ return (0);
+}""" % (
+ self.GetTranslation()
+ )
+
+ return code.split("\n")
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, _var_len):
+ code = [
+ "if (evtag_unmarshal_string(%(buf)s, %(tag)s, &%(var)s) == -1) {",
+ ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+ " return (-1);",
+ "}",
+ ]
+ code = "\n".join(code) % self.GetTranslation(
+ {"buf": buf, "tag": tag_name, "var": var_name}
+ )
+ return code.split("\n")
+
+ @staticmethod
+ def CodeMarshal(buf, tag_name, var_name, _var_len):
+ code = ["evtag_marshal_string(%s, %s, %s);" % (buf, tag_name, var_name)]
+ return code
+
+ def CodeClear(self, structname):
+ code = [
+ "if (%s->%s_set == 1) {" % (structname, self.Name()),
+ " free(%s->%s_data);" % (structname, self.Name()),
+ " %s->%s_data = NULL;" % (structname, self.Name()),
+ " %s->%s_set = 0;" % (structname, self.Name()),
+ "}",
+ ]
+
+ return code
+
+ def CodeInitialize(self, name):
+ code = ["%s->%s_data = NULL;" % (name, self._name)]
+ return code
+
+ def CodeFree(self, name):
+ code = [
+ "if (%s->%s_data != NULL)" % (name, self._name),
+ " free (%s->%s_data);" % (name, self._name),
+ ]
+
+ return code
+
+ def Declaration(self):
+ dcl = ["char *%s_data;" % self._name]
+
+ return dcl
+
+
+class EntryStruct(Entry):
+ def __init__(self, ent_type, name, tag, refname):
+ # Init base class
+ super(EntryStruct, self).__init__(ent_type, name, tag)
+
+ self._optpointer = False
+ self._can_be_array = True
+ self._refname = refname
+ self._ctype = "struct %s*" % refname
+ self._optaddarg = False
+
+ def GetInitializer(self):
+ return "NULL"
+
+ def GetVarLen(self, _var):
+ return "-1"
+
+ def CodeArrayAdd(self, varname, _value):
+ code = [
+ "%(varname)s = %(refname)s_new();",
+ "if (%(varname)s == NULL)",
+ " goto error;",
+ ]
+
+ return TranslateList(code, self.GetTranslation({"varname": varname}))
+
+ def CodeArrayFree(self, var):
+ code = ["%(refname)s_free(%(var)s);" % self.GetTranslation({"var": var})]
+ return code
+
+ def CodeArrayAssign(self, var, srcvar):
+ code = [
+ "int had_error = 0;",
+ "struct evbuffer *tmp = NULL;",
+ "%(refname)s_clear(%(var)s);",
+ "if ((tmp = evbuffer_new()) == NULL) {",
+ ' event_warn("%%s: evbuffer_new()", __func__);',
+ " had_error = 1;",
+ " goto done;",
+ "}",
+ "%(refname)s_marshal(tmp, %(srcvar)s);",
+ "if (%(refname)s_unmarshal(%(var)s, tmp) == -1) {",
+ ' event_warnx("%%s: %(refname)s_unmarshal", __func__);',
+ " had_error = 1;",
+ " goto done;",
+ "}",
+ "done:",
+ "if (tmp != NULL)",
+ " evbuffer_free(tmp);",
+ "if (had_error) {",
+ " %(refname)s_clear(%(var)s);",
+ " return (-1);",
+ "}",
+ ]
+
+ return TranslateList(code, self.GetTranslation({"var": var, "srcvar": srcvar}))
+
+ def CodeGet(self):
+ name = self._name
+ code = [
+ "int",
+ "%s_%s_get(struct %s *msg, %s *value)"
+ % (self._struct.Name(), name, self._struct.Name(), self._ctype),
+ "{",
+ " if (msg->%s_set != 1) {" % name,
+ " msg->%s_data = %s_new();" % (name, self._refname),
+ " if (msg->%s_data == NULL)" % name,
+ " return (-1);",
+ " msg->%s_set = 1;" % name,
+ " }",
+ " *value = msg->%s_data;" % name,
+ " return (0);",
+ "}",
+ ]
+ return code
+
+ def CodeAssign(self):
+ code = (
+ """int
+%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
+ const %(ctype)s value)
+{
+ struct evbuffer *tmp = NULL;
+ if (msg->%(name)s_set) {
+ %(refname)s_clear(msg->%(name)s_data);
+ msg->%(name)s_set = 0;
+ } else {
+ msg->%(name)s_data = %(refname)s_new();
+ if (msg->%(name)s_data == NULL) {
+ event_warn("%%s: %(refname)s_new()", __func__);
+ goto error;
+ }
+ }
+ if ((tmp = evbuffer_new()) == NULL) {
+ event_warn("%%s: evbuffer_new()", __func__);
+ goto error;
+ }
+ %(refname)s_marshal(tmp, value);
+ if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {
+ event_warnx("%%s: %(refname)s_unmarshal", __func__);
+ goto error;
+ }
+ msg->%(name)s_set = 1;
+ evbuffer_free(tmp);
+ return (0);
+ error:
+ if (tmp != NULL)
+ evbuffer_free(tmp);
+ if (msg->%(name)s_data != NULL) {
+ %(refname)s_free(msg->%(name)s_data);
+ msg->%(name)s_data = NULL;
+ }
+ return (-1);
+}"""
+ % self.GetTranslation()
+ )
+ return code.split("\n")
+
+ def CodeComplete(self, structname, var_name):
+ code = [
+ "if (%(structname)s->%(name)s_set && "
+ "%(refname)s_complete(%(var)s) == -1)",
+ " return (-1);",
+ ]
+
+ return TranslateList(
+ code, self.GetTranslation({"structname": structname, "var": var_name})
+ )
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, _var_len):
+ code = [
+ "%(var)s = %(refname)s_new();",
+ "if (%(var)s == NULL)",
+ " return (-1);",
+ "if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag)s, ",
+ " %(var)s) == -1) {",
+ ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+ " return (-1);",
+ "}",
+ ]
+ code = "\n".join(code) % self.GetTranslation(
+ {"buf": buf, "tag": tag_name, "var": var_name}
+ )
+ return code.split("\n")
+
+ def CodeMarshal(self, buf, tag_name, var_name, _var_len):
+ code = [
+ "evtag_marshal_%s(%s, %s, %s);" % (self._refname, buf, tag_name, var_name)
+ ]
+ return code
+
+ def CodeClear(self, structname):
+ code = [
+ "if (%s->%s_set == 1) {" % (structname, self.Name()),
+ " %s_free(%s->%s_data);" % (self._refname, structname, self.Name()),
+ " %s->%s_data = NULL;" % (structname, self.Name()),
+ " %s->%s_set = 0;" % (structname, self.Name()),
+ "}",
+ ]
+
+ return code
+
+ def CodeInitialize(self, name):
+ code = ["%s->%s_data = NULL;" % (name, self._name)]
+ return code
+
+ def CodeFree(self, name):
+ code = [
+ "if (%s->%s_data != NULL)" % (name, self._name),
+ " %s_free(%s->%s_data);" % (self._refname, name, self._name),
+ ]
+
+ return code
+
+ def Declaration(self):
+ dcl = ["%s %s_data;" % (self._ctype, self._name)]
+
+ return dcl
+
+
+class EntryVarBytes(Entry):
+ def __init__(self, ent_type, name, tag):
+ # Init base class
+ super(EntryVarBytes, self).__init__(ent_type, name, tag)
+
+ self._ctype = "ev_uint8_t *"
+
+ @staticmethod
+ def GetInitializer():
+ return "NULL"
+
+ def GetVarLen(self, var):
+ return "%(var)s->%(name)s_length" % self.GetTranslation({"var": var})
+
+ @staticmethod
+ def CodeArrayAdd(varname, _value):
+ # xxx: copy
+ return ["%(varname)s = NULL;" % {"varname": varname}]
+
+ def GetDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, %s *, ev_uint32_t *);"
+ % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def AssignDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, const %s, ev_uint32_t);"
+ % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def CodeAssign(self):
+ name = self._name
+ code = [
+ "int",
+ "%s_%s_assign(struct %s *msg, "
+ "const %s value, ev_uint32_t len)"
+ % (self._struct.Name(), name, self._struct.Name(), self._ctype),
+ "{",
+ " if (msg->%s_data != NULL)" % name,
+ " free (msg->%s_data);" % name,
+ " msg->%s_data = malloc(len);" % name,
+ " if (msg->%s_data == NULL)" % name,
+ " return (-1);",
+ " msg->%s_set = 1;" % name,
+ " msg->%s_length = len;" % name,
+ " memcpy(msg->%s_data, value, len);" % name,
+ " return (0);",
+ "}",
+ ]
+ return code
+
+ def CodeGet(self):
+ name = self._name
+ code = [
+ "int",
+ "%s_%s_get(struct %s *msg, %s *value, ev_uint32_t *plen)"
+ % (self._struct.Name(), name, self._struct.Name(), self._ctype),
+ "{",
+ " if (msg->%s_set != 1)" % name,
+ " return (-1);",
+ " *value = msg->%s_data;" % name,
+ " *plen = msg->%s_length;" % name,
+ " return (0);",
+ "}",
+ ]
+ return code
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, var_len):
+ code = [
+ "if (evtag_payload_length(%(buf)s, &%(varlen)s) == -1)",
+ " return (-1);",
+ # We do not want DoS opportunities
+ "if (%(varlen)s > evbuffer_get_length(%(buf)s))",
+ " return (-1);",
+ "if ((%(var)s = malloc(%(varlen)s)) == NULL)",
+ " return (-1);",
+ "if (evtag_unmarshal_fixed(%(buf)s, %(tag)s, %(var)s, "
+ "%(varlen)s) == -1) {",
+ ' event_warnx("%%s: failed to unmarshal %(name)s", __func__);',
+ " return (-1);",
+ "}",
+ ]
+ code = "\n".join(code) % self.GetTranslation(
+ {"buf": buf, "tag": tag_name, "var": var_name, "varlen": var_len}
+ )
+ return code.split("\n")
+
+ @staticmethod
+ def CodeMarshal(buf, tag_name, var_name, var_len):
+ code = ["evtag_marshal(%s, %s, %s, %s);" % (buf, tag_name, var_name, var_len)]
+ return code
+
+ def CodeClear(self, structname):
+ code = [
+ "if (%s->%s_set == 1) {" % (structname, self.Name()),
+ " free (%s->%s_data);" % (structname, self.Name()),
+ " %s->%s_data = NULL;" % (structname, self.Name()),
+ " %s->%s_length = 0;" % (structname, self.Name()),
+ " %s->%s_set = 0;" % (structname, self.Name()),
+ "}",
+ ]
+
+ return code
+
+ def CodeInitialize(self, name):
+ code = [
+ "%s->%s_data = NULL;" % (name, self._name),
+ "%s->%s_length = 0;" % (name, self._name),
+ ]
+ return code
+
+ def CodeFree(self, name):
+ code = [
+ "if (%s->%s_data != NULL)" % (name, self._name),
+ " free(%s->%s_data);" % (name, self._name),
+ ]
+
+ return code
+
+ def Declaration(self):
+ dcl = [
+ "ev_uint8_t *%s_data;" % self._name,
+ "ev_uint32_t %s_length;" % self._name,
+ ]
+
+ return dcl
+
+
+class EntryArray(Entry):
+ _index = None
+
+ def __init__(self, entry):
+ # Init base class
+ super(EntryArray, self).__init__(entry._type, entry._name, entry._tag)
+
+ self._entry = entry
+ self._refname = entry._refname
+ self._ctype = self._entry._ctype
+ self._optional = True
+ self._optpointer = self._entry._optpointer
+ self._optaddarg = self._entry._optaddarg
+
+ # provide a new function for accessing the variable name
+ def GetVarName(var_name):
+ return "%(var)s->%(name)s_data[%(index)s]" % self._entry.GetTranslation(
+ {"var": var_name, "index": self._index}
+ )
+
+ self._entry.GetVarName = GetVarName
+
+ def GetInitializer(self):
+ return "NULL"
+
+ def GetVarName(self, var):
+ return var
+
+ def GetVarLen(self, _var_name):
+ return "-1"
+
+ def GetDeclaration(self, funcname):
+ """Allows direct access to elements of the array."""
+ code = [
+ "int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);"
+ % self.GetTranslation({"funcname": funcname})
+ ]
+ return code
+
+ def AssignDeclaration(self, funcname):
+ code = [
+ "int %s(struct %s *, int, const %s);"
+ % (funcname, self._struct.Name(), self._ctype)
+ ]
+ return code
+
+ def AddDeclaration(self, funcname):
+ code = [
+ "%(ctype)s %(optpointer)s "
+ "%(funcname)s(struct %(parent_name)s *msg%(optaddarg)s);"
+ % self.GetTranslation({"funcname": funcname})
+ ]
+ return code
+
+ def CodeGet(self):
+ code = """int
+%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,
+ %(ctype)s *value)
+{
+ if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)
+ return (-1);
+ *value = msg->%(name)s_data[offset];
+ return (0);
+}
+""" % (
+ self.GetTranslation()
+ )
+
+ return code.splitlines()
+
+ def CodeAssign(self):
+ code = [
+ "int",
+ "%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,",
+ " const %(ctype)s value)",
+ "{",
+ " if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)",
+ " return (-1);",
+ "",
+ " {",
+ ]
+ code = TranslateList(code, self.GetTranslation())
+
+ codearrayassign = self._entry.CodeArrayAssign(
+ "msg->%(name)s_data[off]" % self.GetTranslation(), "value"
+ )
+ code += [" " + x for x in codearrayassign]
+
+ code += TranslateList([" }", " return (0);", "}"], self.GetTranslation())
+
+ return code
+
+ def CodeAdd(self):
+ codearrayadd = self._entry.CodeArrayAdd(
+ "msg->%(name)s_data[msg->%(name)s_length - 1]" % self.GetTranslation(),
+ "value",
+ )
+ code = [
+ "static int",
+ "%(parent_name)s_%(name)s_expand_to_hold_more("
+ "struct %(parent_name)s *msg)",
+ "{",
+ " int tobe_allocated = msg->%(name)s_num_allocated;",
+ " %(ctype)s* new_data = NULL;",
+ " tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;",
+ " new_data = (%(ctype)s*) realloc(msg->%(name)s_data,",
+ " tobe_allocated * sizeof(%(ctype)s));",
+ " if (new_data == NULL)",
+ " return -1;",
+ " msg->%(name)s_data = new_data;",
+ " msg->%(name)s_num_allocated = tobe_allocated;",
+ " return 0;",
+ "}",
+ "",
+ "%(ctype)s %(optpointer)s",
+ "%(parent_name)s_%(name)s_add(struct %(parent_name)s *msg%(optaddarg)s)",
+ "{",
+ " if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {",
+ " if (%(parent_name)s_%(name)s_expand_to_hold_more(msg)<0)",
+ " goto error;",
+ " }",
+ ]
+
+ code = TranslateList(code, self.GetTranslation())
+
+ code += [" " + x for x in codearrayadd]
+
+ code += TranslateList(
+ [
+ " msg->%(name)s_set = 1;",
+ " return %(optreference)s(msg->%(name)s_data["
+ "msg->%(name)s_length - 1]);",
+ "error:",
+ " --msg->%(name)s_length;",
+ " return (NULL);",
+ "}",
+ ],
+ self.GetTranslation(),
+ )
+
+ return code
+
+ def CodeComplete(self, structname, var_name):
+ self._index = "i"
+ tmp = self._entry.CodeComplete(structname, self._entry.GetVarName(var_name))
+ # skip the whole loop if there is nothing to check
+ if not tmp:
+ return []
+
+ translate = self.GetTranslation({"structname": structname})
+ code = [
+ "{",
+ " int i;",
+ " for (i = 0; i < %(structname)s->%(name)s_length; ++i) {",
+ ]
+
+ code = TranslateList(code, translate)
+
+ code += [" " + x for x in tmp]
+
+ code += [" }", "}"]
+
+ return code
+
+ def CodeUnmarshal(self, buf, tag_name, var_name, _var_len):
+ translate = self.GetTranslation(
+ {
+ "var": var_name,
+ "buf": buf,
+ "tag": tag_name,
+ "init": self._entry.GetInitializer(),
+ }
+ )
+ code = [
+ "if (%(var)s->%(name)s_length >= %(var)s->%(name)s_num_allocated &&",
+ " %(parent_name)s_%(name)s_expand_to_hold_more(%(var)s) < 0) {",
+ ' puts("HEY NOW");',
+ " return (-1);",
+ "}",
+ ]
+
+ # the unmarshal code directly returns
+ code = TranslateList(code, translate)
+
+ self._index = "%(var)s->%(name)s_length" % translate
+ code += self._entry.CodeUnmarshal(
+ buf,
+ tag_name,
+ self._entry.GetVarName(var_name),
+ self._entry.GetVarLen(var_name),
+ )
+
+ code += ["++%(var)s->%(name)s_length;" % translate]
+
+ return code
+
+ def CodeMarshal(self, buf, tag_name, var_name, _var_len):
+ code = ["{", " int i;", " for (i = 0; i < %(var)s->%(name)s_length; ++i) {"]
+
+ self._index = "i"
+ code += self._entry.CodeMarshal(
+ buf,
+ tag_name,
+ self._entry.GetVarName(var_name),
+ self._entry.GetVarLen(var_name),
+ )
+ code += [" }", "}"]
+
+ code = "\n".join(code) % self.GetTranslation({"var": var_name})
+
+ return code.split("\n")
+
+ def CodeClear(self, structname):
+ translate = self.GetTranslation({"structname": structname})
+ codearrayfree = self._entry.CodeArrayFree(
+ "%(structname)s->%(name)s_data[i]"
+ % self.GetTranslation({"structname": structname})
+ )
+
+ code = ["if (%(structname)s->%(name)s_set == 1) {"]
+
+ if codearrayfree:
+ code += [
+ " int i;",
+ " for (i = 0; i < %(structname)s->%(name)s_length; ++i) {",
+ ]
+
+ code = TranslateList(code, translate)
+
+ if codearrayfree:
+ code += [" " + x for x in codearrayfree]
+ code += [" }"]
+
+ code += TranslateList(
+ [
+ " free(%(structname)s->%(name)s_data);",
+ " %(structname)s->%(name)s_data = NULL;",
+ " %(structname)s->%(name)s_set = 0;",
+ " %(structname)s->%(name)s_length = 0;",
+ " %(structname)s->%(name)s_num_allocated = 0;",
+ "}",
+ ],
+ translate,
+ )
+
+ return code
+
+ def CodeInitialize(self, name):
+ code = [
+ "%s->%s_data = NULL;" % (name, self._name),
+ "%s->%s_length = 0;" % (name, self._name),
+ "%s->%s_num_allocated = 0;" % (name, self._name),
+ ]
+ return code
+
+ def CodeFree(self, structname):
+ code = self.CodeClear(structname)
+
+ code += TranslateList(
+ ["free(%(structname)s->%(name)s_data);"],
+ self.GetTranslation({"structname": structname}),
+ )
+
+ return code
+
+ def Declaration(self):
+ dcl = [
+ "%s *%s_data;" % (self._ctype, self._name),
+ "int %s_length;" % self._name,
+ "int %s_num_allocated;" % self._name,
+ ]
+
+ return dcl
+
+
+def NormalizeLine(line):
+
+ line = CPPCOMMENT_RE.sub("", line)
+ line = line.strip()
+ line = WHITESPACE_RE.sub(" ", line)
+
+ return line
+
+
+ENTRY_NAME_RE = re.compile(r"(?P<name>[^\[\]]+)(\[(?P<fixed_length>.*)\])?")
+ENTRY_TAG_NUMBER_RE = re.compile(r"(0x)?\d+", re.I)
+
+
+def ProcessOneEntry(factory, newstruct, entry):
+ optional = False
+ array = False
+ entry_type = ""
+ name = ""
+ tag = ""
+ tag_set = None
+ separator = ""
+ fixed_length = ""
+
+ for token in entry.split(" "):
+ if not entry_type:
+ if not optional and token == "optional":
+ optional = True
+ continue
+
+ if not array and token == "array":
+ array = True
+ continue
+
+ if not entry_type:
+ entry_type = token
+ continue
+
+ if not name:
+ res = ENTRY_NAME_RE.match(token)
+ if not res:
+ raise RpcGenError(
+ r"""Cannot parse name: "%s" around line %d""" % (entry, LINE_COUNT)
+ )
+ name = res.group("name")
+ fixed_length = res.group("fixed_length")
+ continue
+
+ if not separator:
+ separator = token
+ if separator != "=":
+ raise RpcGenError(
+ r'''Expected "=" after name "%s" got "%s"''' % (name, token)
+ )
+ continue
+
+ if not tag_set:
+ tag_set = 1
+ if not ENTRY_TAG_NUMBER_RE.match(token):
+ raise RpcGenError(r'''Expected tag number: "%s"''' % (entry))
+ tag = int(token, 0)
+ continue
+
+ raise RpcGenError(r'''Cannot parse "%s"''' % (entry))
+
+ if not tag_set:
+ raise RpcGenError(r'''Need tag number: "%s"''' % (entry))
+
+ # Create the right entry
+ if entry_type == "bytes":
+ if fixed_length:
+ newentry = factory.EntryBytes(entry_type, name, tag, fixed_length)
+ else:
+ newentry = factory.EntryVarBytes(entry_type, name, tag)
+ elif entry_type == "int" and not fixed_length:
+ newentry = factory.EntryInt(entry_type, name, tag)
+ elif entry_type == "int64" and not fixed_length:
+ newentry = factory.EntryInt(entry_type, name, tag, bits=64)
+ elif entry_type == "string" and not fixed_length:
+ newentry = factory.EntryString(entry_type, name, tag)
+ else:
+ res = STRUCT_REF_RE.match(entry_type)
+ if res:
+ # References another struct defined in our file
+ newentry = factory.EntryStruct(entry_type, name, tag, res.group("name"))
+ else:
+ raise RpcGenError('Bad type: "%s" in "%s"' % (entry_type, entry))
+
+ structs = []
+
+ if optional:
+ newentry.MakeOptional()
+ if array:
+ newentry.MakeArray()
+
+ newentry.SetStruct(newstruct)
+ newentry.SetLineCount(LINE_COUNT)
+ newentry.Verify()
+
+ if array:
+ # We need to encapsulate this entry into a struct
+ newentry = factory.EntryArray(newentry)
+ newentry.SetStruct(newstruct)
+ newentry.SetLineCount(LINE_COUNT)
+ newentry.MakeArray()
+
+ newstruct.AddEntry(newentry)
+
+ return structs
+
+
+def ProcessStruct(factory, data):
+ tokens = data.split(" ")
+
+ # First three tokens are: 'struct' 'name' '{'
+ newstruct = factory.Struct(tokens[1])
+
+ inside = " ".join(tokens[3:-1])
+
+ tokens = inside.split(";")
+
+ structs = []
+
+ for entry in tokens:
+ entry = NormalizeLine(entry)
+ if not entry:
+ continue
+
+ # It's possible that new structs get defined in here
+ structs.extend(ProcessOneEntry(factory, newstruct, entry))
+
+ structs.append(newstruct)
+ return structs
+
+
+C_COMMENT_START = "/*"
+C_COMMENT_END = "*/"
+
+C_COMMENT_START_RE = re.compile(re.escape(C_COMMENT_START))
+C_COMMENT_END_RE = re.compile(re.escape(C_COMMENT_END))
+
+C_COMMENT_START_SUB_RE = re.compile(r"%s.*$" % (re.escape(C_COMMENT_START)))
+C_COMMENT_END_SUB_RE = re.compile(r"%s.*$" % (re.escape(C_COMMENT_END)))
+
+C_MULTILINE_COMMENT_SUB_RE = re.compile(
+ r"%s.*?%s" % (re.escape(C_COMMENT_START), re.escape(C_COMMENT_END))
+)
+CPP_CONDITIONAL_BLOCK_RE = re.compile(r"#(if( |def)|endif)")
+INCLUDE_RE = re.compile(r'#include (".+"|<.+>)')
+
+
+def GetNextStruct(filep):
+ global CPP_DIRECT
+ global LINE_COUNT
+
+ got_struct = False
+ have_c_comment = False
+
+ data = ""
+
+ while True:
+ line = filep.readline()
+ if not line:
+ break
+
+ LINE_COUNT += 1
+ line = line[:-1]
+
+ if not have_c_comment and C_COMMENT_START_RE.search(line):
+ if C_MULTILINE_COMMENT_SUB_RE.search(line):
+ line = C_MULTILINE_COMMENT_SUB_RE.sub("", line)
+ else:
+ line = C_COMMENT_START_SUB_RE.sub("", line)
+ have_c_comment = True
+
+ if have_c_comment:
+ if not C_COMMENT_END_RE.search(line):
+ continue
+ have_c_comment = False
+ line = C_COMMENT_END_SUB_RE.sub("", line)
+
+ line = NormalizeLine(line)
+
+ if not line:
+ continue
+
+ if not got_struct:
+ if INCLUDE_RE.match(line):
+ CPP_DIRECT.append(line)
+ elif CPP_CONDITIONAL_BLOCK_RE.match(line):
+ CPP_DIRECT.append(line)
+ elif PREPROCESSOR_DEF_RE.match(line):
+ HEADER_DIRECT.append(line)
+ elif not STRUCT_DEF_RE.match(line):
+ raise RpcGenError("Missing struct on line %d: %s" % (LINE_COUNT, line))
+ else:
+ got_struct = True
+ data += line
+ continue
+
+ # We are inside the struct
+ tokens = line.split("}")
+ if len(tokens) == 1:
+ data += " " + line
+ continue
+
+ if tokens[1]:
+ raise RpcGenError("Trailing garbage after struct on line %d" % LINE_COUNT)
+
+ # We found the end of the struct
+ data += " %s}" % tokens[0]
+ break
+
+ # Remove any comments, that might be in there
+ data = re.sub(r"/\*.*\*/", "", data)
+
+ return data
+
+
+def Parse(factory, filep):
+ """
+ Parses the input file and returns C code and corresponding header file.
+ """
+
+ entities = []
+
+ while 1:
+ # Just gets the whole struct nicely formatted
+ data = GetNextStruct(filep)
+
+ if not data:
+ break
+
+ entities.extend(ProcessStruct(factory, data))
+
+ return entities
+
+
+class CCodeGenerator(object):
+ def __init__(self):
+ pass
+
+ @staticmethod
+ def GuardName(name):
+ # Use the complete provided path to the input file, with all
+ # non-identifier characters replaced with underscores, to
+ # reduce the chance of a collision between guard macros.
+ return "EVENT_RPCOUT_%s_" % (NONIDENT_RE.sub("_", name).upper())
+
+ def HeaderPreamble(self, name):
+ guard = self.GuardName(name)
+ pre = """
+/*
+ * Automatically generated from %s
+ */
+
+#ifndef %s
+#define %s
+
+""" % (
+ name,
+ guard,
+ guard,
+ )
+
+ if HEADER_DIRECT:
+ for statement in HEADER_DIRECT:
+ pre += "%s\n" % statement
+ pre += "\n"
+
+ pre += """
+#include <event2/util.h> /* for ev_uint*_t */
+#include <event2/rpc.h>
+"""
+
+ return pre
+
+ def HeaderPostamble(self, name):
+ guard = self.GuardName(name)
+ return "#endif /* %s */" % (guard)
+
+ @staticmethod
+ def BodyPreamble(name, header_file):
+ global _NAME
+ global _VERSION
+
+ slash = header_file.rfind("/")
+ if slash != -1:
+ header_file = header_file[slash + 1 :]
+
+ pre = """
+/*
+ * Automatically generated from %(name)s
+ * by %(script_name)s/%(script_version)s. DO NOT EDIT THIS FILE.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <event2/event-config.h>
+#include <event2/event.h>
+#include <event2/buffer.h>
+#include <event2/tag.h>
+
+#if defined(EVENT__HAVE___func__)
+# ifndef __func__
+# define __func__ __func__
+# endif
+#elif defined(EVENT__HAVE___FUNCTION__)
+# define __func__ __FUNCTION__
+#else
+# define __func__ __FILE__
+#endif
+
+""" % {
+ "name": name,
+ "script_name": _NAME,
+ "script_version": _VERSION,
+ }
+
+ for statement in CPP_DIRECT:
+ pre += "%s\n" % statement
+
+ pre += '\n#include "%s"\n\n' % header_file
+
+ pre += "void event_warn(const char *fmt, ...);\n"
+ pre += "void event_warnx(const char *fmt, ...);\n\n"
+
+ return pre
+
+ @staticmethod
+ def HeaderFilename(filename):
+ return ".".join(filename.split(".")[:-1]) + ".h"
+
+ @staticmethod
+ def CodeFilename(filename):
+ return ".".join(filename.split(".")[:-1]) + ".gen.c"
+
+ @staticmethod
+ def Struct(name):
+ return StructCCode(name)
+
+ @staticmethod
+ def EntryBytes(entry_type, name, tag, fixed_length):
+ return EntryBytes(entry_type, name, tag, fixed_length)
+
+ @staticmethod
+ def EntryVarBytes(entry_type, name, tag):
+ return EntryVarBytes(entry_type, name, tag)
+
+ @staticmethod
+ def EntryInt(entry_type, name, tag, bits=32):
+ return EntryInt(entry_type, name, tag, bits)
+
+ @staticmethod
+ def EntryString(entry_type, name, tag):
+ return EntryString(entry_type, name, tag)
+
+ @staticmethod
+ def EntryStruct(entry_type, name, tag, struct_name):
+ return EntryStruct(entry_type, name, tag, struct_name)
+
+ @staticmethod
+ def EntryArray(entry):
+ return EntryArray(entry)
+
+
+class CommandLine(object):
+ def __init__(self, argv=None):
+ """Initialize a command-line to launch event_rpcgen, as if
+ from a command-line with CommandLine(sys.argv). If you're
+ calling this directly, remember to provide a dummy value
+ for sys.argv[0]
+ """
+ global QUIETLY
+
+ self.filename = None
+ self.header_file = None
+ self.impl_file = None
+ self.factory = CCodeGenerator()
+
+ parser = argparse.ArgumentParser(
+ usage="%(prog)s [options] rpc-file [[h-file] c-file]"
+ )
+ parser.add_argument("--quiet", action="store_true", default=False)
+ parser.add_argument("rpc_file", type=argparse.FileType("r"))
+
+ args, extra_args = parser.parse_known_args(args=argv)
+
+ QUIETLY = args.quiet
+
+ if extra_args:
+ if len(extra_args) == 1:
+ self.impl_file = extra_args[0].replace("\\", "/")
+ elif len(extra_args) == 2:
+ self.header_file = extra_args[0].replace("\\", "/")
+ self.impl_file = extra_args[1].replace("\\", "/")
+ else:
+ parser.error("Spurious arguments provided")
+
+ self.rpc_file = args.rpc_file
+
+ if not self.impl_file:
+ self.impl_file = self.factory.CodeFilename(self.rpc_file.name)
+
+ if not self.header_file:
+ self.header_file = self.factory.HeaderFilename(self.impl_file)
+
+ if not self.impl_file.endswith(".c"):
+ parser.error("can only generate C implementation files")
+ if not self.header_file.endswith(".h"):
+ parser.error("can only generate C header files")
+
+ def run(self):
+ filename = self.rpc_file.name
+ header_file = self.header_file
+ impl_file = self.impl_file
+ factory = self.factory
+
+ declare('Reading "%s"' % filename)
+
+ with self.rpc_file:
+ entities = Parse(factory, self.rpc_file)
+
+ declare('... creating "%s"' % header_file)
+ with open(header_file, "w") as header_fp:
+ header_fp.write(factory.HeaderPreamble(filename))
+
+ # Create forward declarations: allows other structs to reference
+ # each other
+ for entry in entities:
+ entry.PrintForwardDeclaration(header_fp)
+ header_fp.write("\n")
+
+ for entry in entities:
+ entry.PrintTags(header_fp)
+ entry.PrintDeclaration(header_fp)
+ header_fp.write(factory.HeaderPostamble(filename))
+
+ declare('... creating "%s"' % impl_file)
+ with open(impl_file, "w") as impl_fp:
+ impl_fp.write(factory.BodyPreamble(filename, header_file))
+ for entry in entities:
+ entry.PrintCode(impl_fp)
+
+
+def main(argv=None):
+ try:
+ CommandLine(argv=argv).run()
+ return 0
+ except RpcGenError as e:
+ sys.stderr.write(e)
+ except EnvironmentError as e:
+ if e.filename and e.strerror:
+ sys.stderr.write("%s: %s" % (e.filename, e.strerror))
+ elif e.strerror:
+ sys.stderr.write(e.strerror)
+ else:
+ raise
+ return 1
+
+
+if __name__ == "__main__":
+ sys.exit(main(argv=sys.argv[1:]))
diff --git a/ipc/chromium/src/third_party/libevent/event_tagging.c b/ipc/chromium/src/third_party/libevent/event_tagging.c
new file mode 100644
index 0000000000..b021e8c8de
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/event_tagging.c
@@ -0,0 +1,609 @@
+/*
+ * Copyright (c) 2003-2009 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#ifdef EVENT__HAVE_SYS_IOCTL_H
+#include <sys/ioctl.h>
+#endif
+#include <sys/queue.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef _WIN32
+#include <syslog.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <limits.h>
+
+#include "event2/event.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+
+/*
+ Here's our wire format:
+
+ Stream = TaggedData*
+
+ TaggedData = Tag Length Data
+ where the integer value of 'Length' is the length of 'data'.
+
+ Tag = HByte* LByte
+ where HByte is a byte with the high bit set, and LByte is a byte
+ with the high bit clear. The integer value of the tag is taken
+ by concatenating the lower 7 bits from all the tags. So for example,
+ the tag 0x66 is encoded as [66], whereas the tag 0x166 is encoded as
+ [82 66]
+
+ Length = Integer
+
+ Integer = NNibbles Nibble* Padding?
+ where NNibbles is a 4-bit value encoding the number of nibbles-1,
+ and each Nibble is 4 bits worth of encoded integer, in big-endian
+ order. If the total encoded integer size is an odd number of nibbles,
+ a final padding nibble with value 0 is appended.
+*/
+
+EVENT2_EXPORT_SYMBOL
+int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+EVENT2_EXPORT_SYMBOL
+int evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf);
+EVENT2_EXPORT_SYMBOL
+int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag);
+EVENT2_EXPORT_SYMBOL
+int evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf);
+
+void
+evtag_init(void)
+{
+}
+
+/*
+ * We encode integers by nibbles; the first nibble contains the number
+ * of significant nibbles - 1; this allows us to encode up to 64-bit
+ * integers. This function is byte-order independent.
+ *
+ * @param number a 32-bit unsigned integer to encode
+ * @param data a pointer to where the data should be written. Must
+ * have at least 5 bytes free.
+ * @return the number of bytes written into data.
+ */
+
+#define ENCODE_INT_INTERNAL(data, number) do { \
+ int off = 1, nibbles = 0; \
+ \
+ memset(data, 0, sizeof(number)+1); \
+ while (number) { \
+ if (off & 0x1) \
+ data[off/2] = (data[off/2] & 0xf0) | (number & 0x0f); \
+ else \
+ data[off/2] = (data[off/2] & 0x0f) | \
+ ((number & 0x0f) << 4); \
+ number >>= 4; \
+ off++; \
+ } \
+ \
+ if (off > 2) \
+ nibbles = off - 2; \
+ \
+ /* Off - 1 is the number of encoded nibbles */ \
+ data[0] = (data[0] & 0x0f) | ((nibbles & 0x0f) << 4); \
+ \
+ return ((off + 1) / 2); \
+} while (0)
+
+static inline int
+encode_int_internal(ev_uint8_t *data, ev_uint32_t number)
+{
+ ENCODE_INT_INTERNAL(data, number);
+}
+
+static inline int
+encode_int64_internal(ev_uint8_t *data, ev_uint64_t number)
+{
+ ENCODE_INT_INTERNAL(data, number);
+}
+
+void
+evtag_encode_int(struct evbuffer *evbuf, ev_uint32_t number)
+{
+ ev_uint8_t data[5];
+ int len = encode_int_internal(data, number);
+ evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_encode_int64(struct evbuffer *evbuf, ev_uint64_t number)
+{
+ ev_uint8_t data[9];
+ int len = encode_int64_internal(data, number);
+ evbuffer_add(evbuf, data, len);
+}
+
+/*
+ * Support variable length encoding of tags; we use the high bit in each
+ * octet as a continuation signal.
+ */
+
+int
+evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t tag)
+{
+ int bytes = 0;
+ ev_uint8_t data[5];
+
+ memset(data, 0, sizeof(data));
+ do {
+ ev_uint8_t lower = tag & 0x7f;
+ tag >>= 7;
+
+ if (tag)
+ lower |= 0x80;
+
+ data[bytes++] = lower;
+ } while (tag);
+
+ if (evbuf != NULL)
+ evbuffer_add(evbuf, data, bytes);
+
+ return (bytes);
+}
+
+static int
+decode_tag_internal(ev_uint32_t *ptag, struct evbuffer *evbuf, int dodrain)
+{
+ ev_uint32_t number = 0;
+ size_t len = evbuffer_get_length(evbuf);
+ ev_uint8_t *data;
+ size_t count = 0;
+ int shift = 0, done = 0;
+
+ /*
+ * the encoding of a number is at most one byte more than its
+ * storage size. however, it may also be much smaller.
+ */
+ data = evbuffer_pullup(
+ evbuf, len < sizeof(number) + 1 ? len : sizeof(number) + 1);
+ if (!data)
+ return (-1);
+
+ while (count++ < len) {
+ ev_uint8_t lower = *data++;
+ if (shift >= 28) {
+ /* Make sure it fits into 32 bits */
+ if (shift > 28)
+ return (-1);
+ if ((lower & 0x7f) > 15)
+ return (-1);
+ }
+ number |= (lower & (unsigned)0x7f) << shift;
+ shift += 7;
+
+ if (!(lower & 0x80)) {
+ done = 1;
+ break;
+ }
+ }
+
+ if (!done)
+ return (-1);
+
+ if (dodrain)
+ evbuffer_drain(evbuf, count);
+
+ if (ptag != NULL)
+ *ptag = number;
+
+ return count > INT_MAX ? INT_MAX : (int)(count);
+}
+
+int
+evtag_decode_tag(ev_uint32_t *ptag, struct evbuffer *evbuf)
+{
+ return (decode_tag_internal(ptag, evbuf, 1 /* dodrain */));
+}
+
+/*
+ * Marshal a data type, the general format is as follows:
+ *
+ * tag number: one byte; length: var bytes; payload: var bytes
+ */
+
+void
+evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag,
+ const void *data, ev_uint32_t len)
+{
+ evtag_encode_tag(evbuf, tag);
+ evtag_encode_int(evbuf, len);
+ evbuffer_add(evbuf, (void *)data, len);
+}
+
+void
+evtag_marshal_buffer(struct evbuffer *evbuf, ev_uint32_t tag,
+ struct evbuffer *data)
+{
+ evtag_encode_tag(evbuf, tag);
+ /* XXX support more than UINT32_MAX data */
+ evtag_encode_int(evbuf, (ev_uint32_t)evbuffer_get_length(data));
+ evbuffer_add_buffer(evbuf, data);
+}
+
+/* Marshaling for integers */
+void
+evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag, ev_uint32_t integer)
+{
+ ev_uint8_t data[5];
+ int len = encode_int_internal(data, integer);
+
+ evtag_encode_tag(evbuf, tag);
+ evtag_encode_int(evbuf, len);
+ evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_marshal_int64(struct evbuffer *evbuf, ev_uint32_t tag,
+ ev_uint64_t integer)
+{
+ ev_uint8_t data[9];
+ int len = encode_int64_internal(data, integer);
+
+ evtag_encode_tag(evbuf, tag);
+ evtag_encode_int(evbuf, len);
+ evbuffer_add(evbuf, data, len);
+}
+
+void
+evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag, const char *string)
+{
+ /* TODO support strings longer than UINT32_MAX ? */
+ evtag_marshal(buf, tag, string, (ev_uint32_t)strlen(string));
+}
+
+void
+evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag, struct timeval *tv)
+{
+ ev_uint8_t data[10];
+ int len = encode_int_internal(data, tv->tv_sec);
+ len += encode_int_internal(data + len, tv->tv_usec);
+ evtag_marshal(evbuf, tag, data, len);
+}
+
+#define DECODE_INT_INTERNAL(number, maxnibbles, pnumber, evbuf, offset) \
+do { \
+ ev_uint8_t *data; \
+ ev_ssize_t len = evbuffer_get_length(evbuf) - offset; \
+ int nibbles = 0; \
+ \
+ if (len <= 0) \
+ return (-1); \
+ \
+ /* XXX(niels): faster? */ \
+ data = evbuffer_pullup(evbuf, offset + 1) + offset; \
+ if (!data) \
+ return (-1); \
+ \
+ nibbles = ((data[0] & 0xf0) >> 4) + 1; \
+ if (nibbles > maxnibbles || (nibbles >> 1) + 1 > len) \
+ return (-1); \
+ len = (nibbles >> 1) + 1; \
+ \
+ data = evbuffer_pullup(evbuf, offset + len) + offset; \
+ if (!data) \
+ return (-1); \
+ \
+ while (nibbles > 0) { \
+ number <<= 4; \
+ if (nibbles & 0x1) \
+ number |= data[nibbles >> 1] & 0x0f; \
+ else \
+ number |= (data[nibbles >> 1] & 0xf0) >> 4; \
+ nibbles--; \
+ } \
+ \
+ *pnumber = number; \
+ \
+ return (int)(len); \
+} while (0)
+
+/* Internal: decode an integer from an evbuffer, without draining it.
+ * Only integers up to 32-bits are supported.
+ *
+ * @param evbuf the buffer to read from
+ * @param offset an index into the buffer at which we should start reading.
+ * @param pnumber a pointer to receive the integer.
+ * @return The length of the number as encoded, or -1 on error.
+ */
+
+static int
+decode_int_internal(ev_uint32_t *pnumber, struct evbuffer *evbuf, int offset)
+{
+ ev_uint32_t number = 0;
+ DECODE_INT_INTERNAL(number, 8, pnumber, evbuf, offset);
+}
+
+static int
+decode_int64_internal(ev_uint64_t *pnumber, struct evbuffer *evbuf, int offset)
+{
+ ev_uint64_t number = 0;
+ DECODE_INT_INTERNAL(number, 16, pnumber, evbuf, offset);
+}
+
+int
+evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf)
+{
+ int res = decode_int_internal(pnumber, evbuf, 0);
+ if (res != -1)
+ evbuffer_drain(evbuf, res);
+
+ return (res == -1 ? -1 : 0);
+}
+
+int
+evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf)
+{
+ int res = decode_int64_internal(pnumber, evbuf, 0);
+ if (res != -1)
+ evbuffer_drain(evbuf, res);
+
+ return (res == -1 ? -1 : 0);
+}
+
+int
+evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag)
+{
+ return (decode_tag_internal(ptag, evbuf, 0 /* dodrain */));
+}
+
+int
+evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength)
+{
+ int res, len;
+
+ len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
+ if (len == -1)
+ return (-1);
+
+ res = decode_int_internal(plength, evbuf, len);
+ if (res == -1)
+ return (-1);
+
+ *plength += res + len;
+
+ return (0);
+}
+
+int
+evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength)
+{
+ int res, len;
+
+ len = decode_tag_internal(NULL, evbuf, 0 /* dodrain */);
+ if (len == -1)
+ return (-1);
+
+ res = decode_int_internal(plength, evbuf, len);
+ if (res == -1)
+ return (-1);
+
+ return (0);
+}
+
+/* just unmarshals the header and returns the length of the remaining data */
+
+int
+evtag_unmarshal_header(struct evbuffer *evbuf, ev_uint32_t *ptag)
+{
+ ev_uint32_t len;
+
+ if (decode_tag_internal(ptag, evbuf, 1 /* dodrain */) == -1)
+ return (-1);
+ if (evtag_decode_int(&len, evbuf) == -1)
+ return (-1);
+
+ if (evbuffer_get_length(evbuf) < len)
+ return (-1);
+
+ return (len);
+}
+
+int
+evtag_consume(struct evbuffer *evbuf)
+{
+ int len;
+ if ((len = evtag_unmarshal_header(evbuf, NULL)) == -1)
+ return (-1);
+ evbuffer_drain(evbuf, len);
+
+ return (0);
+}
+
+/* Reads the data type from an event buffer */
+
+int
+evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag, struct evbuffer *dst)
+{
+ int len;
+
+ if ((len = evtag_unmarshal_header(src, ptag)) == -1)
+ return (-1);
+
+ if (evbuffer_add(dst, evbuffer_pullup(src, len), len) == -1)
+ return (-1);
+
+ evbuffer_drain(src, len);
+
+ return (len);
+}
+
+/* Marshaling for integers */
+
+int
+evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ ev_uint32_t *pinteger)
+{
+ ev_uint32_t tag;
+ ev_uint32_t len;
+ int result;
+
+ if (decode_tag_internal(&tag, evbuf, 1 /* dodrain */) == -1)
+ return (-1);
+ if (need_tag != tag)
+ return (-1);
+ if (evtag_decode_int(&len, evbuf) == -1)
+ return (-1);
+
+ if (evbuffer_get_length(evbuf) < len)
+ return (-1);
+
+ result = decode_int_internal(pinteger, evbuf, 0);
+ evbuffer_drain(evbuf, len);
+ if (result < 0 || (size_t)result > len) /* XXX Should this be != rather than > ?*/
+ return (-1);
+ else
+ return result;
+}
+
+int
+evtag_unmarshal_int64(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ ev_uint64_t *pinteger)
+{
+ ev_uint32_t tag;
+ ev_uint32_t len;
+ int result;
+
+ if (decode_tag_internal(&tag, evbuf, 1 /* dodrain */) == -1)
+ return (-1);
+ if (need_tag != tag)
+ return (-1);
+ if (evtag_decode_int(&len, evbuf) == -1)
+ return (-1);
+
+ if (evbuffer_get_length(evbuf) < len)
+ return (-1);
+
+ result = decode_int64_internal(pinteger, evbuf, 0);
+ evbuffer_drain(evbuf, len);
+ if (result < 0 || (size_t)result > len) /* XXX Should this be != rather than > ?*/
+ return (-1);
+ else
+ return result;
+}
+
+/* Unmarshal a fixed length tag */
+
+int
+evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag, void *data,
+ size_t len)
+{
+ ev_uint32_t tag;
+ int tag_len;
+
+ /* Now unmarshal a tag and check that it matches the tag we want */
+ if ((tag_len = evtag_unmarshal_header(src, &tag)) < 0 ||
+ tag != need_tag)
+ return (-1);
+
+ if ((size_t)tag_len != len)
+ return (-1);
+
+ evbuffer_remove(src, data, len);
+ return (0);
+}
+
+int
+evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ char **pstring)
+{
+ ev_uint32_t tag;
+ int tag_len;
+
+ if ((tag_len = evtag_unmarshal_header(evbuf, &tag)) == -1 ||
+ tag != need_tag)
+ return (-1);
+
+ *pstring = mm_malloc(tag_len + 1);
+ if (*pstring == NULL) {
+ event_warn("%s: malloc", __func__);
+ return -1;
+ }
+ evbuffer_remove(evbuf, *pstring, tag_len);
+ (*pstring)[tag_len] = '\0';
+
+ return (0);
+}
+
+int
+evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ struct timeval *ptv)
+{
+ ev_uint32_t tag;
+ ev_uint32_t integer;
+ int len, offset, offset2;
+ int result = -1;
+
+ if ((len = evtag_unmarshal_header(evbuf, &tag)) == -1)
+ return (-1);
+ if (tag != need_tag)
+ goto done;
+ if ((offset = decode_int_internal(&integer, evbuf, 0)) == -1)
+ goto done;
+ ptv->tv_sec = integer;
+ if ((offset2 = decode_int_internal(&integer, evbuf, offset)) == -1)
+ goto done;
+ ptv->tv_usec = integer;
+ if (offset + offset2 > len) /* XXX Should this be != instead of > ? */
+ goto done;
+
+ result = 0;
+ done:
+ evbuffer_drain(evbuf, len);
+ return result;
+}
diff --git a/ipc/chromium/src/third_party/libevent/evmap-internal.h b/ipc/chromium/src/third_party/libevent/evmap-internal.h
new file mode 100644
index 0000000000..dfc81d5087
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evmap-internal.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVMAP_INTERNAL_H_INCLUDED_
+#define EVMAP_INTERNAL_H_INCLUDED_
+
+/** @file evmap-internal.h
+ *
+ * An event_map is a utility structure to map each fd or signal to zero or
+ * more events. Functions to manipulate event_maps should only be used from
+ * inside libevent. They generally need to hold the lock on the corresponding
+ * event_base.
+ **/
+
+struct event_base;
+struct event;
+
+/** Initialize an event_map for use.
+ */
+void evmap_io_initmap_(struct event_io_map* ctx);
+void evmap_signal_initmap_(struct event_signal_map* ctx);
+
+/** Remove all entries from an event_map.
+
+ @param ctx the map to clear.
+ */
+void evmap_io_clear_(struct event_io_map* ctx);
+void evmap_signal_clear_(struct event_signal_map* ctx);
+
+/** Add an IO event (some combination of EV_READ or EV_WRITE) to an
+ event_base's list of events on a given file descriptor, and tell the
+ underlying eventops about the fd if its state has changed.
+
+ Requires that ev is not already added.
+
+ @param base the event_base to operate on.
+ @param fd the file descriptor corresponding to ev.
+ @param ev the event to add.
+*/
+int evmap_io_add_(struct event_base *base, evutil_socket_t fd, struct event *ev);
+/** Remove an IO event (some combination of EV_READ or EV_WRITE) to an
+ event_base's list of events on a given file descriptor, and tell the
+ underlying eventops about the fd if its state has changed.
+
+ @param base the event_base to operate on.
+ @param fd the file descriptor corresponding to ev.
+ @param ev the event to remove.
+ */
+int evmap_io_del_(struct event_base *base, evutil_socket_t fd, struct event *ev);
+/** Active the set of events waiting on an event_base for a given fd.
+
+ @param base the event_base to operate on.
+ @param fd the file descriptor that has become active.
+ @param events a bitmask of EV_READ|EV_WRITE|EV_ET.
+*/
+void evmap_io_active_(struct event_base *base, evutil_socket_t fd, short events);
+
+
+/* These functions behave in the same way as evmap_io_*, except they work on
+ * signals rather than fds. signals use a linear map everywhere; fds use
+ * either a linear map or a hashtable. */
+int evmap_signal_add_(struct event_base *base, int signum, struct event *ev);
+int evmap_signal_del_(struct event_base *base, int signum, struct event *ev);
+void evmap_signal_active_(struct event_base *base, evutil_socket_t signum, int ncalls);
+
+/* Return the fdinfo object associated with a given fd. If the fd has no
+ * events associated with it, the result may be NULL.
+ */
+void *evmap_io_get_fdinfo_(struct event_io_map *ctx, evutil_socket_t fd);
+
+/* Helper for event_reinit(): Tell the backend to re-add every fd and signal
+ * for which we have a pending event.
+ */
+int evmap_reinit_(struct event_base *base);
+
+/* Helper for event_base_free(): Call event_del() on every pending fd and
+ * signal event.
+ */
+void evmap_delete_all_(struct event_base *base);
+
+/* Helper for event_base_assert_ok_(): Check referential integrity of the
+ * evmaps.
+ */
+void evmap_check_integrity_(struct event_base *base);
+
+/* Helper: Call fn on every fd or signal event, passing as its arguments the
+ * provided event_base, the event, and arg. If fn returns 0, process the next
+ * event. If it returns any other value, return that value and process no
+ * more events.
+ */
+int evmap_foreach_event_(struct event_base *base,
+ event_base_foreach_event_cb fn,
+ void *arg);
+
+#endif /* EVMAP_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/evmap.c b/ipc/chromium/src/third_party/libevent/evmap.c
new file mode 100644
index 0000000000..e4e35c6877
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evmap.c
@@ -0,0 +1,1062 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#if !defined(_WIN32) && defined(EVENT__HAVE_SYS_TIME_H)
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#include <signal.h>
+#include <string.h>
+#include <time.h>
+
+#include "event-internal.h"
+#include "evmap-internal.h"
+#include "mm-internal.h"
+#include "changelist-internal.h"
+
+/** An entry for an evmap_io list: notes all the events that want to read or
+ write on a given fd, and the number of each.
+ */
+struct evmap_io {
+ struct event_dlist events;
+ ev_uint16_t nread;
+ ev_uint16_t nwrite;
+ ev_uint16_t nclose;
+};
+
+/* An entry for an evmap_signal list: notes all the events that want to know
+ when a signal triggers. */
+struct evmap_signal {
+ struct event_dlist events;
+};
+
+/* On some platforms, fds start at 0 and increment by 1 as they are
+ allocated, and old numbers get used. For these platforms, we
+ implement io maps just like signal maps: as an array of pointers to
+ struct evmap_io. But on other platforms (windows), sockets are not
+ 0-indexed, not necessarily consecutive, and not necessarily reused.
+ There, we use a hashtable to implement evmap_io.
+*/
+#ifdef EVMAP_USE_HT
+struct event_map_entry {
+ HT_ENTRY(event_map_entry) map_node;
+ evutil_socket_t fd;
+ union { /* This is a union in case we need to make more things that can
+ be in the hashtable. */
+ struct evmap_io evmap_io;
+ } ent;
+};
+
+/* Helper used by the event_io_map hashtable code; tries to return a good hash
+ * of the fd in e->fd. */
+static inline unsigned
+hashsocket(struct event_map_entry *e)
+{
+ /* On win32, in practice, the low 2-3 bits of a SOCKET seem not to
+ * matter. Our hashtable implementation really likes low-order bits,
+ * though, so let's do the rotate-and-add trick. */
+ unsigned h = (unsigned) e->fd;
+ h += (h >> 2) | (h << 30);
+ return h;
+}
+
+/* Helper used by the event_io_map hashtable code; returns true iff e1 and e2
+ * have the same e->fd. */
+static inline int
+eqsocket(struct event_map_entry *e1, struct event_map_entry *e2)
+{
+ return e1->fd == e2->fd;
+}
+
+HT_PROTOTYPE(event_io_map, event_map_entry, map_node, hashsocket, eqsocket)
+HT_GENERATE(event_io_map, event_map_entry, map_node, hashsocket, eqsocket,
+ 0.5, mm_malloc, mm_realloc, mm_free)
+
+#define GET_IO_SLOT(x, map, slot, type) \
+ do { \
+ struct event_map_entry key_, *ent_; \
+ key_.fd = slot; \
+ ent_ = HT_FIND(event_io_map, map, &key_); \
+ (x) = ent_ ? &ent_->ent.type : NULL; \
+ } while (0);
+
+#define GET_IO_SLOT_AND_CTOR(x, map, slot, type, ctor, fdinfo_len) \
+ do { \
+ struct event_map_entry key_, *ent_; \
+ key_.fd = slot; \
+ HT_FIND_OR_INSERT_(event_io_map, map_node, hashsocket, map, \
+ event_map_entry, &key_, ptr, \
+ { \
+ ent_ = *ptr; \
+ }, \
+ { \
+ ent_ = mm_calloc(1,sizeof(struct event_map_entry)+fdinfo_len); \
+ if (EVUTIL_UNLIKELY(ent_ == NULL)) \
+ return (-1); \
+ ent_->fd = slot; \
+ (ctor)(&ent_->ent.type); \
+ HT_FOI_INSERT_(map_node, map, &key_, ent_, ptr) \
+ }); \
+ (x) = &ent_->ent.type; \
+ } while (0)
+
+void evmap_io_initmap_(struct event_io_map *ctx)
+{
+ HT_INIT(event_io_map, ctx);
+}
+
+void evmap_io_clear_(struct event_io_map *ctx)
+{
+ struct event_map_entry **ent, **next, *this;
+ for (ent = HT_START(event_io_map, ctx); ent; ent = next) {
+ this = *ent;
+ next = HT_NEXT_RMV(event_io_map, ctx, ent);
+ mm_free(this);
+ }
+ HT_CLEAR(event_io_map, ctx); /* remove all storage held by the ctx. */
+}
+#endif
+
+/* Set the variable 'x' to the field in event_map 'map' with fields of type
+ 'struct type *' corresponding to the fd or signal 'slot'. Set 'x' to NULL
+ if there are no entries for 'slot'. Does no bounds-checking. */
+#define GET_SIGNAL_SLOT(x, map, slot, type) \
+ (x) = (struct type *)((map)->entries[slot])
+/* As GET_SLOT, but construct the entry for 'slot' if it is not present,
+ by allocating enough memory for a 'struct type', and initializing the new
+ value by calling the function 'ctor' on it. Makes the function
+ return -1 on allocation failure.
+ */
+#define GET_SIGNAL_SLOT_AND_CTOR(x, map, slot, type, ctor, fdinfo_len) \
+ do { \
+ if ((map)->entries[slot] == NULL) { \
+ (map)->entries[slot] = \
+ mm_calloc(1,sizeof(struct type)+fdinfo_len); \
+ if (EVUTIL_UNLIKELY((map)->entries[slot] == NULL)) \
+ return (-1); \
+ (ctor)((struct type *)(map)->entries[slot]); \
+ } \
+ (x) = (struct type *)((map)->entries[slot]); \
+ } while (0)
+
+/* If we aren't using hashtables, then define the IO_SLOT macros and functions
+ as thin aliases over the SIGNAL_SLOT versions. */
+#ifndef EVMAP_USE_HT
+#define GET_IO_SLOT(x,map,slot,type) GET_SIGNAL_SLOT(x,map,slot,type)
+#define GET_IO_SLOT_AND_CTOR(x,map,slot,type,ctor,fdinfo_len) \
+ GET_SIGNAL_SLOT_AND_CTOR(x,map,slot,type,ctor,fdinfo_len)
+#define FDINFO_OFFSET sizeof(struct evmap_io)
+void
+evmap_io_initmap_(struct event_io_map* ctx)
+{
+ evmap_signal_initmap_(ctx);
+}
+void
+evmap_io_clear_(struct event_io_map* ctx)
+{
+ evmap_signal_clear_(ctx);
+}
+#endif
+
+
+/** Expand 'map' with new entries of width 'msize' until it is big enough
+ to store a value in 'slot'.
+ */
+static int
+evmap_make_space(struct event_signal_map *map, int slot, int msize)
+{
+ if (map->nentries <= slot) {
+ int nentries = map->nentries ? map->nentries : 32;
+ void **tmp;
+
+ if (slot > INT_MAX / 2)
+ return (-1);
+
+ while (nentries <= slot)
+ nentries <<= 1;
+
+ if (nentries > INT_MAX / msize)
+ return (-1);
+
+ tmp = (void **)mm_realloc(map->entries, nentries * msize);
+ if (tmp == NULL)
+ return (-1);
+
+ memset(&tmp[map->nentries], 0,
+ (nentries - map->nentries) * msize);
+
+ map->nentries = nentries;
+ map->entries = tmp;
+ }
+
+ return (0);
+}
+
+void
+evmap_signal_initmap_(struct event_signal_map *ctx)
+{
+ ctx->nentries = 0;
+ ctx->entries = NULL;
+}
+
+void
+evmap_signal_clear_(struct event_signal_map *ctx)
+{
+ if (ctx->entries != NULL) {
+ int i;
+ for (i = 0; i < ctx->nentries; ++i) {
+ if (ctx->entries[i] != NULL)
+ mm_free(ctx->entries[i]);
+ }
+ mm_free(ctx->entries);
+ ctx->entries = NULL;
+ }
+ ctx->nentries = 0;
+}
+
+
+/* code specific to file descriptors */
+
+/** Constructor for struct evmap_io */
+static void
+evmap_io_init(struct evmap_io *entry)
+{
+ LIST_INIT(&entry->events);
+ entry->nread = 0;
+ entry->nwrite = 0;
+ entry->nclose = 0;
+}
+
+
+/* return -1 on error, 0 on success if nothing changed in the event backend,
+ * and 1 on success if something did. */
+int
+evmap_io_add_(struct event_base *base, evutil_socket_t fd, struct event *ev)
+{
+ const struct eventop *evsel = base->evsel;
+ struct event_io_map *io = &base->io;
+ struct evmap_io *ctx = NULL;
+ int nread, nwrite, nclose, retval = 0;
+ short res = 0, old = 0;
+ struct event *old_ev;
+
+ EVUTIL_ASSERT(fd == ev->ev_fd);
+
+ if (fd < 0)
+ return 0;
+
+#ifndef EVMAP_USE_HT
+ if (fd >= io->nentries) {
+ if (evmap_make_space(io, fd, sizeof(struct evmap_io *)) == -1)
+ return (-1);
+ }
+#endif
+ GET_IO_SLOT_AND_CTOR(ctx, io, fd, evmap_io, evmap_io_init,
+ evsel->fdinfo_len);
+
+ nread = ctx->nread;
+ nwrite = ctx->nwrite;
+ nclose = ctx->nclose;
+
+ if (nread)
+ old |= EV_READ;
+ if (nwrite)
+ old |= EV_WRITE;
+ if (nclose)
+ old |= EV_CLOSED;
+
+ if (ev->ev_events & EV_READ) {
+ if (++nread == 1)
+ res |= EV_READ;
+ }
+ if (ev->ev_events & EV_WRITE) {
+ if (++nwrite == 1)
+ res |= EV_WRITE;
+ }
+ if (ev->ev_events & EV_CLOSED) {
+ if (++nclose == 1)
+ res |= EV_CLOSED;
+ }
+ if (EVUTIL_UNLIKELY(nread > 0xffff || nwrite > 0xffff || nclose > 0xffff)) {
+ event_warnx("Too many events reading or writing on fd %d",
+ (int)fd);
+ return -1;
+ }
+ if (EVENT_DEBUG_MODE_IS_ON() &&
+ (old_ev = LIST_FIRST(&ctx->events)) &&
+ (old_ev->ev_events&EV_ET) != (ev->ev_events&EV_ET)) {
+ event_warnx("Tried to mix edge-triggered and non-edge-triggered"
+ " events on fd %d", (int)fd);
+ return -1;
+ }
+
+ if (res) {
+ void *extra = ((char*)ctx) + sizeof(struct evmap_io);
+ /* XXX(niels): we cannot mix edge-triggered and
+ * level-triggered, we should probably assert on
+ * this. */
+ if (evsel->add(base, ev->ev_fd,
+ old, (ev->ev_events & EV_ET) | res, extra) == -1)
+ return (-1);
+ retval = 1;
+ }
+
+ ctx->nread = (ev_uint16_t) nread;
+ ctx->nwrite = (ev_uint16_t) nwrite;
+ ctx->nclose = (ev_uint16_t) nclose;
+ LIST_INSERT_HEAD(&ctx->events, ev, ev_io_next);
+
+ return (retval);
+}
+
+/* return -1 on error, 0 on success if nothing changed in the event backend,
+ * and 1 on success if something did. */
+int
+evmap_io_del_(struct event_base *base, evutil_socket_t fd, struct event *ev)
+{
+ const struct eventop *evsel = base->evsel;
+ struct event_io_map *io = &base->io;
+ struct evmap_io *ctx;
+ int nread, nwrite, nclose, retval = 0;
+ short res = 0, old = 0;
+
+ if (fd < 0)
+ return 0;
+
+ EVUTIL_ASSERT(fd == ev->ev_fd);
+
+#ifndef EVMAP_USE_HT
+ if (fd >= io->nentries)
+ return (-1);
+#endif
+
+ GET_IO_SLOT(ctx, io, fd, evmap_io);
+
+ nread = ctx->nread;
+ nwrite = ctx->nwrite;
+ nclose = ctx->nclose;
+
+ if (nread)
+ old |= EV_READ;
+ if (nwrite)
+ old |= EV_WRITE;
+ if (nclose)
+ old |= EV_CLOSED;
+
+ if (ev->ev_events & EV_READ) {
+ if (--nread == 0)
+ res |= EV_READ;
+ EVUTIL_ASSERT(nread >= 0);
+ }
+ if (ev->ev_events & EV_WRITE) {
+ if (--nwrite == 0)
+ res |= EV_WRITE;
+ EVUTIL_ASSERT(nwrite >= 0);
+ }
+ if (ev->ev_events & EV_CLOSED) {
+ if (--nclose == 0)
+ res |= EV_CLOSED;
+ EVUTIL_ASSERT(nclose >= 0);
+ }
+
+ if (res) {
+ void *extra = ((char*)ctx) + sizeof(struct evmap_io);
+ if (evsel->del(base, ev->ev_fd,
+ old, (ev->ev_events & EV_ET) | res, extra) == -1) {
+ retval = -1;
+ } else {
+ retval = 1;
+ }
+ }
+
+ ctx->nread = nread;
+ ctx->nwrite = nwrite;
+ ctx->nclose = nclose;
+ LIST_REMOVE(ev, ev_io_next);
+
+ return (retval);
+}
+
+void
+evmap_io_active_(struct event_base *base, evutil_socket_t fd, short events)
+{
+ struct event_io_map *io = &base->io;
+ struct evmap_io *ctx;
+ struct event *ev;
+
+#ifndef EVMAP_USE_HT
+ if (fd < 0 || fd >= io->nentries)
+ return;
+#endif
+ GET_IO_SLOT(ctx, io, fd, evmap_io);
+
+ if (NULL == ctx)
+ return;
+ LIST_FOREACH(ev, &ctx->events, ev_io_next) {
+ if (ev->ev_events & (events & ~EV_ET))
+ event_active_nolock_(ev, ev->ev_events & events, 1);
+ }
+}
+
+/* code specific to signals */
+
+static void
+evmap_signal_init(struct evmap_signal *entry)
+{
+ LIST_INIT(&entry->events);
+}
+
+
+int
+evmap_signal_add_(struct event_base *base, int sig, struct event *ev)
+{
+ const struct eventop *evsel = base->evsigsel;
+ struct event_signal_map *map = &base->sigmap;
+ struct evmap_signal *ctx = NULL;
+
+ if (sig < 0 || sig >= NSIG)
+ return (-1);
+
+ if (sig >= map->nentries) {
+ if (evmap_make_space(
+ map, sig, sizeof(struct evmap_signal *)) == -1)
+ return (-1);
+ }
+ GET_SIGNAL_SLOT_AND_CTOR(ctx, map, sig, evmap_signal, evmap_signal_init,
+ base->evsigsel->fdinfo_len);
+
+ if (LIST_EMPTY(&ctx->events)) {
+ if (evsel->add(base, ev->ev_fd, 0, EV_SIGNAL, NULL)
+ == -1)
+ return (-1);
+ }
+
+ LIST_INSERT_HEAD(&ctx->events, ev, ev_signal_next);
+
+ return (1);
+}
+
+int
+evmap_signal_del_(struct event_base *base, int sig, struct event *ev)
+{
+ const struct eventop *evsel = base->evsigsel;
+ struct event_signal_map *map = &base->sigmap;
+ struct evmap_signal *ctx;
+
+ if (sig < 0 || sig >= map->nentries)
+ return (-1);
+
+ GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
+
+ LIST_REMOVE(ev, ev_signal_next);
+
+ if (LIST_FIRST(&ctx->events) == NULL) {
+ if (evsel->del(base, ev->ev_fd, 0, EV_SIGNAL, NULL) == -1)
+ return (-1);
+ }
+
+ return (1);
+}
+
+void
+evmap_signal_active_(struct event_base *base, evutil_socket_t sig, int ncalls)
+{
+ struct event_signal_map *map = &base->sigmap;
+ struct evmap_signal *ctx;
+ struct event *ev;
+
+ if (sig < 0 || sig >= map->nentries)
+ return;
+ GET_SIGNAL_SLOT(ctx, map, sig, evmap_signal);
+
+ if (!ctx)
+ return;
+ LIST_FOREACH(ev, &ctx->events, ev_signal_next)
+ event_active_nolock_(ev, EV_SIGNAL, ncalls);
+}
+
+void *
+evmap_io_get_fdinfo_(struct event_io_map *map, evutil_socket_t fd)
+{
+ struct evmap_io *ctx;
+ GET_IO_SLOT(ctx, map, fd, evmap_io);
+ if (ctx)
+ return ((char*)ctx) + sizeof(struct evmap_io);
+ else
+ return NULL;
+}
+
+/* Callback type for evmap_io_foreach_fd */
+typedef int (*evmap_io_foreach_fd_cb)(
+ struct event_base *, evutil_socket_t, struct evmap_io *, void *);
+
+/* Multipurpose helper function: Iterate over every file descriptor event_base
+ * for which we could have EV_READ or EV_WRITE events. For each such fd, call
+ * fn(base, signum, evmap_io, arg), where fn is the user-provided
+ * function, base is the event_base, signum is the signal number, evmap_io
+ * is an evmap_io structure containing a list of events pending on the
+ * file descriptor, and arg is the user-supplied argument.
+ *
+ * If fn returns 0, continue on to the next signal. Otherwise, return the same
+ * value that fn returned.
+ *
+ * Note that there is no guarantee that the file descriptors will be processed
+ * in any particular order.
+ */
+static int
+evmap_io_foreach_fd(struct event_base *base,
+ evmap_io_foreach_fd_cb fn,
+ void *arg)
+{
+ evutil_socket_t fd;
+ struct event_io_map *iomap = &base->io;
+ int r = 0;
+#ifdef EVMAP_USE_HT
+ struct event_map_entry **mapent;
+ HT_FOREACH(mapent, event_io_map, iomap) {
+ struct evmap_io *ctx = &(*mapent)->ent.evmap_io;
+ fd = (*mapent)->fd;
+#else
+ for (fd = 0; fd < iomap->nentries; ++fd) {
+ struct evmap_io *ctx = iomap->entries[fd];
+ if (!ctx)
+ continue;
+#endif
+ if ((r = fn(base, fd, ctx, arg)))
+ break;
+ }
+ return r;
+}
+
+/* Callback type for evmap_signal_foreach_signal */
+typedef int (*evmap_signal_foreach_signal_cb)(
+ struct event_base *, int, struct evmap_signal *, void *);
+
+/* Multipurpose helper function: Iterate over every signal number in the
+ * event_base for which we could have signal events. For each such signal,
+ * call fn(base, signum, evmap_signal, arg), where fn is the user-provided
+ * function, base is the event_base, signum is the signal number, evmap_signal
+ * is an evmap_signal structure containing a list of events pending on the
+ * signal, and arg is the user-supplied argument.
+ *
+ * If fn returns 0, continue on to the next signal. Otherwise, return the same
+ * value that fn returned.
+ */
+static int
+evmap_signal_foreach_signal(struct event_base *base,
+ evmap_signal_foreach_signal_cb fn,
+ void *arg)
+{
+ struct event_signal_map *sigmap = &base->sigmap;
+ int r = 0;
+ int signum;
+
+ for (signum = 0; signum < sigmap->nentries; ++signum) {
+ struct evmap_signal *ctx = sigmap->entries[signum];
+ if (!ctx)
+ continue;
+ if ((r = fn(base, signum, ctx, arg)))
+ break;
+ }
+ return r;
+}
+
+/* Helper for evmap_reinit_: tell the backend to add every fd for which we have
+ * pending events, with the appropriate combination of EV_READ, EV_WRITE, and
+ * EV_ET. */
+static int
+evmap_io_reinit_iter_fn(struct event_base *base, evutil_socket_t fd,
+ struct evmap_io *ctx, void *arg)
+{
+ const struct eventop *evsel = base->evsel;
+ void *extra;
+ int *result = arg;
+ short events = 0;
+ struct event *ev;
+ EVUTIL_ASSERT(ctx);
+
+ extra = ((char*)ctx) + sizeof(struct evmap_io);
+ if (ctx->nread)
+ events |= EV_READ;
+ if (ctx->nwrite)
+ events |= EV_WRITE;
+ if (ctx->nclose)
+ events |= EV_CLOSED;
+ if (evsel->fdinfo_len)
+ memset(extra, 0, evsel->fdinfo_len);
+ if (events &&
+ (ev = LIST_FIRST(&ctx->events)) &&
+ (ev->ev_events & EV_ET))
+ events |= EV_ET;
+ if (evsel->add(base, fd, 0, events, extra) == -1)
+ *result = -1;
+
+ return 0;
+}
+
+/* Helper for evmap_reinit_: tell the backend to add every signal for which we
+ * have pending events. */
+static int
+evmap_signal_reinit_iter_fn(struct event_base *base,
+ int signum, struct evmap_signal *ctx, void *arg)
+{
+ const struct eventop *evsel = base->evsigsel;
+ int *result = arg;
+
+ if (!LIST_EMPTY(&ctx->events)) {
+ if (evsel->add(base, signum, 0, EV_SIGNAL, NULL) == -1)
+ *result = -1;
+ }
+ return 0;
+}
+
+int
+evmap_reinit_(struct event_base *base)
+{
+ int result = 0;
+
+ evmap_io_foreach_fd(base, evmap_io_reinit_iter_fn, &result);
+ if (result < 0)
+ return -1;
+ evmap_signal_foreach_signal(base, evmap_signal_reinit_iter_fn, &result);
+ if (result < 0)
+ return -1;
+ return 0;
+}
+
+/* Helper for evmap_delete_all_: delete every event in an event_dlist. */
+static int
+delete_all_in_dlist(struct event_dlist *dlist)
+{
+ struct event *ev;
+ while ((ev = LIST_FIRST(dlist)))
+ event_del(ev);
+ return 0;
+}
+
+/* Helper for evmap_delete_all_: delete every event pending on an fd. */
+static int
+evmap_io_delete_all_iter_fn(struct event_base *base, evutil_socket_t fd,
+ struct evmap_io *io_info, void *arg)
+{
+ return delete_all_in_dlist(&io_info->events);
+}
+
+/* Helper for evmap_delete_all_: delete every event pending on a signal. */
+static int
+evmap_signal_delete_all_iter_fn(struct event_base *base, int signum,
+ struct evmap_signal *sig_info, void *arg)
+{
+ return delete_all_in_dlist(&sig_info->events);
+}
+
+void
+evmap_delete_all_(struct event_base *base)
+{
+ evmap_signal_foreach_signal(base, evmap_signal_delete_all_iter_fn, NULL);
+ evmap_io_foreach_fd(base, evmap_io_delete_all_iter_fn, NULL);
+}
+
+/** Per-fd structure for use with changelists. It keeps track, for each fd or
+ * signal using the changelist, of where its entry in the changelist is.
+ */
+struct event_changelist_fdinfo {
+ int idxplus1; /* this is the index +1, so that memset(0) will make it
+ * a no-such-element */
+};
+
+void
+event_changelist_init_(struct event_changelist *changelist)
+{
+ changelist->changes = NULL;
+ changelist->changes_size = 0;
+ changelist->n_changes = 0;
+}
+
+/** Helper: return the changelist_fdinfo corresponding to a given change. */
+static inline struct event_changelist_fdinfo *
+event_change_get_fdinfo(struct event_base *base,
+ const struct event_change *change)
+{
+ char *ptr;
+ if (change->read_change & EV_CHANGE_SIGNAL) {
+ struct evmap_signal *ctx;
+ GET_SIGNAL_SLOT(ctx, &base->sigmap, change->fd, evmap_signal);
+ ptr = ((char*)ctx) + sizeof(struct evmap_signal);
+ } else {
+ struct evmap_io *ctx;
+ GET_IO_SLOT(ctx, &base->io, change->fd, evmap_io);
+ ptr = ((char*)ctx) + sizeof(struct evmap_io);
+ }
+ return (void*)ptr;
+}
+
+/** Callback helper for event_changelist_assert_ok */
+static int
+event_changelist_assert_ok_foreach_iter_fn(
+ struct event_base *base,
+ evutil_socket_t fd, struct evmap_io *io, void *arg)
+{
+ struct event_changelist *changelist = &base->changelist;
+ struct event_changelist_fdinfo *f;
+ f = (void*)
+ ( ((char*)io) + sizeof(struct evmap_io) );
+ if (f->idxplus1) {
+ struct event_change *c = &changelist->changes[f->idxplus1 - 1];
+ EVUTIL_ASSERT(c->fd == fd);
+ }
+ return 0;
+}
+
+/** Make sure that the changelist is consistent with the evmap structures. */
+static void
+event_changelist_assert_ok(struct event_base *base)
+{
+ int i;
+ struct event_changelist *changelist = &base->changelist;
+
+ EVUTIL_ASSERT(changelist->changes_size >= changelist->n_changes);
+ for (i = 0; i < changelist->n_changes; ++i) {
+ struct event_change *c = &changelist->changes[i];
+ struct event_changelist_fdinfo *f;
+ EVUTIL_ASSERT(c->fd >= 0);
+ f = event_change_get_fdinfo(base, c);
+ EVUTIL_ASSERT(f);
+ EVUTIL_ASSERT(f->idxplus1 == i + 1);
+ }
+
+ evmap_io_foreach_fd(base,
+ event_changelist_assert_ok_foreach_iter_fn,
+ NULL);
+}
+
+#ifdef DEBUG_CHANGELIST
+#define event_changelist_check(base) event_changelist_assert_ok((base))
+#else
+#define event_changelist_check(base) ((void)0)
+#endif
+
+void
+event_changelist_remove_all_(struct event_changelist *changelist,
+ struct event_base *base)
+{
+ int i;
+
+ event_changelist_check(base);
+
+ for (i = 0; i < changelist->n_changes; ++i) {
+ struct event_change *ch = &changelist->changes[i];
+ struct event_changelist_fdinfo *fdinfo =
+ event_change_get_fdinfo(base, ch);
+ EVUTIL_ASSERT(fdinfo->idxplus1 == i + 1);
+ fdinfo->idxplus1 = 0;
+ }
+
+ changelist->n_changes = 0;
+
+ event_changelist_check(base);
+}
+
+void
+event_changelist_freemem_(struct event_changelist *changelist)
+{
+ if (changelist->changes)
+ mm_free(changelist->changes);
+ event_changelist_init_(changelist); /* zero it all out. */
+}
+
+/** Increase the size of 'changelist' to hold more changes. */
+static int
+event_changelist_grow(struct event_changelist *changelist)
+{
+ int new_size;
+ struct event_change *new_changes;
+ if (changelist->changes_size < 64)
+ new_size = 64;
+ else
+ new_size = changelist->changes_size * 2;
+
+ new_changes = mm_realloc(changelist->changes,
+ new_size * sizeof(struct event_change));
+
+ if (EVUTIL_UNLIKELY(new_changes == NULL))
+ return (-1);
+
+ changelist->changes = new_changes;
+ changelist->changes_size = new_size;
+
+ return (0);
+}
+
+/** Return a pointer to the changelist entry for the file descriptor or signal
+ * 'fd', whose fdinfo is 'fdinfo'. If none exists, construct it, setting its
+ * old_events field to old_events.
+ */
+static struct event_change *
+event_changelist_get_or_construct(struct event_changelist *changelist,
+ evutil_socket_t fd,
+ short old_events,
+ struct event_changelist_fdinfo *fdinfo)
+{
+ struct event_change *change;
+
+ if (fdinfo->idxplus1 == 0) {
+ int idx;
+ EVUTIL_ASSERT(changelist->n_changes <= changelist->changes_size);
+
+ if (changelist->n_changes == changelist->changes_size) {
+ if (event_changelist_grow(changelist) < 0)
+ return NULL;
+ }
+
+ idx = changelist->n_changes++;
+ change = &changelist->changes[idx];
+ fdinfo->idxplus1 = idx + 1;
+
+ memset(change, 0, sizeof(struct event_change));
+ change->fd = fd;
+ change->old_events = old_events;
+ } else {
+ change = &changelist->changes[fdinfo->idxplus1 - 1];
+ EVUTIL_ASSERT(change->fd == fd);
+ }
+ return change;
+}
+
+int
+event_changelist_add_(struct event_base *base, evutil_socket_t fd, short old, short events,
+ void *p)
+{
+ struct event_changelist *changelist = &base->changelist;
+ struct event_changelist_fdinfo *fdinfo = p;
+ struct event_change *change;
+ ev_uint8_t evchange = EV_CHANGE_ADD | (events & (EV_ET|EV_PERSIST|EV_SIGNAL));
+
+ event_changelist_check(base);
+
+ change = event_changelist_get_or_construct(changelist, fd, old, fdinfo);
+ if (!change)
+ return -1;
+
+ /* An add replaces any previous delete, but doesn't result in a no-op,
+ * since the delete might fail (because the fd had been closed since
+ * the last add, for instance. */
+
+ if (events & (EV_READ|EV_SIGNAL))
+ change->read_change = evchange;
+ if (events & EV_WRITE)
+ change->write_change = evchange;
+ if (events & EV_CLOSED)
+ change->close_change = evchange;
+
+ event_changelist_check(base);
+ return (0);
+}
+
+int
+event_changelist_del_(struct event_base *base, evutil_socket_t fd, short old, short events,
+ void *p)
+{
+ struct event_changelist *changelist = &base->changelist;
+ struct event_changelist_fdinfo *fdinfo = p;
+ struct event_change *change;
+ ev_uint8_t del = EV_CHANGE_DEL | (events & EV_ET);
+
+ event_changelist_check(base);
+ change = event_changelist_get_or_construct(changelist, fd, old, fdinfo);
+ event_changelist_check(base);
+ if (!change)
+ return -1;
+
+ /* A delete on an event set that doesn't contain the event to be
+ deleted produces a no-op. This effectively emoves any previous
+ uncommitted add, rather than replacing it: on those platforms where
+ "add, delete, dispatch" is not the same as "no-op, dispatch", we
+ want the no-op behavior.
+
+ If we have a no-op item, we could remove it it from the list
+ entirely, but really there's not much point: skipping the no-op
+ change when we do the dispatch later is far cheaper than rejuggling
+ the array now.
+
+ As this stands, it also lets through deletions of events that are
+ not currently set.
+ */
+
+ if (events & (EV_READ|EV_SIGNAL)) {
+ if (!(change->old_events & (EV_READ | EV_SIGNAL)))
+ change->read_change = 0;
+ else
+ change->read_change = del;
+ }
+ if (events & EV_WRITE) {
+ if (!(change->old_events & EV_WRITE))
+ change->write_change = 0;
+ else
+ change->write_change = del;
+ }
+ if (events & EV_CLOSED) {
+ if (!(change->old_events & EV_CLOSED))
+ change->close_change = 0;
+ else
+ change->close_change = del;
+ }
+
+ event_changelist_check(base);
+ return (0);
+}
+
+/* Helper for evmap_check_integrity_: verify that all of the events pending on
+ * given fd are set up correctly, and that the nread and nwrite counts on that
+ * fd are correct. */
+static int
+evmap_io_check_integrity_fn(struct event_base *base, evutil_socket_t fd,
+ struct evmap_io *io_info, void *arg)
+{
+ struct event *ev;
+ int n_read = 0, n_write = 0, n_close = 0;
+
+ /* First, make sure the list itself isn't corrupt. Otherwise,
+ * running LIST_FOREACH could be an exciting adventure. */
+ EVUTIL_ASSERT_LIST_OK(&io_info->events, event, ev_io_next);
+
+ LIST_FOREACH(ev, &io_info->events, ev_io_next) {
+ EVUTIL_ASSERT(ev->ev_flags & EVLIST_INSERTED);
+ EVUTIL_ASSERT(ev->ev_fd == fd);
+ EVUTIL_ASSERT(!(ev->ev_events & EV_SIGNAL));
+ EVUTIL_ASSERT((ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED)));
+ if (ev->ev_events & EV_READ)
+ ++n_read;
+ if (ev->ev_events & EV_WRITE)
+ ++n_write;
+ if (ev->ev_events & EV_CLOSED)
+ ++n_close;
+ }
+
+ EVUTIL_ASSERT(n_read == io_info->nread);
+ EVUTIL_ASSERT(n_write == io_info->nwrite);
+ EVUTIL_ASSERT(n_close == io_info->nclose);
+
+ return 0;
+}
+
+/* Helper for evmap_check_integrity_: verify that all of the events pending
+ * on given signal are set up correctly. */
+static int
+evmap_signal_check_integrity_fn(struct event_base *base,
+ int signum, struct evmap_signal *sig_info, void *arg)
+{
+ struct event *ev;
+ /* First, make sure the list itself isn't corrupt. */
+ EVUTIL_ASSERT_LIST_OK(&sig_info->events, event, ev_signal_next);
+
+ LIST_FOREACH(ev, &sig_info->events, ev_io_next) {
+ EVUTIL_ASSERT(ev->ev_flags & EVLIST_INSERTED);
+ EVUTIL_ASSERT(ev->ev_fd == signum);
+ EVUTIL_ASSERT((ev->ev_events & EV_SIGNAL));
+ EVUTIL_ASSERT(!(ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED)));
+ }
+ return 0;
+}
+
+void
+evmap_check_integrity_(struct event_base *base)
+{
+ evmap_io_foreach_fd(base, evmap_io_check_integrity_fn, NULL);
+ evmap_signal_foreach_signal(base, evmap_signal_check_integrity_fn, NULL);
+
+ if (base->evsel->add == event_changelist_add_)
+ event_changelist_assert_ok(base);
+}
+
+/* Helper type for evmap_foreach_event_: Bundles a function to call on every
+ * event, and the user-provided void* to use as its third argument. */
+struct evmap_foreach_event_helper {
+ event_base_foreach_event_cb fn;
+ void *arg;
+};
+
+/* Helper for evmap_foreach_event_: calls a provided function on every event
+ * pending on a given fd. */
+static int
+evmap_io_foreach_event_fn(struct event_base *base, evutil_socket_t fd,
+ struct evmap_io *io_info, void *arg)
+{
+ struct evmap_foreach_event_helper *h = arg;
+ struct event *ev;
+ int r;
+ LIST_FOREACH(ev, &io_info->events, ev_io_next) {
+ if ((r = h->fn(base, ev, h->arg)))
+ return r;
+ }
+ return 0;
+}
+
+/* Helper for evmap_foreach_event_: calls a provided function on every event
+ * pending on a given signal. */
+static int
+evmap_signal_foreach_event_fn(struct event_base *base, int signum,
+ struct evmap_signal *sig_info, void *arg)
+{
+ struct event *ev;
+ struct evmap_foreach_event_helper *h = arg;
+ int r;
+ LIST_FOREACH(ev, &sig_info->events, ev_signal_next) {
+ if ((r = h->fn(base, ev, h->arg)))
+ return r;
+ }
+ return 0;
+}
+
+int
+evmap_foreach_event_(struct event_base *base,
+ event_base_foreach_event_cb fn, void *arg)
+{
+ struct evmap_foreach_event_helper h;
+ int r;
+ h.fn = fn;
+ h.arg = arg;
+ if ((r = evmap_io_foreach_fd(base, evmap_io_foreach_event_fn, &h)))
+ return r;
+ return evmap_signal_foreach_signal(base, evmap_signal_foreach_event_fn, &h);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/evport.c b/ipc/chromium/src/third_party/libevent/evport.c
new file mode 100644
index 0000000000..a014386bfe
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evport.c
@@ -0,0 +1,451 @@
+/*
+ * Submitted by David Pacheco (dp.spambait@gmail.com)
+ *
+ * Copyright 2006-2007 Niels Provos
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY SUN MICROSYSTEMS, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS, INC. BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * Copyright (c) 2007 Sun Microsystems. All rights reserved.
+ * Use is subject to license terms.
+ */
+
+/*
+ * evport.c: event backend using Solaris 10 event ports. See port_create(3C).
+ * This implementation is loosely modeled after the one used for select(2) (in
+ * select.c).
+ *
+ * The outstanding events are tracked in a data structure called evport_data.
+ * Each entry in the ed_fds array corresponds to a file descriptor, and contains
+ * pointers to the read and write events that correspond to that fd. (That is,
+ * when the file is readable, the "read" event should handle it, etc.)
+ *
+ * evport_add and evport_del update this data structure. evport_dispatch uses it
+ * to determine where to callback when an event occurs (which it gets from
+ * port_getn).
+ *
+ * Helper functions are used: grow() grows the file descriptor array as
+ * necessary when large fd's come in. reassociate() takes care of maintaining
+ * the proper file-descriptor/event-port associations.
+ *
+ * As in the select(2) implementation, signals are handled by evsignal.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_EVENT_PORTS
+
+#include <sys/time.h>
+#include <sys/queue.h>
+#include <errno.h>
+#include <poll.h>
+#include <port.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "event2/thread.h"
+
+#include "evthread-internal.h"
+#include "event-internal.h"
+#include "log-internal.h"
+#include "evsignal-internal.h"
+#include "evmap-internal.h"
+
+#define INITIAL_EVENTS_PER_GETN 8
+#define MAX_EVENTS_PER_GETN 4096
+
+/*
+ * Per-file-descriptor information about what events we're subscribed to. These
+ * fields are NULL if no event is subscribed to either of them.
+ */
+
+struct fd_info {
+ /* combinations of EV_READ and EV_WRITE */
+ short fdi_what;
+ /* Index of this fd within ed_pending, plus 1. Zero if this fd is
+ * not in ed_pending. (The +1 is a hack so that memset(0) will set
+ * it to a nil index. */
+ int pending_idx_plus_1;
+};
+
+#define FDI_HAS_READ(fdi) ((fdi)->fdi_what & EV_READ)
+#define FDI_HAS_WRITE(fdi) ((fdi)->fdi_what & EV_WRITE)
+#define FDI_HAS_EVENTS(fdi) (FDI_HAS_READ(fdi) || FDI_HAS_WRITE(fdi))
+#define FDI_TO_SYSEVENTS(fdi) (FDI_HAS_READ(fdi) ? POLLIN : 0) | \
+ (FDI_HAS_WRITE(fdi) ? POLLOUT : 0)
+
+struct evport_data {
+ int ed_port; /* event port for system events */
+ /* How many elements of ed_pending should we look at? */
+ int ed_npending;
+ /* How many elements are allocated in ed_pending and pevtlist? */
+ int ed_maxevents;
+ /* fdi's that we need to reassoc */
+ int *ed_pending;
+ /* storage space for incoming events. */
+ port_event_t *ed_pevtlist;
+
+};
+
+static void* evport_init(struct event_base *);
+static int evport_add(struct event_base *, int fd, short old, short events, void *);
+static int evport_del(struct event_base *, int fd, short old, short events, void *);
+static int evport_dispatch(struct event_base *, struct timeval *);
+static void evport_dealloc(struct event_base *);
+static int grow(struct evport_data *, int min_events);
+
+const struct eventop evportops = {
+ "evport",
+ evport_init,
+ evport_add,
+ evport_del,
+ evport_dispatch,
+ evport_dealloc,
+ 1, /* need reinit */
+ 0, /* features */
+ sizeof(struct fd_info), /* fdinfo length */
+};
+
+/*
+ * Initialize the event port implementation.
+ */
+
+static void*
+evport_init(struct event_base *base)
+{
+ struct evport_data *evpd;
+
+ if (!(evpd = mm_calloc(1, sizeof(struct evport_data))))
+ return (NULL);
+
+ if ((evpd->ed_port = port_create()) == -1) {
+ mm_free(evpd);
+ return (NULL);
+ }
+
+ if (grow(evpd, INITIAL_EVENTS_PER_GETN) < 0) {
+ close(evpd->ed_port);
+ mm_free(evpd);
+ return NULL;
+ }
+
+ evpd->ed_npending = 0;
+
+ evsig_init_(base);
+
+ return (evpd);
+}
+
+static int
+grow(struct evport_data *data, int min_events)
+{
+ int newsize;
+ int *new_pending;
+ port_event_t *new_pevtlist;
+ if (data->ed_maxevents) {
+ newsize = data->ed_maxevents;
+ do {
+ newsize *= 2;
+ } while (newsize < min_events);
+ } else {
+ newsize = min_events;
+ }
+
+ new_pending = mm_realloc(data->ed_pending, sizeof(int)*newsize);
+ if (new_pending == NULL)
+ return -1;
+ data->ed_pending = new_pending;
+ new_pevtlist = mm_realloc(data->ed_pevtlist, sizeof(port_event_t)*newsize);
+ if (new_pevtlist == NULL)
+ return -1;
+ data->ed_pevtlist = new_pevtlist;
+
+ data->ed_maxevents = newsize;
+ return 0;
+}
+
+#ifdef CHECK_INVARIANTS
+/*
+ * Checks some basic properties about the evport_data structure. Because it
+ * checks all file descriptors, this function can be expensive when the maximum
+ * file descriptor ever used is rather large.
+ */
+
+static void
+check_evportop(struct evport_data *evpd)
+{
+ EVUTIL_ASSERT(evpd);
+ EVUTIL_ASSERT(evpd->ed_port > 0);
+}
+
+/*
+ * Verifies very basic integrity of a given port_event.
+ */
+static void
+check_event(port_event_t* pevt)
+{
+ /*
+ * We've only registered for PORT_SOURCE_FD events. The only
+ * other thing we can legitimately receive is PORT_SOURCE_ALERT,
+ * but since we're not using port_alert either, we can assume
+ * PORT_SOURCE_FD.
+ */
+ EVUTIL_ASSERT(pevt->portev_source == PORT_SOURCE_FD);
+}
+
+#else
+#define check_evportop(epop)
+#define check_event(pevt)
+#endif /* CHECK_INVARIANTS */
+
+/*
+ * (Re)associates the given file descriptor with the event port. The OS events
+ * are specified (implicitly) from the fd_info struct.
+ */
+static int
+reassociate(struct evport_data *epdp, struct fd_info *fdip, int fd)
+{
+ int sysevents = FDI_TO_SYSEVENTS(fdip);
+
+ if (sysevents != 0) {
+ if (port_associate(epdp->ed_port, PORT_SOURCE_FD,
+ fd, sysevents, fdip) == -1) {
+ event_warn("port_associate");
+ return (-1);
+ }
+ }
+
+ check_evportop(epdp);
+
+ return (0);
+}
+
+/*
+ * Main event loop - polls port_getn for some number of events, and processes
+ * them.
+ */
+
+static int
+evport_dispatch(struct event_base *base, struct timeval *tv)
+{
+ int i, res;
+ struct evport_data *epdp = base->evbase;
+ port_event_t *pevtlist = epdp->ed_pevtlist;
+
+ /*
+ * port_getn will block until it has at least nevents events. It will
+ * also return how many it's given us (which may be more than we asked
+ * for, as long as it's less than our maximum (ed_maxevents)) in
+ * nevents.
+ */
+ int nevents = 1;
+
+ /*
+ * We have to convert a struct timeval to a struct timespec
+ * (only difference is nanoseconds vs. microseconds). If no time-based
+ * events are active, we should wait for I/O (and tv == NULL).
+ */
+ struct timespec ts;
+ struct timespec *ts_p = NULL;
+ if (tv != NULL) {
+ ts.tv_sec = tv->tv_sec;
+ ts.tv_nsec = tv->tv_usec * 1000;
+ ts_p = &ts;
+ }
+
+ /*
+ * Before doing anything else, we need to reassociate the events we hit
+ * last time which need reassociation. See comment at the end of the
+ * loop below.
+ */
+ for (i = 0; i < epdp->ed_npending; ++i) {
+ struct fd_info *fdi = NULL;
+ const int fd = epdp->ed_pending[i];
+ if (fd != -1) {
+ /* We might have cleared out this event; we need
+ * to be sure that it's still set. */
+ fdi = evmap_io_get_fdinfo_(&base->io, fd);
+ }
+
+ if (fdi != NULL && FDI_HAS_EVENTS(fdi)) {
+ reassociate(epdp, fdi, fd);
+ /* epdp->ed_pending[i] = -1; */
+ fdi->pending_idx_plus_1 = 0;
+ }
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = port_getn(epdp->ed_port, pevtlist, epdp->ed_maxevents,
+ (unsigned int *) &nevents, ts_p);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (res == -1) {
+ if (errno == EINTR || errno == EAGAIN) {
+ return (0);
+ } else if (errno == ETIME) {
+ if (nevents == 0)
+ return (0);
+ } else {
+ event_warn("port_getn");
+ return (-1);
+ }
+ }
+
+ event_debug(("%s: port_getn reports %d events", __func__, nevents));
+
+ for (i = 0; i < nevents; ++i) {
+ port_event_t *pevt = &pevtlist[i];
+ int fd = (int) pevt->portev_object;
+ struct fd_info *fdi = pevt->portev_user;
+ /*EVUTIL_ASSERT(evmap_io_get_fdinfo_(&base->io, fd) == fdi);*/
+
+ check_evportop(epdp);
+ check_event(pevt);
+ epdp->ed_pending[i] = fd;
+ fdi->pending_idx_plus_1 = i + 1;
+
+ /*
+ * Figure out what kind of event it was
+ * (because we have to pass this to the callback)
+ */
+ res = 0;
+ if (pevt->portev_events & (POLLERR|POLLHUP)) {
+ res = EV_READ | EV_WRITE;
+ } else {
+ if (pevt->portev_events & POLLIN)
+ res |= EV_READ;
+ if (pevt->portev_events & POLLOUT)
+ res |= EV_WRITE;
+ }
+
+ /*
+ * Check for the error situations or a hangup situation
+ */
+ if (pevt->portev_events & (POLLERR|POLLHUP|POLLNVAL))
+ res |= EV_READ|EV_WRITE;
+
+ evmap_io_active_(base, fd, res);
+ } /* end of all events gotten */
+ epdp->ed_npending = nevents;
+
+ if (nevents == epdp->ed_maxevents &&
+ epdp->ed_maxevents < MAX_EVENTS_PER_GETN) {
+ /* we used all the space this time. We should be ready
+ * for more events next time around. */
+ grow(epdp, epdp->ed_maxevents * 2);
+ }
+
+ check_evportop(epdp);
+
+ return (0);
+}
+
+
+/*
+ * Adds the given event (so that you will be notified when it happens via
+ * the callback function).
+ */
+
+static int
+evport_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct evport_data *evpd = base->evbase;
+ struct fd_info *fdi = p;
+
+ check_evportop(evpd);
+
+ fdi->fdi_what |= events;
+
+ return reassociate(evpd, fdi, fd);
+}
+
+/*
+ * Removes the given event from the list of events to wait for.
+ */
+
+static int
+evport_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct evport_data *evpd = base->evbase;
+ struct fd_info *fdi = p;
+ int associated = ! fdi->pending_idx_plus_1;
+
+ check_evportop(evpd);
+
+ fdi->fdi_what &= ~(events &(EV_READ|EV_WRITE));
+
+ if (associated) {
+ if (!FDI_HAS_EVENTS(fdi) &&
+ port_dissociate(evpd->ed_port, PORT_SOURCE_FD, fd) == -1) {
+ /*
+ * Ignore EBADFD error the fd could have been closed
+ * before event_del() was called.
+ */
+ if (errno != EBADFD) {
+ event_warn("port_dissociate");
+ return (-1);
+ }
+ } else {
+ if (FDI_HAS_EVENTS(fdi)) {
+ return (reassociate(evpd, fdi, fd));
+ }
+ }
+ } else {
+ if ((fdi->fdi_what & (EV_READ|EV_WRITE)) == 0) {
+ const int i = fdi->pending_idx_plus_1 - 1;
+ EVUTIL_ASSERT(evpd->ed_pending[i] == fd);
+ evpd->ed_pending[i] = -1;
+ fdi->pending_idx_plus_1 = 0;
+ }
+ }
+ return 0;
+}
+
+
+static void
+evport_dealloc(struct event_base *base)
+{
+ struct evport_data *evpd = base->evbase;
+
+ evsig_dealloc_(base);
+
+ close(evpd->ed_port);
+
+ if (evpd->ed_pending)
+ mm_free(evpd->ed_pending);
+ if (evpd->ed_pevtlist)
+ mm_free(evpd->ed_pevtlist);
+
+ mm_free(evpd);
+}
+
+#endif /* EVENT__HAVE_EVENT_PORTS */
diff --git a/ipc/chromium/src/third_party/libevent/evrpc-internal.h b/ipc/chromium/src/third_party/libevent/evrpc-internal.h
new file mode 100644
index 0000000000..9eb376386d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evrpc-internal.h
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVRPC_INTERNAL_H_INCLUDED_
+#define EVRPC_INTERNAL_H_INCLUDED_
+
+#include "event2/http.h"
+#include "http-internal.h"
+
+struct evrpc;
+struct evrpc_request_wrapper;
+
+#define EVRPC_URI_PREFIX "/.rpc."
+
+struct evrpc_hook {
+ TAILQ_ENTRY(evrpc_hook) next;
+
+ /* returns EVRPC_TERMINATE; if the rpc should be aborted.
+ * a hook is is allowed to rewrite the evbuffer
+ */
+ int (*process)(void *, struct evhttp_request *,
+ struct evbuffer *, void *);
+ void *process_arg;
+};
+
+TAILQ_HEAD(evrpc_hook_list, evrpc_hook);
+
+/*
+ * this is shared between the base and the pool, so that we can reuse
+ * the hook adding functions; we alias both evrpc_pool and evrpc_base
+ * to this common structure.
+ */
+
+struct evrpc_hook_ctx;
+TAILQ_HEAD(evrpc_pause_list, evrpc_hook_ctx);
+
+struct evrpc_hooks_ {
+ /* hooks for processing outbound and inbound rpcs */
+ struct evrpc_hook_list in_hooks;
+ struct evrpc_hook_list out_hooks;
+
+ struct evrpc_pause_list pause_requests;
+};
+
+#define input_hooks common.in_hooks
+#define output_hooks common.out_hooks
+#define paused_requests common.pause_requests
+
+struct evrpc_base {
+ struct evrpc_hooks_ common;
+
+ /* the HTTP server under which we register our RPC calls */
+ struct evhttp* http_server;
+
+ /* a list of all RPCs registered with us */
+ TAILQ_HEAD(evrpc_list, evrpc) registered_rpcs;
+};
+
+struct evrpc_req_generic;
+void evrpc_reqstate_free_(struct evrpc_req_generic* rpc_state);
+
+/* A pool for holding evhttp_connection objects */
+struct evrpc_pool {
+ struct evrpc_hooks_ common;
+
+ struct event_base *base;
+
+ struct evconq connections;
+
+ int timeout;
+
+ TAILQ_HEAD(evrpc_requestq, evrpc_request_wrapper) (requests);
+};
+
+struct evrpc_hook_ctx {
+ TAILQ_ENTRY(evrpc_hook_ctx) next;
+
+ void *ctx;
+ void (*cb)(void *, enum EVRPC_HOOK_RESULT);
+};
+
+struct evrpc_meta {
+ TAILQ_ENTRY(evrpc_meta) next;
+ char *key;
+
+ void *data;
+ size_t data_size;
+};
+
+TAILQ_HEAD(evrpc_meta_list, evrpc_meta);
+
+struct evrpc_hook_meta {
+ struct evrpc_meta_list meta_data;
+ struct evhttp_connection *evcon;
+};
+
+/* allows association of meta data with a request */
+static void evrpc_hook_associate_meta_(struct evrpc_hook_meta **pctx,
+ struct evhttp_connection *evcon);
+
+/* creates a new meta data store */
+static struct evrpc_hook_meta *evrpc_hook_meta_new_(void);
+
+/* frees the meta data associated with a request */
+static void evrpc_hook_context_free_(struct evrpc_hook_meta *ctx);
+
+/* the server side of an rpc */
+
+/* We alias the RPC specific structs to this voided one */
+struct evrpc_req_generic {
+ /*
+ * allows association of meta data via hooks - needs to be
+ * synchronized with evrpc_request_wrapper
+ */
+ struct evrpc_hook_meta *hook_meta;
+
+ /* the unmarshaled request object */
+ void *request;
+
+ /* the empty reply object that needs to be filled in */
+ void *reply;
+
+ /*
+ * the static structure for this rpc; that can be used to
+ * automatically unmarshal and marshal the http buffers.
+ */
+ struct evrpc *rpc;
+
+ /*
+ * the http request structure on which we need to answer.
+ */
+ struct evhttp_request* http_req;
+
+ /*
+ * Temporary data store for marshaled data
+ */
+ struct evbuffer* rpc_data;
+};
+
+/* the client side of an rpc request */
+struct evrpc_request_wrapper {
+ /*
+ * allows association of meta data via hooks - needs to be
+ * synchronized with evrpc_req_generic.
+ */
+ struct evrpc_hook_meta *hook_meta;
+
+ TAILQ_ENTRY(evrpc_request_wrapper) next;
+
+ /* pool on which this rpc request is being made */
+ struct evrpc_pool *pool;
+
+ /* connection on which the request is being sent */
+ struct evhttp_connection *evcon;
+
+ /* the actual request */
+ struct evhttp_request *req;
+
+ /* event for implementing request timeouts */
+ struct event ev_timeout;
+
+ /* the name of the rpc */
+ char *name;
+
+ /* callback */
+ void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg);
+ void *cb_arg;
+
+ void *request;
+ void *reply;
+
+ /* unmarshals the buffer into the proper request structure */
+ void (*request_marshal)(struct evbuffer *, void *);
+
+ /* removes all stored state in the reply */
+ void (*reply_clear)(void *);
+
+ /* marshals the reply into a buffer */
+ int (*reply_unmarshal)(void *, struct evbuffer*);
+};
+
+#endif /* EVRPC_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/evrpc.c b/ipc/chromium/src/third_party/libevent/evrpc.c
new file mode 100644
index 0000000000..4a60ca5f07
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evrpc.c
@@ -0,0 +1,1171 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <stdio.h>
+#include <stdlib.h>
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <signal.h>
+#include <string.h>
+
+#include <sys/queue.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/rpc.h"
+#include "event2/rpc_struct.h"
+#include "evrpc-internal.h"
+#include "event2/http.h"
+#include "event2/buffer.h"
+#include "event2/tag.h"
+#include "event2/http_struct.h"
+#include "event2/http_compat.h"
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+
+struct evrpc_base *
+evrpc_init(struct evhttp *http_server)
+{
+ struct evrpc_base* base = mm_calloc(1, sizeof(struct evrpc_base));
+ if (base == NULL)
+ return (NULL);
+
+ /* we rely on the tagging sub system */
+ evtag_init();
+
+ TAILQ_INIT(&base->registered_rpcs);
+ TAILQ_INIT(&base->input_hooks);
+ TAILQ_INIT(&base->output_hooks);
+
+ TAILQ_INIT(&base->paused_requests);
+
+ base->http_server = http_server;
+
+ return (base);
+}
+
+void
+evrpc_free(struct evrpc_base *base)
+{
+ struct evrpc *rpc;
+ struct evrpc_hook *hook;
+ struct evrpc_hook_ctx *pause;
+ int r;
+
+ while ((rpc = TAILQ_FIRST(&base->registered_rpcs)) != NULL) {
+ r = evrpc_unregister_rpc(base, rpc->uri);
+ EVUTIL_ASSERT(r == 0);
+ }
+ while ((pause = TAILQ_FIRST(&base->paused_requests)) != NULL) {
+ TAILQ_REMOVE(&base->paused_requests, pause, next);
+ mm_free(pause);
+ }
+ while ((hook = TAILQ_FIRST(&base->input_hooks)) != NULL) {
+ r = evrpc_remove_hook(base, EVRPC_INPUT, hook);
+ EVUTIL_ASSERT(r);
+ }
+ while ((hook = TAILQ_FIRST(&base->output_hooks)) != NULL) {
+ r = evrpc_remove_hook(base, EVRPC_OUTPUT, hook);
+ EVUTIL_ASSERT(r);
+ }
+ mm_free(base);
+}
+
+void *
+evrpc_add_hook(void *vbase,
+ enum EVRPC_HOOK_TYPE hook_type,
+ int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
+ void *cb_arg)
+{
+ struct evrpc_hooks_ *base = vbase;
+ struct evrpc_hook_list *head = NULL;
+ struct evrpc_hook *hook = NULL;
+ switch (hook_type) {
+ case EVRPC_INPUT:
+ head = &base->in_hooks;
+ break;
+ case EVRPC_OUTPUT:
+ head = &base->out_hooks;
+ break;
+ default:
+ EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
+ }
+
+ hook = mm_calloc(1, sizeof(struct evrpc_hook));
+ EVUTIL_ASSERT(hook != NULL);
+
+ hook->process = cb;
+ hook->process_arg = cb_arg;
+ TAILQ_INSERT_TAIL(head, hook, next);
+
+ return (hook);
+}
+
+static int
+evrpc_remove_hook_internal(struct evrpc_hook_list *head, void *handle)
+{
+ struct evrpc_hook *hook = NULL;
+ TAILQ_FOREACH(hook, head, next) {
+ if (hook == handle) {
+ TAILQ_REMOVE(head, hook, next);
+ mm_free(hook);
+ return (1);
+ }
+ }
+
+ return (0);
+}
+
+/*
+ * remove the hook specified by the handle
+ */
+
+int
+evrpc_remove_hook(void *vbase, enum EVRPC_HOOK_TYPE hook_type, void *handle)
+{
+ struct evrpc_hooks_ *base = vbase;
+ struct evrpc_hook_list *head = NULL;
+ switch (hook_type) {
+ case EVRPC_INPUT:
+ head = &base->in_hooks;
+ break;
+ case EVRPC_OUTPUT:
+ head = &base->out_hooks;
+ break;
+ default:
+ EVUTIL_ASSERT(hook_type == EVRPC_INPUT || hook_type == EVRPC_OUTPUT);
+ }
+
+ return (evrpc_remove_hook_internal(head, handle));
+}
+
+static int
+evrpc_process_hooks(struct evrpc_hook_list *head, void *ctx,
+ struct evhttp_request *req, struct evbuffer *evbuf)
+{
+ struct evrpc_hook *hook;
+ TAILQ_FOREACH(hook, head, next) {
+ int res = hook->process(ctx, req, evbuf, hook->process_arg);
+ if (res != EVRPC_CONTINUE)
+ return (res);
+ }
+
+ return (EVRPC_CONTINUE);
+}
+
+static void evrpc_pool_schedule(struct evrpc_pool *pool);
+static void evrpc_request_cb(struct evhttp_request *, void *);
+
+/*
+ * Registers a new RPC with the HTTP server. The evrpc object is expected
+ * to have been filled in via the EVRPC_REGISTER_OBJECT macro which in turn
+ * calls this function.
+ */
+
+static char *
+evrpc_construct_uri(const char *uri)
+{
+ char *constructed_uri;
+ size_t constructed_uri_len;
+
+ constructed_uri_len = strlen(EVRPC_URI_PREFIX) + strlen(uri) + 1;
+ if ((constructed_uri = mm_malloc(constructed_uri_len)) == NULL)
+ event_err(1, "%s: failed to register rpc at %s",
+ __func__, uri);
+ memcpy(constructed_uri, EVRPC_URI_PREFIX, strlen(EVRPC_URI_PREFIX));
+ memcpy(constructed_uri + strlen(EVRPC_URI_PREFIX), uri, strlen(uri));
+ constructed_uri[constructed_uri_len - 1] = '\0';
+
+ return (constructed_uri);
+}
+
+int
+evrpc_register_rpc(struct evrpc_base *base, struct evrpc *rpc,
+ void (*cb)(struct evrpc_req_generic *, void *), void *cb_arg)
+{
+ char *constructed_uri = evrpc_construct_uri(rpc->uri);
+
+ rpc->base = base;
+ rpc->cb = cb;
+ rpc->cb_arg = cb_arg;
+
+ TAILQ_INSERT_TAIL(&base->registered_rpcs, rpc, next);
+
+ evhttp_set_cb(base->http_server,
+ constructed_uri,
+ evrpc_request_cb,
+ rpc);
+
+ mm_free(constructed_uri);
+
+ return (0);
+}
+
+int
+evrpc_unregister_rpc(struct evrpc_base *base, const char *name)
+{
+ char *registered_uri = NULL;
+ struct evrpc *rpc;
+ int r;
+
+ /* find the right rpc; linear search might be slow */
+ TAILQ_FOREACH(rpc, &base->registered_rpcs, next) {
+ if (strcmp(rpc->uri, name) == 0)
+ break;
+ }
+ if (rpc == NULL) {
+ /* We did not find an RPC with this name */
+ return (-1);
+ }
+ TAILQ_REMOVE(&base->registered_rpcs, rpc, next);
+
+ registered_uri = evrpc_construct_uri(name);
+
+ /* remove the http server callback */
+ r = evhttp_del_cb(base->http_server, registered_uri);
+ EVUTIL_ASSERT(r == 0);
+
+ mm_free(registered_uri);
+
+ mm_free((char *)rpc->uri);
+ mm_free(rpc);
+ return (0);
+}
+
+static int evrpc_pause_request(void *vbase, void *ctx,
+ void (*cb)(void *, enum EVRPC_HOOK_RESULT));
+static void evrpc_request_cb_closure(void *, enum EVRPC_HOOK_RESULT);
+
+static void
+evrpc_request_cb(struct evhttp_request *req, void *arg)
+{
+ struct evrpc *rpc = arg;
+ struct evrpc_req_generic *rpc_state = NULL;
+
+ /* let's verify the outside parameters */
+ if (req->type != EVHTTP_REQ_POST ||
+ evbuffer_get_length(req->input_buffer) <= 0)
+ goto error;
+
+ rpc_state = mm_calloc(1, sizeof(struct evrpc_req_generic));
+ if (rpc_state == NULL)
+ goto error;
+ rpc_state->rpc = rpc;
+ rpc_state->http_req = req;
+ rpc_state->rpc_data = NULL;
+
+ if (TAILQ_FIRST(&rpc->base->input_hooks) != NULL) {
+ int hook_res;
+
+ evrpc_hook_associate_meta_(&rpc_state->hook_meta, req->evcon);
+
+ /*
+ * allow hooks to modify the outgoing request
+ */
+ hook_res = evrpc_process_hooks(&rpc->base->input_hooks,
+ rpc_state, req, req->input_buffer);
+ switch (hook_res) {
+ case EVRPC_TERMINATE:
+ goto error;
+ case EVRPC_PAUSE:
+ evrpc_pause_request(rpc->base, rpc_state,
+ evrpc_request_cb_closure);
+ return;
+ case EVRPC_CONTINUE:
+ break;
+ default:
+ EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+ hook_res == EVRPC_CONTINUE ||
+ hook_res == EVRPC_PAUSE);
+ }
+ }
+
+ evrpc_request_cb_closure(rpc_state, EVRPC_CONTINUE);
+ return;
+
+error:
+ if (rpc_state)
+ evrpc_reqstate_free_(rpc_state);
+ evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+ return;
+}
+
+static void
+evrpc_request_cb_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+ struct evrpc_req_generic *rpc_state = arg;
+ struct evrpc *rpc;
+ struct evhttp_request *req;
+
+ EVUTIL_ASSERT(rpc_state);
+ rpc = rpc_state->rpc;
+ req = rpc_state->http_req;
+
+ if (hook_res == EVRPC_TERMINATE)
+ goto error;
+
+ /* let's check that we can parse the request */
+ rpc_state->request = rpc->request_new(rpc->request_new_arg);
+ if (rpc_state->request == NULL)
+ goto error;
+
+ if (rpc->request_unmarshal(
+ rpc_state->request, req->input_buffer) == -1) {
+ /* we failed to parse the request; that's a bummer */
+ goto error;
+ }
+
+ /* at this point, we have a well formed request, prepare the reply */
+
+ rpc_state->reply = rpc->reply_new(rpc->reply_new_arg);
+ if (rpc_state->reply == NULL)
+ goto error;
+
+ /* give the rpc to the user; they can deal with it */
+ rpc->cb(rpc_state, rpc->cb_arg);
+
+ return;
+
+error:
+ evrpc_reqstate_free_(rpc_state);
+ evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+ return;
+}
+
+
+void
+evrpc_reqstate_free_(struct evrpc_req_generic* rpc_state)
+{
+ struct evrpc *rpc;
+ EVUTIL_ASSERT(rpc_state != NULL);
+ rpc = rpc_state->rpc;
+
+ /* clean up all memory */
+ if (rpc_state->hook_meta != NULL)
+ evrpc_hook_context_free_(rpc_state->hook_meta);
+ if (rpc_state->request != NULL)
+ rpc->request_free(rpc_state->request);
+ if (rpc_state->reply != NULL)
+ rpc->reply_free(rpc_state->reply);
+ if (rpc_state->rpc_data != NULL)
+ evbuffer_free(rpc_state->rpc_data);
+ mm_free(rpc_state);
+}
+
+static void
+evrpc_request_done_closure(void *, enum EVRPC_HOOK_RESULT);
+
+void
+evrpc_request_done(struct evrpc_req_generic *rpc_state)
+{
+ struct evhttp_request *req;
+ struct evrpc *rpc;
+
+ EVUTIL_ASSERT(rpc_state);
+
+ req = rpc_state->http_req;
+ rpc = rpc_state->rpc;
+
+ if (rpc->reply_complete(rpc_state->reply) == -1) {
+ /* the reply was not completely filled in. error out */
+ goto error;
+ }
+
+ if ((rpc_state->rpc_data = evbuffer_new()) == NULL) {
+ /* out of memory */
+ goto error;
+ }
+
+ /* serialize the reply */
+ rpc->reply_marshal(rpc_state->rpc_data, rpc_state->reply);
+
+ if (TAILQ_FIRST(&rpc->base->output_hooks) != NULL) {
+ int hook_res;
+
+ evrpc_hook_associate_meta_(&rpc_state->hook_meta, req->evcon);
+
+ /* do hook based tweaks to the request */
+ hook_res = evrpc_process_hooks(&rpc->base->output_hooks,
+ rpc_state, req, rpc_state->rpc_data);
+ switch (hook_res) {
+ case EVRPC_TERMINATE:
+ goto error;
+ case EVRPC_PAUSE:
+ if (evrpc_pause_request(rpc->base, rpc_state,
+ evrpc_request_done_closure) == -1)
+ goto error;
+ return;
+ case EVRPC_CONTINUE:
+ break;
+ default:
+ EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+ hook_res == EVRPC_CONTINUE ||
+ hook_res == EVRPC_PAUSE);
+ }
+ }
+
+ evrpc_request_done_closure(rpc_state, EVRPC_CONTINUE);
+ return;
+
+error:
+ evrpc_reqstate_free_(rpc_state);
+ evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+ return;
+}
+
+void *
+evrpc_get_request(struct evrpc_req_generic *req)
+{
+ return req->request;
+}
+
+void *
+evrpc_get_reply(struct evrpc_req_generic *req)
+{
+ return req->reply;
+}
+
+static void
+evrpc_request_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+ struct evrpc_req_generic *rpc_state = arg;
+ struct evhttp_request *req;
+ EVUTIL_ASSERT(rpc_state);
+ req = rpc_state->http_req;
+
+ if (hook_res == EVRPC_TERMINATE)
+ goto error;
+
+ /* on success, we are going to transmit marshaled binary data */
+ if (evhttp_find_header(req->output_headers, "Content-Type") == NULL) {
+ evhttp_add_header(req->output_headers,
+ "Content-Type", "application/octet-stream");
+ }
+ evhttp_send_reply(req, HTTP_OK, "OK", rpc_state->rpc_data);
+
+ evrpc_reqstate_free_(rpc_state);
+
+ return;
+
+error:
+ evrpc_reqstate_free_(rpc_state);
+ evhttp_send_error(req, HTTP_SERVUNAVAIL, NULL);
+ return;
+}
+
+
+/* Client implementation of RPC site */
+
+static int evrpc_schedule_request(struct evhttp_connection *connection,
+ struct evrpc_request_wrapper *ctx);
+
+struct evrpc_pool *
+evrpc_pool_new(struct event_base *base)
+{
+ struct evrpc_pool *pool = mm_calloc(1, sizeof(struct evrpc_pool));
+ if (pool == NULL)
+ return (NULL);
+
+ TAILQ_INIT(&pool->connections);
+ TAILQ_INIT(&pool->requests);
+
+ TAILQ_INIT(&pool->paused_requests);
+
+ TAILQ_INIT(&pool->input_hooks);
+ TAILQ_INIT(&pool->output_hooks);
+
+ pool->base = base;
+ pool->timeout = -1;
+
+ return (pool);
+}
+
+static void
+evrpc_request_wrapper_free(struct evrpc_request_wrapper *request)
+{
+ if (request->hook_meta != NULL)
+ evrpc_hook_context_free_(request->hook_meta);
+ mm_free(request->name);
+ mm_free(request);
+}
+
+void
+evrpc_pool_free(struct evrpc_pool *pool)
+{
+ struct evhttp_connection *connection;
+ struct evrpc_request_wrapper *request;
+ struct evrpc_hook_ctx *pause;
+ struct evrpc_hook *hook;
+ int r;
+
+ while ((request = TAILQ_FIRST(&pool->requests)) != NULL) {
+ TAILQ_REMOVE(&pool->requests, request, next);
+ evrpc_request_wrapper_free(request);
+ }
+
+ while ((pause = TAILQ_FIRST(&pool->paused_requests)) != NULL) {
+ TAILQ_REMOVE(&pool->paused_requests, pause, next);
+ mm_free(pause);
+ }
+
+ while ((connection = TAILQ_FIRST(&pool->connections)) != NULL) {
+ TAILQ_REMOVE(&pool->connections, connection, next);
+ evhttp_connection_free(connection);
+ }
+
+ while ((hook = TAILQ_FIRST(&pool->input_hooks)) != NULL) {
+ r = evrpc_remove_hook(pool, EVRPC_INPUT, hook);
+ EVUTIL_ASSERT(r);
+ }
+
+ while ((hook = TAILQ_FIRST(&pool->output_hooks)) != NULL) {
+ r = evrpc_remove_hook(pool, EVRPC_OUTPUT, hook);
+ EVUTIL_ASSERT(r);
+ }
+
+ mm_free(pool);
+}
+
+/*
+ * Add a connection to the RPC pool. A request scheduled on the pool
+ * may use any available connection.
+ */
+
+void
+evrpc_pool_add_connection(struct evrpc_pool *pool,
+ struct evhttp_connection *connection)
+{
+ EVUTIL_ASSERT(connection->http_server == NULL);
+ TAILQ_INSERT_TAIL(&pool->connections, connection, next);
+
+ /*
+ * associate an event base with this connection
+ */
+ if (pool->base != NULL)
+ evhttp_connection_set_base(connection, pool->base);
+
+ /*
+ * unless a timeout was specifically set for a connection,
+ * the connection inherits the timeout from the pool.
+ */
+ if (!evutil_timerisset(&connection->timeout))
+ evhttp_connection_set_timeout(connection, pool->timeout);
+
+ /*
+ * if we have any requests pending, schedule them with the new
+ * connections.
+ */
+
+ if (TAILQ_FIRST(&pool->requests) != NULL) {
+ struct evrpc_request_wrapper *request =
+ TAILQ_FIRST(&pool->requests);
+ TAILQ_REMOVE(&pool->requests, request, next);
+ evrpc_schedule_request(connection, request);
+ }
+}
+
+void
+evrpc_pool_remove_connection(struct evrpc_pool *pool,
+ struct evhttp_connection *connection)
+{
+ TAILQ_REMOVE(&pool->connections, connection, next);
+}
+
+void
+evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs)
+{
+ struct evhttp_connection *evcon;
+ TAILQ_FOREACH(evcon, &pool->connections, next) {
+ evhttp_connection_set_timeout(evcon, timeout_in_secs);
+ }
+ pool->timeout = timeout_in_secs;
+}
+
+
+static void evrpc_reply_done(struct evhttp_request *, void *);
+static void evrpc_request_timeout(evutil_socket_t, short, void *);
+
+/*
+ * Finds a connection object associated with the pool that is currently
+ * idle and can be used to make a request.
+ */
+static struct evhttp_connection *
+evrpc_pool_find_connection(struct evrpc_pool *pool)
+{
+ struct evhttp_connection *connection;
+ TAILQ_FOREACH(connection, &pool->connections, next) {
+ if (TAILQ_FIRST(&connection->requests) == NULL)
+ return (connection);
+ }
+
+ return (NULL);
+}
+
+/*
+ * Prototypes responsible for evrpc scheduling and hooking
+ */
+
+static void evrpc_schedule_request_closure(void *ctx, enum EVRPC_HOOK_RESULT);
+
+/*
+ * We assume that the ctx is no longer queued on the pool.
+ */
+static int
+evrpc_schedule_request(struct evhttp_connection *connection,
+ struct evrpc_request_wrapper *ctx)
+{
+ struct evhttp_request *req = NULL;
+ struct evrpc_pool *pool = ctx->pool;
+ struct evrpc_status status;
+
+ if ((req = evhttp_request_new(evrpc_reply_done, ctx)) == NULL)
+ goto error;
+
+ /* serialize the request data into the output buffer */
+ ctx->request_marshal(req->output_buffer, ctx->request);
+
+ /* we need to know the connection that we might have to abort */
+ ctx->evcon = connection;
+
+ /* if we get paused we also need to know the request */
+ ctx->req = req;
+
+ if (TAILQ_FIRST(&pool->output_hooks) != NULL) {
+ int hook_res;
+
+ evrpc_hook_associate_meta_(&ctx->hook_meta, connection);
+
+ /* apply hooks to the outgoing request */
+ hook_res = evrpc_process_hooks(&pool->output_hooks,
+ ctx, req, req->output_buffer);
+
+ switch (hook_res) {
+ case EVRPC_TERMINATE:
+ goto error;
+ case EVRPC_PAUSE:
+ /* we need to be explicitly resumed */
+ if (evrpc_pause_request(pool, ctx,
+ evrpc_schedule_request_closure) == -1)
+ goto error;
+ return (0);
+ case EVRPC_CONTINUE:
+ /* we can just continue */
+ break;
+ default:
+ EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+ hook_res == EVRPC_CONTINUE ||
+ hook_res == EVRPC_PAUSE);
+ }
+ }
+
+ evrpc_schedule_request_closure(ctx, EVRPC_CONTINUE);
+ return (0);
+
+error:
+ memset(&status, 0, sizeof(status));
+ status.error = EVRPC_STATUS_ERR_UNSTARTED;
+ (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+ evrpc_request_wrapper_free(ctx);
+ return (-1);
+}
+
+static void
+evrpc_schedule_request_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+ struct evrpc_request_wrapper *ctx = arg;
+ struct evhttp_connection *connection = ctx->evcon;
+ struct evhttp_request *req = ctx->req;
+ struct evrpc_pool *pool = ctx->pool;
+ struct evrpc_status status;
+ char *uri = NULL;
+ int res = 0;
+
+ if (hook_res == EVRPC_TERMINATE)
+ goto error;
+
+ uri = evrpc_construct_uri(ctx->name);
+ if (uri == NULL)
+ goto error;
+
+ if (pool->timeout > 0) {
+ /*
+ * a timeout after which the whole rpc is going to be aborted.
+ */
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_sec = pool->timeout;
+ evtimer_add(&ctx->ev_timeout, &tv);
+ }
+
+ /* start the request over the connection */
+ res = evhttp_make_request(connection, req, EVHTTP_REQ_POST, uri);
+ mm_free(uri);
+
+ if (res == -1)
+ goto error;
+
+ return;
+
+error:
+ memset(&status, 0, sizeof(status));
+ status.error = EVRPC_STATUS_ERR_UNSTARTED;
+ (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+ evrpc_request_wrapper_free(ctx);
+}
+
+/* we just queue the paused request on the pool under the req object */
+static int
+evrpc_pause_request(void *vbase, void *ctx,
+ void (*cb)(void *, enum EVRPC_HOOK_RESULT))
+{
+ struct evrpc_hooks_ *base = vbase;
+ struct evrpc_hook_ctx *pause = mm_malloc(sizeof(*pause));
+ if (pause == NULL)
+ return (-1);
+
+ pause->ctx = ctx;
+ pause->cb = cb;
+
+ TAILQ_INSERT_TAIL(&base->pause_requests, pause, next);
+ return (0);
+}
+
+int
+evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res)
+{
+ struct evrpc_hooks_ *base = vbase;
+ struct evrpc_pause_list *head = &base->pause_requests;
+ struct evrpc_hook_ctx *pause;
+
+ TAILQ_FOREACH(pause, head, next) {
+ if (pause->ctx == ctx)
+ break;
+ }
+
+ if (pause == NULL)
+ return (-1);
+
+ (*pause->cb)(pause->ctx, res);
+ TAILQ_REMOVE(head, pause, next);
+ mm_free(pause);
+ return (0);
+}
+
+int
+evrpc_make_request(struct evrpc_request_wrapper *ctx)
+{
+ struct evrpc_pool *pool = ctx->pool;
+
+ /* initialize the event structure for this rpc */
+ evtimer_assign(&ctx->ev_timeout, pool->base, evrpc_request_timeout, ctx);
+
+ /* we better have some available connections on the pool */
+ EVUTIL_ASSERT(TAILQ_FIRST(&pool->connections) != NULL);
+
+ /*
+ * if no connection is available, we queue the request on the pool,
+ * the next time a connection is empty, the rpc will be send on that.
+ */
+ TAILQ_INSERT_TAIL(&pool->requests, ctx, next);
+
+ evrpc_pool_schedule(pool);
+
+ return (0);
+}
+
+
+struct evrpc_request_wrapper *
+evrpc_make_request_ctx(
+ struct evrpc_pool *pool, void *request, void *reply,
+ const char *rpcname,
+ void (*req_marshal)(struct evbuffer*, void *),
+ void (*rpl_clear)(void *),
+ int (*rpl_unmarshal)(void *, struct evbuffer *),
+ void (*cb)(struct evrpc_status *, void *, void *, void *),
+ void *cbarg)
+{
+ struct evrpc_request_wrapper *ctx = (struct evrpc_request_wrapper *)
+ mm_malloc(sizeof(struct evrpc_request_wrapper));
+ if (ctx == NULL)
+ return (NULL);
+
+ ctx->pool = pool;
+ ctx->hook_meta = NULL;
+ ctx->evcon = NULL;
+ ctx->name = mm_strdup(rpcname);
+ if (ctx->name == NULL) {
+ mm_free(ctx);
+ return (NULL);
+ }
+ ctx->cb = cb;
+ ctx->cb_arg = cbarg;
+ ctx->request = request;
+ ctx->reply = reply;
+ ctx->request_marshal = req_marshal;
+ ctx->reply_clear = rpl_clear;
+ ctx->reply_unmarshal = rpl_unmarshal;
+
+ return (ctx);
+}
+
+static void
+evrpc_reply_done_closure(void *, enum EVRPC_HOOK_RESULT);
+
+static void
+evrpc_reply_done(struct evhttp_request *req, void *arg)
+{
+ struct evrpc_request_wrapper *ctx = arg;
+ struct evrpc_pool *pool = ctx->pool;
+ int hook_res = EVRPC_CONTINUE;
+
+ /* cancel any timeout we might have scheduled */
+ event_del(&ctx->ev_timeout);
+
+ ctx->req = req;
+
+ /* we need to get the reply now */
+ if (req == NULL) {
+ evrpc_reply_done_closure(ctx, EVRPC_CONTINUE);
+ return;
+ }
+
+ if (TAILQ_FIRST(&pool->input_hooks) != NULL) {
+ evrpc_hook_associate_meta_(&ctx->hook_meta, ctx->evcon);
+
+ /* apply hooks to the incoming request */
+ hook_res = evrpc_process_hooks(&pool->input_hooks,
+ ctx, req, req->input_buffer);
+
+ switch (hook_res) {
+ case EVRPC_TERMINATE:
+ case EVRPC_CONTINUE:
+ break;
+ case EVRPC_PAUSE:
+ /*
+ * if we get paused we also need to know the
+ * request. unfortunately, the underlying
+ * layer is going to free it. we need to
+ * request ownership explicitly
+ */
+ evhttp_request_own(req);
+
+ evrpc_pause_request(pool, ctx,
+ evrpc_reply_done_closure);
+ return;
+ default:
+ EVUTIL_ASSERT(hook_res == EVRPC_TERMINATE ||
+ hook_res == EVRPC_CONTINUE ||
+ hook_res == EVRPC_PAUSE);
+ }
+ }
+
+ evrpc_reply_done_closure(ctx, hook_res);
+
+ /* http request is being freed by underlying layer */
+}
+
+static void
+evrpc_reply_done_closure(void *arg, enum EVRPC_HOOK_RESULT hook_res)
+{
+ struct evrpc_request_wrapper *ctx = arg;
+ struct evhttp_request *req = ctx->req;
+ struct evrpc_pool *pool = ctx->pool;
+ struct evrpc_status status;
+ int res = -1;
+
+ memset(&status, 0, sizeof(status));
+ status.http_req = req;
+
+ /* we need to get the reply now */
+ if (req == NULL) {
+ status.error = EVRPC_STATUS_ERR_TIMEOUT;
+ } else if (hook_res == EVRPC_TERMINATE) {
+ status.error = EVRPC_STATUS_ERR_HOOKABORTED;
+ } else {
+ res = ctx->reply_unmarshal(ctx->reply, req->input_buffer);
+ if (res == -1)
+ status.error = EVRPC_STATUS_ERR_BADPAYLOAD;
+ }
+
+ if (res == -1) {
+ /* clear everything that we might have written previously */
+ ctx->reply_clear(ctx->reply);
+ }
+
+ (*ctx->cb)(&status, ctx->request, ctx->reply, ctx->cb_arg);
+
+ evrpc_request_wrapper_free(ctx);
+
+ /* the http layer owned the original request structure, but if we
+ * got paused, we asked for ownership and need to free it here. */
+ if (req != NULL && evhttp_request_is_owned(req))
+ evhttp_request_free(req);
+
+ /* see if we can schedule another request */
+ evrpc_pool_schedule(pool);
+}
+
+static void
+evrpc_pool_schedule(struct evrpc_pool *pool)
+{
+ struct evrpc_request_wrapper *ctx = TAILQ_FIRST(&pool->requests);
+ struct evhttp_connection *evcon;
+
+ /* if no requests are pending, we have no work */
+ if (ctx == NULL)
+ return;
+
+ if ((evcon = evrpc_pool_find_connection(pool)) != NULL) {
+ TAILQ_REMOVE(&pool->requests, ctx, next);
+ evrpc_schedule_request(evcon, ctx);
+ }
+}
+
+static void
+evrpc_request_timeout(evutil_socket_t fd, short what, void *arg)
+{
+ struct evrpc_request_wrapper *ctx = arg;
+ struct evhttp_connection *evcon = ctx->evcon;
+ EVUTIL_ASSERT(evcon != NULL);
+
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_TIMEOUT);
+}
+
+/*
+ * frees potential meta data associated with a request.
+ */
+
+static void
+evrpc_meta_data_free(struct evrpc_meta_list *meta_data)
+{
+ struct evrpc_meta *entry;
+ EVUTIL_ASSERT(meta_data != NULL);
+
+ while ((entry = TAILQ_FIRST(meta_data)) != NULL) {
+ TAILQ_REMOVE(meta_data, entry, next);
+ mm_free(entry->key);
+ mm_free(entry->data);
+ mm_free(entry);
+ }
+}
+
+static struct evrpc_hook_meta *
+evrpc_hook_meta_new_(void)
+{
+ struct evrpc_hook_meta *ctx;
+ ctx = mm_malloc(sizeof(struct evrpc_hook_meta));
+ EVUTIL_ASSERT(ctx != NULL);
+
+ TAILQ_INIT(&ctx->meta_data);
+ ctx->evcon = NULL;
+
+ return (ctx);
+}
+
+static void
+evrpc_hook_associate_meta_(struct evrpc_hook_meta **pctx,
+ struct evhttp_connection *evcon)
+{
+ struct evrpc_hook_meta *ctx = *pctx;
+ if (ctx == NULL)
+ *pctx = ctx = evrpc_hook_meta_new_();
+ ctx->evcon = evcon;
+}
+
+static void
+evrpc_hook_context_free_(struct evrpc_hook_meta *ctx)
+{
+ evrpc_meta_data_free(&ctx->meta_data);
+ mm_free(ctx);
+}
+
+/* Adds meta data */
+void
+evrpc_hook_add_meta(void *ctx, const char *key,
+ const void *data, size_t data_size)
+{
+ struct evrpc_request_wrapper *req = ctx;
+ struct evrpc_hook_meta *store = NULL;
+ struct evrpc_meta *meta = NULL;
+
+ if ((store = req->hook_meta) == NULL)
+ store = req->hook_meta = evrpc_hook_meta_new_();
+
+ meta = mm_malloc(sizeof(struct evrpc_meta));
+ EVUTIL_ASSERT(meta != NULL);
+ meta->key = mm_strdup(key);
+ EVUTIL_ASSERT(meta->key != NULL);
+ meta->data_size = data_size;
+ meta->data = mm_malloc(data_size);
+ EVUTIL_ASSERT(meta->data != NULL);
+ memcpy(meta->data, data, data_size);
+
+ TAILQ_INSERT_TAIL(&store->meta_data, meta, next);
+}
+
+int
+evrpc_hook_find_meta(void *ctx, const char *key, void **data, size_t *data_size)
+{
+ struct evrpc_request_wrapper *req = ctx;
+ struct evrpc_meta *meta = NULL;
+
+ if (req->hook_meta == NULL)
+ return (-1);
+
+ TAILQ_FOREACH(meta, &req->hook_meta->meta_data, next) {
+ if (strcmp(meta->key, key) == 0) {
+ *data = meta->data;
+ *data_size = meta->data_size;
+ return (0);
+ }
+ }
+
+ return (-1);
+}
+
+struct evhttp_connection *
+evrpc_hook_get_connection(void *ctx)
+{
+ struct evrpc_request_wrapper *req = ctx;
+ return (req->hook_meta != NULL ? req->hook_meta->evcon : NULL);
+}
+
+int
+evrpc_send_request_generic(struct evrpc_pool *pool,
+ void *request, void *reply,
+ void (*cb)(struct evrpc_status *, void *, void *, void *),
+ void *cb_arg,
+ const char *rpcname,
+ void (*req_marshal)(struct evbuffer *, void *),
+ void (*rpl_clear)(void *),
+ int (*rpl_unmarshal)(void *, struct evbuffer *))
+{
+ struct evrpc_status status;
+ struct evrpc_request_wrapper *ctx;
+ ctx = evrpc_make_request_ctx(pool, request, reply,
+ rpcname, req_marshal, rpl_clear, rpl_unmarshal, cb, cb_arg);
+ if (ctx == NULL)
+ goto error;
+ return (evrpc_make_request(ctx));
+error:
+ memset(&status, 0, sizeof(status));
+ status.error = EVRPC_STATUS_ERR_UNSTARTED;
+ (*(cb))(&status, request, reply, cb_arg);
+ return (-1);
+}
+
+/** Takes a request object and fills it in with the right magic */
+static struct evrpc *
+evrpc_register_object(const char *name,
+ void *(*req_new)(void*), void *req_new_arg, void (*req_free)(void *),
+ int (*req_unmarshal)(void *, struct evbuffer *),
+ void *(*rpl_new)(void*), void *rpl_new_arg, void (*rpl_free)(void *),
+ int (*rpl_complete)(void *),
+ void (*rpl_marshal)(struct evbuffer *, void *))
+{
+ struct evrpc* rpc = (struct evrpc *)mm_calloc(1, sizeof(struct evrpc));
+ if (rpc == NULL)
+ return (NULL);
+ rpc->uri = mm_strdup(name);
+ if (rpc->uri == NULL) {
+ mm_free(rpc);
+ return (NULL);
+ }
+ rpc->request_new = req_new;
+ rpc->request_new_arg = req_new_arg;
+ rpc->request_free = req_free;
+ rpc->request_unmarshal = req_unmarshal;
+ rpc->reply_new = rpl_new;
+ rpc->reply_new_arg = rpl_new_arg;
+ rpc->reply_free = rpl_free;
+ rpc->reply_complete = rpl_complete;
+ rpc->reply_marshal = rpl_marshal;
+ return (rpc);
+}
+
+int
+evrpc_register_generic(struct evrpc_base *base, const char *name,
+ void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
+ void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
+ int (*req_unmarshal)(void *, struct evbuffer *),
+ void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
+ int (*rpl_complete)(void *),
+ void (*rpl_marshal)(struct evbuffer *, void *))
+{
+ struct evrpc* rpc =
+ evrpc_register_object(name, req_new, req_new_arg, req_free, req_unmarshal,
+ rpl_new, rpl_new_arg, rpl_free, rpl_complete, rpl_marshal);
+ if (rpc == NULL)
+ return (-1);
+ evrpc_register_rpc(base, rpc,
+ (void (*)(struct evrpc_req_generic*, void *))callback, cbarg);
+ return (0);
+}
+
+/** accessors for obscure and undocumented functionality */
+struct evrpc_pool *
+evrpc_request_get_pool(struct evrpc_request_wrapper *ctx)
+{
+ return (ctx->pool);
+}
+
+void
+evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
+ struct evrpc_pool *pool)
+{
+ ctx->pool = pool;
+}
+
+void
+evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
+ void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
+ void *cb_arg)
+{
+ ctx->cb = cb;
+ ctx->cb_arg = cb_arg;
+}
diff --git a/ipc/chromium/src/third_party/libevent/evsignal-internal.h b/ipc/chromium/src/third_party/libevent/evsignal-internal.h
new file mode 100644
index 0000000000..5cff03b525
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evsignal-internal.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVSIGNAL_INTERNAL_H_INCLUDED_
+#define EVSIGNAL_INTERNAL_H_INCLUDED_
+
+#ifndef evutil_socket_t
+#include "event2/util.h"
+#endif
+#include <signal.h>
+
+typedef void (*ev_sighandler_t)(int);
+
+/* Data structure for the default signal-handling implementation in signal.c
+ */
+struct evsig_info {
+ /* Event watching ev_signal_pair[1] */
+ struct event ev_signal;
+ /* Socketpair used to send notifications from the signal handler */
+ evutil_socket_t ev_signal_pair[2];
+ /* True iff we've added the ev_signal event yet. */
+ int ev_signal_added;
+ /* Count of the number of signals we're currently watching. */
+ int ev_n_signals_added;
+
+ /* Array of previous signal handler objects before Libevent started
+ * messing with them. Used to restore old signal handlers. */
+#ifdef EVENT__HAVE_SIGACTION
+ struct sigaction **sh_old;
+#else
+ ev_sighandler_t **sh_old;
+#endif
+ /* Size of sh_old. */
+ int sh_old_max;
+};
+int evsig_init_(struct event_base *);
+void evsig_dealloc_(struct event_base *);
+
+void evsig_set_base_(struct event_base *base);
+void evsig_free_globals_(void);
+
+#endif /* EVSIGNAL_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/evthread-internal.h b/ipc/chromium/src/third_party/libevent/evthread-internal.h
new file mode 100644
index 0000000000..83e409f09b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evthread-internal.h
@@ -0,0 +1,406 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVTHREAD_INTERNAL_H_INCLUDED_
+#define EVTHREAD_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include "event2/thread.h"
+#include "util-internal.h"
+
+struct event_base;
+
+#if !defined(_WIN32) && !defined(__CYGWIN__)
+/* On Windows, the way we currently make DLLs, it's not allowed for us to
+ * have shared global structures. Thus, we only do the direct-call-to-function
+ * code path if we know that the local shared library system supports it.
+ */
+#define EVTHREAD_EXPOSE_STRUCTS
+#endif
+
+#if ! defined(EVENT__DISABLE_THREAD_SUPPORT) && defined(EVTHREAD_EXPOSE_STRUCTS)
+/* Global function pointers to lock-related functions. NULL if locking isn't
+ enabled. */
+EVENT2_EXPORT_SYMBOL
+extern struct evthread_lock_callbacks evthread_lock_fns_;
+EVENT2_EXPORT_SYMBOL
+extern struct evthread_condition_callbacks evthread_cond_fns_;
+extern unsigned long (*evthread_id_fn_)(void);
+EVENT2_EXPORT_SYMBOL
+extern int evthread_lock_debugging_enabled_;
+
+/** Return the ID of the current thread, or 1 if threading isn't enabled. */
+#define EVTHREAD_GET_ID() \
+ (evthread_id_fn_ ? evthread_id_fn_() : 1)
+
+/** Return true iff we're in the thread that is currently (or most recently)
+ * running a given event_base's loop. Requires lock. */
+#define EVBASE_IN_THREAD(base) \
+ (evthread_id_fn_ == NULL || \
+ (base)->th_owner_id == evthread_id_fn_())
+
+/** Return true iff we need to notify the base's main thread about changes to
+ * its state, because it's currently running the main loop in another
+ * thread. Requires lock. */
+#define EVBASE_NEED_NOTIFY(base) \
+ (evthread_id_fn_ != NULL && \
+ (base)->running_loop && \
+ (base)->th_owner_id != evthread_id_fn_())
+
+/** Allocate a new lock, and store it in lockvar, a void*. Sets lockvar to
+ NULL if locking is not enabled. */
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) \
+ ((lockvar) = evthread_lock_fns_.alloc ? \
+ evthread_lock_fns_.alloc(locktype) : NULL)
+
+/** Free a given lock, if it is present and locking is enabled. */
+#define EVTHREAD_FREE_LOCK(lockvar, locktype) \
+ do { \
+ void *lock_tmp_ = (lockvar); \
+ if (lock_tmp_ && evthread_lock_fns_.free) \
+ evthread_lock_fns_.free(lock_tmp_, (locktype)); \
+ } while (0)
+
+/** Acquire a lock. */
+#define EVLOCK_LOCK(lockvar,mode) \
+ do { \
+ if (lockvar) \
+ evthread_lock_fns_.lock(mode, lockvar); \
+ } while (0)
+
+/** Release a lock */
+#define EVLOCK_UNLOCK(lockvar,mode) \
+ do { \
+ if (lockvar) \
+ evthread_lock_fns_.unlock(mode, lockvar); \
+ } while (0)
+
+/** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
+#define EVLOCK_SORTLOCKS_(lockvar1, lockvar2) \
+ do { \
+ if (lockvar1 && lockvar2 && lockvar1 > lockvar2) { \
+ void *tmp = lockvar1; \
+ lockvar1 = lockvar2; \
+ lockvar2 = tmp; \
+ } \
+ } while (0)
+
+/** Lock an event_base, if it is set up for locking. Acquires the lock
+ in the base structure whose field is named 'lockvar'. */
+#define EVBASE_ACQUIRE_LOCK(base, lockvar) do { \
+ EVLOCK_LOCK((base)->lockvar, 0); \
+ } while (0)
+
+/** Unlock an event_base, if it is set up for locking. */
+#define EVBASE_RELEASE_LOCK(base, lockvar) do { \
+ EVLOCK_UNLOCK((base)->lockvar, 0); \
+ } while (0)
+
+/** If lock debugging is enabled, and lock is non-null, assert that 'lock' is
+ * locked and held by us. */
+#define EVLOCK_ASSERT_LOCKED(lock) \
+ do { \
+ if ((lock) && evthread_lock_debugging_enabled_) { \
+ EVUTIL_ASSERT(evthread_is_debug_lock_held_(lock)); \
+ } \
+ } while (0)
+
+/** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
+ * manage to get it. */
+static inline int EVLOCK_TRY_LOCK_(void *lock);
+static inline int
+EVLOCK_TRY_LOCK_(void *lock)
+{
+ if (lock && evthread_lock_fns_.lock) {
+ int r = evthread_lock_fns_.lock(EVTHREAD_TRY, lock);
+ return !r;
+ } else {
+ /* Locking is disabled either globally or for this thing;
+ * of course we count as having the lock. */
+ return 1;
+ }
+}
+
+/** Allocate a new condition variable and store it in the void *, condvar */
+#define EVTHREAD_ALLOC_COND(condvar) \
+ do { \
+ (condvar) = evthread_cond_fns_.alloc_condition ? \
+ evthread_cond_fns_.alloc_condition(0) : NULL; \
+ } while (0)
+/** Deallocate and free a condition variable in condvar */
+#define EVTHREAD_FREE_COND(cond) \
+ do { \
+ if (cond) \
+ evthread_cond_fns_.free_condition((cond)); \
+ } while (0)
+/** Signal one thread waiting on cond */
+#define EVTHREAD_COND_SIGNAL(cond) \
+ ( (cond) ? evthread_cond_fns_.signal_condition((cond), 0) : 0 )
+/** Signal all threads waiting on cond */
+#define EVTHREAD_COND_BROADCAST(cond) \
+ ( (cond) ? evthread_cond_fns_.signal_condition((cond), 1) : 0 )
+/** Wait until the condition 'cond' is signalled. Must be called while
+ * holding 'lock'. The lock will be released until the condition is
+ * signalled, at which point it will be acquired again. Returns 0 for
+ * success, -1 for failure. */
+#define EVTHREAD_COND_WAIT(cond, lock) \
+ ( (cond) ? evthread_cond_fns_.wait_condition((cond), (lock), NULL) : 0 )
+/** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed. Returns 1
+ * on timeout. */
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv) \
+ ( (cond) ? evthread_cond_fns_.wait_condition((cond), (lock), (tv)) : 0 )
+
+/** True iff locking functions have been configured. */
+#define EVTHREAD_LOCKING_ENABLED() \
+ (evthread_lock_fns_.lock != NULL)
+
+#elif ! defined(EVENT__DISABLE_THREAD_SUPPORT)
+
+unsigned long evthreadimpl_get_id_(void);
+EVENT2_EXPORT_SYMBOL
+int evthreadimpl_is_lock_debugging_enabled_(void);
+EVENT2_EXPORT_SYMBOL
+void *evthreadimpl_lock_alloc_(unsigned locktype);
+EVENT2_EXPORT_SYMBOL
+void evthreadimpl_lock_free_(void *lock, unsigned locktype);
+EVENT2_EXPORT_SYMBOL
+int evthreadimpl_lock_lock_(unsigned mode, void *lock);
+EVENT2_EXPORT_SYMBOL
+int evthreadimpl_lock_unlock_(unsigned mode, void *lock);
+EVENT2_EXPORT_SYMBOL
+void *evthreadimpl_cond_alloc_(unsigned condtype);
+EVENT2_EXPORT_SYMBOL
+void evthreadimpl_cond_free_(void *cond);
+EVENT2_EXPORT_SYMBOL
+int evthreadimpl_cond_signal_(void *cond, int broadcast);
+EVENT2_EXPORT_SYMBOL
+int evthreadimpl_cond_wait_(void *cond, void *lock, const struct timeval *tv);
+int evthreadimpl_locking_enabled_(void);
+
+#define EVTHREAD_GET_ID() evthreadimpl_get_id_()
+#define EVBASE_IN_THREAD(base) \
+ ((base)->th_owner_id == evthreadimpl_get_id_())
+#define EVBASE_NEED_NOTIFY(base) \
+ ((base)->running_loop && \
+ ((base)->th_owner_id != evthreadimpl_get_id_()))
+
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) \
+ ((lockvar) = evthreadimpl_lock_alloc_(locktype))
+
+#define EVTHREAD_FREE_LOCK(lockvar, locktype) \
+ do { \
+ void *lock_tmp_ = (lockvar); \
+ if (lock_tmp_) \
+ evthreadimpl_lock_free_(lock_tmp_, (locktype)); \
+ } while (0)
+
+/** Acquire a lock. */
+#define EVLOCK_LOCK(lockvar,mode) \
+ do { \
+ if (lockvar) \
+ evthreadimpl_lock_lock_(mode, lockvar); \
+ } while (0)
+
+/** Release a lock */
+#define EVLOCK_UNLOCK(lockvar,mode) \
+ do { \
+ if (lockvar) \
+ evthreadimpl_lock_unlock_(mode, lockvar); \
+ } while (0)
+
+/** Lock an event_base, if it is set up for locking. Acquires the lock
+ in the base structure whose field is named 'lockvar'. */
+#define EVBASE_ACQUIRE_LOCK(base, lockvar) do { \
+ EVLOCK_LOCK((base)->lockvar, 0); \
+ } while (0)
+
+/** Unlock an event_base, if it is set up for locking. */
+#define EVBASE_RELEASE_LOCK(base, lockvar) do { \
+ EVLOCK_UNLOCK((base)->lockvar, 0); \
+ } while (0)
+
+/** If lock debugging is enabled, and lock is non-null, assert that 'lock' is
+ * locked and held by us. */
+#define EVLOCK_ASSERT_LOCKED(lock) \
+ do { \
+ if ((lock) && evthreadimpl_is_lock_debugging_enabled_()) { \
+ EVUTIL_ASSERT(evthread_is_debug_lock_held_(lock)); \
+ } \
+ } while (0)
+
+/** Try to grab the lock for 'lockvar' without blocking, and return 1 if we
+ * manage to get it. */
+static inline int EVLOCK_TRY_LOCK_(void *lock);
+static inline int
+EVLOCK_TRY_LOCK_(void *lock)
+{
+ if (lock) {
+ int r = evthreadimpl_lock_lock_(EVTHREAD_TRY, lock);
+ return !r;
+ } else {
+ /* Locking is disabled either globally or for this thing;
+ * of course we count as having the lock. */
+ return 1;
+ }
+}
+
+/** Allocate a new condition variable and store it in the void *, condvar */
+#define EVTHREAD_ALLOC_COND(condvar) \
+ do { \
+ (condvar) = evthreadimpl_cond_alloc_(0); \
+ } while (0)
+/** Deallocate and free a condition variable in condvar */
+#define EVTHREAD_FREE_COND(cond) \
+ do { \
+ if (cond) \
+ evthreadimpl_cond_free_((cond)); \
+ } while (0)
+/** Signal one thread waiting on cond */
+#define EVTHREAD_COND_SIGNAL(cond) \
+ ( (cond) ? evthreadimpl_cond_signal_((cond), 0) : 0 )
+/** Signal all threads waiting on cond */
+#define EVTHREAD_COND_BROADCAST(cond) \
+ ( (cond) ? evthreadimpl_cond_signal_((cond), 1) : 0 )
+/** Wait until the condition 'cond' is signalled. Must be called while
+ * holding 'lock'. The lock will be released until the condition is
+ * signalled, at which point it will be acquired again. Returns 0 for
+ * success, -1 for failure. */
+#define EVTHREAD_COND_WAIT(cond, lock) \
+ ( (cond) ? evthreadimpl_cond_wait_((cond), (lock), NULL) : 0 )
+/** As EVTHREAD_COND_WAIT, but gives up after 'tv' has elapsed. Returns 1
+ * on timeout. */
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, tv) \
+ ( (cond) ? evthreadimpl_cond_wait_((cond), (lock), (tv)) : 0 )
+
+#define EVTHREAD_LOCKING_ENABLED() \
+ (evthreadimpl_locking_enabled_())
+
+#else /* EVENT__DISABLE_THREAD_SUPPORT */
+
+#define EVTHREAD_GET_ID() 1
+#define EVTHREAD_ALLOC_LOCK(lockvar, locktype) EVUTIL_NIL_STMT_
+#define EVTHREAD_FREE_LOCK(lockvar, locktype) EVUTIL_NIL_STMT_
+
+#define EVLOCK_LOCK(lockvar, mode) EVUTIL_NIL_STMT_
+#define EVLOCK_UNLOCK(lockvar, mode) EVUTIL_NIL_STMT_
+#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2) EVUTIL_NIL_STMT_
+#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2) EVUTIL_NIL_STMT_
+
+#define EVBASE_IN_THREAD(base) 1
+#define EVBASE_NEED_NOTIFY(base) 0
+#define EVBASE_ACQUIRE_LOCK(base, lock) EVUTIL_NIL_STMT_
+#define EVBASE_RELEASE_LOCK(base, lock) EVUTIL_NIL_STMT_
+#define EVLOCK_ASSERT_LOCKED(lock) EVUTIL_NIL_STMT_
+
+#define EVLOCK_TRY_LOCK_(lock) 1
+
+#define EVTHREAD_ALLOC_COND(condvar) EVUTIL_NIL_STMT_
+#define EVTHREAD_FREE_COND(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_SIGNAL(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_BROADCAST(cond) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_WAIT(cond, lock) EVUTIL_NIL_STMT_
+#define EVTHREAD_COND_WAIT_TIMED(cond, lock, howlong) EVUTIL_NIL_STMT_
+
+#define EVTHREAD_LOCKING_ENABLED() 0
+
+#endif
+
+/* This code is shared between both lock impls */
+#if ! defined(EVENT__DISABLE_THREAD_SUPPORT)
+/** Helper: put lockvar1 and lockvar2 into pointerwise ascending order. */
+#define EVLOCK_SORTLOCKS_(lockvar1, lockvar2) \
+ do { \
+ if (lockvar1 && lockvar2 && lockvar1 > lockvar2) { \
+ void *tmp = lockvar1; \
+ lockvar1 = lockvar2; \
+ lockvar2 = tmp; \
+ } \
+ } while (0)
+
+/** Acquire both lock1 and lock2. Always allocates locks in the same order,
+ * so that two threads locking two locks with LOCK2 will not deadlock. */
+#define EVLOCK_LOCK2(lock1,lock2,mode1,mode2) \
+ do { \
+ void *lock1_tmplock_ = (lock1); \
+ void *lock2_tmplock_ = (lock2); \
+ EVLOCK_SORTLOCKS_(lock1_tmplock_,lock2_tmplock_); \
+ EVLOCK_LOCK(lock1_tmplock_,mode1); \
+ if (lock2_tmplock_ != lock1_tmplock_) \
+ EVLOCK_LOCK(lock2_tmplock_,mode2); \
+ } while (0)
+/** Release both lock1 and lock2. */
+#define EVLOCK_UNLOCK2(lock1,lock2,mode1,mode2) \
+ do { \
+ void *lock1_tmplock_ = (lock1); \
+ void *lock2_tmplock_ = (lock2); \
+ EVLOCK_SORTLOCKS_(lock1_tmplock_,lock2_tmplock_); \
+ if (lock2_tmplock_ != lock1_tmplock_) \
+ EVLOCK_UNLOCK(lock2_tmplock_,mode2); \
+ EVLOCK_UNLOCK(lock1_tmplock_,mode1); \
+ } while (0)
+
+EVENT2_EXPORT_SYMBOL
+int evthread_is_debug_lock_held_(void *lock);
+void *evthread_debug_get_real_lock_(void *lock);
+
+void *evthread_setup_global_lock_(void *lock_, unsigned locktype,
+ int enable_locks);
+
+#define EVTHREAD_SETUP_GLOBAL_LOCK(lockvar, locktype) \
+ do { \
+ lockvar = evthread_setup_global_lock_(lockvar, \
+ (locktype), enable_locks); \
+ if (!lockvar) { \
+ event_warn("Couldn't allocate %s", #lockvar); \
+ return -1; \
+ } \
+ } while (0);
+
+int event_global_setup_locks_(const int enable_locks);
+int evsig_global_setup_locks_(const int enable_locks);
+int evutil_global_setup_locks_(const int enable_locks);
+int evutil_secure_rng_global_setup_locks_(const int enable_locks);
+
+/** Return current evthread_lock_callbacks */
+EVENT2_EXPORT_SYMBOL
+struct evthread_lock_callbacks *evthread_get_lock_callbacks(void);
+/** Return current evthread_condition_callbacks */
+struct evthread_condition_callbacks *evthread_get_condition_callbacks(void);
+/** Disable locking for internal usage (like global shutdown) */
+void evthreadimpl_disable_lock_debugging_(void);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVTHREAD_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/evthread.c b/ipc/chromium/src/third_party/libevent/evthread.c
new file mode 100644
index 0000000000..3eac594d64
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evthread.c
@@ -0,0 +1,509 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+
+#include "event2/thread.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "evthread-internal.h"
+
+#ifdef EVTHREAD_EXPOSE_STRUCTS
+#define GLOBAL
+#else
+#define GLOBAL static
+#endif
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+extern int event_debug_created_threadable_ctx_;
+extern int event_debug_mode_on_;
+#endif
+
+/* globals */
+GLOBAL int evthread_lock_debugging_enabled_ = 0;
+GLOBAL struct evthread_lock_callbacks evthread_lock_fns_ = {
+ 0, 0, NULL, NULL, NULL, NULL
+};
+GLOBAL unsigned long (*evthread_id_fn_)(void) = NULL;
+GLOBAL struct evthread_condition_callbacks evthread_cond_fns_ = {
+ 0, NULL, NULL, NULL, NULL
+};
+
+/* Used for debugging */
+static struct evthread_lock_callbacks original_lock_fns_ = {
+ 0, 0, NULL, NULL, NULL, NULL
+};
+static struct evthread_condition_callbacks original_cond_fns_ = {
+ 0, NULL, NULL, NULL, NULL
+};
+
+void
+evthread_set_id_callback(unsigned long (*id_fn)(void))
+{
+ evthread_id_fn_ = id_fn;
+}
+
+struct evthread_lock_callbacks *evthread_get_lock_callbacks()
+{
+ return evthread_lock_debugging_enabled_
+ ? &original_lock_fns_ : &evthread_lock_fns_;
+}
+struct evthread_condition_callbacks *evthread_get_condition_callbacks()
+{
+ return evthread_lock_debugging_enabled_
+ ? &original_cond_fns_ : &evthread_cond_fns_;
+}
+void evthreadimpl_disable_lock_debugging_(void)
+{
+ evthread_lock_debugging_enabled_ = 0;
+}
+
+int
+evthread_set_lock_callbacks(const struct evthread_lock_callbacks *cbs)
+{
+ struct evthread_lock_callbacks *target = evthread_get_lock_callbacks();
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_mode_on_) {
+ if (event_debug_created_threadable_ctx_) {
+ event_errx(1, "evthread initialization must be called BEFORE anything else!");
+ }
+ }
+#endif
+
+ if (!cbs) {
+ if (target->alloc)
+ event_warnx("Trying to disable lock functions after "
+ "they have been set up will probaby not work.");
+ memset(target, 0, sizeof(evthread_lock_fns_));
+ return 0;
+ }
+ if (target->alloc) {
+ /* Uh oh; we already had locking callbacks set up.*/
+ if (target->lock_api_version == cbs->lock_api_version &&
+ target->supported_locktypes == cbs->supported_locktypes &&
+ target->alloc == cbs->alloc &&
+ target->free == cbs->free &&
+ target->lock == cbs->lock &&
+ target->unlock == cbs->unlock) {
+ /* no change -- allow this. */
+ return 0;
+ }
+ event_warnx("Can't change lock callbacks once they have been "
+ "initialized.");
+ return -1;
+ }
+ if (cbs->alloc && cbs->free && cbs->lock && cbs->unlock) {
+ memcpy(target, cbs, sizeof(evthread_lock_fns_));
+ return event_global_setup_locks_(1);
+ } else {
+ return -1;
+ }
+}
+
+int
+evthread_set_condition_callbacks(const struct evthread_condition_callbacks *cbs)
+{
+ struct evthread_condition_callbacks *target = evthread_get_condition_callbacks();
+
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_mode_on_) {
+ if (event_debug_created_threadable_ctx_) {
+ event_errx(1, "evthread initialization must be called BEFORE anything else!");
+ }
+ }
+#endif
+
+ if (!cbs) {
+ if (target->alloc_condition)
+ event_warnx("Trying to disable condition functions "
+ "after they have been set up will probaby not "
+ "work.");
+ memset(target, 0, sizeof(evthread_cond_fns_));
+ return 0;
+ }
+ if (target->alloc_condition) {
+ /* Uh oh; we already had condition callbacks set up.*/
+ if (target->condition_api_version == cbs->condition_api_version &&
+ target->alloc_condition == cbs->alloc_condition &&
+ target->free_condition == cbs->free_condition &&
+ target->signal_condition == cbs->signal_condition &&
+ target->wait_condition == cbs->wait_condition) {
+ /* no change -- allow this. */
+ return 0;
+ }
+ event_warnx("Can't change condition callbacks once they "
+ "have been initialized.");
+ return -1;
+ }
+ if (cbs->alloc_condition && cbs->free_condition &&
+ cbs->signal_condition && cbs->wait_condition) {
+ memcpy(target, cbs, sizeof(evthread_cond_fns_));
+ }
+ if (evthread_lock_debugging_enabled_) {
+ evthread_cond_fns_.alloc_condition = cbs->alloc_condition;
+ evthread_cond_fns_.free_condition = cbs->free_condition;
+ evthread_cond_fns_.signal_condition = cbs->signal_condition;
+ }
+ return 0;
+}
+
+#define DEBUG_LOCK_SIG 0xdeb0b10c
+
+struct debug_lock {
+ unsigned signature;
+ unsigned locktype;
+ unsigned long held_by;
+ /* XXXX if we ever use read-write locks, we will need a separate
+ * lock to protect count. */
+ int count;
+ void *lock;
+};
+
+static void *
+debug_lock_alloc(unsigned locktype)
+{
+ struct debug_lock *result = mm_malloc(sizeof(struct debug_lock));
+ if (!result)
+ return NULL;
+ if (original_lock_fns_.alloc) {
+ if (!(result->lock = original_lock_fns_.alloc(
+ locktype|EVTHREAD_LOCKTYPE_RECURSIVE))) {
+ mm_free(result);
+ return NULL;
+ }
+ } else {
+ result->lock = NULL;
+ }
+ result->signature = DEBUG_LOCK_SIG;
+ result->locktype = locktype;
+ result->count = 0;
+ result->held_by = 0;
+ return result;
+}
+
+static void
+debug_lock_free(void *lock_, unsigned locktype)
+{
+ struct debug_lock *lock = lock_;
+ EVUTIL_ASSERT(lock->count == 0);
+ EVUTIL_ASSERT(locktype == lock->locktype);
+ EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
+ if (original_lock_fns_.free) {
+ original_lock_fns_.free(lock->lock,
+ lock->locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
+ }
+ lock->lock = NULL;
+ lock->count = -100;
+ lock->signature = 0x12300fda;
+ mm_free(lock);
+}
+
+static void
+evthread_debug_lock_mark_locked(unsigned mode, struct debug_lock *lock)
+{
+ EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
+ ++lock->count;
+ if (!(lock->locktype & EVTHREAD_LOCKTYPE_RECURSIVE))
+ EVUTIL_ASSERT(lock->count == 1);
+ if (evthread_id_fn_) {
+ unsigned long me;
+ me = evthread_id_fn_();
+ if (lock->count > 1)
+ EVUTIL_ASSERT(lock->held_by == me);
+ lock->held_by = me;
+ }
+}
+
+static int
+debug_lock_lock(unsigned mode, void *lock_)
+{
+ struct debug_lock *lock = lock_;
+ int res = 0;
+ if (lock->locktype & EVTHREAD_LOCKTYPE_READWRITE)
+ EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
+ else
+ EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
+ if (original_lock_fns_.lock)
+ res = original_lock_fns_.lock(mode, lock->lock);
+ if (!res) {
+ evthread_debug_lock_mark_locked(mode, lock);
+ }
+ return res;
+}
+
+static void
+evthread_debug_lock_mark_unlocked(unsigned mode, struct debug_lock *lock)
+{
+ EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
+ if (lock->locktype & EVTHREAD_LOCKTYPE_READWRITE)
+ EVUTIL_ASSERT(mode & (EVTHREAD_READ|EVTHREAD_WRITE));
+ else
+ EVUTIL_ASSERT((mode & (EVTHREAD_READ|EVTHREAD_WRITE)) == 0);
+ if (evthread_id_fn_) {
+ unsigned long me;
+ me = evthread_id_fn_();
+ EVUTIL_ASSERT(lock->held_by == me);
+ if (lock->count == 1)
+ lock->held_by = 0;
+ }
+ --lock->count;
+ EVUTIL_ASSERT(lock->count >= 0);
+}
+
+static int
+debug_lock_unlock(unsigned mode, void *lock_)
+{
+ struct debug_lock *lock = lock_;
+ int res = 0;
+ evthread_debug_lock_mark_unlocked(mode, lock);
+ if (original_lock_fns_.unlock)
+ res = original_lock_fns_.unlock(mode, lock->lock);
+ return res;
+}
+
+static int
+debug_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
+{
+ int r;
+ struct debug_lock *lock = lock_;
+ EVUTIL_ASSERT(lock);
+ EVUTIL_ASSERT(DEBUG_LOCK_SIG == lock->signature);
+ EVLOCK_ASSERT_LOCKED(lock_);
+ evthread_debug_lock_mark_unlocked(0, lock);
+ r = original_cond_fns_.wait_condition(cond_, lock->lock, tv);
+ evthread_debug_lock_mark_locked(0, lock);
+ return r;
+}
+
+/* misspelled version for backward compatibility */
+void
+evthread_enable_lock_debuging(void)
+{
+ evthread_enable_lock_debugging();
+}
+
+void
+evthread_enable_lock_debugging(void)
+{
+ struct evthread_lock_callbacks cbs = {
+ EVTHREAD_LOCK_API_VERSION,
+ EVTHREAD_LOCKTYPE_RECURSIVE,
+ debug_lock_alloc,
+ debug_lock_free,
+ debug_lock_lock,
+ debug_lock_unlock
+ };
+ if (evthread_lock_debugging_enabled_)
+ return;
+ memcpy(&original_lock_fns_, &evthread_lock_fns_,
+ sizeof(struct evthread_lock_callbacks));
+ memcpy(&evthread_lock_fns_, &cbs,
+ sizeof(struct evthread_lock_callbacks));
+
+ memcpy(&original_cond_fns_, &evthread_cond_fns_,
+ sizeof(struct evthread_condition_callbacks));
+ evthread_cond_fns_.wait_condition = debug_cond_wait;
+ evthread_lock_debugging_enabled_ = 1;
+
+ /* XXX return value should get checked. */
+ event_global_setup_locks_(0);
+}
+
+int
+evthread_is_debug_lock_held_(void *lock_)
+{
+ struct debug_lock *lock = lock_;
+ if (! lock->count)
+ return 0;
+ if (evthread_id_fn_) {
+ unsigned long me = evthread_id_fn_();
+ if (lock->held_by != me)
+ return 0;
+ }
+ return 1;
+}
+
+void *
+evthread_debug_get_real_lock_(void *lock_)
+{
+ struct debug_lock *lock = lock_;
+ return lock->lock;
+}
+
+void *
+evthread_setup_global_lock_(void *lock_, unsigned locktype, int enable_locks)
+{
+ /* there are four cases here:
+ 1) we're turning on debugging; locking is not on.
+ 2) we're turning on debugging; locking is on.
+ 3) we're turning on locking; debugging is not on.
+ 4) we're turning on locking; debugging is on. */
+
+ if (!enable_locks && original_lock_fns_.alloc == NULL) {
+ /* Case 1: allocate a debug lock. */
+ EVUTIL_ASSERT(lock_ == NULL);
+ return debug_lock_alloc(locktype);
+ } else if (!enable_locks && original_lock_fns_.alloc != NULL) {
+ /* Case 2: wrap the lock in a debug lock. */
+ struct debug_lock *lock;
+ EVUTIL_ASSERT(lock_ != NULL);
+
+ if (!(locktype & EVTHREAD_LOCKTYPE_RECURSIVE)) {
+ /* We can't wrap it: We need a recursive lock */
+ original_lock_fns_.free(lock_, locktype);
+ return debug_lock_alloc(locktype);
+ }
+ lock = mm_malloc(sizeof(struct debug_lock));
+ if (!lock) {
+ original_lock_fns_.free(lock_, locktype);
+ return NULL;
+ }
+ lock->lock = lock_;
+ lock->locktype = locktype;
+ lock->count = 0;
+ lock->held_by = 0;
+ return lock;
+ } else if (enable_locks && ! evthread_lock_debugging_enabled_) {
+ /* Case 3: allocate a regular lock */
+ EVUTIL_ASSERT(lock_ == NULL);
+ return evthread_lock_fns_.alloc(locktype);
+ } else {
+ /* Case 4: Fill in a debug lock with a real lock */
+ struct debug_lock *lock = lock_ ? lock_ : debug_lock_alloc(locktype);
+ EVUTIL_ASSERT(enable_locks &&
+ evthread_lock_debugging_enabled_);
+ EVUTIL_ASSERT(lock->locktype == locktype);
+ if (!lock->lock) {
+ lock->lock = original_lock_fns_.alloc(
+ locktype|EVTHREAD_LOCKTYPE_RECURSIVE);
+ if (!lock->lock) {
+ lock->count = -200;
+ mm_free(lock);
+ return NULL;
+ }
+ }
+ return lock;
+ }
+}
+
+
+#ifndef EVTHREAD_EXPOSE_STRUCTS
+unsigned long
+evthreadimpl_get_id_()
+{
+ return evthread_id_fn_ ? evthread_id_fn_() : 1;
+}
+void *
+evthreadimpl_lock_alloc_(unsigned locktype)
+{
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_mode_on_) {
+ event_debug_created_threadable_ctx_ = 1;
+ }
+#endif
+
+ return evthread_lock_fns_.alloc ?
+ evthread_lock_fns_.alloc(locktype) : NULL;
+}
+void
+evthreadimpl_lock_free_(void *lock, unsigned locktype)
+{
+ if (evthread_lock_fns_.free)
+ evthread_lock_fns_.free(lock, locktype);
+}
+int
+evthreadimpl_lock_lock_(unsigned mode, void *lock)
+{
+ if (evthread_lock_fns_.lock)
+ return evthread_lock_fns_.lock(mode, lock);
+ else
+ return 0;
+}
+int
+evthreadimpl_lock_unlock_(unsigned mode, void *lock)
+{
+ if (evthread_lock_fns_.unlock)
+ return evthread_lock_fns_.unlock(mode, lock);
+ else
+ return 0;
+}
+void *
+evthreadimpl_cond_alloc_(unsigned condtype)
+{
+#ifndef EVENT__DISABLE_DEBUG_MODE
+ if (event_debug_mode_on_) {
+ event_debug_created_threadable_ctx_ = 1;
+ }
+#endif
+
+ return evthread_cond_fns_.alloc_condition ?
+ evthread_cond_fns_.alloc_condition(condtype) : NULL;
+}
+void
+evthreadimpl_cond_free_(void *cond)
+{
+ if (evthread_cond_fns_.free_condition)
+ evthread_cond_fns_.free_condition(cond);
+}
+int
+evthreadimpl_cond_signal_(void *cond, int broadcast)
+{
+ if (evthread_cond_fns_.signal_condition)
+ return evthread_cond_fns_.signal_condition(cond, broadcast);
+ else
+ return 0;
+}
+int
+evthreadimpl_cond_wait_(void *cond, void *lock, const struct timeval *tv)
+{
+ if (evthread_cond_fns_.wait_condition)
+ return evthread_cond_fns_.wait_condition(cond, lock, tv);
+ else
+ return 0;
+}
+int
+evthreadimpl_is_lock_debugging_enabled_(void)
+{
+ return evthread_lock_debugging_enabled_;
+}
+
+int
+evthreadimpl_locking_enabled_(void)
+{
+ return evthread_lock_fns_.lock != NULL;
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/evthread_pthread.c b/ipc/chromium/src/third_party/libevent/evthread_pthread.c
new file mode 100644
index 0000000000..4e11f74970
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evthread_pthread.c
@@ -0,0 +1,191 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+/* With glibc we need to define _GNU_SOURCE to get PTHREAD_MUTEX_RECURSIVE.
+ * This comes from evconfig-private.h
+ */
+#include <pthread.h>
+
+struct event_base;
+#include "event2/thread.h"
+
+#include <stdlib.h>
+#include <string.h>
+#include "mm-internal.h"
+#include "evthread-internal.h"
+
+static pthread_mutexattr_t attr_recursive;
+
+static void *
+evthread_posix_lock_alloc(unsigned locktype)
+{
+ pthread_mutexattr_t *attr = NULL;
+ pthread_mutex_t *lock = mm_malloc(sizeof(pthread_mutex_t));
+ if (!lock)
+ return NULL;
+ if (locktype & EVTHREAD_LOCKTYPE_RECURSIVE)
+ attr = &attr_recursive;
+ if (pthread_mutex_init(lock, attr)) {
+ mm_free(lock);
+ return NULL;
+ }
+ return lock;
+}
+
+static void
+evthread_posix_lock_free(void *lock_, unsigned locktype)
+{
+ pthread_mutex_t *lock = lock_;
+ pthread_mutex_destroy(lock);
+ mm_free(lock);
+}
+
+static int
+evthread_posix_lock(unsigned mode, void *lock_)
+{
+ pthread_mutex_t *lock = lock_;
+ if (mode & EVTHREAD_TRY)
+ return pthread_mutex_trylock(lock);
+ else
+ return pthread_mutex_lock(lock);
+}
+
+static int
+evthread_posix_unlock(unsigned mode, void *lock_)
+{
+ pthread_mutex_t *lock = lock_;
+ return pthread_mutex_unlock(lock);
+}
+
+static unsigned long
+evthread_posix_get_id(void)
+{
+ union {
+ pthread_t thr;
+#if EVENT__SIZEOF_PTHREAD_T > EVENT__SIZEOF_LONG
+ ev_uint64_t id;
+#else
+ unsigned long id;
+#endif
+ } r;
+#if EVENT__SIZEOF_PTHREAD_T < EVENT__SIZEOF_LONG
+ memset(&r, 0, sizeof(r));
+#endif
+ r.thr = pthread_self();
+ return (unsigned long)r.id;
+}
+
+static void *
+evthread_posix_cond_alloc(unsigned condflags)
+{
+ pthread_cond_t *cond = mm_malloc(sizeof(pthread_cond_t));
+ if (!cond)
+ return NULL;
+ if (pthread_cond_init(cond, NULL)) {
+ mm_free(cond);
+ return NULL;
+ }
+ return cond;
+}
+
+static void
+evthread_posix_cond_free(void *cond_)
+{
+ pthread_cond_t *cond = cond_;
+ pthread_cond_destroy(cond);
+ mm_free(cond);
+}
+
+static int
+evthread_posix_cond_signal(void *cond_, int broadcast)
+{
+ pthread_cond_t *cond = cond_;
+ int r;
+ if (broadcast)
+ r = pthread_cond_broadcast(cond);
+ else
+ r = pthread_cond_signal(cond);
+ return r ? -1 : 0;
+}
+
+static int
+evthread_posix_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
+{
+ int r;
+ pthread_cond_t *cond = cond_;
+ pthread_mutex_t *lock = lock_;
+
+ if (tv) {
+ struct timeval now, abstime;
+ struct timespec ts;
+ evutil_gettimeofday(&now, NULL);
+ evutil_timeradd(&now, tv, &abstime);
+ ts.tv_sec = abstime.tv_sec;
+ ts.tv_nsec = abstime.tv_usec*1000;
+ r = pthread_cond_timedwait(cond, lock, &ts);
+ if (r == ETIMEDOUT)
+ return 1;
+ else if (r)
+ return -1;
+ else
+ return 0;
+ } else {
+ r = pthread_cond_wait(cond, lock);
+ return r ? -1 : 0;
+ }
+}
+
+int
+evthread_use_pthreads(void)
+{
+ struct evthread_lock_callbacks cbs = {
+ EVTHREAD_LOCK_API_VERSION,
+ EVTHREAD_LOCKTYPE_RECURSIVE,
+ evthread_posix_lock_alloc,
+ evthread_posix_lock_free,
+ evthread_posix_lock,
+ evthread_posix_unlock
+ };
+ struct evthread_condition_callbacks cond_cbs = {
+ EVTHREAD_CONDITION_API_VERSION,
+ evthread_posix_cond_alloc,
+ evthread_posix_cond_free,
+ evthread_posix_cond_signal,
+ evthread_posix_cond_wait
+ };
+ /* Set ourselves up to get recursive locks. */
+ if (pthread_mutexattr_init(&attr_recursive))
+ return -1;
+ if (pthread_mutexattr_settype(&attr_recursive, PTHREAD_MUTEX_RECURSIVE))
+ return -1;
+
+ evthread_set_lock_callbacks(&cbs);
+ evthread_set_condition_callbacks(&cond_cbs);
+ evthread_set_id_callback(evthread_posix_get_id);
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/evthread_win32.c b/ipc/chromium/src/third_party/libevent/evthread_win32.c
new file mode 100644
index 0000000000..2ec80560a5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evthread_win32.c
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#include <sys/locking.h>
+#endif
+
+struct event_base;
+#include "event2/thread.h"
+
+#include "mm-internal.h"
+#include "evthread-internal.h"
+#include "time-internal.h"
+
+#define SPIN_COUNT 2000
+
+static void *
+evthread_win32_lock_create(unsigned locktype)
+{
+ CRITICAL_SECTION *lock = mm_malloc(sizeof(CRITICAL_SECTION));
+ if (!lock)
+ return NULL;
+ if (InitializeCriticalSectionAndSpinCount(lock, SPIN_COUNT) == 0) {
+ mm_free(lock);
+ return NULL;
+ }
+ return lock;
+}
+
+static void
+evthread_win32_lock_free(void *lock_, unsigned locktype)
+{
+ CRITICAL_SECTION *lock = lock_;
+ DeleteCriticalSection(lock);
+ mm_free(lock);
+}
+
+static int
+evthread_win32_lock(unsigned mode, void *lock_)
+{
+ CRITICAL_SECTION *lock = lock_;
+ if ((mode & EVTHREAD_TRY)) {
+ return ! TryEnterCriticalSection(lock);
+ } else {
+ EnterCriticalSection(lock);
+ return 0;
+ }
+}
+
+static int
+evthread_win32_unlock(unsigned mode, void *lock_)
+{
+ CRITICAL_SECTION *lock = lock_;
+ LeaveCriticalSection(lock);
+ return 0;
+}
+
+static unsigned long
+evthread_win32_get_id(void)
+{
+ return (unsigned long) GetCurrentThreadId();
+}
+
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+static void WINAPI (*InitializeConditionVariable_fn)(PCONDITION_VARIABLE)
+ = NULL;
+static BOOL WINAPI (*SleepConditionVariableCS_fn)(
+ PCONDITION_VARIABLE, PCRITICAL_SECTION, DWORD) = NULL;
+static void WINAPI (*WakeAllConditionVariable_fn)(PCONDITION_VARIABLE) = NULL;
+static void WINAPI (*WakeConditionVariable_fn)(PCONDITION_VARIABLE) = NULL;
+
+static int
+evthread_win32_condvar_init(void)
+{
+ HANDLE lib;
+
+ lib = GetModuleHandle(TEXT("kernel32.dll"));
+ if (lib == NULL)
+ return 0;
+
+#define LOAD(name) \
+ name##_fn = GetProcAddress(lib, #name)
+ LOAD(InitializeConditionVariable);
+ LOAD(SleepConditionVariableCS);
+ LOAD(WakeAllConditionVariable);
+ LOAD(WakeConditionVariable);
+
+ return InitializeConditionVariable_fn && SleepConditionVariableCS_fn &&
+ WakeAllConditionVariable_fn && WakeConditionVariable_fn;
+}
+
+/* XXXX Even if we can build this, we don't necessarily want to: the functions
+ * in question didn't exist before Vista, so we'd better LoadProc them. */
+static void *
+evthread_win32_condvar_alloc(unsigned condflags)
+{
+ CONDITION_VARIABLE *cond = mm_malloc(sizeof(CONDITION_VARIABLE));
+ if (!cond)
+ return NULL;
+ InitializeConditionVariable_fn(cond);
+ return cond;
+}
+
+static void
+evthread_win32_condvar_free(void *cond_)
+{
+ CONDITION_VARIABLE *cond = cond_;
+ /* There doesn't _seem_ to be a cleaup fn here... */
+ mm_free(cond);
+}
+
+static int
+evthread_win32_condvar_signal(void *cond, int broadcast)
+{
+ CONDITION_VARIABLE *cond = cond_;
+ if (broadcast)
+ WakeAllConditionVariable_fn(cond);
+ else
+ WakeConditionVariable_fn(cond);
+ return 0;
+}
+
+static int
+evthread_win32_condvar_wait(void *cond_, void *lock_, const struct timeval *tv)
+{
+ CONDITION_VARIABLE *cond = cond_;
+ CRITICAL_SECTION *lock = lock_;
+ DWORD ms, err;
+ BOOL result;
+
+ if (tv)
+ ms = evutil_tv_to_msec_(tv);
+ else
+ ms = INFINITE;
+ result = SleepConditionVariableCS_fn(cond, lock, ms);
+ if (result) {
+ if (GetLastError() == WAIT_TIMEOUT)
+ return 1;
+ else
+ return -1;
+ } else {
+ return 0;
+ }
+}
+#endif
+
+struct evthread_win32_cond {
+ HANDLE event;
+
+ CRITICAL_SECTION lock;
+ int n_waiting;
+ int n_to_wake;
+ int generation;
+};
+
+static void *
+evthread_win32_cond_alloc(unsigned flags)
+{
+ struct evthread_win32_cond *cond;
+ if (!(cond = mm_malloc(sizeof(struct evthread_win32_cond))))
+ return NULL;
+ if (InitializeCriticalSectionAndSpinCount(&cond->lock, SPIN_COUNT)==0) {
+ mm_free(cond);
+ return NULL;
+ }
+ if ((cond->event = CreateEvent(NULL,TRUE,FALSE,NULL)) == NULL) {
+ DeleteCriticalSection(&cond->lock);
+ mm_free(cond);
+ return NULL;
+ }
+ cond->n_waiting = cond->n_to_wake = cond->generation = 0;
+ return cond;
+}
+
+static void
+evthread_win32_cond_free(void *cond_)
+{
+ struct evthread_win32_cond *cond = cond_;
+ DeleteCriticalSection(&cond->lock);
+ CloseHandle(cond->event);
+ mm_free(cond);
+}
+
+static int
+evthread_win32_cond_signal(void *cond_, int broadcast)
+{
+ struct evthread_win32_cond *cond = cond_;
+ EnterCriticalSection(&cond->lock);
+ if (broadcast)
+ cond->n_to_wake = cond->n_waiting;
+ else
+ ++cond->n_to_wake;
+ cond->generation++;
+ SetEvent(cond->event);
+ LeaveCriticalSection(&cond->lock);
+ return 0;
+}
+
+static int
+evthread_win32_cond_wait(void *cond_, void *lock_, const struct timeval *tv)
+{
+ struct evthread_win32_cond *cond = cond_;
+ CRITICAL_SECTION *lock = lock_;
+ int generation_at_start;
+ int waiting = 1;
+ int result = -1;
+ DWORD ms = INFINITE, ms_orig = INFINITE, startTime, endTime;
+ if (tv)
+ ms_orig = ms = evutil_tv_to_msec_(tv);
+
+ EnterCriticalSection(&cond->lock);
+ ++cond->n_waiting;
+ generation_at_start = cond->generation;
+ LeaveCriticalSection(&cond->lock);
+
+ LeaveCriticalSection(lock);
+
+ startTime = GetTickCount();
+ do {
+ DWORD res;
+ res = WaitForSingleObject(cond->event, ms);
+ EnterCriticalSection(&cond->lock);
+ if (cond->n_to_wake &&
+ cond->generation != generation_at_start) {
+ --cond->n_to_wake;
+ --cond->n_waiting;
+ result = 0;
+ waiting = 0;
+ goto out;
+ } else if (res != WAIT_OBJECT_0) {
+ result = (res==WAIT_TIMEOUT) ? 1 : -1;
+ --cond->n_waiting;
+ waiting = 0;
+ goto out;
+ } else if (ms != INFINITE) {
+ endTime = GetTickCount();
+ if (startTime + ms_orig <= endTime) {
+ result = 1; /* Timeout */
+ --cond->n_waiting;
+ waiting = 0;
+ goto out;
+ } else {
+ ms = startTime + ms_orig - endTime;
+ }
+ }
+ /* If we make it here, we are still waiting. */
+ if (cond->n_to_wake == 0) {
+ /* There is nobody else who should wake up; reset
+ * the event. */
+ ResetEvent(cond->event);
+ }
+ out:
+ LeaveCriticalSection(&cond->lock);
+ } while (waiting);
+
+ EnterCriticalSection(lock);
+
+ EnterCriticalSection(&cond->lock);
+ if (!cond->n_waiting)
+ ResetEvent(cond->event);
+ LeaveCriticalSection(&cond->lock);
+
+ return result;
+}
+
+int
+evthread_use_windows_threads(void)
+{
+ struct evthread_lock_callbacks cbs = {
+ EVTHREAD_LOCK_API_VERSION,
+ EVTHREAD_LOCKTYPE_RECURSIVE,
+ evthread_win32_lock_create,
+ evthread_win32_lock_free,
+ evthread_win32_lock,
+ evthread_win32_unlock
+ };
+
+
+ struct evthread_condition_callbacks cond_cbs = {
+ EVTHREAD_CONDITION_API_VERSION,
+ evthread_win32_cond_alloc,
+ evthread_win32_cond_free,
+ evthread_win32_cond_signal,
+ evthread_win32_cond_wait
+ };
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+ struct evthread_condition_callbacks condvar_cbs = {
+ EVTHREAD_CONDITION_API_VERSION,
+ evthread_win32_condvar_alloc,
+ evthread_win32_condvar_free,
+ evthread_win32_condvar_signal,
+ evthread_win32_condvar_wait
+ };
+#endif
+
+ evthread_set_lock_callbacks(&cbs);
+ evthread_set_id_callback(evthread_win32_get_id);
+#ifdef WIN32_HAVE_CONDITION_VARIABLES
+ if (evthread_win32_condvar_init()) {
+ evthread_set_condition_callbacks(&condvar_cbs);
+ return 0;
+ }
+#endif
+ evthread_set_condition_callbacks(&cond_cbs);
+
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/evutil.c b/ipc/chromium/src/third_party/libevent/evutil.c
new file mode 100644
index 0000000000..9817f08643
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evutil.c
@@ -0,0 +1,2765 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <winerror.h>
+#include <ws2tcpip.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#include <io.h>
+#include <tchar.h>
+#include <process.h>
+#undef _WIN32_WINNT
+/* For structs needed by GetAdaptersAddresses */
+#define _WIN32_WINNT 0x0501
+#include <iphlpapi.h>
+#include <netioapi.h>
+#endif
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef EVENT__HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_TCP_H
+#include <netinet/tcp.h>
+#endif
+#ifdef EVENT__HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#include <time.h>
+#include <sys/stat.h>
+#ifndef _WIN32
+#include <net/if.h>
+#endif
+#ifdef EVENT__HAVE_IFADDRS_H
+#include <ifaddrs.h>
+#endif
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+#include "evthread-internal.h"
+
+#include "strlcpy-internal.h"
+#include "ipv6-internal.h"
+
+#ifdef _WIN32
+#define HT_NO_CACHE_HASH_VALUES
+#include "ht-internal.h"
+#define open _open
+#define read _read
+#define close _close
+#ifndef fstat
+#define fstat _fstati64
+#endif
+#ifndef stat
+#define stat _stati64
+#endif
+#define mode_t int
+#endif
+
+int
+evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode)
+{
+ int fd;
+
+#ifdef O_CLOEXEC
+ fd = open(pathname, flags|O_CLOEXEC, (mode_t)mode);
+ if (fd >= 0 || errno == EINVAL)
+ return fd;
+ /* If we got an EINVAL, fall through and try without O_CLOEXEC */
+#endif
+ fd = open(pathname, flags, (mode_t)mode);
+ if (fd < 0)
+ return -1;
+
+#if defined(FD_CLOEXEC)
+ if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) {
+ close(fd);
+ return -1;
+ }
+#endif
+
+ return fd;
+}
+
+/**
+ Read the contents of 'filename' into a newly allocated NUL-terminated
+ string. Set *content_out to hold this string, and *len_out to hold its
+ length (not including the appended NUL). If 'is_binary', open the file in
+ binary mode.
+
+ Returns 0 on success, -1 if the open fails, and -2 for all other failures.
+
+ Used internally only; may go away in a future version.
+ */
+int
+evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
+ int is_binary)
+{
+ int fd, r;
+ struct stat st;
+ char *mem;
+ size_t read_so_far=0;
+ int mode = O_RDONLY;
+
+ EVUTIL_ASSERT(content_out);
+ EVUTIL_ASSERT(len_out);
+ *content_out = NULL;
+ *len_out = 0;
+
+#ifdef O_BINARY
+ if (is_binary)
+ mode |= O_BINARY;
+#endif
+
+ fd = evutil_open_closeonexec_(filename, mode, 0);
+ if (fd < 0)
+ return -1;
+ if (fstat(fd, &st) || st.st_size < 0 ||
+ st.st_size > EV_SSIZE_MAX-1 ) {
+ close(fd);
+ return -2;
+ }
+ mem = mm_malloc((size_t)st.st_size + 1);
+ if (!mem) {
+ close(fd);
+ return -2;
+ }
+ read_so_far = 0;
+#ifdef _WIN32
+#define N_TO_READ(x) ((x) > INT_MAX) ? INT_MAX : ((int)(x))
+#else
+#define N_TO_READ(x) (x)
+#endif
+ while ((r = read(fd, mem+read_so_far, N_TO_READ(st.st_size - read_so_far))) > 0) {
+ read_so_far += r;
+ if (read_so_far >= (size_t)st.st_size)
+ break;
+ EVUTIL_ASSERT(read_so_far < (size_t)st.st_size);
+ }
+ close(fd);
+ if (r < 0) {
+ mm_free(mem);
+ return -2;
+ }
+ mem[read_so_far] = 0;
+
+ *len_out = read_so_far;
+ *content_out = mem;
+ return 0;
+}
+
+int
+evutil_socketpair(int family, int type, int protocol, evutil_socket_t fd[2])
+{
+#ifndef _WIN32
+ return socketpair(family, type, protocol, fd);
+#else
+ return evutil_ersatz_socketpair_(family, type, protocol, fd);
+#endif
+}
+
+int
+evutil_ersatz_socketpair_(int family, int type, int protocol,
+ evutil_socket_t fd[2])
+{
+ /* This code is originally from Tor. Used with permission. */
+
+ /* This socketpair does not work when localhost is down. So
+ * it's really not the same thing at all. But it's close enough
+ * for now, and really, when localhost is down sometimes, we
+ * have other problems too.
+ */
+#ifdef _WIN32
+#define ERR(e) WSA##e
+#else
+#define ERR(e) e
+#endif
+ evutil_socket_t listener = -1;
+ evutil_socket_t connector = -1;
+ evutil_socket_t acceptor = -1;
+ struct sockaddr_in listen_addr;
+ struct sockaddr_in connect_addr;
+ ev_socklen_t size;
+ int saved_errno = -1;
+ int family_test;
+
+ family_test = family != AF_INET;
+#ifdef AF_UNIX
+ family_test = family_test && (family != AF_UNIX);
+#endif
+ if (protocol || family_test) {
+ EVUTIL_SET_SOCKET_ERROR(ERR(EAFNOSUPPORT));
+ return -1;
+ }
+
+ if (!fd) {
+ EVUTIL_SET_SOCKET_ERROR(ERR(EINVAL));
+ return -1;
+ }
+
+ listener = socket(AF_INET, type, 0);
+ if (listener < 0)
+ return -1;
+ memset(&listen_addr, 0, sizeof(listen_addr));
+ listen_addr.sin_family = AF_INET;
+ listen_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ listen_addr.sin_port = 0; /* kernel chooses port. */
+ if (bind(listener, (struct sockaddr *) &listen_addr, sizeof (listen_addr))
+ == -1)
+ goto tidy_up_and_fail;
+ if (listen(listener, 1) == -1)
+ goto tidy_up_and_fail;
+
+ connector = socket(AF_INET, type, 0);
+ if (connector < 0)
+ goto tidy_up_and_fail;
+
+ memset(&connect_addr, 0, sizeof(connect_addr));
+
+ /* We want to find out the port number to connect to. */
+ size = sizeof(connect_addr);
+ if (getsockname(listener, (struct sockaddr *) &connect_addr, &size) == -1)
+ goto tidy_up_and_fail;
+ if (size != sizeof (connect_addr))
+ goto abort_tidy_up_and_fail;
+ if (connect(connector, (struct sockaddr *) &connect_addr,
+ sizeof(connect_addr)) == -1)
+ goto tidy_up_and_fail;
+
+ size = sizeof(listen_addr);
+ acceptor = accept(listener, (struct sockaddr *) &listen_addr, &size);
+ if (acceptor < 0)
+ goto tidy_up_and_fail;
+ if (size != sizeof(listen_addr))
+ goto abort_tidy_up_and_fail;
+ /* Now check we are talking to ourself by matching port and host on the
+ two sockets. */
+ if (getsockname(connector, (struct sockaddr *) &connect_addr, &size) == -1)
+ goto tidy_up_and_fail;
+ if (size != sizeof (connect_addr)
+ || listen_addr.sin_family != connect_addr.sin_family
+ || listen_addr.sin_addr.s_addr != connect_addr.sin_addr.s_addr
+ || listen_addr.sin_port != connect_addr.sin_port)
+ goto abort_tidy_up_and_fail;
+ evutil_closesocket(listener);
+ fd[0] = connector;
+ fd[1] = acceptor;
+
+ return 0;
+
+ abort_tidy_up_and_fail:
+ saved_errno = ERR(ECONNABORTED);
+ tidy_up_and_fail:
+ if (saved_errno < 0)
+ saved_errno = EVUTIL_SOCKET_ERROR();
+ if (listener != -1)
+ evutil_closesocket(listener);
+ if (connector != -1)
+ evutil_closesocket(connector);
+ if (acceptor != -1)
+ evutil_closesocket(acceptor);
+
+ EVUTIL_SET_SOCKET_ERROR(saved_errno);
+ return -1;
+#undef ERR
+}
+
+int
+evutil_make_socket_nonblocking(evutil_socket_t fd)
+{
+#ifdef _WIN32
+ {
+ unsigned long nonblocking = 1;
+ if (ioctlsocket(fd, FIONBIO, &nonblocking) == SOCKET_ERROR) {
+ event_sock_warn(fd, "fcntl(%d, F_GETFL)", (int)fd);
+ return -1;
+ }
+ }
+#else
+ {
+ int flags;
+ if ((flags = fcntl(fd, F_GETFL, NULL)) < 0) {
+ event_warn("fcntl(%d, F_GETFL)", fd);
+ return -1;
+ }
+ if (!(flags & O_NONBLOCK)) {
+ if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
+ event_warn("fcntl(%d, F_SETFL)", fd);
+ return -1;
+ }
+ }
+ }
+#endif
+ return 0;
+}
+
+/* Faster version of evutil_make_socket_nonblocking for internal use.
+ *
+ * Requires that no F_SETFL flags were previously set on the fd.
+ */
+static int
+evutil_fast_socket_nonblocking(evutil_socket_t fd)
+{
+#ifdef _WIN32
+ return evutil_make_socket_nonblocking(fd);
+#else
+ if (fcntl(fd, F_SETFL, O_NONBLOCK) == -1) {
+ event_warn("fcntl(%d, F_SETFL)", fd);
+ return -1;
+ }
+ return 0;
+#endif
+}
+
+int
+evutil_make_listen_socket_reuseable(evutil_socket_t sock)
+{
+#if defined(SO_REUSEADDR) && !defined(_WIN32)
+ int one = 1;
+ /* REUSEADDR on Unix means, "don't hang on to this address after the
+ * listener is closed." On Windows, though, it means "don't keep other
+ * processes from binding to this address while we're using it. */
+ return setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*) &one,
+ (ev_socklen_t)sizeof(one));
+#else
+ return 0;
+#endif
+}
+
+int
+evutil_make_listen_socket_reuseable_port(evutil_socket_t sock)
+{
+#if defined __linux__ && defined(SO_REUSEPORT)
+ int one = 1;
+ /* REUSEPORT on Linux 3.9+ means, "Multiple servers (processes or
+ * threads) can bind to the same port if they each set the option. */
+ return setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void*) &one,
+ (ev_socklen_t)sizeof(one));
+#else
+ return 0;
+#endif
+}
+
+int
+evutil_make_listen_socket_ipv6only(evutil_socket_t sock)
+{
+#if defined(IPV6_V6ONLY)
+ int one = 1;
+ return setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*) &one,
+ (ev_socklen_t)sizeof(one));
+#endif
+ return 0;
+}
+
+int
+evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock)
+{
+#if defined(EVENT__HAVE_NETINET_TCP_H) && defined(TCP_DEFER_ACCEPT)
+ int one = 1;
+
+ /* TCP_DEFER_ACCEPT tells the kernel to call defer accept() only after data
+ * has arrived and ready to read */
+ return setsockopt(sock, IPPROTO_TCP, TCP_DEFER_ACCEPT, &one,
+ (ev_socklen_t)sizeof(one));
+#endif
+ return 0;
+}
+
+int
+evutil_make_socket_closeonexec(evutil_socket_t fd)
+{
+#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
+ int flags;
+ if ((flags = fcntl(fd, F_GETFD, NULL)) < 0) {
+ event_warn("fcntl(%d, F_GETFD)", fd);
+ return -1;
+ }
+ if (!(flags & FD_CLOEXEC)) {
+ if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
+ event_warn("fcntl(%d, F_SETFD)", fd);
+ return -1;
+ }
+ }
+#endif
+ return 0;
+}
+
+/* Faster version of evutil_make_socket_closeonexec for internal use.
+ *
+ * Requires that no F_SETFD flags were previously set on the fd.
+ */
+static int
+evutil_fast_socket_closeonexec(evutil_socket_t fd)
+{
+#if !defined(_WIN32) && defined(EVENT__HAVE_SETFD)
+ if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
+ event_warn("fcntl(%d, F_SETFD)", fd);
+ return -1;
+ }
+#endif
+ return 0;
+}
+
+int
+evutil_closesocket(evutil_socket_t sock)
+{
+#ifndef _WIN32
+ return close(sock);
+#else
+ return closesocket(sock);
+#endif
+}
+
+ev_int64_t
+evutil_strtoll(const char *s, char **endptr, int base)
+{
+#ifdef EVENT__HAVE_STRTOLL
+ return (ev_int64_t)strtoll(s, endptr, base);
+#elif EVENT__SIZEOF_LONG == 8
+ return (ev_int64_t)strtol(s, endptr, base);
+#elif defined(_WIN32) && defined(_MSC_VER) && _MSC_VER < 1300
+ /* XXXX on old versions of MS APIs, we only support base
+ * 10. */
+ ev_int64_t r;
+ if (base != 10)
+ return 0;
+ r = (ev_int64_t) _atoi64(s);
+ while (isspace(*s))
+ ++s;
+ if (*s == '-')
+ ++s;
+ while (isdigit(*s))
+ ++s;
+ if (endptr)
+ *endptr = (char*) s;
+ return r;
+#elif defined(_WIN32)
+ return (ev_int64_t) _strtoi64(s, endptr, base);
+#elif defined(EVENT__SIZEOF_LONG_LONG) && EVENT__SIZEOF_LONG_LONG == 8
+ long long r;
+ int n;
+ if (base != 10 && base != 16)
+ return 0;
+ if (base == 10) {
+ n = sscanf(s, "%lld", &r);
+ } else {
+ unsigned long long ru=0;
+ n = sscanf(s, "%llx", &ru);
+ if (ru > EV_INT64_MAX)
+ return 0;
+ r = (long long) ru;
+ }
+ if (n != 1)
+ return 0;
+ while (EVUTIL_ISSPACE_(*s))
+ ++s;
+ if (*s == '-')
+ ++s;
+ if (base == 10) {
+ while (EVUTIL_ISDIGIT_(*s))
+ ++s;
+ } else {
+ while (EVUTIL_ISXDIGIT_(*s))
+ ++s;
+ }
+ if (endptr)
+ *endptr = (char*) s;
+ return r;
+#else
+#error "I don't know how to parse 64-bit integers."
+#endif
+}
+
+#ifdef _WIN32
+int
+evutil_socket_geterror(evutil_socket_t sock)
+{
+ int optval, optvallen=sizeof(optval);
+ int err = WSAGetLastError();
+ if (err == WSAEWOULDBLOCK && sock >= 0) {
+ if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)&optval,
+ &optvallen))
+ return err;
+ if (optval)
+ return optval;
+ }
+ return err;
+}
+#endif
+
+/* XXX we should use an enum here. */
+/* 2 for connection refused, 1 for connected, 0 for not yet, -1 for error. */
+int
+evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen)
+{
+ int made_fd = 0;
+
+ if (*fd_ptr < 0) {
+ if ((*fd_ptr = socket(sa->sa_family, SOCK_STREAM, 0)) < 0)
+ goto err;
+ made_fd = 1;
+ if (evutil_make_socket_nonblocking(*fd_ptr) < 0) {
+ goto err;
+ }
+ }
+
+ if (connect(*fd_ptr, sa, socklen) < 0) {
+ int e = evutil_socket_geterror(*fd_ptr);
+ if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
+ return 0;
+ if (EVUTIL_ERR_CONNECT_REFUSED(e))
+ return 2;
+ goto err;
+ } else {
+ return 1;
+ }
+
+err:
+ if (made_fd) {
+ evutil_closesocket(*fd_ptr);
+ *fd_ptr = -1;
+ }
+ return -1;
+}
+
+/* Check whether a socket on which we called connect() is done
+ connecting. Return 1 for connected, 0 for not yet, -1 for error. In the
+ error case, set the current socket errno to the error that happened during
+ the connect operation. */
+int
+evutil_socket_finished_connecting_(evutil_socket_t fd)
+{
+ int e;
+ ev_socklen_t elen = sizeof(e);
+
+ if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&e, &elen) < 0)
+ return -1;
+
+ if (e) {
+ if (EVUTIL_ERR_CONNECT_RETRIABLE(e))
+ return 0;
+ EVUTIL_SET_SOCKET_ERROR(e);
+ return -1;
+ }
+
+ return 1;
+}
+
+#if (EVUTIL_AI_PASSIVE|EVUTIL_AI_CANONNAME|EVUTIL_AI_NUMERICHOST| \
+ EVUTIL_AI_NUMERICSERV|EVUTIL_AI_V4MAPPED|EVUTIL_AI_ALL| \
+ EVUTIL_AI_ADDRCONFIG) != \
+ (EVUTIL_AI_PASSIVE^EVUTIL_AI_CANONNAME^EVUTIL_AI_NUMERICHOST^ \
+ EVUTIL_AI_NUMERICSERV^EVUTIL_AI_V4MAPPED^EVUTIL_AI_ALL^ \
+ EVUTIL_AI_ADDRCONFIG)
+#error "Some of our EVUTIL_AI_* flags seem to overlap with system AI_* flags"
+#endif
+
+/* We sometimes need to know whether we have an ipv4 address and whether we
+ have an ipv6 address. If 'have_checked_interfaces', then we've already done
+ the test. If 'had_ipv4_address', then it turns out we had an ipv4 address.
+ If 'had_ipv6_address', then it turns out we had an ipv6 address. These are
+ set by evutil_check_interfaces. */
+static int have_checked_interfaces, had_ipv4_address, had_ipv6_address;
+
+/* True iff the IPv4 address 'addr', in host order, is in 127.0.0.0/8 */
+static inline int evutil_v4addr_is_localhost(ev_uint32_t addr)
+{ return addr>>24 == 127; }
+
+/* True iff the IPv4 address 'addr', in host order, is link-local
+ * 169.254.0.0/16 (RFC3927) */
+static inline int evutil_v4addr_is_linklocal(ev_uint32_t addr)
+{ return ((addr & 0xffff0000U) == 0xa9fe0000U); }
+
+/* True iff the IPv4 address 'addr', in host order, is a class D
+ * (multiclass) address. */
+static inline int evutil_v4addr_is_classd(ev_uint32_t addr)
+{ return ((addr>>24) & 0xf0) == 0xe0; }
+
+int
+evutil_v4addr_is_local_(const struct in_addr *in)
+{
+ const ev_uint32_t addr = ntohl(in->s_addr);
+ return addr == INADDR_ANY ||
+ evutil_v4addr_is_localhost(addr) ||
+ evutil_v4addr_is_linklocal(addr) ||
+ evutil_v4addr_is_classd(addr);
+}
+int
+evutil_v6addr_is_local_(const struct in6_addr *in)
+{
+ static const char ZEROES[] =
+ "\x00\x00\x00\x00\x00\x00\x00\x00"
+ "\x00\x00\x00\x00\x00\x00\x00\x00";
+
+ const unsigned char *addr = (const unsigned char *)in->s6_addr;
+ return !memcmp(addr, ZEROES, 8) ||
+ ((addr[0] & 0xfe) == 0xfc) ||
+ (addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80) ||
+ (addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0) ||
+ (addr[0] == 0xff);
+}
+
+static void
+evutil_found_ifaddr(const struct sockaddr *sa)
+{
+ if (sa->sa_family == AF_INET) {
+ const struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+ if (!evutil_v4addr_is_local_(&sin->sin_addr)) {
+ event_debug(("Detected an IPv4 interface"));
+ had_ipv4_address = 1;
+ }
+ } else if (sa->sa_family == AF_INET6) {
+ const struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+ if (!evutil_v6addr_is_local_(&sin6->sin6_addr)) {
+ event_debug(("Detected an IPv6 interface"));
+ had_ipv6_address = 1;
+ }
+ }
+}
+
+#ifdef _WIN32
+typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
+ ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
+#endif
+
+static int
+evutil_check_ifaddrs(void)
+{
+#if defined(EVENT__HAVE_GETIFADDRS)
+ /* Most free Unixy systems provide getifaddrs, which gives us a linked list
+ * of struct ifaddrs. */
+ struct ifaddrs *ifa = NULL;
+ const struct ifaddrs *i;
+ if (getifaddrs(&ifa) < 0) {
+ event_warn("Unable to call getifaddrs()");
+ return -1;
+ }
+
+ for (i = ifa; i; i = i->ifa_next) {
+ if (!i->ifa_addr)
+ continue;
+ evutil_found_ifaddr(i->ifa_addr);
+ }
+
+ freeifaddrs(ifa);
+ return 0;
+#elif defined(_WIN32)
+ /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
+ "GetAdaptersInfo", but that's deprecated; let's just try
+ GetAdaptersAddresses and fall back to connect+getsockname.
+ */
+ HMODULE lib = evutil_load_windows_system_library_(TEXT("iphlpapi.dll"));
+ GetAdaptersAddresses_fn_t fn;
+ ULONG size, res;
+ IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
+ int result = -1;
+
+#define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
+ GAA_FLAG_SKIP_MULTICAST | \
+ GAA_FLAG_SKIP_DNS_SERVER)
+
+ if (!lib)
+ goto done;
+
+ if (!(fn = (GetAdaptersAddresses_fn_t) GetProcAddress(lib, "GetAdaptersAddresses")))
+ goto done;
+
+ /* Guess how much space we need. */
+ size = 15*1024;
+ addresses = mm_malloc(size);
+ if (!addresses)
+ goto done;
+ res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
+ if (res == ERROR_BUFFER_OVERFLOW) {
+ /* we didn't guess that we needed enough space; try again */
+ mm_free(addresses);
+ addresses = mm_malloc(size);
+ if (!addresses)
+ goto done;
+ res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
+ }
+ if (res != NO_ERROR)
+ goto done;
+
+ for (address = addresses; address; address = address->Next) {
+ IP_ADAPTER_UNICAST_ADDRESS *a;
+ for (a = address->FirstUnicastAddress; a; a = a->Next) {
+ /* Yes, it's a linked list inside a linked list */
+ struct sockaddr *sa = a->Address.lpSockaddr;
+ evutil_found_ifaddr(sa);
+ }
+ }
+
+ result = 0;
+done:
+ if (lib)
+ FreeLibrary(lib);
+ if (addresses)
+ mm_free(addresses);
+ return result;
+#else
+ return -1;
+#endif
+}
+
+/* Test whether we have an ipv4 interface and an ipv6 interface. Return 0 if
+ * the test seemed successful. */
+static int
+evutil_check_interfaces(void)
+{
+ evutil_socket_t fd = -1;
+ struct sockaddr_in sin, sin_out;
+ struct sockaddr_in6 sin6, sin6_out;
+ ev_socklen_t sin_out_len = sizeof(sin_out);
+ ev_socklen_t sin6_out_len = sizeof(sin6_out);
+ int r;
+ if (have_checked_interfaces)
+ return 0;
+
+ /* From this point on we have done the ipv4/ipv6 interface check */
+ have_checked_interfaces = 1;
+
+ if (evutil_check_ifaddrs() == 0) {
+ /* Use a nice sane interface, if this system has one. */
+ return 0;
+ }
+
+ /* Ugh. There was no nice sane interface. So to check whether we have
+ * an interface open for a given protocol, will try to make a UDP
+ * 'connection' to a remote host on the internet. We don't actually
+ * use it, so the address doesn't matter, but we want to pick one that
+ * keep us from using a host- or link-local interface. */
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(53);
+ r = evutil_inet_pton(AF_INET, "18.244.0.188", &sin.sin_addr);
+ EVUTIL_ASSERT(r);
+
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(53);
+ r = evutil_inet_pton(AF_INET6, "2001:4860:b002::68", &sin6.sin6_addr);
+ EVUTIL_ASSERT(r);
+
+ memset(&sin_out, 0, sizeof(sin_out));
+ memset(&sin6_out, 0, sizeof(sin6_out));
+
+ /* XXX some errnos mean 'no address'; some mean 'not enough sockets'. */
+ if ((fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
+ connect(fd, (struct sockaddr*)&sin, sizeof(sin)) == 0 &&
+ getsockname(fd, (struct sockaddr*)&sin_out, &sin_out_len) == 0) {
+ /* We might have an IPv4 interface. */
+ evutil_found_ifaddr((struct sockaddr*) &sin_out);
+ }
+ if (fd >= 0)
+ evutil_closesocket(fd);
+
+ if ((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)) >= 0 &&
+ connect(fd, (struct sockaddr*)&sin6, sizeof(sin6)) == 0 &&
+ getsockname(fd, (struct sockaddr*)&sin6_out, &sin6_out_len) == 0) {
+ /* We might have an IPv6 interface. */
+ evutil_found_ifaddr((struct sockaddr*) &sin6_out);
+ }
+
+ if (fd >= 0)
+ evutil_closesocket(fd);
+
+ return 0;
+}
+
+/* Internal addrinfo flag. This one is set when we allocate the addrinfo from
+ * inside libevent. Otherwise, the built-in getaddrinfo() function allocated
+ * it, and we should trust what they said.
+ **/
+#define EVUTIL_AI_LIBEVENT_ALLOCATED 0x80000000
+
+/* Helper: construct a new addrinfo containing the socket address in
+ * 'sa', which must be a sockaddr_in or a sockaddr_in6. Take the
+ * socktype and protocol info from hints. If they weren't set, then
+ * allocate both a TCP and a UDP addrinfo.
+ */
+struct evutil_addrinfo *
+evutil_new_addrinfo_(struct sockaddr *sa, ev_socklen_t socklen,
+ const struct evutil_addrinfo *hints)
+{
+ struct evutil_addrinfo *res;
+ EVUTIL_ASSERT(hints);
+
+ if (hints->ai_socktype == 0 && hints->ai_protocol == 0) {
+ /* Indecisive user! Give them a UDP and a TCP. */
+ struct evutil_addrinfo *r1, *r2;
+ struct evutil_addrinfo tmp;
+ memcpy(&tmp, hints, sizeof(tmp));
+ tmp.ai_socktype = SOCK_STREAM; tmp.ai_protocol = IPPROTO_TCP;
+ r1 = evutil_new_addrinfo_(sa, socklen, &tmp);
+ if (!r1)
+ return NULL;
+ tmp.ai_socktype = SOCK_DGRAM; tmp.ai_protocol = IPPROTO_UDP;
+ r2 = evutil_new_addrinfo_(sa, socklen, &tmp);
+ if (!r2) {
+ evutil_freeaddrinfo(r1);
+ return NULL;
+ }
+ r1->ai_next = r2;
+ return r1;
+ }
+
+ /* We're going to allocate extra space to hold the sockaddr. */
+ res = mm_calloc(1,sizeof(struct evutil_addrinfo)+socklen);
+ if (!res)
+ return NULL;
+ res->ai_addr = (struct sockaddr*)
+ (((char*)res) + sizeof(struct evutil_addrinfo));
+ memcpy(res->ai_addr, sa, socklen);
+ res->ai_addrlen = socklen;
+ res->ai_family = sa->sa_family; /* Same or not? XXX */
+ res->ai_flags = EVUTIL_AI_LIBEVENT_ALLOCATED;
+ res->ai_socktype = hints->ai_socktype;
+ res->ai_protocol = hints->ai_protocol;
+
+ return res;
+}
+
+/* Append the addrinfo 'append' to the end of 'first', and return the start of
+ * the list. Either element can be NULL, in which case we return the element
+ * that is not NULL. */
+struct evutil_addrinfo *
+evutil_addrinfo_append_(struct evutil_addrinfo *first,
+ struct evutil_addrinfo *append)
+{
+ struct evutil_addrinfo *ai = first;
+ if (!ai)
+ return append;
+ while (ai->ai_next)
+ ai = ai->ai_next;
+ ai->ai_next = append;
+
+ return first;
+}
+
+static int
+parse_numeric_servname(const char *servname)
+{
+ int n;
+ char *endptr=NULL;
+ n = (int) strtol(servname, &endptr, 10);
+ if (n>=0 && n <= 65535 && servname[0] && endptr && !endptr[0])
+ return n;
+ else
+ return -1;
+}
+
+/** Parse a service name in 'servname', which can be a decimal port.
+ * Return the port number, or -1 on error.
+ */
+static int
+evutil_parse_servname(const char *servname, const char *protocol,
+ const struct evutil_addrinfo *hints)
+{
+ int n = parse_numeric_servname(servname);
+ if (n>=0)
+ return n;
+#if defined(EVENT__HAVE_GETSERVBYNAME) || defined(_WIN32)
+ if (!(hints->ai_flags & EVUTIL_AI_NUMERICSERV)) {
+ struct servent *ent = getservbyname(servname, protocol);
+ if (ent) {
+ return ntohs(ent->s_port);
+ }
+ }
+#endif
+ return -1;
+}
+
+/* Return a string corresponding to a protocol number that we can pass to
+ * getservyname. */
+static const char *
+evutil_unparse_protoname(int proto)
+{
+ switch (proto) {
+ case 0:
+ return NULL;
+ case IPPROTO_TCP:
+ return "tcp";
+ case IPPROTO_UDP:
+ return "udp";
+#ifdef IPPROTO_SCTP
+ case IPPROTO_SCTP:
+ return "sctp";
+#endif
+ default:
+#ifdef EVENT__HAVE_GETPROTOBYNUMBER
+ {
+ struct protoent *ent = getprotobynumber(proto);
+ if (ent)
+ return ent->p_name;
+ }
+#endif
+ return NULL;
+ }
+}
+
+static void
+evutil_getaddrinfo_infer_protocols(struct evutil_addrinfo *hints)
+{
+ /* If we can guess the protocol from the socktype, do so. */
+ if (!hints->ai_protocol && hints->ai_socktype) {
+ if (hints->ai_socktype == SOCK_DGRAM)
+ hints->ai_protocol = IPPROTO_UDP;
+ else if (hints->ai_socktype == SOCK_STREAM)
+ hints->ai_protocol = IPPROTO_TCP;
+ }
+
+ /* Set the socktype if it isn't set. */
+ if (!hints->ai_socktype && hints->ai_protocol) {
+ if (hints->ai_protocol == IPPROTO_UDP)
+ hints->ai_socktype = SOCK_DGRAM;
+ else if (hints->ai_protocol == IPPROTO_TCP)
+ hints->ai_socktype = SOCK_STREAM;
+#ifdef IPPROTO_SCTP
+ else if (hints->ai_protocol == IPPROTO_SCTP)
+ hints->ai_socktype = SOCK_STREAM;
+#endif
+ }
+}
+
+#if AF_UNSPEC != PF_UNSPEC
+#error "I cannot build on a system where AF_UNSPEC != PF_UNSPEC"
+#endif
+
+/** Implements the part of looking up hosts by name that's common to both
+ * the blocking and nonblocking resolver:
+ * - Adjust 'hints' to have a reasonable socktype and protocol.
+ * - Look up the port based on 'servname', and store it in *portnum,
+ * - Handle the nodename==NULL case
+ * - Handle some invalid arguments cases.
+ * - Handle the cases where nodename is an IPv4 or IPv6 address.
+ *
+ * If we need the resolver to look up the hostname, we return
+ * EVUTIL_EAI_NEED_RESOLVE. Otherwise, we can completely implement
+ * getaddrinfo: we return 0 or an appropriate EVUTIL_EAI_* error, and
+ * set *res as getaddrinfo would.
+ */
+int
+evutil_getaddrinfo_common_(const char *nodename, const char *servname,
+ struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum)
+{
+ int port = 0;
+ unsigned int if_index;
+ const char *pname;
+
+ if (nodename == NULL && servname == NULL)
+ return EVUTIL_EAI_NONAME;
+
+ /* We only understand 3 families */
+ if (hints->ai_family != PF_UNSPEC && hints->ai_family != PF_INET &&
+ hints->ai_family != PF_INET6)
+ return EVUTIL_EAI_FAMILY;
+
+ evutil_getaddrinfo_infer_protocols(hints);
+
+ /* Look up the port number and protocol, if possible. */
+ pname = evutil_unparse_protoname(hints->ai_protocol);
+ if (servname) {
+ /* XXXX We could look at the protocol we got back from
+ * getservbyname, but it doesn't seem too useful. */
+ port = evutil_parse_servname(servname, pname, hints);
+ if (port < 0) {
+ return EVUTIL_EAI_NONAME;
+ }
+ }
+
+ /* If we have no node name, then we're supposed to bind to 'any' and
+ * connect to localhost. */
+ if (nodename == NULL) {
+ struct evutil_addrinfo *res4=NULL, *res6=NULL;
+ if (hints->ai_family != PF_INET) { /* INET6 or UNSPEC. */
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(port);
+ if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
+ /* Bind to :: */
+ } else {
+ /* connect to ::1 */
+ sin6.sin6_addr.s6_addr[15] = 1;
+ }
+ res6 = evutil_new_addrinfo_((struct sockaddr*)&sin6,
+ sizeof(sin6), hints);
+ if (!res6)
+ return EVUTIL_EAI_MEMORY;
+ }
+
+ if (hints->ai_family != PF_INET6) { /* INET or UNSPEC */
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(port);
+ if (hints->ai_flags & EVUTIL_AI_PASSIVE) {
+ /* Bind to 0.0.0.0 */
+ } else {
+ /* connect to 127.0.0.1 */
+ sin.sin_addr.s_addr = htonl(0x7f000001);
+ }
+ res4 = evutil_new_addrinfo_((struct sockaddr*)&sin,
+ sizeof(sin), hints);
+ if (!res4) {
+ if (res6)
+ evutil_freeaddrinfo(res6);
+ return EVUTIL_EAI_MEMORY;
+ }
+ }
+ *res = evutil_addrinfo_append_(res4, res6);
+ return 0;
+ }
+
+ /* If we can, we should try to parse the hostname without resolving
+ * it. */
+ /* Try ipv6. */
+ if (hints->ai_family == PF_INET6 || hints->ai_family == PF_UNSPEC) {
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+ if (1 == evutil_inet_pton_scope(
+ AF_INET6, nodename, &sin6.sin6_addr, &if_index)) {
+ /* Got an ipv6 address. */
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(port);
+ sin6.sin6_scope_id = if_index;
+ *res = evutil_new_addrinfo_((struct sockaddr*)&sin6,
+ sizeof(sin6), hints);
+ if (!*res)
+ return EVUTIL_EAI_MEMORY;
+ return 0;
+ }
+ }
+
+ /* Try ipv4. */
+ if (hints->ai_family == PF_INET || hints->ai_family == PF_UNSPEC) {
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ if (1==evutil_inet_pton(AF_INET, nodename, &sin.sin_addr)) {
+ /* Got an ipv4 address. */
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(port);
+ *res = evutil_new_addrinfo_((struct sockaddr*)&sin,
+ sizeof(sin), hints);
+ if (!*res)
+ return EVUTIL_EAI_MEMORY;
+ return 0;
+ }
+ }
+
+
+ /* If we have reached this point, we definitely need to do a DNS
+ * lookup. */
+ if ((hints->ai_flags & EVUTIL_AI_NUMERICHOST)) {
+ /* If we're not allowed to do one, then say so. */
+ return EVUTIL_EAI_NONAME;
+ }
+ *portnum = port;
+ return EVUTIL_EAI_NEED_RESOLVE;
+}
+
+#ifdef EVENT__HAVE_GETADDRINFO
+#define USE_NATIVE_GETADDRINFO
+#endif
+
+#ifdef USE_NATIVE_GETADDRINFO
+/* A mask of all the flags that we declare, so we can clear them before calling
+ * the native getaddrinfo */
+static const unsigned int ALL_NONNATIVE_AI_FLAGS =
+#ifndef AI_PASSIVE
+ EVUTIL_AI_PASSIVE |
+#endif
+#ifndef AI_CANONNAME
+ EVUTIL_AI_CANONNAME |
+#endif
+#ifndef AI_NUMERICHOST
+ EVUTIL_AI_NUMERICHOST |
+#endif
+#ifndef AI_NUMERICSERV
+ EVUTIL_AI_NUMERICSERV |
+#endif
+#ifndef AI_ADDRCONFIG
+ EVUTIL_AI_ADDRCONFIG |
+#endif
+#ifndef AI_ALL
+ EVUTIL_AI_ALL |
+#endif
+#ifndef AI_V4MAPPED
+ EVUTIL_AI_V4MAPPED |
+#endif
+ EVUTIL_AI_LIBEVENT_ALLOCATED;
+
+static const unsigned int ALL_NATIVE_AI_FLAGS =
+#ifdef AI_PASSIVE
+ AI_PASSIVE |
+#endif
+#ifdef AI_CANONNAME
+ AI_CANONNAME |
+#endif
+#ifdef AI_NUMERICHOST
+ AI_NUMERICHOST |
+#endif
+#ifdef AI_NUMERICSERV
+ AI_NUMERICSERV |
+#endif
+#ifdef AI_ADDRCONFIG
+ AI_ADDRCONFIG |
+#endif
+#ifdef AI_ALL
+ AI_ALL |
+#endif
+#ifdef AI_V4MAPPED
+ AI_V4MAPPED |
+#endif
+ 0;
+#endif
+
+#ifndef USE_NATIVE_GETADDRINFO
+/* Helper for systems with no getaddrinfo(): make one or more addrinfos out of
+ * a struct hostent.
+ */
+static struct evutil_addrinfo *
+addrinfo_from_hostent(const struct hostent *ent,
+ int port, const struct evutil_addrinfo *hints)
+{
+ int i;
+ struct sockaddr_in sin;
+ struct sockaddr_in6 sin6;
+ struct sockaddr *sa;
+ int socklen;
+ struct evutil_addrinfo *res=NULL, *ai;
+ void *addrp;
+
+ if (ent->h_addrtype == PF_INET) {
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(port);
+ sa = (struct sockaddr *)&sin;
+ socklen = sizeof(struct sockaddr_in);
+ addrp = &sin.sin_addr;
+ if (ent->h_length != sizeof(sin.sin_addr)) {
+ event_warnx("Weird h_length from gethostbyname");
+ return NULL;
+ }
+ } else if (ent->h_addrtype == PF_INET6) {
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(port);
+ sa = (struct sockaddr *)&sin6;
+ socklen = sizeof(struct sockaddr_in6);
+ addrp = &sin6.sin6_addr;
+ if (ent->h_length != sizeof(sin6.sin6_addr)) {
+ event_warnx("Weird h_length from gethostbyname");
+ return NULL;
+ }
+ } else
+ return NULL;
+
+ for (i = 0; ent->h_addr_list[i]; ++i) {
+ memcpy(addrp, ent->h_addr_list[i], ent->h_length);
+ ai = evutil_new_addrinfo_(sa, socklen, hints);
+ if (!ai) {
+ evutil_freeaddrinfo(res);
+ return NULL;
+ }
+ res = evutil_addrinfo_append_(res, ai);
+ }
+
+ if (res && ((hints->ai_flags & EVUTIL_AI_CANONNAME) && ent->h_name)) {
+ res->ai_canonname = mm_strdup(ent->h_name);
+ if (res->ai_canonname == NULL) {
+ evutil_freeaddrinfo(res);
+ return NULL;
+ }
+ }
+
+ return res;
+}
+#endif
+
+/* If the EVUTIL_AI_ADDRCONFIG flag is set on hints->ai_flags, and
+ * hints->ai_family is PF_UNSPEC, then revise the value of hints->ai_family so
+ * that we'll only get addresses we could maybe connect to.
+ */
+void
+evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints)
+{
+ if (!(hints->ai_flags & EVUTIL_AI_ADDRCONFIG))
+ return;
+ if (hints->ai_family != PF_UNSPEC)
+ return;
+ evutil_check_interfaces();
+ if (had_ipv4_address && !had_ipv6_address) {
+ hints->ai_family = PF_INET;
+ } else if (!had_ipv4_address && had_ipv6_address) {
+ hints->ai_family = PF_INET6;
+ }
+}
+
+#ifdef USE_NATIVE_GETADDRINFO
+static int need_numeric_port_hack_=0;
+static int need_socktype_protocol_hack_=0;
+static int tested_for_getaddrinfo_hacks=0;
+
+/* Some older BSDs (like OpenBSD up to 4.6) used to believe that
+ giving a numeric port without giving an ai_socktype was verboten.
+ We test for this so we can apply an appropriate workaround. If it
+ turns out that the bug is present, then:
+
+ - If nodename==NULL and servname is numeric, we build an answer
+ ourselves using evutil_getaddrinfo_common_().
+
+ - If nodename!=NULL and servname is numeric, then we set
+ servname=NULL when calling getaddrinfo, and post-process the
+ result to set the ports on it.
+
+ We test for this bug at runtime, since otherwise we can't have the
+ same binary run on multiple BSD versions.
+
+ - Some versions of Solaris believe that it's nice to leave to protocol
+ field set to 0. We test for this so we can apply an appropriate
+ workaround.
+*/
+static struct evutil_addrinfo *ai_find_protocol(struct evutil_addrinfo *ai)
+{
+ while (ai) {
+ if (ai->ai_protocol)
+ return ai;
+ ai = ai->ai_next;
+ }
+ return NULL;
+}
+static void
+test_for_getaddrinfo_hacks(void)
+{
+ int r, r2;
+ struct evutil_addrinfo *ai=NULL, *ai2=NULL, *ai3=NULL;
+ struct evutil_addrinfo hints;
+
+ memset(&hints,0,sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_flags =
+#ifdef AI_NUMERICHOST
+ AI_NUMERICHOST |
+#endif
+#ifdef AI_NUMERICSERV
+ AI_NUMERICSERV |
+#endif
+ 0;
+ r = getaddrinfo("1.2.3.4", "80", &hints, &ai);
+ getaddrinfo("1.2.3.4", NULL, &hints, &ai3);
+ hints.ai_socktype = SOCK_STREAM;
+ r2 = getaddrinfo("1.2.3.4", "80", &hints, &ai2);
+ if (r2 == 0 && r != 0) {
+ need_numeric_port_hack_=1;
+ }
+ if (!ai_find_protocol(ai2) || !ai_find_protocol(ai3)) {
+ need_socktype_protocol_hack_=1;
+ }
+
+ if (ai)
+ freeaddrinfo(ai);
+ if (ai2)
+ freeaddrinfo(ai2);
+ if (ai3)
+ freeaddrinfo(ai3);
+ tested_for_getaddrinfo_hacks=1;
+}
+
+static inline int
+need_numeric_port_hack(void)
+{
+ if (!tested_for_getaddrinfo_hacks)
+ test_for_getaddrinfo_hacks();
+ return need_numeric_port_hack_;
+}
+
+static inline int
+need_socktype_protocol_hack(void)
+{
+ if (!tested_for_getaddrinfo_hacks)
+ test_for_getaddrinfo_hacks();
+ return need_socktype_protocol_hack_;
+}
+
+static void
+apply_numeric_port_hack(int port, struct evutil_addrinfo **ai)
+{
+ /* Now we run through the list and set the ports on all of the
+ * results where ports would make sense. */
+ for ( ; *ai; ai = &(*ai)->ai_next) {
+ struct sockaddr *sa = (*ai)->ai_addr;
+ if (sa && sa->sa_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in*)sa;
+ sin->sin_port = htons(port);
+ } else if (sa && sa->sa_family == AF_INET6) {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)sa;
+ sin6->sin6_port = htons(port);
+ } else {
+ /* A numeric port makes no sense here; remove this one
+ * from the list. */
+ struct evutil_addrinfo *victim = *ai;
+ *ai = victim->ai_next;
+ victim->ai_next = NULL;
+ freeaddrinfo(victim);
+ }
+ }
+}
+
+static int
+apply_socktype_protocol_hack(struct evutil_addrinfo *ai)
+{
+ struct evutil_addrinfo *ai_new;
+ for (; ai; ai = ai->ai_next) {
+ evutil_getaddrinfo_infer_protocols(ai);
+ if (ai->ai_socktype || ai->ai_protocol)
+ continue;
+ ai_new = mm_malloc(sizeof(*ai_new));
+ if (!ai_new)
+ return -1;
+ memcpy(ai_new, ai, sizeof(*ai_new));
+ ai->ai_socktype = SOCK_STREAM;
+ ai->ai_protocol = IPPROTO_TCP;
+ ai_new->ai_socktype = SOCK_DGRAM;
+ ai_new->ai_protocol = IPPROTO_UDP;
+
+ ai_new->ai_next = ai->ai_next;
+ ai->ai_next = ai_new;
+ }
+ return 0;
+}
+#endif
+
+int
+evutil_getaddrinfo(const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res)
+{
+#ifdef USE_NATIVE_GETADDRINFO
+ struct evutil_addrinfo hints;
+ int portnum=-1, need_np_hack, err;
+
+ if (hints_in) {
+ memcpy(&hints, hints_in, sizeof(hints));
+ } else {
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ }
+
+#ifndef AI_ADDRCONFIG
+ /* Not every system has AI_ADDRCONFIG, so fake it. */
+ if (hints.ai_family == PF_UNSPEC &&
+ (hints.ai_flags & EVUTIL_AI_ADDRCONFIG)) {
+ evutil_adjust_hints_for_addrconfig_(&hints);
+ }
+#endif
+
+#ifndef AI_NUMERICSERV
+ /* Not every system has AI_NUMERICSERV, so fake it. */
+ if (hints.ai_flags & EVUTIL_AI_NUMERICSERV) {
+ if (servname && parse_numeric_servname(servname)<0)
+ return EVUTIL_EAI_NONAME;
+ }
+#endif
+
+ /* Enough operating systems handle enough common non-resolve
+ * cases here weirdly enough that we are better off just
+ * overriding them. For example:
+ *
+ * - Windows doesn't like to infer the protocol from the
+ * socket type, or fill in socket or protocol types much at
+ * all. It also seems to do its own broken implicit
+ * always-on version of AI_ADDRCONFIG that keeps it from
+ * ever resolving even a literal IPv6 address when
+ * ai_addrtype is PF_UNSPEC.
+ */
+#ifdef _WIN32
+ {
+ int tmp_port;
+ err = evutil_getaddrinfo_common_(nodename,servname,&hints,
+ res, &tmp_port);
+ if (err == 0 ||
+ err == EVUTIL_EAI_MEMORY ||
+ err == EVUTIL_EAI_NONAME)
+ return err;
+ /* If we make it here, the system getaddrinfo can
+ * have a crack at it. */
+ }
+#endif
+
+ /* See documentation for need_numeric_port_hack above.*/
+ need_np_hack = need_numeric_port_hack() && servname && !hints.ai_socktype
+ && ((portnum=parse_numeric_servname(servname)) >= 0);
+ if (need_np_hack) {
+ if (!nodename)
+ return evutil_getaddrinfo_common_(
+ NULL,servname,&hints, res, &portnum);
+ servname = NULL;
+ }
+
+ if (need_socktype_protocol_hack()) {
+ evutil_getaddrinfo_infer_protocols(&hints);
+ }
+
+ /* Make sure that we didn't actually steal any AI_FLAGS values that
+ * the system is using. (This is a constant expression, and should ge
+ * optimized out.)
+ *
+ * XXXX Turn this into a compile-time failure rather than a run-time
+ * failure.
+ */
+ EVUTIL_ASSERT((ALL_NONNATIVE_AI_FLAGS & ALL_NATIVE_AI_FLAGS) == 0);
+
+ /* Clear any flags that only libevent understands. */
+ hints.ai_flags &= ~ALL_NONNATIVE_AI_FLAGS;
+
+ err = getaddrinfo(nodename, servname, &hints, res);
+ if (need_np_hack)
+ apply_numeric_port_hack(portnum, res);
+
+ if (need_socktype_protocol_hack()) {
+ if (apply_socktype_protocol_hack(*res) < 0) {
+ evutil_freeaddrinfo(*res);
+ *res = NULL;
+ return EVUTIL_EAI_MEMORY;
+ }
+ }
+ return err;
+#else
+ int port=0, err;
+ struct hostent *ent = NULL;
+ struct evutil_addrinfo hints;
+
+ if (hints_in) {
+ memcpy(&hints, hints_in, sizeof(hints));
+ } else {
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ }
+
+ evutil_adjust_hints_for_addrconfig_(&hints);
+
+ err = evutil_getaddrinfo_common_(nodename, servname, &hints, res, &port);
+ if (err != EVUTIL_EAI_NEED_RESOLVE) {
+ /* We either succeeded or failed. No need to continue */
+ return err;
+ }
+
+ err = 0;
+ /* Use any of the various gethostbyname_r variants as available. */
+ {
+#ifdef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG
+ /* This one is what glibc provides. */
+ char buf[2048];
+ struct hostent hostent;
+ int r;
+ r = gethostbyname_r(nodename, &hostent, buf, sizeof(buf), &ent,
+ &err);
+#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_5_ARG)
+ char buf[2048];
+ struct hostent hostent;
+ ent = gethostbyname_r(nodename, &hostent, buf, sizeof(buf),
+ &err);
+#elif defined(EVENT__HAVE_GETHOSTBYNAME_R_3_ARG)
+ struct hostent_data data;
+ struct hostent hostent;
+ memset(&data, 0, sizeof(data));
+ err = gethostbyname_r(nodename, &hostent, &data);
+ ent = err ? NULL : &hostent;
+#else
+ /* fall back to gethostbyname. */
+ /* XXXX This needs a lock everywhere but Windows. */
+ ent = gethostbyname(nodename);
+#ifdef _WIN32
+ err = WSAGetLastError();
+#else
+ err = h_errno;
+#endif
+#endif
+
+ /* Now we have either ent or err set. */
+ if (!ent) {
+ /* XXX is this right for windows ? */
+ switch (err) {
+ case TRY_AGAIN:
+ return EVUTIL_EAI_AGAIN;
+ case NO_RECOVERY:
+ default:
+ return EVUTIL_EAI_FAIL;
+ case HOST_NOT_FOUND:
+ return EVUTIL_EAI_NONAME;
+ case NO_ADDRESS:
+#if NO_DATA != NO_ADDRESS
+ case NO_DATA:
+#endif
+ return EVUTIL_EAI_NODATA;
+ }
+ }
+
+ if (ent->h_addrtype != hints.ai_family &&
+ hints.ai_family != PF_UNSPEC) {
+ /* This wasn't the type we were hoping for. Too bad
+ * we never had a chance to ask gethostbyname for what
+ * we wanted. */
+ return EVUTIL_EAI_NONAME;
+ }
+
+ /* Make sure we got _some_ answers. */
+ if (ent->h_length == 0)
+ return EVUTIL_EAI_NODATA;
+
+ /* If we got an address type we don't know how to make a
+ sockaddr for, give up. */
+ if (ent->h_addrtype != PF_INET && ent->h_addrtype != PF_INET6)
+ return EVUTIL_EAI_FAMILY;
+
+ *res = addrinfo_from_hostent(ent, port, &hints);
+ if (! *res)
+ return EVUTIL_EAI_MEMORY;
+ }
+
+ return 0;
+#endif
+}
+
+void
+evutil_freeaddrinfo(struct evutil_addrinfo *ai)
+{
+#ifdef EVENT__HAVE_GETADDRINFO
+ if (!(ai->ai_flags & EVUTIL_AI_LIBEVENT_ALLOCATED)) {
+ freeaddrinfo(ai);
+ return;
+ }
+#endif
+ while (ai) {
+ struct evutil_addrinfo *next = ai->ai_next;
+ if (ai->ai_canonname)
+ mm_free(ai->ai_canonname);
+ mm_free(ai);
+ ai = next;
+ }
+}
+
+static evdns_getaddrinfo_fn evdns_getaddrinfo_impl = NULL;
+static evdns_getaddrinfo_cancel_fn evdns_getaddrinfo_cancel_impl = NULL;
+
+void
+evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn)
+{
+ if (!evdns_getaddrinfo_impl)
+ evdns_getaddrinfo_impl = fn;
+}
+void
+evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn)
+{
+ if (!evdns_getaddrinfo_cancel_impl)
+ evdns_getaddrinfo_cancel_impl = fn;
+}
+
+/* Internal helper function: act like evdns_getaddrinfo if dns_base is set;
+ * otherwise do a blocking resolve and pass the result to the callback in the
+ * way that evdns_getaddrinfo would.
+ */
+struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
+ struct evdns_base *dns_base,
+ const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in,
+ void (*cb)(int, struct evutil_addrinfo *, void *), void *arg)
+{
+ if (dns_base && evdns_getaddrinfo_impl) {
+ return evdns_getaddrinfo_impl(
+ dns_base, nodename, servname, hints_in, cb, arg);
+ } else {
+ struct evutil_addrinfo *ai=NULL;
+ int err;
+ err = evutil_getaddrinfo(nodename, servname, hints_in, &ai);
+ cb(err, ai, arg);
+ return NULL;
+ }
+}
+
+void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data)
+{
+ if (evdns_getaddrinfo_cancel_impl && data) {
+ evdns_getaddrinfo_cancel_impl(data);
+ }
+}
+
+const char *
+evutil_gai_strerror(int err)
+{
+ /* As a sneaky side-benefit, this case statement will get most
+ * compilers to tell us if any of the error codes we defined
+ * conflict with the platform's native error codes. */
+ switch (err) {
+ case EVUTIL_EAI_CANCEL:
+ return "Request canceled";
+ case 0:
+ return "No error";
+
+ case EVUTIL_EAI_ADDRFAMILY:
+ return "address family for nodename not supported";
+ case EVUTIL_EAI_AGAIN:
+ return "temporary failure in name resolution";
+ case EVUTIL_EAI_BADFLAGS:
+ return "invalid value for ai_flags";
+ case EVUTIL_EAI_FAIL:
+ return "non-recoverable failure in name resolution";
+ case EVUTIL_EAI_FAMILY:
+ return "ai_family not supported";
+ case EVUTIL_EAI_MEMORY:
+ return "memory allocation failure";
+ case EVUTIL_EAI_NODATA:
+ return "no address associated with nodename";
+ case EVUTIL_EAI_NONAME:
+ return "nodename nor servname provided, or not known";
+ case EVUTIL_EAI_SERVICE:
+ return "servname not supported for ai_socktype";
+ case EVUTIL_EAI_SOCKTYPE:
+ return "ai_socktype not supported";
+ case EVUTIL_EAI_SYSTEM:
+ return "system error";
+ default:
+#if defined(USE_NATIVE_GETADDRINFO) && defined(_WIN32)
+ return gai_strerrorA(err);
+#elif defined(USE_NATIVE_GETADDRINFO)
+ return gai_strerror(err);
+#else
+ return "Unknown error code";
+#endif
+ }
+}
+
+#ifdef _WIN32
+/* destructively remove a trailing line terminator from s */
+static void
+chomp (char *s)
+{
+ size_t len;
+ if (s && (len = strlen (s)) > 0 && s[len - 1] == '\n') {
+ s[--len] = 0;
+ if (len > 0 && s[len - 1] == '\r')
+ s[--len] = 0;
+ }
+}
+
+/* FormatMessage returns allocated strings, but evutil_socket_error_to_string
+ * is supposed to return a string which is good indefinitely without having
+ * to be freed. To make this work without leaking memory, we cache the
+ * string the first time FormatMessage is called on a particular error
+ * code, and then return the cached string on subsequent calls with the
+ * same code. The strings aren't freed until libevent_global_shutdown
+ * (or never). We use a linked list to cache the errors, because we
+ * only expect there to be a few dozen, and that should be fast enough.
+ */
+
+struct cached_sock_errs_entry {
+ HT_ENTRY(cached_sock_errs_entry) node;
+ DWORD code;
+ char *msg; /* allocated with LocalAlloc; free with LocalFree */
+};
+
+static inline unsigned
+hash_cached_sock_errs(const struct cached_sock_errs_entry *e)
+{
+ /* Use Murmur3's 32-bit finalizer as an integer hash function */
+ DWORD h = e->code;
+ h ^= h >> 16;
+ h *= 0x85ebca6b;
+ h ^= h >> 13;
+ h *= 0xc2b2ae35;
+ h ^= h >> 16;
+ return h;
+}
+
+static inline int
+eq_cached_sock_errs(const struct cached_sock_errs_entry *a,
+ const struct cached_sock_errs_entry *b)
+{
+ return a->code == b->code;
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+static void *windows_socket_errors_lock_ = NULL;
+#endif
+
+static HT_HEAD(cached_sock_errs_map, cached_sock_errs_entry)
+ windows_socket_errors = HT_INITIALIZER();
+
+HT_PROTOTYPE(cached_sock_errs_map,
+ cached_sock_errs_entry,
+ node,
+ hash_cached_sock_errs,
+ eq_cached_sock_errs);
+
+HT_GENERATE(cached_sock_errs_map,
+ cached_sock_errs_entry,
+ node,
+ hash_cached_sock_errs,
+ eq_cached_sock_errs,
+ 0.5,
+ mm_malloc,
+ mm_realloc,
+ mm_free);
+
+/** Equivalent to strerror, but for windows socket errors. */
+const char *
+evutil_socket_error_to_string(int errcode)
+{
+ struct cached_sock_errs_entry *errs, *newerr, find;
+ char *msg = NULL;
+
+ EVLOCK_LOCK(windows_socket_errors_lock_, 0);
+
+ find.code = errcode;
+ errs = HT_FIND(cached_sock_errs_map, &windows_socket_errors, &find);
+ if (errs) {
+ msg = errs->msg;
+ goto done;
+ }
+
+ if (0 != FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS |
+ FORMAT_MESSAGE_ALLOCATE_BUFFER,
+ NULL, errcode, 0, (char *)&msg, 0, NULL))
+ chomp (msg); /* because message has trailing newline */
+ else {
+ size_t len = 50;
+ /* use LocalAlloc because FormatMessage does */
+ msg = LocalAlloc(LMEM_FIXED, len);
+ if (!msg) {
+ msg = (char *)"LocalAlloc failed during Winsock error";
+ goto done;
+ }
+ evutil_snprintf(msg, len, "winsock error 0x%08x", errcode);
+ }
+
+ newerr = (struct cached_sock_errs_entry *)
+ mm_malloc(sizeof (struct cached_sock_errs_entry));
+
+ if (!newerr) {
+ LocalFree(msg);
+ msg = (char *)"malloc failed during Winsock error";
+ goto done;
+ }
+
+ newerr->code = errcode;
+ newerr->msg = msg;
+ HT_INSERT(cached_sock_errs_map, &windows_socket_errors, newerr);
+
+ done:
+ EVLOCK_UNLOCK(windows_socket_errors_lock_, 0);
+
+ return msg;
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+evutil_global_setup_locks_(const int enable_locks)
+{
+ EVTHREAD_SETUP_GLOBAL_LOCK(windows_socket_errors_lock_, 0);
+ return 0;
+}
+#endif
+
+static void
+evutil_free_sock_err_globals(void)
+{
+ struct cached_sock_errs_entry **errs, *tofree;
+
+ for (errs = HT_START(cached_sock_errs_map, &windows_socket_errors)
+ ; errs; ) {
+ tofree = *errs;
+ errs = HT_NEXT_RMV(cached_sock_errs_map,
+ &windows_socket_errors,
+ errs);
+ LocalFree(tofree->msg);
+ mm_free(tofree);
+ }
+
+ HT_CLEAR(cached_sock_errs_map, &windows_socket_errors);
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (windows_socket_errors_lock_ != NULL) {
+ EVTHREAD_FREE_LOCK(windows_socket_errors_lock_, 0);
+ windows_socket_errors_lock_ = NULL;
+ }
+#endif
+}
+
+#else
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+evutil_global_setup_locks_(const int enable_locks)
+{
+ return 0;
+}
+#endif
+
+static void
+evutil_free_sock_err_globals(void)
+{
+}
+
+#endif
+
+int
+evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
+{
+ int r;
+ va_list ap;
+ va_start(ap, format);
+ r = evutil_vsnprintf(buf, buflen, format, ap);
+ va_end(ap);
+ return r;
+}
+
+int
+evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
+{
+ int r;
+ if (!buflen)
+ return 0;
+#if defined(_MSC_VER) || defined(_WIN32)
+ r = _vsnprintf(buf, buflen, format, ap);
+ if (r < 0)
+ r = _vscprintf(format, ap);
+#elif defined(sgi)
+ /* Make sure we always use the correct vsnprintf on IRIX */
+ extern int _xpg5_vsnprintf(char * __restrict,
+ __SGI_LIBC_NAMESPACE_QUALIFIER size_t,
+ const char * __restrict, /* va_list */ char *);
+
+ r = _xpg5_vsnprintf(buf, buflen, format, ap);
+#else
+ r = vsnprintf(buf, buflen, format, ap);
+#endif
+ buf[buflen-1] = '\0';
+ return r;
+}
+
+#define USE_INTERNAL_NTOP
+#define USE_INTERNAL_PTON
+
+const char *
+evutil_inet_ntop(int af, const void *src, char *dst, size_t len)
+{
+#if defined(EVENT__HAVE_INET_NTOP) && !defined(USE_INTERNAL_NTOP)
+ return inet_ntop(af, src, dst, len);
+#else
+ if (af == AF_INET) {
+ const struct in_addr *in = src;
+ const ev_uint32_t a = ntohl(in->s_addr);
+ int r;
+ r = evutil_snprintf(dst, len, "%d.%d.%d.%d",
+ (int)(ev_uint8_t)((a>>24)&0xff),
+ (int)(ev_uint8_t)((a>>16)&0xff),
+ (int)(ev_uint8_t)((a>>8 )&0xff),
+ (int)(ev_uint8_t)((a )&0xff));
+ if (r<0||(size_t)r>=len)
+ return NULL;
+ else
+ return dst;
+#ifdef AF_INET6
+ } else if (af == AF_INET6) {
+ const struct in6_addr *addr = src;
+ char buf[64], *cp;
+ int longestGapLen = 0, longestGapPos = -1, i,
+ curGapPos = -1, curGapLen = 0;
+ ev_uint16_t words[8];
+ for (i = 0; i < 8; ++i) {
+ words[i] =
+ (((ev_uint16_t)addr->s6_addr[2*i])<<8) + addr->s6_addr[2*i+1];
+ }
+ if (words[0] == 0 && words[1] == 0 && words[2] == 0 && words[3] == 0 &&
+ words[4] == 0 && ((words[5] == 0 && words[6] && words[7]) ||
+ (words[5] == 0xffff))) {
+ /* This is an IPv4 address. */
+ if (words[5] == 0) {
+ evutil_snprintf(buf, sizeof(buf), "::%d.%d.%d.%d",
+ addr->s6_addr[12], addr->s6_addr[13],
+ addr->s6_addr[14], addr->s6_addr[15]);
+ } else {
+ evutil_snprintf(buf, sizeof(buf), "::%x:%d.%d.%d.%d", words[5],
+ addr->s6_addr[12], addr->s6_addr[13],
+ addr->s6_addr[14], addr->s6_addr[15]);
+ }
+ if (strlen(buf) > len)
+ return NULL;
+ strlcpy(dst, buf, len);
+ return dst;
+ }
+ i = 0;
+ while (i < 8) {
+ if (words[i] == 0) {
+ curGapPos = i++;
+ curGapLen = 1;
+ while (i<8 && words[i] == 0) {
+ ++i; ++curGapLen;
+ }
+ if (curGapLen > longestGapLen) {
+ longestGapPos = curGapPos;
+ longestGapLen = curGapLen;
+ }
+ } else {
+ ++i;
+ }
+ }
+ if (longestGapLen<=1)
+ longestGapPos = -1;
+
+ cp = buf;
+ for (i = 0; i < 8; ++i) {
+ if (words[i] == 0 && longestGapPos == i) {
+ if (i == 0)
+ *cp++ = ':';
+ *cp++ = ':';
+ while (i < 8 && words[i] == 0)
+ ++i;
+ --i; /* to compensate for loop increment. */
+ } else {
+ evutil_snprintf(cp,
+ sizeof(buf)-(cp-buf), "%x", (unsigned)words[i]);
+ cp += strlen(cp);
+ if (i != 7)
+ *cp++ = ':';
+ }
+ }
+ *cp = '\0';
+ if (strlen(buf) > len)
+ return NULL;
+ strlcpy(dst, buf, len);
+ return dst;
+#endif
+ } else {
+ return NULL;
+ }
+#endif
+}
+
+int
+evutil_inet_pton_scope(int af, const char *src, void *dst, unsigned *indexp)
+{
+ int r;
+ unsigned if_index;
+ char *check, *cp, *tmp_src;
+
+ *indexp = 0; /* Reasonable default */
+
+ /* Bail out if not IPv6 */
+ if (af != AF_INET6)
+ return evutil_inet_pton(af, src, dst);
+
+ cp = strchr(src, '%');
+
+ /* Bail out if no zone ID */
+ if (cp == NULL)
+ return evutil_inet_pton(af, src, dst);
+
+ if_index = if_nametoindex(cp + 1);
+ if (if_index == 0) {
+ /* Could be numeric */
+ if_index = strtoul(cp + 1, &check, 10);
+ if (check[0] != '\0')
+ return 0;
+ }
+ *indexp = if_index;
+ tmp_src = mm_strdup(src);
+ cp = strchr(tmp_src, '%');
+ *cp = '\0';
+ r = evutil_inet_pton(af, tmp_src, dst);
+ free(tmp_src);
+ return r;
+}
+
+int
+evutil_inet_pton(int af, const char *src, void *dst)
+{
+#if defined(EVENT__HAVE_INET_PTON) && !defined(USE_INTERNAL_PTON)
+ return inet_pton(af, src, dst);
+#else
+ if (af == AF_INET) {
+ unsigned a,b,c,d;
+ char more;
+ struct in_addr *addr = dst;
+ if (sscanf(src, "%u.%u.%u.%u%c", &a,&b,&c,&d,&more) != 4)
+ return 0;
+ if (a > 255) return 0;
+ if (b > 255) return 0;
+ if (c > 255) return 0;
+ if (d > 255) return 0;
+ addr->s_addr = htonl((a<<24) | (b<<16) | (c<<8) | d);
+ return 1;
+#ifdef AF_INET6
+ } else if (af == AF_INET6) {
+ struct in6_addr *out = dst;
+ ev_uint16_t words[8];
+ int gapPos = -1, i, setWords=0;
+ const char *dot = strchr(src, '.');
+ const char *eow; /* end of words. */
+ if (dot == src)
+ return 0;
+ else if (!dot)
+ eow = src+strlen(src);
+ else {
+ unsigned byte1,byte2,byte3,byte4;
+ char more;
+ for (eow = dot-1; eow >= src && EVUTIL_ISDIGIT_(*eow); --eow)
+ ;
+ ++eow;
+
+ /* We use "scanf" because some platform inet_aton()s are too lax
+ * about IPv4 addresses of the form "1.2.3" */
+ if (sscanf(eow, "%u.%u.%u.%u%c",
+ &byte1,&byte2,&byte3,&byte4,&more) != 4)
+ return 0;
+
+ if (byte1 > 255 ||
+ byte2 > 255 ||
+ byte3 > 255 ||
+ byte4 > 255)
+ return 0;
+
+ words[6] = (byte1<<8) | byte2;
+ words[7] = (byte3<<8) | byte4;
+ setWords += 2;
+ }
+
+ i = 0;
+ while (src < eow) {
+ if (i > 7)
+ return 0;
+ if (EVUTIL_ISXDIGIT_(*src)) {
+ char *next;
+ long r = strtol(src, &next, 16);
+ if (next > 4+src)
+ return 0;
+ if (next == src)
+ return 0;
+ if (r<0 || r>65536)
+ return 0;
+
+ words[i++] = (ev_uint16_t)r;
+ setWords++;
+ src = next;
+ if (*src != ':' && src != eow)
+ return 0;
+ ++src;
+ } else if (*src == ':' && i > 0 && gapPos==-1) {
+ gapPos = i;
+ ++src;
+ } else if (*src == ':' && i == 0 && src[1] == ':' && gapPos==-1) {
+ gapPos = i;
+ src += 2;
+ } else {
+ return 0;
+ }
+ }
+
+ if (setWords > 8 ||
+ (setWords == 8 && gapPos != -1) ||
+ (setWords < 8 && gapPos == -1))
+ return 0;
+
+ if (gapPos >= 0) {
+ int nToMove = setWords - (dot ? 2 : 0) - gapPos;
+ int gapLen = 8 - setWords;
+ /* assert(nToMove >= 0); */
+ if (nToMove < 0)
+ return -1; /* should be impossible */
+ memmove(&words[gapPos+gapLen], &words[gapPos],
+ sizeof(ev_uint16_t)*nToMove);
+ memset(&words[gapPos], 0, sizeof(ev_uint16_t)*gapLen);
+ }
+ for (i = 0; i < 8; ++i) {
+ out->s6_addr[2*i ] = words[i] >> 8;
+ out->s6_addr[2*i+1] = words[i] & 0xff;
+ }
+
+ return 1;
+#endif
+ } else {
+ return -1;
+ }
+#endif
+}
+
+int
+evutil_parse_sockaddr_port(const char *ip_as_string, struct sockaddr *out, int *outlen)
+{
+ int port;
+ unsigned int if_index;
+ char buf[128];
+ const char *cp, *addr_part, *port_part;
+ int is_ipv6;
+ /* recognized formats are:
+ * [ipv6]:port
+ * ipv6
+ * [ipv6]
+ * ipv4:port
+ * ipv4
+ */
+
+ cp = strchr(ip_as_string, ':');
+ if (*ip_as_string == '[') {
+ size_t len;
+ if (!(cp = strchr(ip_as_string, ']'))) {
+ return -1;
+ }
+ len = ( cp-(ip_as_string + 1) );
+ if (len > sizeof(buf)-1) {
+ return -1;
+ }
+ memcpy(buf, ip_as_string+1, len);
+ buf[len] = '\0';
+ addr_part = buf;
+ if (cp[1] == ':')
+ port_part = cp+2;
+ else
+ port_part = NULL;
+ is_ipv6 = 1;
+ } else if (cp && strchr(cp+1, ':')) {
+ is_ipv6 = 1;
+ addr_part = ip_as_string;
+ port_part = NULL;
+ } else if (cp) {
+ is_ipv6 = 0;
+ if (cp - ip_as_string > (int)sizeof(buf)-1) {
+ return -1;
+ }
+ memcpy(buf, ip_as_string, cp-ip_as_string);
+ buf[cp-ip_as_string] = '\0';
+ addr_part = buf;
+ port_part = cp+1;
+ } else {
+ addr_part = ip_as_string;
+ port_part = NULL;
+ is_ipv6 = 0;
+ }
+
+ if (port_part == NULL) {
+ port = 0;
+ } else {
+ port = atoi(port_part);
+ if (port <= 0 || port > 65535) {
+ return -1;
+ }
+ }
+
+ if (!addr_part)
+ return -1; /* Should be impossible. */
+#ifdef AF_INET6
+ if (is_ipv6)
+ {
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+ sin6.sin6_len = sizeof(sin6);
+#endif
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(port);
+ if (1 != evutil_inet_pton_scope(
+ AF_INET6, addr_part, &sin6.sin6_addr, &if_index)) {
+ return -1;
+ }
+ if ((int)sizeof(sin6) > *outlen)
+ return -1;
+ sin6.sin6_scope_id = if_index;
+ memset(out, 0, *outlen);
+ memcpy(out, &sin6, sizeof(sin6));
+ *outlen = sizeof(sin6);
+ return 0;
+ }
+ else
+#endif
+ {
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+ sin.sin_len = sizeof(sin);
+#endif
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(port);
+ if (1 != evutil_inet_pton(AF_INET, addr_part, &sin.sin_addr))
+ return -1;
+ if ((int)sizeof(sin) > *outlen)
+ return -1;
+ memset(out, 0, *outlen);
+ memcpy(out, &sin, sizeof(sin));
+ *outlen = sizeof(sin);
+ return 0;
+ }
+}
+
+const char *
+evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen)
+{
+ char b[128];
+ const char *res=NULL;
+ int port;
+ if (sa->sa_family == AF_INET) {
+ const struct sockaddr_in *sin = (const struct sockaddr_in*)sa;
+ res = evutil_inet_ntop(AF_INET, &sin->sin_addr,b,sizeof(b));
+ port = ntohs(sin->sin_port);
+ if (res) {
+ evutil_snprintf(out, outlen, "%s:%d", b, port);
+ return out;
+ }
+ } else if (sa->sa_family == AF_INET6) {
+ const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6*)sa;
+ res = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr,b,sizeof(b));
+ port = ntohs(sin6->sin6_port);
+ if (res) {
+ evutil_snprintf(out, outlen, "[%s]:%d", b, port);
+ return out;
+ }
+ }
+
+ evutil_snprintf(out, outlen, "<addr with socktype %d>",
+ (int)sa->sa_family);
+ return out;
+}
+
+int
+evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
+ int include_port)
+{
+ int r;
+ if (0 != (r = (sa1->sa_family - sa2->sa_family)))
+ return r;
+
+ if (sa1->sa_family == AF_INET) {
+ const struct sockaddr_in *sin1, *sin2;
+ sin1 = (const struct sockaddr_in *)sa1;
+ sin2 = (const struct sockaddr_in *)sa2;
+ if (sin1->sin_addr.s_addr < sin2->sin_addr.s_addr)
+ return -1;
+ else if (sin1->sin_addr.s_addr > sin2->sin_addr.s_addr)
+ return 1;
+ else if (include_port &&
+ (r = ((int)sin1->sin_port - (int)sin2->sin_port)))
+ return r;
+ else
+ return 0;
+ }
+#ifdef AF_INET6
+ else if (sa1->sa_family == AF_INET6) {
+ const struct sockaddr_in6 *sin1, *sin2;
+ sin1 = (const struct sockaddr_in6 *)sa1;
+ sin2 = (const struct sockaddr_in6 *)sa2;
+ if ((r = memcmp(sin1->sin6_addr.s6_addr, sin2->sin6_addr.s6_addr, 16)))
+ return r;
+ else if (include_port &&
+ (r = ((int)sin1->sin6_port - (int)sin2->sin6_port)))
+ return r;
+ else
+ return 0;
+ }
+#endif
+ return 1;
+}
+
+/* Tables to implement ctypes-replacement EVUTIL_IS*() functions. Each table
+ * has 256 bits to look up whether a character is in some set or not. This
+ * fails on non-ASCII platforms, but so does every other place where we
+ * take a char and write it onto the network.
+ **/
+static const ev_uint32_t EVUTIL_ISALPHA_TABLE[8] =
+ { 0, 0, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISALNUM_TABLE[8] =
+ { 0, 0x3ff0000, 0x7fffffe, 0x7fffffe, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISSPACE_TABLE[8] = { 0x3e00, 0x1, 0, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISXDIGIT_TABLE[8] =
+ { 0, 0x3ff0000, 0x7e, 0x7e, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISDIGIT_TABLE[8] = { 0, 0x3ff0000, 0, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISPRINT_TABLE[8] =
+ { 0, 0xffffffff, 0xffffffff, 0x7fffffff, 0, 0, 0, 0x0 };
+static const ev_uint32_t EVUTIL_ISUPPER_TABLE[8] = { 0, 0, 0x7fffffe, 0, 0, 0, 0, 0 };
+static const ev_uint32_t EVUTIL_ISLOWER_TABLE[8] = { 0, 0, 0, 0x7fffffe, 0, 0, 0, 0 };
+/* Upper-casing and lowercasing tables to map characters to upper/lowercase
+ * equivalents. */
+static const unsigned char EVUTIL_TOUPPER_TABLE[256] = {
+ 0,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,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,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,
+};
+static const unsigned char EVUTIL_TOLOWER_TABLE[256] = {
+ 0,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,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,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,
+};
+
+#define IMPL_CTYPE_FN(name) \
+ int EVUTIL_##name##_(char c) { \
+ ev_uint8_t u = c; \
+ return !!(EVUTIL_##name##_TABLE[(u >> 5) & 7] & (1U << (u & 31))); \
+ }
+IMPL_CTYPE_FN(ISALPHA)
+IMPL_CTYPE_FN(ISALNUM)
+IMPL_CTYPE_FN(ISSPACE)
+IMPL_CTYPE_FN(ISDIGIT)
+IMPL_CTYPE_FN(ISXDIGIT)
+IMPL_CTYPE_FN(ISPRINT)
+IMPL_CTYPE_FN(ISLOWER)
+IMPL_CTYPE_FN(ISUPPER)
+
+char EVUTIL_TOLOWER_(char c)
+{
+ return ((char)EVUTIL_TOLOWER_TABLE[(ev_uint8_t)c]);
+}
+char EVUTIL_TOUPPER_(char c)
+{
+ return ((char)EVUTIL_TOUPPER_TABLE[(ev_uint8_t)c]);
+}
+int
+evutil_ascii_strcasecmp(const char *s1, const char *s2)
+{
+ char c1, c2;
+ while (1) {
+ c1 = EVUTIL_TOLOWER_(*s1++);
+ c2 = EVUTIL_TOLOWER_(*s2++);
+ if (c1 < c2)
+ return -1;
+ else if (c1 > c2)
+ return 1;
+ else if (c1 == 0)
+ return 0;
+ }
+}
+int evutil_ascii_strncasecmp(const char *s1, const char *s2, size_t n)
+{
+ char c1, c2;
+ while (n--) {
+ c1 = EVUTIL_TOLOWER_(*s1++);
+ c2 = EVUTIL_TOLOWER_(*s2++);
+ if (c1 < c2)
+ return -1;
+ else if (c1 > c2)
+ return 1;
+ else if (c1 == 0)
+ return 0;
+ }
+ return 0;
+}
+
+void
+evutil_rtrim_lws_(char *str)
+{
+ char *cp;
+
+ if (str == NULL)
+ return;
+
+ if ((cp = strchr(str, '\0')) == NULL || (cp == str))
+ return;
+
+ --cp;
+
+ while (*cp == ' ' || *cp == '\t') {
+ *cp = '\0';
+ if (cp == str)
+ break;
+ --cp;
+ }
+}
+
+static int
+evutil_issetugid(void)
+{
+#ifdef EVENT__HAVE_ISSETUGID
+ return issetugid();
+#else
+
+#ifdef EVENT__HAVE_GETEUID
+ if (getuid() != geteuid())
+ return 1;
+#endif
+#ifdef EVENT__HAVE_GETEGID
+ if (getgid() != getegid())
+ return 1;
+#endif
+ return 0;
+#endif
+}
+
+const char *
+evutil_getenv_(const char *varname)
+{
+ if (evutil_issetugid())
+ return NULL;
+
+ return getenv(varname);
+}
+
+ev_uint32_t
+evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed)
+{
+ if (seed == 0) {
+ struct timeval tv;
+ evutil_gettimeofday(&tv, NULL);
+ seed = (ev_uint32_t)tv.tv_sec + (ev_uint32_t)tv.tv_usec;
+#ifdef _WIN32
+ seed += (ev_uint32_t) _getpid();
+#else
+ seed += (ev_uint32_t) getpid();
+#endif
+ }
+ state->seed = seed;
+ return seed;
+}
+
+ev_int32_t
+evutil_weakrand_(struct evutil_weakrand_state *state)
+{
+ /* This RNG implementation is a linear congruential generator, with
+ * modulus 2^31, multiplier 1103515245, and addend 12345. It's also
+ * used by OpenBSD, and by Glibc's TYPE_0 RNG.
+ *
+ * The linear congruential generator is not an industrial-strength
+ * RNG! It's fast, but it can have higher-order patterns. Notably,
+ * the low bits tend to have periodicity.
+ */
+ state->seed = ((state->seed) * 1103515245 + 12345) & 0x7fffffff;
+ return (ev_int32_t)(state->seed);
+}
+
+ev_int32_t
+evutil_weakrand_range_(struct evutil_weakrand_state *state, ev_int32_t top)
+{
+ ev_int32_t divisor, result;
+
+ /* We can't just do weakrand() % top, since the low bits of the LCG
+ * are less random than the high ones. (Specifically, since the LCG
+ * modulus is 2^N, every 2^m for m<N will divide the modulus, and so
+ * therefore the low m bits of the LCG will have period 2^m.) */
+ divisor = EVUTIL_WEAKRAND_MAX / top;
+ do {
+ result = evutil_weakrand_(state) / divisor;
+ } while (result >= top);
+ return result;
+}
+
+/**
+ * Volatile pointer to memset: we use this to keep the compiler from
+ * eliminating our call to memset.
+ */
+void * (*volatile evutil_memset_volatile_)(void *, int, size_t) = memset;
+
+void
+evutil_memclear_(void *mem, size_t len)
+{
+ evutil_memset_volatile_(mem, 0, len);
+}
+
+int
+evutil_sockaddr_is_loopback_(const struct sockaddr *addr)
+{
+ static const char LOOPBACK_S6[16] =
+ "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\1";
+ if (addr->sa_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in *)addr;
+ return (ntohl(sin->sin_addr.s_addr) & 0xff000000) == 0x7f000000;
+ } else if (addr->sa_family == AF_INET6) {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
+ return !memcmp(sin6->sin6_addr.s6_addr, LOOPBACK_S6, 16);
+ }
+ return 0;
+}
+
+int
+evutil_hex_char_to_int_(char c)
+{
+ switch(c)
+ {
+ case '0': return 0;
+ case '1': return 1;
+ case '2': return 2;
+ case '3': return 3;
+ case '4': return 4;
+ case '5': return 5;
+ case '6': return 6;
+ case '7': return 7;
+ case '8': return 8;
+ case '9': return 9;
+ case 'A': case 'a': return 10;
+ case 'B': case 'b': return 11;
+ case 'C': case 'c': return 12;
+ case 'D': case 'd': return 13;
+ case 'E': case 'e': return 14;
+ case 'F': case 'f': return 15;
+ }
+ return -1;
+}
+
+#ifdef _WIN32
+HMODULE
+evutil_load_windows_system_library_(const TCHAR *library_name)
+{
+ TCHAR path[MAX_PATH];
+ unsigned n;
+ n = GetSystemDirectory(path, MAX_PATH);
+ if (n == 0 || n + _tcslen(library_name) + 2 >= MAX_PATH)
+ return 0;
+ _tcscat(path, TEXT("\\"));
+ _tcscat(path, library_name);
+ return LoadLibrary(path);
+}
+#endif
+
+/* Internal wrapper around 'socket' to provide Linux-style support for
+ * syscall-saving methods where available.
+ *
+ * In addition to regular socket behavior, you can use a bitwise or to set the
+ * flags EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'type' argument,
+ * to make the socket nonblocking or close-on-exec with as few syscalls as
+ * possible.
+ */
+evutil_socket_t
+evutil_socket_(int domain, int type, int protocol)
+{
+ evutil_socket_t r;
+#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
+ r = socket(domain, type, protocol);
+ if (r >= 0)
+ return r;
+ else if ((type & (SOCK_NONBLOCK|SOCK_CLOEXEC)) == 0)
+ return -1;
+#endif
+#define SOCKET_TYPE_MASK (~(EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC))
+ r = socket(domain, type & SOCKET_TYPE_MASK, protocol);
+ if (r < 0)
+ return -1;
+ if (type & EVUTIL_SOCK_NONBLOCK) {
+ if (evutil_fast_socket_nonblocking(r) < 0) {
+ evutil_closesocket(r);
+ return -1;
+ }
+ }
+ if (type & EVUTIL_SOCK_CLOEXEC) {
+ if (evutil_fast_socket_closeonexec(r) < 0) {
+ evutil_closesocket(r);
+ return -1;
+ }
+ }
+ return r;
+}
+
+/* Internal wrapper around 'accept' or 'accept4' to provide Linux-style
+ * support for syscall-saving methods where available.
+ *
+ * In addition to regular accept behavior, you can set one or more of flags
+ * EVUTIL_SOCK_NONBLOCK and EVUTIL_SOCK_CLOEXEC in the 'flags' argument, to
+ * make the socket nonblocking or close-on-exec with as few syscalls as
+ * possible.
+ */
+evutil_socket_t
+evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
+ ev_socklen_t *addrlen, int flags)
+{
+ evutil_socket_t result;
+#if defined(EVENT__HAVE_ACCEPT4) && defined(SOCK_CLOEXEC) && defined(SOCK_NONBLOCK)
+ result = accept4(sockfd, addr, addrlen, flags);
+ if (result >= 0 || (errno != EINVAL && errno != ENOSYS)) {
+ /* A nonnegative result means that we succeeded, so return.
+ * Failing with EINVAL means that an option wasn't supported,
+ * and failing with ENOSYS means that the syscall wasn't
+ * there: in those cases we want to fall back. Otherwise, we
+ * got a real error, and we should return. */
+ return result;
+ }
+#endif
+ result = accept(sockfd, addr, addrlen);
+ if (result < 0)
+ return result;
+
+ if (flags & EVUTIL_SOCK_CLOEXEC) {
+ if (evutil_fast_socket_closeonexec(result) < 0) {
+ evutil_closesocket(result);
+ return -1;
+ }
+ }
+ if (flags & EVUTIL_SOCK_NONBLOCK) {
+ if (evutil_fast_socket_nonblocking(result) < 0) {
+ evutil_closesocket(result);
+ return -1;
+ }
+ }
+ return result;
+}
+
+/* Internal function: Set fd[0] and fd[1] to a pair of fds such that writes on
+ * fd[1] get read from fd[0]. Make both fds nonblocking and close-on-exec.
+ * Return 0 on success, -1 on failure.
+ */
+int
+evutil_make_internal_pipe_(evutil_socket_t fd[2])
+{
+ /*
+ Making the second socket nonblocking is a bit subtle, given that we
+ ignore any EAGAIN returns when writing to it, and you don't usally
+ do that for a nonblocking socket. But if the kernel gives us EAGAIN,
+ then there's no need to add any more data to the buffer, since
+ the main thread is already either about to wake up and drain it,
+ or woken up and in the process of draining it.
+ */
+
+#if defined(EVENT__HAVE_PIPE2)
+ if (pipe2(fd, O_NONBLOCK|O_CLOEXEC) == 0)
+ return 0;
+#endif
+#if defined(EVENT__HAVE_PIPE)
+ if (pipe(fd) == 0) {
+ if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
+ evutil_fast_socket_nonblocking(fd[1]) < 0 ||
+ evutil_fast_socket_closeonexec(fd[0]) < 0 ||
+ evutil_fast_socket_closeonexec(fd[1]) < 0) {
+ close(fd[0]);
+ close(fd[1]);
+ fd[0] = fd[1] = -1;
+ return -1;
+ }
+ return 0;
+ } else {
+ event_warn("%s: pipe", __func__);
+ }
+#endif
+
+#ifdef _WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+ if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, fd) == 0) {
+ if (evutil_fast_socket_nonblocking(fd[0]) < 0 ||
+ evutil_fast_socket_nonblocking(fd[1]) < 0 ||
+ evutil_fast_socket_closeonexec(fd[0]) < 0 ||
+ evutil_fast_socket_closeonexec(fd[1]) < 0) {
+ evutil_closesocket(fd[0]);
+ evutil_closesocket(fd[1]);
+ fd[0] = fd[1] = -1;
+ return -1;
+ }
+ return 0;
+ }
+ fd[0] = fd[1] = -1;
+ return -1;
+}
+
+/* Wrapper around eventfd on systems that provide it. Unlike the system
+ * eventfd, it always supports EVUTIL_EFD_CLOEXEC and EVUTIL_EFD_NONBLOCK as
+ * flags. Returns -1 on error or if eventfd is not supported.
+ */
+evutil_socket_t
+evutil_eventfd_(unsigned initval, int flags)
+{
+#if defined(EVENT__HAVE_EVENTFD) && defined(EVENT__HAVE_SYS_EVENTFD_H)
+ int r;
+#if defined(EFD_CLOEXEC) && defined(EFD_NONBLOCK)
+ r = eventfd(initval, flags);
+ if (r >= 0 || flags == 0)
+ return r;
+#endif
+ r = eventfd(initval, 0);
+ if (r < 0)
+ return r;
+ if (flags & EVUTIL_EFD_CLOEXEC) {
+ if (evutil_fast_socket_closeonexec(r) < 0) {
+ evutil_closesocket(r);
+ return -1;
+ }
+ }
+ if (flags & EVUTIL_EFD_NONBLOCK) {
+ if (evutil_fast_socket_nonblocking(r) < 0) {
+ evutil_closesocket(r);
+ return -1;
+ }
+ }
+ return r;
+#else
+ return -1;
+#endif
+}
+
+void
+evutil_free_globals_(void)
+{
+ evutil_free_secure_rng_globals_();
+ evutil_free_sock_err_globals();
+}
diff --git a/ipc/chromium/src/third_party/libevent/evutil_rand.c b/ipc/chromium/src/third_party/libevent/evutil_rand.c
new file mode 100644
index 0000000000..8e9afdaa67
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evutil_rand.c
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* This file has our secure PRNG code. On platforms that have arc4random(),
+ * we just use that. Otherwise, we include arc4random.c as a bunch of static
+ * functions, and wrap it lightly. We don't expose the arc4random*() APIs
+ * because A) they aren't in our namespace, and B) it's not nice to name your
+ * APIs after their implementations. We keep them in a separate file
+ * so that other people can rip it out and use it for whatever.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <limits.h>
+
+#include "util-internal.h"
+#include "evthread-internal.h"
+
+#ifdef EVENT__HAVE_ARC4RANDOM
+#include <stdlib.h>
+#include <string.h>
+int
+evutil_secure_rng_set_urandom_device_file(char *fname)
+{
+ (void) fname;
+ return -1;
+}
+int
+evutil_secure_rng_init(void)
+{
+ /* call arc4random() now to force it to self-initialize */
+ (void) arc4random();
+ return 0;
+}
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+evutil_secure_rng_global_setup_locks_(const int enable_locks)
+{
+ return 0;
+}
+#endif
+static void
+evutil_free_secure_rng_globals_locks(void)
+{
+}
+
+static void
+ev_arc4random_buf(void *buf, size_t n)
+{
+#if defined(EVENT__HAVE_ARC4RANDOM_BUF) && !defined(__APPLE__)
+ arc4random_buf(buf, n);
+ return;
+#else
+ unsigned char *b = buf;
+
+#if defined(EVENT__HAVE_ARC4RANDOM_BUF)
+ /* OSX 10.7 introducd arc4random_buf, so if you build your program
+ * there, you'll get surprised when older versions of OSX fail to run.
+ * To solve this, we can check whether the function pointer is set,
+ * and fall back otherwise. (OSX does this using some linker
+ * trickery.)
+ */
+ {
+ void (*tptr)(void *,size_t) =
+ (void (*)(void*,size_t))arc4random_buf;
+ if (tptr != NULL) {
+ arc4random_buf(buf, n);
+ return;
+ }
+ }
+#endif
+ /* Make sure that we start out with b at a 4-byte alignment; plenty
+ * of CPUs care about this for 32-bit access. */
+ if (n >= 4 && ((ev_uintptr_t)b) & 3) {
+ ev_uint32_t u = arc4random();
+ int n_bytes = 4 - (((ev_uintptr_t)b) & 3);
+ memcpy(b, &u, n_bytes);
+ b += n_bytes;
+ n -= n_bytes;
+ }
+ while (n >= 4) {
+ *(ev_uint32_t*)b = arc4random();
+ b += 4;
+ n -= 4;
+ }
+ if (n) {
+ ev_uint32_t u = arc4random();
+ memcpy(b, &u, n);
+ }
+#endif
+}
+
+#else /* !EVENT__HAVE_ARC4RANDOM { */
+
+#ifdef EVENT__ssize_t
+#define ssize_t EVENT__ssize_t
+#endif
+#define ARC4RANDOM_EXPORT static
+#define ARC4_LOCK_() EVLOCK_LOCK(arc4rand_lock, 0)
+#define ARC4_UNLOCK_() EVLOCK_UNLOCK(arc4rand_lock, 0)
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+static void *arc4rand_lock;
+#endif
+
+#define ARC4RANDOM_UINT32 ev_uint32_t
+#define ARC4RANDOM_NOSTIR
+#define ARC4RANDOM_NORANDOM
+#define ARC4RANDOM_NOUNIFORM
+
+#include "./arc4random.c"
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+evutil_secure_rng_global_setup_locks_(const int enable_locks)
+{
+ EVTHREAD_SETUP_GLOBAL_LOCK(arc4rand_lock, 0);
+ return 0;
+}
+#endif
+
+static void
+evutil_free_secure_rng_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (arc4rand_lock != NULL) {
+ EVTHREAD_FREE_LOCK(arc4rand_lock, 0);
+ arc4rand_lock = NULL;
+ }
+#endif
+ return;
+}
+
+int
+evutil_secure_rng_set_urandom_device_file(char *fname)
+{
+#ifdef TRY_SEED_URANDOM
+ ARC4_LOCK_();
+ arc4random_urandom_filename = fname;
+ ARC4_UNLOCK_();
+#endif
+ return 0;
+}
+
+int
+evutil_secure_rng_init(void)
+{
+ int val;
+
+ ARC4_LOCK_();
+ val = (!arc4_stir()) ? 0 : -1;
+ ARC4_UNLOCK_();
+ return val;
+}
+
+static void
+ev_arc4random_buf(void *buf, size_t n)
+{
+ arc4random_buf(buf, n);
+}
+
+#endif /* } !EVENT__HAVE_ARC4RANDOM */
+
+void
+evutil_secure_rng_get_bytes(void *buf, size_t n)
+{
+ ev_arc4random_buf(buf, n);
+}
+
+#if !defined(EVENT__HAVE_ARC4RANDOM) || defined(EVENT__HAVE_ARC4RANDOM_ADDRANDOM)
+void
+evutil_secure_rng_add_bytes(const char *buf, size_t n)
+{
+ arc4random_addrandom((unsigned char*)buf,
+ n>(size_t)INT_MAX ? INT_MAX : (int)n);
+}
+#endif
+
+void
+evutil_free_secure_rng_globals_(void)
+{
+ evutil_free_secure_rng_globals_locks();
+}
diff --git a/ipc/chromium/src/third_party/libevent/evutil_time.c b/ipc/chromium/src/third_party/libevent/evutil_time.c
new file mode 100644
index 0000000000..c327218227
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/evutil_time.c
@@ -0,0 +1,621 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_STDLIB_H
+#include <stdlib.h>
+#endif
+#include <errno.h>
+#include <limits.h>
+#ifndef EVENT__HAVE_GETTIMEOFDAY
+#include <sys/timeb.h>
+#endif
+#if !defined(EVENT__HAVE_NANOSLEEP) && !defined(EVENT__HAVE_USLEEP) && \
+ !defined(_WIN32)
+#include <sys/select.h>
+#endif
+#include <time.h>
+#include <sys/stat.h>
+#include <string.h>
+
+/** evutil_usleep_() */
+#if defined(_WIN32)
+#elif defined(EVENT__HAVE_NANOSLEEP)
+#elif defined(EVENT__HAVE_USLEEP)
+#include <unistd.h>
+#endif
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "mm-internal.h"
+
+#ifndef EVENT__HAVE_GETTIMEOFDAY
+/* No gettimeofday; this must be windows. */
+
+typedef void (WINAPI *GetSystemTimePreciseAsFileTime_fn_t) (LPFILETIME);
+
+int
+evutil_gettimeofday(struct timeval *tv, struct timezone *tz)
+{
+#ifdef _MSC_VER
+#define U64_LITERAL(n) n##ui64
+#else
+#define U64_LITERAL(n) n##llu
+#endif
+
+ /* Conversion logic taken from Tor, which in turn took it
+ * from Perl. GetSystemTimeAsFileTime returns its value as
+ * an unaligned (!) 64-bit value containing the number of
+ * 100-nanosecond intervals since 1 January 1601 UTC. */
+#define EPOCH_BIAS U64_LITERAL(116444736000000000)
+#define UNITS_PER_SEC U64_LITERAL(10000000)
+#define USEC_PER_SEC U64_LITERAL(1000000)
+#define UNITS_PER_USEC U64_LITERAL(10)
+ union {
+ FILETIME ft_ft;
+ ev_uint64_t ft_64;
+ } ft;
+
+ if (tv == NULL)
+ return -1;
+
+ static GetSystemTimePreciseAsFileTime_fn_t GetSystemTimePreciseAsFileTime_fn = NULL;
+ static int check_precise = 1;
+
+ if (EVUTIL_UNLIKELY(check_precise)) {
+ HMODULE h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
+ if (h != NULL)
+ GetSystemTimePreciseAsFileTime_fn =
+ (GetSystemTimePreciseAsFileTime_fn_t)
+ GetProcAddress(h, "GetSystemTimePreciseAsFileTime");
+ check_precise = 0;
+ }
+
+ if (GetSystemTimePreciseAsFileTime_fn != NULL)
+ GetSystemTimePreciseAsFileTime_fn(&ft.ft_ft);
+ else
+ GetSystemTimeAsFileTime(&ft.ft_ft);
+
+ if (EVUTIL_UNLIKELY(ft.ft_64 < EPOCH_BIAS)) {
+ /* Time before the unix epoch. */
+ return -1;
+ }
+ ft.ft_64 -= EPOCH_BIAS;
+ tv->tv_sec = (long) (ft.ft_64 / UNITS_PER_SEC);
+ tv->tv_usec = (long) ((ft.ft_64 / UNITS_PER_USEC) % USEC_PER_SEC);
+ return 0;
+}
+#endif
+
+#define MAX_SECONDS_IN_MSEC_LONG \
+ (((LONG_MAX) - 999) / 1000)
+
+long
+evutil_tv_to_msec_(const struct timeval *tv)
+{
+ if (tv->tv_usec > 1000000 || tv->tv_sec > MAX_SECONDS_IN_MSEC_LONG)
+ return -1;
+
+ return (tv->tv_sec * 1000) + ((tv->tv_usec + 999) / 1000);
+}
+
+/*
+ Replacement for usleep on platforms that don't have one. Not guaranteed to
+ be any more finegrained than 1 msec.
+ */
+void
+evutil_usleep_(const struct timeval *tv)
+{
+ if (!tv)
+ return;
+#if defined(_WIN32)
+ {
+ __int64 usec;
+ LARGE_INTEGER li;
+ HANDLE timer;
+
+ usec = tv->tv_sec * 1000000LL + tv->tv_usec;
+ if (!usec)
+ return;
+
+ li.QuadPart = -10LL * usec;
+ timer = CreateWaitableTimer(NULL, TRUE, NULL);
+ if (!timer)
+ return;
+
+ SetWaitableTimer(timer, &li, 0, NULL, NULL, 0);
+ WaitForSingleObject(timer, INFINITE);
+ CloseHandle(timer);
+ }
+#elif defined(EVENT__HAVE_NANOSLEEP)
+ {
+ struct timespec ts;
+ ts.tv_sec = tv->tv_sec;
+ ts.tv_nsec = tv->tv_usec*1000;
+ nanosleep(&ts, NULL);
+ }
+#elif defined(EVENT__HAVE_USLEEP)
+ /* Some systems don't like to usleep more than 999999 usec */
+ sleep(tv->tv_sec);
+ usleep(tv->tv_usec);
+#else
+ {
+ struct timeval tv2 = *tv;
+ select(0, NULL, NULL, NULL, &tv2);
+ }
+#endif
+}
+
+int
+evutil_date_rfc1123(char *date, const size_t datelen, const struct tm *tm)
+{
+ static const char *DAYS[] =
+ { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
+ static const char *MONTHS[] =
+ { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
+
+ time_t t = time(NULL);
+
+#if defined(EVENT__HAVE__GMTIME64_S) || !defined(_WIN32)
+ struct tm sys;
+#endif
+
+ /* If `tm` is null, set system's current time. */
+ if (tm == NULL) {
+#if !defined(_WIN32)
+ gmtime_r(&t, &sys);
+ tm = &sys;
+ /** detect _gmtime64()/_gmtime64_s() */
+#elif defined(EVENT__HAVE__GMTIME64_S)
+ errno_t err;
+ err = _gmtime64_s(&sys, &t);
+ if (err) {
+ event_errx(1, "Invalid argument to _gmtime64_s");
+ } else {
+ tm = &sys;
+ }
+#elif defined(EVENT__HAVE__GMTIME64)
+ tm = _gmtime64(&t);
+#else
+ tm = gmtime(&t);
+#endif
+ }
+
+ return evutil_snprintf(
+ date, datelen, "%s, %02d %s %4d %02d:%02d:%02d GMT",
+ DAYS[tm->tm_wday], tm->tm_mday, MONTHS[tm->tm_mon],
+ 1900 + tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec);
+}
+
+/*
+ This function assumes it's called repeatedly with a
+ not-actually-so-monotonic time source whose outputs are in 'tv'. It
+ implements a trivial ratcheting mechanism so that the values never go
+ backwards.
+ */
+static void
+adjust_monotonic_time(struct evutil_monotonic_timer *base,
+ struct timeval *tv)
+{
+ evutil_timeradd(tv, &base->adjust_monotonic_clock, tv);
+
+ if (evutil_timercmp(tv, &base->last_time, <)) {
+ /* Guess it wasn't monotonic after all. */
+ struct timeval adjust;
+ evutil_timersub(&base->last_time, tv, &adjust);
+ evutil_timeradd(&adjust, &base->adjust_monotonic_clock,
+ &base->adjust_monotonic_clock);
+ *tv = base->last_time;
+ }
+ base->last_time = *tv;
+}
+
+/*
+ Allocate a new struct evutil_monotonic_timer
+ */
+struct evutil_monotonic_timer *
+evutil_monotonic_timer_new(void)
+{
+ struct evutil_monotonic_timer *p = NULL;
+
+ p = mm_malloc(sizeof(*p));
+ if (!p) goto done;
+
+ memset(p, 0, sizeof(*p));
+
+ done:
+ return p;
+}
+
+/*
+ Free a struct evutil_monotonic_timer
+ */
+void
+evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer)
+{
+ if (timer) {
+ mm_free(timer);
+ }
+}
+
+/*
+ Set up a struct evutil_monotonic_timer for initial use
+ */
+int
+evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
+ int flags)
+{
+ return evutil_configure_monotonic_time_(timer, flags);
+}
+
+/*
+ Query the current monotonic time
+ */
+int
+evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
+ struct timeval *tp)
+{
+ return evutil_gettime_monotonic_(timer, tp);
+}
+
+
+#if defined(HAVE_POSIX_MONOTONIC)
+/* =====
+ The POSIX clock_gettime() interface provides a few ways to get at a
+ monotonic clock. CLOCK_MONOTONIC is most widely supported. Linux also
+ provides a CLOCK_MONOTONIC_COARSE with accuracy of about 1-4 msec.
+
+ On all platforms I'm aware of, CLOCK_MONOTONIC really is monotonic.
+ Platforms don't agree about whether it should jump on a sleep/resume.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+ int flags)
+{
+ /* CLOCK_MONOTONIC exists on FreeBSD, Linux, and Solaris. You need to
+ * check for it at runtime, because some older kernel versions won't
+ * have it working. */
+#ifdef CLOCK_MONOTONIC_COARSE
+ const int precise = flags & EV_MONOT_PRECISE;
+#endif
+ const int fallback = flags & EV_MONOT_FALLBACK;
+ struct timespec ts;
+
+#ifdef CLOCK_MONOTONIC_COARSE
+ if (CLOCK_MONOTONIC_COARSE < 0) {
+ /* Technically speaking, nothing keeps CLOCK_* from being
+ * negative (as far as I know). This check and the one below
+ * make sure that it's safe for us to use -1 as an "unset"
+ * value. */
+ event_errx(1,"I didn't expect CLOCK_MONOTONIC_COARSE to be < 0");
+ }
+ if (! precise && ! fallback) {
+ if (clock_gettime(CLOCK_MONOTONIC_COARSE, &ts) == 0) {
+ base->monotonic_clock = CLOCK_MONOTONIC_COARSE;
+ return 0;
+ }
+ }
+#endif
+ if (!fallback && clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
+ base->monotonic_clock = CLOCK_MONOTONIC;
+ return 0;
+ }
+
+ if (CLOCK_MONOTONIC < 0) {
+ event_errx(1,"I didn't expect CLOCK_MONOTONIC to be < 0");
+ }
+
+ base->monotonic_clock = -1;
+ return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+ struct timeval *tp)
+{
+ struct timespec ts;
+
+ if (base->monotonic_clock < 0) {
+ if (evutil_gettimeofday(tp, NULL) < 0)
+ return -1;
+ adjust_monotonic_time(base, tp);
+ return 0;
+ }
+
+ if (clock_gettime(base->monotonic_clock, &ts) == -1)
+ return -1;
+ tp->tv_sec = ts.tv_sec;
+ tp->tv_usec = ts.tv_nsec / 1000;
+
+ return 0;
+}
+#endif
+
+#if defined(HAVE_MACH_MONOTONIC)
+/* ======
+ Apple is a little late to the POSIX party. And why not? Instead of
+ clock_gettime(), they provide mach_absolute_time(). Its units are not
+ fixed; we need to use mach_timebase_info() to get the right functions to
+ convert its units into nanoseconds.
+
+ To all appearances, mach_absolute_time() seems to be honest-to-goodness
+ monotonic. Whether it stops during sleep or not is unspecified in
+ principle, and dependent on CPU architecture in practice.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+ int flags)
+{
+ const int fallback = flags & EV_MONOT_FALLBACK;
+ struct mach_timebase_info mi;
+ memset(base, 0, sizeof(*base));
+ /* OSX has mach_absolute_time() */
+ if (!fallback &&
+ mach_timebase_info(&mi) == 0 &&
+ mach_absolute_time() != 0) {
+ /* mach_timebase_info tells us how to convert
+ * mach_absolute_time() into nanoseconds, but we
+ * want to use microseconds instead. */
+ mi.denom *= 1000;
+ memcpy(&base->mach_timebase_units, &mi, sizeof(mi));
+ } else {
+ base->mach_timebase_units.numer = 0;
+ }
+ return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+ struct timeval *tp)
+{
+ ev_uint64_t abstime, usec;
+ if (base->mach_timebase_units.numer == 0) {
+ if (evutil_gettimeofday(tp, NULL) < 0)
+ return -1;
+ adjust_monotonic_time(base, tp);
+ return 0;
+ }
+
+ abstime = mach_absolute_time();
+ usec = (abstime * base->mach_timebase_units.numer)
+ / (base->mach_timebase_units.denom);
+ tp->tv_sec = usec / 1000000;
+ tp->tv_usec = usec % 1000000;
+
+ return 0;
+}
+#endif
+
+#if defined(HAVE_WIN32_MONOTONIC)
+/* =====
+ Turn we now to Windows. Want monontonic time on Windows?
+
+ Windows has QueryPerformanceCounter(), which gives time most high-
+ resolution time. It's a pity it's not so monotonic in practice; it's
+ also got some fun bugs, especially: with older Windowses, under
+ virtualizations, with funny hardware, on multiprocessor systems, and so
+ on. PEP418 [1] has a nice roundup of the issues here.
+
+ There's GetTickCount64() on Vista and later, which gives a number of 1-msec
+ ticks since startup. The accuracy here might be as bad as 10-20 msec, I
+ hear. There's an undocumented function (NtSetTimerResolution) that
+ allegedly increases the accuracy. Good luck!
+
+ There's also GetTickCount(), which is only 32 bits, but seems to be
+ supported on pre-Vista versions of Windows. Apparently, you can coax
+ another 14 bits out of it, giving you 2231 years before rollover.
+
+ The less said about timeGetTime() the better.
+
+ "We don't care. We don't have to. We're the Phone Company."
+ -- Lily Tomlin, SNL
+
+ Our strategy, if precise timers are turned off, is to just use the best
+ GetTickCount equivalent available. If we've been asked for precise timing,
+ then we mostly[2] assume that GetTickCount is monotonic, and correct
+ GetPerformanceCounter to approximate it.
+
+ [1] http://www.python.org/dev/peps/pep-0418
+ [2] Of course, we feed the Windows stuff into adjust_monotonic_time()
+ anyway, just in case it isn't.
+
+ */
+/*
+ Parts of our logic in the win32 timer code here are closely based on
+ BitTorrent's libUTP library. That code is subject to the following
+ license:
+
+ Copyright (c) 2010 BitTorrent, Inc.
+
+ Permission is hereby granted, free of charge, to any person obtaining a
+ copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+ OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+static ev_uint64_t
+evutil_GetTickCount_(struct evutil_monotonic_timer *base)
+{
+ if (base->GetTickCount64_fn) {
+ /* Let's just use GetTickCount64 if we can. */
+ return base->GetTickCount64_fn();
+ } else if (base->GetTickCount_fn) {
+ /* Greg Hazel assures me that this works, that BitTorrent has
+ * done it for years, and this it won't turn around and
+ * bite us. He says they found it on some game programmers'
+ * forum some time around 2007.
+ */
+ ev_uint64_t v = base->GetTickCount_fn();
+ return (DWORD)v | ((v >> 18) & 0xFFFFFFFF00000000);
+ } else {
+ /* Here's the fallback implementation. We have to use
+ * GetTickCount() with its given signature, so we only get
+ * 32 bits worth of milliseconds, which will roll ove every
+ * 49 days or so. */
+ DWORD ticks = GetTickCount();
+ if (ticks < base->last_tick_count) {
+ base->adjust_tick_count += ((ev_uint64_t)1) << 32;
+ }
+ base->last_tick_count = ticks;
+ return ticks + base->adjust_tick_count;
+ }
+}
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+ int flags)
+{
+ const int precise = flags & EV_MONOT_PRECISE;
+ const int fallback = flags & EV_MONOT_FALLBACK;
+ HANDLE h;
+ memset(base, 0, sizeof(*base));
+
+ h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
+ if (h != NULL && !fallback) {
+ base->GetTickCount64_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount64");
+ base->GetTickCount_fn = (ev_GetTickCount_func)GetProcAddress(h, "GetTickCount");
+ }
+
+ base->first_tick = base->last_tick_count = evutil_GetTickCount_(base);
+ if (precise && !fallback) {
+ LARGE_INTEGER freq;
+ if (QueryPerformanceFrequency(&freq)) {
+ LARGE_INTEGER counter;
+ QueryPerformanceCounter(&counter);
+ base->first_counter = counter.QuadPart;
+ base->usec_per_count = 1.0e6 / freq.QuadPart;
+ base->use_performance_counter = 1;
+ }
+ }
+
+ return 0;
+}
+
+static inline ev_int64_t
+abs64(ev_int64_t i)
+{
+ return i < 0 ? -i : i;
+}
+
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+ struct timeval *tp)
+{
+ ev_uint64_t ticks = evutil_GetTickCount_(base);
+ if (base->use_performance_counter) {
+ /* Here's a trick we took from BitTorrent's libutp, at Greg
+ * Hazel's recommendation. We use QueryPerformanceCounter for
+ * our high-resolution timer, but use GetTickCount*() to keep
+ * it sane, and adjust_monotonic_time() to keep it monotonic.
+ */
+ LARGE_INTEGER counter;
+ ev_int64_t counter_elapsed, counter_usec_elapsed, ticks_elapsed;
+ QueryPerformanceCounter(&counter);
+ counter_elapsed = (ev_int64_t)
+ (counter.QuadPart - base->first_counter);
+ ticks_elapsed = ticks - base->first_tick;
+ /* TODO: This may upset VC6. If you need this to work with
+ * VC6, please supply an appropriate patch. */
+ counter_usec_elapsed = (ev_int64_t)
+ (counter_elapsed * base->usec_per_count);
+
+ if (abs64(ticks_elapsed*1000 - counter_usec_elapsed) > 1000000) {
+ /* It appears that the QueryPerformanceCounter()
+ * result is more than 1 second away from
+ * GetTickCount() result. Let's adjust it to be as
+ * accurate as we can; adjust_monotnonic_time() below
+ * will keep it monotonic. */
+ counter_usec_elapsed = ticks_elapsed * 1000;
+ base->first_counter = (ev_uint64_t) (counter.QuadPart - counter_usec_elapsed / base->usec_per_count);
+ }
+ tp->tv_sec = (time_t) (counter_usec_elapsed / 1000000);
+ tp->tv_usec = counter_usec_elapsed % 1000000;
+
+ } else {
+ /* We're just using GetTickCount(). */
+ tp->tv_sec = (time_t) (ticks / 1000);
+ tp->tv_usec = (ticks % 1000) * 1000;
+ }
+ adjust_monotonic_time(base, tp);
+
+ return 0;
+}
+#endif
+
+#if defined(HAVE_FALLBACK_MONOTONIC)
+/* =====
+ And if none of the other options work, let's just use gettimeofday(), and
+ ratchet it forward so that it acts like a monotonic timer, whether it
+ wants to or not.
+ */
+
+int
+evutil_configure_monotonic_time_(struct evutil_monotonic_timer *base,
+ int precise)
+{
+ memset(base, 0, sizeof(*base));
+ return 0;
+}
+
+int
+evutil_gettime_monotonic_(struct evutil_monotonic_timer *base,
+ struct timeval *tp)
+{
+ if (evutil_gettimeofday(tp, NULL) < 0)
+ return -1;
+ adjust_monotonic_time(base, tp);
+ return 0;
+
+}
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/extra/abi-check/README.md b/ipc/chromium/src/third_party/libevent/extra/abi-check/README.md
new file mode 100644
index 0000000000..77fdd94128
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/extra/abi-check/README.md
@@ -0,0 +1,35 @@
+## libevent ABI/API changes
+
+
+This script is used to generate information about changes in libevent ABI/API
+between various versions using [LVC tools](https://github.com/lvc). Such an
+overview can help developers migrate from one version to another.
+
+Here is the `abi_check.sh`, which is used to generate ABI/API timeline for
+libevent.
+
+You can limit the number of included libevent versions via a number given
+as a parameter to the script. For example
+
+```shell
+$ ./abi_check.sh 3
+```
+
+generates overview for the last 3 versions and the current version.
+If no parameter given, it will generate overview for the last 2 versions and
+the current version by default.
+
+But this script requires some tools that are available in the following docker image:
+
+```
+docker.pkg.github.com/azat/docker-images/lvc-debian
+```
+
+And the full command looks like:
+
+```shell
+ docker run --rm -it -v $PWD:/src:ro -w /src -v tmp/le-abi-check-root:/abi-root -e ABI_CHECK_ROOT=/abi-root docker.pkg.github.com/azat/docker-images/lvc-debian /src/extra/abi-check/abi_check.sh
+```
+
+'timeline/libevent/index.html' is the final result and can be viewed
+[here](https://libevent.org/abi)
diff --git a/ipc/chromium/src/third_party/libevent/extra/abi-check/abi_check.sh b/ipc/chromium/src/third_party/libevent/extra/abi-check/abi_check.sh
new file mode 100755
index 0000000000..e860657e9b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/extra/abi-check/abi_check.sh
@@ -0,0 +1,53 @@
+#!/usr/bin/env bash
+
+# Requirements:
+# - wdiff
+# - rfcdiff
+# - universal-ctags
+# - abi-tracker
+# - abi-monitor
+# - git
+#
+# All of this are included in:
+# docker.pkg.github.com/azat/docker-images/lvc-debian:latest
+#
+# TODO:
+# - move image into libevent namespace
+
+# verify backward compatibility of API/ABI changes
+
+set -e
+
+LIMIT=${1:-2}
+EVENT_SOURCE_DIR=${EVENT_SOURCE_DIR:-"$(cd "$(dirname "$0")"/../.. && pwd)"}
+ABI_CHECK_ROOT=${ABI_CHECK_ROOT:-$EVENT_SOURCE_DIR/.abi-check}
+ABI_CHECK_WORKSPACE=${ABI_CHECK_WORKSPACE:-"work/abi-check"}
+
+mkdir -p "$ABI_CHECK_ROOT/$ABI_CHECK_WORKSPACE"
+cd "$ABI_CHECK_ROOT/$ABI_CHECK_WORKSPACE"
+
+# copy current source code and profile into workspace
+mkdir -p src/libevent/current
+mkdir -p installed/libevent/current
+( # to avoid cd back
+ cd "$EVENT_SOURCE_DIR"
+ # XXX: not `git archive` since it will not copy changes that are not in index,
+ # and maybe some issues on CI (since it does not contain full clone)
+ find . -maxdepth 1 -mindepth 1 | {
+ git check-ignore --no-index --verbose --non-matching --stdin
+ } | fgrep :: | cut -f2 | grep -v /.git/ | tee /dev/stderr | {
+ xargs cp -r -t "$ABI_CHECK_ROOT/$ABI_CHECK_WORKSPACE/src/libevent/current/"
+ }
+ cp extra/abi-check/libevent.json "$ABI_CHECK_ROOT/$ABI_CHECK_WORKSPACE/"
+)
+
+# run LVC tools
+abi-monitor -get -limit "$LIMIT" libevent.json
+# XXX: abi-monitor 1.12 supports "-make -j8", but 1.10 does not
+# (we can detect which version we have, and add this options)
+abi-monitor -v current -build libevent.json
+abi-monitor -build libevent.json
+abi-tracker -build libevent.json
+
+# remove useless files
+rm -rf src installed build_logs libevent.json
diff --git a/ipc/chromium/src/third_party/libevent/extra/abi-check/libevent.json b/ipc/chromium/src/third_party/libevent/extra/abi-check/libevent.json
new file mode 100644
index 0000000000..42930e933c
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/extra/abi-check/libevent.json
@@ -0,0 +1,12 @@
+{
+ "Name": "libevent",
+ "Title": "Libevent",
+ "SourceUrl": "https://github.com/libevent/libevent/tags",
+ "Git": "https://github.com/libevent/libevent.git",
+ "Maintainer": "Nick Mathewson, Azat Khuzhin and Niels Provos",
+ "MaintainerUrl": "https://libevent.org",
+ "BuildSystem": "Autotools",
+ "HeadersDiff": "On",
+ "Package": "release-",
+ "ReleasePattern": "\A([\d\-\.\_]+)(|\-beta|\-rc|\-stable)\Z",
+}
diff --git a/ipc/chromium/src/third_party/libevent/extra/lsan.supp b/ipc/chromium/src/third_party/libevent/extra/lsan.supp
new file mode 100644
index 0000000000..c1b130bf7e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/extra/lsan.supp
@@ -0,0 +1,3 @@
+# TODO: temporary, until tests itself will be fixed
+leak:libcrypto.so
+leak:libssl.so
diff --git a/ipc/chromium/src/third_party/libevent/extra/tsan.supp b/ipc/chromium/src/third_party/libevent/extra/tsan.supp
new file mode 100644
index 0000000000..414a12c16f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/extra/tsan.supp
@@ -0,0 +1,2 @@
+# https://github.com/libevent/libevent/issues/777
+race:event_debug_mode_too_late
diff --git a/ipc/chromium/src/third_party/libevent/ht-internal.h b/ipc/chromium/src/third_party/libevent/ht-internal.h
new file mode 100644
index 0000000000..50375bbaa9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ht-internal.h
@@ -0,0 +1,487 @@
+/* Copyright 2002 Christopher Clark */
+/* Copyright 2005-2012 Nick Mathewson */
+/* Copyright 2009-2012 Niels Provos and Nick Mathewson */
+/* See license at end. */
+
+/* Based on ideas by Christopher Clark and interfaces from Niels Provos. */
+
+#ifndef HT_INTERNAL_H_INCLUDED_
+#define HT_INTERNAL_H_INCLUDED_
+
+#define HT_HEAD(name, type) \
+ struct name { \
+ /* The hash table itself. */ \
+ struct type **hth_table; \
+ /* How long is the hash table? */ \
+ unsigned hth_table_length; \
+ /* How many elements does the table contain? */ \
+ unsigned hth_n_entries; \
+ /* How many elements will we allow in the table before resizing it? */ \
+ unsigned hth_load_limit; \
+ /* Position of hth_table_length in the primes table. */ \
+ int hth_prime_idx; \
+ }
+
+#define HT_INITIALIZER() \
+ { NULL, 0, 0, 0, -1 }
+
+#ifdef HT_NO_CACHE_HASH_VALUES
+#define HT_ENTRY(type) \
+ struct { \
+ struct type *hte_next; \
+ }
+#else
+#define HT_ENTRY(type) \
+ struct { \
+ struct type *hte_next; \
+ unsigned hte_hash; \
+ }
+#endif
+
+#define HT_EMPTY(head) \
+ ((head)->hth_n_entries == 0)
+
+/* How many elements in 'head'? */
+#define HT_SIZE(head) \
+ ((head)->hth_n_entries)
+
+/* Return memory usage for a hashtable (not counting the entries themselves) */
+#define HT_MEM_USAGE(head) \
+ (sizeof(*head) + (head)->hth_table_length * sizeof(void*))
+
+#define HT_FIND(name, head, elm) name##_HT_FIND((head), (elm))
+#define HT_INSERT(name, head, elm) name##_HT_INSERT((head), (elm))
+#define HT_REPLACE(name, head, elm) name##_HT_REPLACE((head), (elm))
+#define HT_REMOVE(name, head, elm) name##_HT_REMOVE((head), (elm))
+#define HT_START(name, head) name##_HT_START(head)
+#define HT_NEXT(name, head, elm) name##_HT_NEXT((head), (elm))
+#define HT_NEXT_RMV(name, head, elm) name##_HT_NEXT_RMV((head), (elm))
+#define HT_CLEAR(name, head) name##_HT_CLEAR(head)
+#define HT_INIT(name, head) name##_HT_INIT(head)
+/* Helper: */
+static inline unsigned
+ht_improve_hash_(unsigned h)
+{
+ /* Aim to protect against poor hash functions by adding logic here
+ * - logic taken from java 1.4 hashtable source */
+ h += ~(h << 9);
+ h ^= ((h >> 14) | (h << 18)); /* >>> */
+ h += (h << 4);
+ h ^= ((h >> 10) | (h << 22)); /* >>> */
+ return h;
+}
+
+#if 0
+/** Basic string hash function, from Java standard String.hashCode(). */
+static inline unsigned
+ht_string_hash_(const char *s)
+{
+ unsigned h = 0;
+ int m = 1;
+ while (*s) {
+ h += ((signed char)*s++)*m;
+ m = (m<<5)-1; /* m *= 31 */
+ }
+ return h;
+}
+#endif
+
+/** Basic string hash function, from Python's str.__hash__() */
+static inline unsigned
+ht_string_hash_(const char *s)
+{
+ unsigned h;
+ const unsigned char *cp = (const unsigned char *)s;
+ h = *cp << 7;
+ while (*cp) {
+ h = (1000003*h) ^ *cp++;
+ }
+ /* This conversion truncates the length of the string, but that's ok. */
+ h ^= (unsigned)(cp-(const unsigned char*)s);
+ return h;
+}
+
+#ifndef HT_NO_CACHE_HASH_VALUES
+#define HT_SET_HASH_(elm, field, hashfn) \
+ do { (elm)->field.hte_hash = hashfn(elm); } while (0)
+#define HT_SET_HASHVAL_(elm, field, val) \
+ do { (elm)->field.hte_hash = (val); } while (0)
+#define HT_ELT_HASH_(elm, field, hashfn) \
+ ((elm)->field.hte_hash)
+#else
+#define HT_SET_HASH_(elm, field, hashfn) \
+ ((void)0)
+#define HT_ELT_HASH_(elm, field, hashfn) \
+ (hashfn(elm))
+#define HT_SET_HASHVAL_(elm, field, val) \
+ ((void)0)
+#endif
+
+/* Helper: alias for the bucket containing 'elm'. */
+#define HT_BUCKET_(head, field, elm, hashfn) \
+ ((head)->hth_table[HT_ELT_HASH_(elm,field,hashfn) % head->hth_table_length])
+
+#define HT_FOREACH(x, name, head) \
+ for ((x) = HT_START(name, head); \
+ (x) != NULL; \
+ (x) = HT_NEXT(name, head, x))
+
+#define HT_PROTOTYPE(name, type, field, hashfn, eqfn) \
+ int name##_HT_GROW(struct name *ht, unsigned min_capacity); \
+ void name##_HT_CLEAR(struct name *ht); \
+ int name##_HT_REP_IS_BAD_(const struct name *ht); \
+ static inline void \
+ name##_HT_INIT(struct name *head) { \
+ head->hth_table_length = 0; \
+ head->hth_table = NULL; \
+ head->hth_n_entries = 0; \
+ head->hth_load_limit = 0; \
+ head->hth_prime_idx = -1; \
+ } \
+ /* Helper: returns a pointer to the right location in the table \
+ * 'head' to find or insert the element 'elm'. */ \
+ static inline struct type ** \
+ name##_HT_FIND_P_(struct name *head, struct type *elm) \
+ { \
+ struct type **p; \
+ if (!head->hth_table) \
+ return NULL; \
+ p = &HT_BUCKET_(head, field, elm, hashfn); \
+ while (*p) { \
+ if (eqfn(*p, elm)) \
+ return p; \
+ p = &(*p)->field.hte_next; \
+ } \
+ return p; \
+ } \
+ /* Return a pointer to the element in the table 'head' matching 'elm', \
+ * or NULL if no such element exists */ \
+ static inline struct type * \
+ name##_HT_FIND(const struct name *head, struct type *elm) \
+ { \
+ struct type **p; \
+ struct name *h = (struct name *) head; \
+ HT_SET_HASH_(elm, field, hashfn); \
+ p = name##_HT_FIND_P_(h, elm); \
+ return p ? *p : NULL; \
+ } \
+ /* Insert the element 'elm' into the table 'head'. Do not call this \
+ * function if the table might already contain a matching element. */ \
+ static inline void \
+ name##_HT_INSERT(struct name *head, struct type *elm) \
+ { \
+ struct type **p; \
+ if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
+ name##_HT_GROW(head, head->hth_n_entries+1); \
+ ++head->hth_n_entries; \
+ HT_SET_HASH_(elm, field, hashfn); \
+ p = &HT_BUCKET_(head, field, elm, hashfn); \
+ elm->field.hte_next = *p; \
+ *p = elm; \
+ } \
+ /* Insert the element 'elm' into the table 'head'. If there already \
+ * a matching element in the table, replace that element and return \
+ * it. */ \
+ static inline struct type * \
+ name##_HT_REPLACE(struct name *head, struct type *elm) \
+ { \
+ struct type **p, *r; \
+ if (!head->hth_table || head->hth_n_entries >= head->hth_load_limit) \
+ name##_HT_GROW(head, head->hth_n_entries+1); \
+ HT_SET_HASH_(elm, field, hashfn); \
+ p = name##_HT_FIND_P_(head, elm); \
+ r = *p; \
+ *p = elm; \
+ if (r && (r!=elm)) { \
+ elm->field.hte_next = r->field.hte_next; \
+ r->field.hte_next = NULL; \
+ return r; \
+ } else { \
+ ++head->hth_n_entries; \
+ return NULL; \
+ } \
+ } \
+ /* Remove any element matching 'elm' from the table 'head'. If such \
+ * an element is found, return it; otherwise return NULL. */ \
+ static inline struct type * \
+ name##_HT_REMOVE(struct name *head, struct type *elm) \
+ { \
+ struct type **p, *r; \
+ HT_SET_HASH_(elm, field, hashfn); \
+ p = name##_HT_FIND_P_(head,elm); \
+ if (!p || !*p) \
+ return NULL; \
+ r = *p; \
+ *p = r->field.hte_next; \
+ r->field.hte_next = NULL; \
+ --head->hth_n_entries; \
+ return r; \
+ } \
+ /* Invoke the function 'fn' on every element of the table 'head', \
+ * using 'data' as its second argument. If the function returns \
+ * nonzero, remove the most recently examined element before invoking \
+ * the function again. */ \
+ static inline void \
+ name##_HT_FOREACH_FN(struct name *head, \
+ int (*fn)(struct type *, void *), \
+ void *data) \
+ { \
+ unsigned idx; \
+ struct type **p, **nextp, *next; \
+ if (!head->hth_table) \
+ return; \
+ for (idx=0; idx < head->hth_table_length; ++idx) { \
+ p = &head->hth_table[idx]; \
+ while (*p) { \
+ nextp = &(*p)->field.hte_next; \
+ next = *nextp; \
+ if (fn(*p, data)) { \
+ --head->hth_n_entries; \
+ *p = next; \
+ } else { \
+ p = nextp; \
+ } \
+ } \
+ } \
+ } \
+ /* Return a pointer to the first element in the table 'head', under \
+ * an arbitrary order. This order is stable under remove operations, \
+ * but not under others. If the table is empty, return NULL. */ \
+ static inline struct type ** \
+ name##_HT_START(struct name *head) \
+ { \
+ unsigned b = 0; \
+ while (b < head->hth_table_length) { \
+ if (head->hth_table[b]) \
+ return &head->hth_table[b]; \
+ ++b; \
+ } \
+ return NULL; \
+ } \
+ /* Return the next element in 'head' after 'elm', under the arbitrary \
+ * order used by HT_START. If there are no more elements, return \
+ * NULL. If 'elm' is to be removed from the table, you must call \
+ * this function for the next value before you remove it. \
+ */ \
+ static inline struct type ** \
+ name##_HT_NEXT(struct name *head, struct type **elm) \
+ { \
+ if ((*elm)->field.hte_next) { \
+ return &(*elm)->field.hte_next; \
+ } else { \
+ unsigned b = (HT_ELT_HASH_(*elm, field, hashfn) % head->hth_table_length)+1; \
+ while (b < head->hth_table_length) { \
+ if (head->hth_table[b]) \
+ return &head->hth_table[b]; \
+ ++b; \
+ } \
+ return NULL; \
+ } \
+ } \
+ static inline struct type ** \
+ name##_HT_NEXT_RMV(struct name *head, struct type **elm) \
+ { \
+ unsigned h = HT_ELT_HASH_(*elm, field, hashfn); \
+ *elm = (*elm)->field.hte_next; \
+ --head->hth_n_entries; \
+ if (*elm) { \
+ return elm; \
+ } else { \
+ unsigned b = (h % head->hth_table_length)+1; \
+ while (b < head->hth_table_length) { \
+ if (head->hth_table[b]) \
+ return &head->hth_table[b]; \
+ ++b; \
+ } \
+ return NULL; \
+ } \
+ }
+
+#define HT_GENERATE(name, type, field, hashfn, eqfn, load, mallocfn, \
+ reallocfn, freefn) \
+ static unsigned name##_PRIMES[] = { \
+ 53, 97, 193, 389, \
+ 769, 1543, 3079, 6151, \
+ 12289, 24593, 49157, 98317, \
+ 196613, 393241, 786433, 1572869, \
+ 3145739, 6291469, 12582917, 25165843, \
+ 50331653, 100663319, 201326611, 402653189, \
+ 805306457, 1610612741 \
+ }; \
+ static unsigned name##_N_PRIMES = \
+ (unsigned)(sizeof(name##_PRIMES)/sizeof(name##_PRIMES[0])); \
+ /* Expand the internal table of 'head' until it is large enough to \
+ * hold 'size' elements. Return 0 on success, -1 on allocation \
+ * failure. */ \
+ int \
+ name##_HT_GROW(struct name *head, unsigned size) \
+ { \
+ unsigned new_len, new_load_limit; \
+ int prime_idx; \
+ struct type **new_table; \
+ if (head->hth_prime_idx == (int)name##_N_PRIMES - 1) \
+ return 0; \
+ if (head->hth_load_limit > size) \
+ return 0; \
+ prime_idx = head->hth_prime_idx; \
+ do { \
+ new_len = name##_PRIMES[++prime_idx]; \
+ new_load_limit = (unsigned)(load*new_len); \
+ } while (new_load_limit <= size && \
+ prime_idx < (int)name##_N_PRIMES); \
+ if ((new_table = mallocfn(new_len*sizeof(struct type*)))) { \
+ unsigned b; \
+ memset(new_table, 0, new_len*sizeof(struct type*)); \
+ for (b = 0; b < head->hth_table_length; ++b) { \
+ struct type *elm, *next; \
+ unsigned b2; \
+ elm = head->hth_table[b]; \
+ while (elm) { \
+ next = elm->field.hte_next; \
+ b2 = HT_ELT_HASH_(elm, field, hashfn) % new_len; \
+ elm->field.hte_next = new_table[b2]; \
+ new_table[b2] = elm; \
+ elm = next; \
+ } \
+ } \
+ if (head->hth_table) \
+ freefn(head->hth_table); \
+ head->hth_table = new_table; \
+ } else { \
+ unsigned b, b2; \
+ new_table = reallocfn(head->hth_table, new_len*sizeof(struct type*)); \
+ if (!new_table) return -1; \
+ memset(new_table + head->hth_table_length, 0, \
+ (new_len - head->hth_table_length)*sizeof(struct type*)); \
+ for (b=0; b < head->hth_table_length; ++b) { \
+ struct type *e, **pE; \
+ for (pE = &new_table[b], e = *pE; e != NULL; e = *pE) { \
+ b2 = HT_ELT_HASH_(e, field, hashfn) % new_len; \
+ if (b2 == b) { \
+ pE = &e->field.hte_next; \
+ } else { \
+ *pE = e->field.hte_next; \
+ e->field.hte_next = new_table[b2]; \
+ new_table[b2] = e; \
+ } \
+ } \
+ } \
+ head->hth_table = new_table; \
+ } \
+ head->hth_table_length = new_len; \
+ head->hth_prime_idx = prime_idx; \
+ head->hth_load_limit = new_load_limit; \
+ return 0; \
+ } \
+ /* Free all storage held by 'head'. Does not free 'head' itself, or \
+ * individual elements. */ \
+ void \
+ name##_HT_CLEAR(struct name *head) \
+ { \
+ if (head->hth_table) \
+ freefn(head->hth_table); \
+ name##_HT_INIT(head); \
+ } \
+ /* Debugging helper: return false iff the representation of 'head' is \
+ * internally consistent. */ \
+ int \
+ name##_HT_REP_IS_BAD_(const struct name *head) \
+ { \
+ unsigned n, i; \
+ struct type *elm; \
+ if (!head->hth_table_length) { \
+ if (!head->hth_table && !head->hth_n_entries && \
+ !head->hth_load_limit && head->hth_prime_idx == -1) \
+ return 0; \
+ else \
+ return 1; \
+ } \
+ if (!head->hth_table || head->hth_prime_idx < 0 || \
+ !head->hth_load_limit) \
+ return 2; \
+ if (head->hth_n_entries > head->hth_load_limit) \
+ return 3; \
+ if (head->hth_table_length != name##_PRIMES[head->hth_prime_idx]) \
+ return 4; \
+ if (head->hth_load_limit != (unsigned)(load*head->hth_table_length)) \
+ return 5; \
+ for (n = i = 0; i < head->hth_table_length; ++i) { \
+ for (elm = head->hth_table[i]; elm; elm = elm->field.hte_next) { \
+ if (HT_ELT_HASH_(elm, field, hashfn) != hashfn(elm)) \
+ return 1000 + i; \
+ if ((HT_ELT_HASH_(elm, field, hashfn) % head->hth_table_length) != i) \
+ return 10000 + i; \
+ ++n; \
+ } \
+ } \
+ if (n != head->hth_n_entries) \
+ return 6; \
+ return 0; \
+ }
+
+/** Implements an over-optimized "find and insert if absent" block;
+ * not meant for direct usage by typical code, or usage outside the critical
+ * path.*/
+#define HT_FIND_OR_INSERT_(name, field, hashfn, head, eltype, elm, var, y, n) \
+ { \
+ struct name *var##_head_ = head; \
+ struct eltype **var; \
+ if (!var##_head_->hth_table || \
+ var##_head_->hth_n_entries >= var##_head_->hth_load_limit) \
+ name##_HT_GROW(var##_head_, var##_head_->hth_n_entries+1); \
+ HT_SET_HASH_((elm), field, hashfn); \
+ var = name##_HT_FIND_P_(var##_head_, (elm)); \
+ if (*var) { \
+ y; \
+ } else { \
+ n; \
+ } \
+ }
+#define HT_FOI_INSERT_(field, head, elm, newent, var) \
+ { \
+ HT_SET_HASHVAL_(newent, field, (elm)->field.hte_hash); \
+ newent->field.hte_next = NULL; \
+ *var = newent; \
+ ++((head)->hth_n_entries); \
+ }
+
+/*
+ * Copyright 2005, Nick Mathewson. Implementation logic is adapted from code
+ * by Christopher Clark, retrofit to allow drop-in memory management, and to
+ * use the same interface as Niels Provos's tree.h. This is probably still
+ * a derived work, so the original license below still applies.
+ *
+ * Copyright (c) 2002, Christopher Clark
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * * Neither the name of the original author; nor the names of any contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#endif
+
diff --git a/ipc/chromium/src/third_party/libevent/http-internal.h b/ipc/chromium/src/third_party/libevent/http-internal.h
new file mode 100644
index 0000000000..feaf436d74
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/http-internal.h
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2001-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * This header file contains definitions for dealing with HTTP requests
+ * that are internal to libevent. As user of the library, you should not
+ * need to know about these.
+ */
+
+#ifndef HTTP_INTERNAL_H_INCLUDED_
+#define HTTP_INTERNAL_H_INCLUDED_
+
+#include "event2/event_struct.h"
+#include "util-internal.h"
+#include "defer-internal.h"
+
+#define HTTP_CONNECT_TIMEOUT 45
+#define HTTP_WRITE_TIMEOUT 50
+#define HTTP_READ_TIMEOUT 50
+
+enum message_read_status {
+ ALL_DATA_READ = 1,
+ MORE_DATA_EXPECTED = 0,
+ DATA_CORRUPTED = -1,
+ REQUEST_CANCELED = -2,
+ DATA_TOO_LONG = -3
+};
+
+struct evbuffer;
+struct addrinfo;
+struct evhttp_request;
+
+/* Indicates an unknown request method. */
+#define EVHTTP_REQ_UNKNOWN_ (1<<15)
+
+enum evhttp_connection_state {
+ EVCON_DISCONNECTED, /**< not currently connected not trying either*/
+ EVCON_CONNECTING, /**< tries to currently connect */
+ EVCON_IDLE, /**< connection is established */
+ EVCON_READING_FIRSTLINE,/**< reading Request-Line (incoming conn) or
+ **< Status-Line (outgoing conn) */
+ EVCON_READING_HEADERS, /**< reading request/response headers */
+ EVCON_READING_BODY, /**< reading request/response body */
+ EVCON_READING_TRAILER, /**< reading request/response chunked trailer */
+ EVCON_WRITING /**< writing request/response headers/body */
+};
+
+struct event_base;
+
+/* A client or server connection. */
+struct evhttp_connection {
+ /* we use this tailq only if this connection was created for an http
+ * server */
+ TAILQ_ENTRY(evhttp_connection) next;
+
+ evutil_socket_t fd;
+ struct bufferevent *bufev;
+
+ struct event retry_ev; /* for retrying connects */
+
+ char *bind_address; /* address to use for binding the src */
+ ev_uint16_t bind_port; /* local port for binding the src */
+
+ char *address; /* address to connect to */
+ ev_uint16_t port;
+
+ size_t max_headers_size;
+ ev_uint64_t max_body_size;
+
+ int flags;
+#define EVHTTP_CON_INCOMING 0x0001 /* only one request on it ever */
+#define EVHTTP_CON_OUTGOING 0x0002 /* multiple requests possible */
+#define EVHTTP_CON_CLOSEDETECT 0x0004 /* detecting if persistent close */
+/* set when we want to auto free the connection */
+#define EVHTTP_CON_AUTOFREE EVHTTP_CON_PUBLIC_FLAGS_END
+/* Installed when attempt to read HTTP error after write failed, see
+ * EVHTTP_CON_READ_ON_WRITE_ERROR */
+#define EVHTTP_CON_READING_ERROR (EVHTTP_CON_AUTOFREE << 1)
+
+ struct timeval timeout; /* timeout for events */
+ int retry_cnt; /* retry count */
+ int retry_max; /* maximum number of retries */
+ struct timeval initial_retry_timeout; /* Timeout for low long to wait
+ * after first failing attempt
+ * before retry */
+
+ enum evhttp_connection_state state;
+
+ /* for server connections, the http server they are connected with */
+ struct evhttp *http_server;
+
+ TAILQ_HEAD(evcon_requestq, evhttp_request) requests;
+
+ void (*cb)(struct evhttp_connection *, void *);
+ void *cb_arg;
+
+ void (*closecb)(struct evhttp_connection *, void *);
+ void *closecb_arg;
+
+ struct event_callback read_more_deferred_cb;
+
+ struct event_base *base;
+ struct evdns_base *dns_base;
+ int ai_family;
+};
+
+/* A callback for an http server */
+struct evhttp_cb {
+ TAILQ_ENTRY(evhttp_cb) next;
+
+ char *what;
+
+ void (*cb)(struct evhttp_request *req, void *);
+ void *cbarg;
+};
+
+/* both the http server as well as the rpc system need to queue connections */
+TAILQ_HEAD(evconq, evhttp_connection);
+
+/* each bound socket is stored in one of these */
+struct evhttp_bound_socket {
+ TAILQ_ENTRY(evhttp_bound_socket) next;
+
+ struct evconnlistener *listener;
+};
+
+/* server alias list item. */
+struct evhttp_server_alias {
+ TAILQ_ENTRY(evhttp_server_alias) next;
+
+ char *alias; /* the server alias. */
+};
+
+struct evhttp {
+ /* Next vhost, if this is a vhost. */
+ TAILQ_ENTRY(evhttp) next_vhost;
+
+ /* All listeners for this host */
+ TAILQ_HEAD(boundq, evhttp_bound_socket) sockets;
+
+ TAILQ_HEAD(httpcbq, evhttp_cb) callbacks;
+
+ /* All live connections on this host. */
+ struct evconq connections;
+
+ TAILQ_HEAD(vhostsq, evhttp) virtualhosts;
+
+ TAILQ_HEAD(aliasq, evhttp_server_alias) aliases;
+
+ /* NULL if this server is not a vhost */
+ char *vhost_pattern;
+
+ struct timeval timeout;
+
+ size_t default_max_headers_size;
+ ev_uint64_t default_max_body_size;
+ int flags;
+ const char *default_content_type;
+
+ /* Bitmask of all HTTP methods that we accept and pass to user
+ * callbacks. */
+ ev_uint16_t allowed_methods;
+
+ /* Fallback callback if all the other callbacks for this connection
+ don't match. */
+ void (*gencb)(struct evhttp_request *req, void *);
+ void *gencbarg;
+ struct bufferevent* (*bevcb)(struct event_base *, void *);
+ void *bevcbarg;
+
+ struct event_base *base;
+};
+
+/* XXX most of these functions could be static. */
+
+/* resets the connection; can be reused for more requests */
+void evhttp_connection_reset_(struct evhttp_connection *);
+
+/* connects if necessary */
+int evhttp_connection_connect_(struct evhttp_connection *);
+
+enum evhttp_request_error;
+/* notifies the current request that it failed; resets connection */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_fail_(struct evhttp_connection *,
+ enum evhttp_request_error error);
+
+enum message_read_status;
+
+EVENT2_EXPORT_SYMBOL
+enum message_read_status evhttp_parse_firstline_(struct evhttp_request *, struct evbuffer*);
+EVENT2_EXPORT_SYMBOL
+enum message_read_status evhttp_parse_headers_(struct evhttp_request *, struct evbuffer*);
+
+void evhttp_start_read_(struct evhttp_connection *);
+void evhttp_start_write_(struct evhttp_connection *);
+
+/* response sending HTML the data in the buffer */
+void evhttp_response_code_(struct evhttp_request *, int, const char *);
+void evhttp_send_page_(struct evhttp_request *, struct evbuffer *);
+
+EVENT2_EXPORT_SYMBOL
+int evhttp_decode_uri_internal(const char *uri, size_t length,
+ char *ret, int decode_plus);
+
+#endif /* HTTP_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/http.c b/ipc/chromium/src/third_party/libevent/http.c
new file mode 100644
index 0000000000..04f089bc01
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/http.c
@@ -0,0 +1,5128 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+
+#ifdef HAVE_SYS_IOCCOM_H
+#include <sys/ioccom.h>
+#endif
+#ifdef EVENT__HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/stat.h>
+#else /* _WIN32 */
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif /* _WIN32 */
+
+#ifdef EVENT__HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+#ifdef EVENT__HAVE_AFUNIX_H
+#include <afunix.h>
+#endif
+
+#include <sys/queue.h>
+
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+#ifdef EVENT__HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+#ifdef EVENT__HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef _WIN32
+#include <syslog.h>
+#endif /* !_WIN32 */
+#include <signal.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#undef timeout_pending
+#undef timeout_initialized
+
+#include "strlcpy-internal.h"
+#include "event2/http.h"
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/http_struct.h"
+#include "event2/http_compat.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "log-internal.h"
+#include "util-internal.h"
+#include "http-internal.h"
+#include "mm-internal.h"
+#include "bufferevent-internal.h"
+
+#ifndef EVENT__HAVE_GETNAMEINFO
+#define NI_MAXSERV 32
+#define NI_MAXHOST 1025
+
+#ifndef NI_NUMERICHOST
+#define NI_NUMERICHOST 1
+#endif
+
+#ifndef NI_NUMERICSERV
+#define NI_NUMERICSERV 2
+#endif
+
+static int
+fake_getnameinfo(const struct sockaddr *sa, size_t salen, char *host,
+ size_t hostlen, char *serv, size_t servlen, int flags)
+{
+ struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+
+ if (serv != NULL) {
+ char tmpserv[16];
+ evutil_snprintf(tmpserv, sizeof(tmpserv),
+ "%d", ntohs(sin->sin_port));
+ if (strlcpy(serv, tmpserv, servlen) >= servlen)
+ return (-1);
+ }
+
+ if (host != NULL) {
+ if (flags & NI_NUMERICHOST) {
+ if (strlcpy(host, inet_ntoa(sin->sin_addr),
+ hostlen) >= hostlen)
+ return (-1);
+ else
+ return (0);
+ } else {
+ struct hostent *hp;
+ hp = gethostbyaddr((char *)&sin->sin_addr,
+ sizeof(struct in_addr), AF_INET);
+ if (hp == NULL)
+ return (-2);
+
+ if (strlcpy(host, hp->h_name, hostlen) >= hostlen)
+ return (-1);
+ else
+ return (0);
+ }
+ }
+ return (0);
+}
+
+#endif
+
+#define REQ_VERSION_BEFORE(req, major_v, minor_v) \
+ ((req)->major < (major_v) || \
+ ((req)->major == (major_v) && (req)->minor < (minor_v)))
+
+#define REQ_VERSION_ATLEAST(req, major_v, minor_v) \
+ ((req)->major > (major_v) || \
+ ((req)->major == (major_v) && (req)->minor >= (minor_v)))
+
+#ifndef MIN
+#define MIN(a,b) (((a)<(b))?(a):(b))
+#endif
+
+extern int debug;
+
+static evutil_socket_t create_bind_socket_nonblock(struct evutil_addrinfo *, int reuse);
+static evutil_socket_t bind_socket(const char *, ev_uint16_t, int reuse);
+static void name_from_addr(struct sockaddr *, ev_socklen_t, char **, char **);
+static struct evhttp_uri *evhttp_uri_parse_authority(char *source_uri);
+static int evhttp_associate_new_request_with_connection(
+ struct evhttp_connection *evcon);
+static void evhttp_connection_start_detectclose(
+ struct evhttp_connection *evcon);
+static void evhttp_connection_stop_detectclose(
+ struct evhttp_connection *evcon);
+static void evhttp_request_dispatch(struct evhttp_connection* evcon);
+static void evhttp_read_firstline(struct evhttp_connection *evcon,
+ struct evhttp_request *req);
+static void evhttp_read_header(struct evhttp_connection *evcon,
+ struct evhttp_request *req);
+static int evhttp_add_header_internal(struct evkeyvalq *headers,
+ const char *key, const char *value);
+static const char *evhttp_response_phrase_internal(int code);
+static void evhttp_get_request(struct evhttp *, evutil_socket_t, struct sockaddr *, ev_socklen_t);
+static void evhttp_write_buffer(struct evhttp_connection *,
+ void (*)(struct evhttp_connection *, void *), void *);
+static void evhttp_make_header(struct evhttp_connection *, struct evhttp_request *);
+
+/* callbacks for bufferevent */
+static void evhttp_read_cb(struct bufferevent *, void *);
+static void evhttp_write_cb(struct bufferevent *, void *);
+static void evhttp_error_cb(struct bufferevent *bufev, short what, void *arg);
+static int evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
+ const char *hostname);
+
+#ifndef EVENT__HAVE_STRSEP
+/* strsep replacement for platforms that lack it. Only works if
+ * del is one character long. */
+static char *
+strsep(char **s, const char *del)
+{
+ char *d, *tok;
+ EVUTIL_ASSERT(strlen(del) == 1);
+ if (!s || !*s)
+ return NULL;
+ tok = *s;
+ d = strstr(tok, del);
+ if (d) {
+ *d = '\0';
+ *s = d + 1;
+ } else
+ *s = NULL;
+ return tok;
+}
+#endif
+
+static size_t
+html_replace(const char ch, const char **escaped)
+{
+ switch (ch) {
+ case '<':
+ *escaped = "&lt;";
+ return 4;
+ case '>':
+ *escaped = "&gt;";
+ return 4;
+ case '"':
+ *escaped = "&quot;";
+ return 6;
+ case '\'':
+ *escaped = "&#039;";
+ return 6;
+ case '&':
+ *escaped = "&amp;";
+ return 5;
+ default:
+ break;
+ }
+
+ return 1;
+}
+
+/*
+ * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
+ * &#039; and &amp; correspondingly.
+ *
+ * The returned string needs to be freed by the caller.
+ */
+
+char *
+evhttp_htmlescape(const char *html)
+{
+ size_t i;
+ size_t new_size = 0, old_size = 0;
+ char *escaped_html, *p;
+
+ if (html == NULL)
+ return (NULL);
+
+ old_size = strlen(html);
+ for (i = 0; i < old_size; ++i) {
+ const char *replaced = NULL;
+ const size_t replace_size = html_replace(html[i], &replaced);
+ if (replace_size > EV_SIZE_MAX - new_size) {
+ event_warn("%s: html_replace overflow", __func__);
+ return (NULL);
+ }
+ new_size += replace_size;
+ }
+
+ if (new_size == EV_SIZE_MAX)
+ return (NULL);
+ p = escaped_html = mm_malloc(new_size + 1);
+ if (escaped_html == NULL) {
+ event_warn("%s: malloc(%lu)", __func__,
+ (unsigned long)(new_size + 1));
+ return (NULL);
+ }
+ for (i = 0; i < old_size; ++i) {
+ const char *replaced = &html[i];
+ const size_t len = html_replace(html[i], &replaced);
+ memcpy(p, replaced, len);
+ p += len;
+ }
+
+ *p = '\0';
+
+ return (escaped_html);
+}
+
+/** Given an evhttp_cmd_type, returns a constant string containing the
+ * equivalent HTTP command, or NULL if the evhttp_command_type is
+ * unrecognized. */
+static const char *
+evhttp_method(enum evhttp_cmd_type type)
+{
+ const char *method;
+
+ switch (type) {
+ case EVHTTP_REQ_GET:
+ method = "GET";
+ break;
+ case EVHTTP_REQ_POST:
+ method = "POST";
+ break;
+ case EVHTTP_REQ_HEAD:
+ method = "HEAD";
+ break;
+ case EVHTTP_REQ_PUT:
+ method = "PUT";
+ break;
+ case EVHTTP_REQ_DELETE:
+ method = "DELETE";
+ break;
+ case EVHTTP_REQ_OPTIONS:
+ method = "OPTIONS";
+ break;
+ case EVHTTP_REQ_TRACE:
+ method = "TRACE";
+ break;
+ case EVHTTP_REQ_CONNECT:
+ method = "CONNECT";
+ break;
+ case EVHTTP_REQ_PATCH:
+ method = "PATCH";
+ break;
+ default:
+ method = NULL;
+ break;
+ }
+
+ return (method);
+}
+
+/**
+ * Determines if a response should have a body.
+ * Follows the rules in RFC 2616 section 4.3.
+ * @return 1 if the response MUST have a body; 0 if the response MUST NOT have
+ * a body.
+ */
+static int
+evhttp_response_needs_body(struct evhttp_request *req)
+{
+ return (req->response_code != HTTP_NOCONTENT &&
+ req->response_code != HTTP_NOTMODIFIED &&
+ (req->response_code < 100 || req->response_code >= 200) &&
+ req->type != EVHTTP_REQ_CONNECT &&
+ req->type != EVHTTP_REQ_HEAD);
+}
+
+/** Helper: called after we've added some data to an evcon's bufferevent's
+ * output buffer. Sets the evconn's writing-is-done callback, and puts
+ * the bufferevent into writing mode.
+ */
+static void
+evhttp_write_buffer(struct evhttp_connection *evcon,
+ void (*cb)(struct evhttp_connection *, void *), void *arg)
+{
+ event_debug(("%s: preparing to write buffer\n", __func__));
+
+ /* Set call back */
+ evcon->cb = cb;
+ evcon->cb_arg = arg;
+
+ /* Disable the read callback: we don't actually care about data;
+ * we only care about close detection. (We don't disable reading --
+ * EV_READ, since we *do* want to learn about any close events.) */
+ bufferevent_setcb(evcon->bufev,
+ NULL, /*read*/
+ evhttp_write_cb,
+ evhttp_error_cb,
+ evcon);
+
+ bufferevent_enable(evcon->bufev, EV_READ|EV_WRITE);
+}
+
+static void
+evhttp_send_continue_done(struct evhttp_connection *evcon, void *arg)
+{
+ bufferevent_disable(evcon->bufev, EV_WRITE);
+}
+
+static void
+evhttp_send_continue(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ bufferevent_enable(evcon->bufev, EV_WRITE);
+ evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+ "HTTP/%d.%d 100 Continue\r\n\r\n",
+ req->major, req->minor);
+ evcon->cb = evhttp_send_continue_done;
+ evcon->cb_arg = NULL;
+ bufferevent_setcb(evcon->bufev,
+ evhttp_read_cb,
+ evhttp_write_cb,
+ evhttp_error_cb,
+ evcon);
+}
+
+/** Helper: returns true iff evconn is in any connected state. */
+static int
+evhttp_connected(struct evhttp_connection *evcon)
+{
+ switch (evcon->state) {
+ case EVCON_DISCONNECTED:
+ case EVCON_CONNECTING:
+ return (0);
+ case EVCON_IDLE:
+ case EVCON_READING_FIRSTLINE:
+ case EVCON_READING_HEADERS:
+ case EVCON_READING_BODY:
+ case EVCON_READING_TRAILER:
+ case EVCON_WRITING:
+ default:
+ return (1);
+ }
+}
+
+/* Create the headers needed for an outgoing HTTP request, adds them to
+ * the request's header list, and writes the request line to the
+ * connection's output buffer.
+ */
+static void
+evhttp_make_header_request(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ const char *method;
+
+ evhttp_remove_header(req->output_headers, "Proxy-Connection");
+
+ /* Generate request line */
+ if (!(method = evhttp_method(req->type))) {
+ method = "NULL";
+ }
+
+ evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+ "%s %s HTTP/%d.%d\r\n",
+ method, req->uri, req->major, req->minor);
+
+ /* Add the content length on a post or put request if missing */
+ if ((req->type == EVHTTP_REQ_POST || req->type == EVHTTP_REQ_PUT) &&
+ evhttp_find_header(req->output_headers, "Content-Length") == NULL){
+ char size[22];
+ evutil_snprintf(size, sizeof(size), EV_SIZE_FMT,
+ EV_SIZE_ARG(evbuffer_get_length(req->output_buffer)));
+ evhttp_add_header(req->output_headers, "Content-Length", size);
+ }
+}
+
+/** Return true if the list of headers in 'headers', intepreted with respect
+ * to flags, means that we should send a "connection: close" when the request
+ * is done. */
+static int
+evhttp_is_connection_close(int flags, struct evkeyvalq* headers)
+{
+ if (flags & EVHTTP_PROXY_REQUEST) {
+ /* proxy connection */
+ const char *connection = evhttp_find_header(headers, "Proxy-Connection");
+ return (connection == NULL || evutil_ascii_strcasecmp(connection, "keep-alive") != 0);
+ } else {
+ const char *connection = evhttp_find_header(headers, "Connection");
+ return (connection != NULL && evutil_ascii_strcasecmp(connection, "close") == 0);
+ }
+}
+static int
+evhttp_is_request_connection_close(struct evhttp_request *req)
+{
+ if (req->type == EVHTTP_REQ_CONNECT)
+ return 0;
+
+ return
+ evhttp_is_connection_close(req->flags, req->input_headers) ||
+ evhttp_is_connection_close(req->flags, req->output_headers);
+}
+
+/* Return true iff 'headers' contains 'Connection: keep-alive' */
+static int
+evhttp_is_connection_keepalive(struct evkeyvalq* headers)
+{
+ const char *connection = evhttp_find_header(headers, "Connection");
+ return (connection != NULL
+ && evutil_ascii_strncasecmp(connection, "keep-alive", 10) == 0);
+}
+
+/* Add a correct "Date" header to headers, unless it already has one. */
+static void
+evhttp_maybe_add_date_header(struct evkeyvalq *headers)
+{
+ if (evhttp_find_header(headers, "Date") == NULL) {
+ char date[50];
+ if (sizeof(date) - evutil_date_rfc1123(date, sizeof(date), NULL) > 0) {
+ evhttp_add_header(headers, "Date", date);
+ }
+ }
+}
+
+/* Add a "Content-Length" header with value 'content_length' to headers,
+ * unless it already has a content-length or transfer-encoding header. */
+static void
+evhttp_maybe_add_content_length_header(struct evkeyvalq *headers,
+ size_t content_length)
+{
+ if (evhttp_find_header(headers, "Transfer-Encoding") == NULL &&
+ evhttp_find_header(headers, "Content-Length") == NULL) {
+ char len[22];
+ evutil_snprintf(len, sizeof(len), EV_SIZE_FMT,
+ EV_SIZE_ARG(content_length));
+ evhttp_add_header(headers, "Content-Length", len);
+ }
+}
+
+/*
+ * Create the headers needed for an HTTP reply in req->output_headers,
+ * and write the first HTTP response for req line to evcon.
+ */
+static void
+evhttp_make_header_response(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ int is_keepalive = evhttp_is_connection_keepalive(req->input_headers);
+ evbuffer_add_printf(bufferevent_get_output(evcon->bufev),
+ "HTTP/%d.%d %d %s\r\n",
+ req->major, req->minor, req->response_code,
+ req->response_code_line);
+
+ if (req->major == 1) {
+ if (req->minor >= 1)
+ evhttp_maybe_add_date_header(req->output_headers);
+
+ /*
+ * if the protocol is 1.0; and the connection was keep-alive
+ * we need to add a keep-alive header, too.
+ */
+ if (req->minor == 0 && is_keepalive)
+ evhttp_add_header(req->output_headers,
+ "Connection", "keep-alive");
+
+ if ((req->minor >= 1 || is_keepalive) &&
+ evhttp_response_needs_body(req)) {
+ /*
+ * we need to add the content length if the
+ * user did not give it, this is required for
+ * persistent connections to work.
+ */
+ evhttp_maybe_add_content_length_header(
+ req->output_headers,
+ evbuffer_get_length(req->output_buffer));
+ }
+ }
+
+ /* Potentially add headers for unidentified content. */
+ if (evhttp_response_needs_body(req)) {
+ if (evhttp_find_header(req->output_headers,
+ "Content-Type") == NULL
+ && evcon->http_server->default_content_type) {
+ evhttp_add_header(req->output_headers,
+ "Content-Type",
+ evcon->http_server->default_content_type);
+ }
+ }
+
+ /* if the request asked for a close, we send a close, too */
+ if (evhttp_is_connection_close(req->flags, req->input_headers)) {
+ evhttp_remove_header(req->output_headers, "Connection");
+ if (!(req->flags & EVHTTP_PROXY_REQUEST))
+ evhttp_add_header(req->output_headers, "Connection", "close");
+ evhttp_remove_header(req->output_headers, "Proxy-Connection");
+ }
+}
+
+enum expect { NO, CONTINUE, OTHER };
+static enum expect evhttp_have_expect(struct evhttp_request *req, int input)
+{
+ const char *expect;
+ struct evkeyvalq *h = input ? req->input_headers : req->output_headers;
+
+ if (!(req->kind == EVHTTP_REQUEST) || !REQ_VERSION_ATLEAST(req, 1, 1))
+ return NO;
+
+ expect = evhttp_find_header(h, "Expect");
+ if (!expect)
+ return NO;
+
+ return !evutil_ascii_strcasecmp(expect, "100-continue") ? CONTINUE : OTHER;
+}
+
+
+/** Generate all headers appropriate for sending the http request in req (or
+ * the response, if we're sending a response), and write them to evcon's
+ * bufferevent. Also writes all data from req->output_buffer */
+static void
+evhttp_make_header(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+ struct evkeyval *header;
+ struct evbuffer *output = bufferevent_get_output(evcon->bufev);
+
+ /*
+ * Depending if this is a HTTP request or response, we might need to
+ * add some new headers or remove existing headers.
+ */
+ if (req->kind == EVHTTP_REQUEST) {
+ evhttp_make_header_request(evcon, req);
+ } else {
+ evhttp_make_header_response(evcon, req);
+ }
+
+ TAILQ_FOREACH(header, req->output_headers, next) {
+ evbuffer_add_printf(output, "%s: %s\r\n",
+ header->key, header->value);
+ }
+ evbuffer_add(output, "\r\n", 2);
+
+ if (evhttp_have_expect(req, 0) != CONTINUE &&
+ evbuffer_get_length(req->output_buffer)) {
+ /*
+ * For a request, we add the POST data, for a reply, this
+ * is the regular data.
+ */
+ evbuffer_add_buffer(output, req->output_buffer);
+ }
+}
+
+void
+evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
+ ev_ssize_t new_max_headers_size)
+{
+ if (new_max_headers_size<0)
+ evcon->max_headers_size = EV_SIZE_MAX;
+ else
+ evcon->max_headers_size = new_max_headers_size;
+}
+void
+evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
+ ev_ssize_t new_max_body_size)
+{
+ if (new_max_body_size<0)
+ evcon->max_body_size = EV_UINT64_MAX;
+ else
+ evcon->max_body_size = new_max_body_size;
+}
+
+static int
+evhttp_connection_incoming_fail(struct evhttp_request *req,
+ enum evhttp_request_error error)
+{
+ switch (error) {
+ case EVREQ_HTTP_DATA_TOO_LONG:
+ req->response_code = HTTP_ENTITYTOOLARGE;
+ break;
+ default:
+ req->response_code = HTTP_BADREQUEST;
+ }
+
+ switch (error) {
+ case EVREQ_HTTP_TIMEOUT:
+ case EVREQ_HTTP_EOF:
+ /*
+ * these are cases in which we probably should just
+ * close the connection and not send a reply. this
+ * case may happen when a browser keeps a persistent
+ * connection open and we timeout on the read. when
+ * the request is still being used for sending, we
+ * need to disassociated it from the connection here.
+ */
+ if (!req->userdone) {
+ /* remove it so that it will not be freed */
+ TAILQ_REMOVE(&req->evcon->requests, req, next);
+ /* indicate that this request no longer has a
+ * connection object
+ */
+ req->evcon = NULL;
+ }
+ return (-1);
+ case EVREQ_HTTP_INVALID_HEADER:
+ case EVREQ_HTTP_BUFFER_ERROR:
+ case EVREQ_HTTP_REQUEST_CANCEL:
+ case EVREQ_HTTP_DATA_TOO_LONG:
+ default: /* xxx: probably should just error on default */
+ /* the callback looks at the uri to determine errors */
+ if (req->uri) {
+ mm_free(req->uri);
+ req->uri = NULL;
+ }
+ if (req->uri_elems) {
+ evhttp_uri_free(req->uri_elems);
+ req->uri_elems = NULL;
+ }
+
+ /*
+ * the callback needs to send a reply, once the reply has
+ * been send, the connection should get freed.
+ */
+ (*req->cb)(req, req->cb_arg);
+ }
+
+ return (0);
+}
+
+/* Free connection ownership of which can be acquired by user using
+ * evhttp_request_own(). */
+static inline void
+evhttp_request_free_auto(struct evhttp_request *req)
+{
+ if (!(req->flags & EVHTTP_USER_OWNED))
+ evhttp_request_free(req);
+}
+
+static void
+evhttp_request_free_(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+ TAILQ_REMOVE(&evcon->requests, req, next);
+ evhttp_request_free_auto(req);
+}
+
+/* Called when evcon has experienced a (non-recoverable? -NM) error, as
+ * given in error. If it's an outgoing connection, reset the connection,
+ * retry any pending requests, and inform the user. If it's incoming,
+ * delegates to evhttp_connection_incoming_fail(). */
+void
+evhttp_connection_fail_(struct evhttp_connection *evcon,
+ enum evhttp_request_error error)
+{
+ const int errsave = EVUTIL_SOCKET_ERROR();
+ struct evhttp_request* req = TAILQ_FIRST(&evcon->requests);
+ void (*cb)(struct evhttp_request *, void *);
+ void *cb_arg;
+ void (*error_cb)(enum evhttp_request_error, void *);
+ void *error_cb_arg;
+ EVUTIL_ASSERT(req != NULL);
+
+ bufferevent_disable(evcon->bufev, EV_READ|EV_WRITE);
+
+ if (evcon->flags & EVHTTP_CON_INCOMING) {
+ /*
+ * for incoming requests, there are two different
+ * failure cases. it's either a network level error
+ * or an http layer error. for problems on the network
+ * layer like timeouts we just drop the connections.
+ * For HTTP problems, we might have to send back a
+ * reply before the connection can be freed.
+ */
+ if (evhttp_connection_incoming_fail(req, error) == -1)
+ evhttp_connection_free(evcon);
+ return;
+ }
+
+ error_cb = req->error_cb;
+ error_cb_arg = req->cb_arg;
+ /* when the request was canceled, the callback is not executed */
+ if (error != EVREQ_HTTP_REQUEST_CANCEL) {
+ /* save the callback for later; the cb might free our object */
+ cb = req->cb;
+ cb_arg = req->cb_arg;
+ } else {
+ cb = NULL;
+ cb_arg = NULL;
+ }
+
+ /* do not fail all requests; the next request is going to get
+ * send over a new connection. when a user cancels a request,
+ * all other pending requests should be processed as normal
+ */
+ evhttp_request_free_(evcon, req);
+
+ /* reset the connection */
+ evhttp_connection_reset_(evcon);
+
+ /* We are trying the next request that was queued on us */
+ if (TAILQ_FIRST(&evcon->requests) != NULL)
+ evhttp_connection_connect_(evcon);
+ else
+ if ((evcon->flags & EVHTTP_CON_OUTGOING) &&
+ (evcon->flags & EVHTTP_CON_AUTOFREE)) {
+ evhttp_connection_free(evcon);
+ }
+
+ /* The call to evhttp_connection_reset_ overwrote errno.
+ * Let's restore the original errno, so that the user's
+ * callback can have a better idea of what the error was.
+ */
+ EVUTIL_SET_SOCKET_ERROR(errsave);
+
+ /* inform the user */
+ if (error_cb != NULL)
+ error_cb(error, error_cb_arg);
+ if (cb != NULL)
+ (*cb)(NULL, cb_arg);
+}
+
+/* Bufferevent callback: invoked when any data has been written from an
+ * http connection's bufferevent */
+static void
+evhttp_write_cb(struct bufferevent *bufev, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+
+ /* Activate our call back */
+ if (evcon->cb != NULL)
+ (*evcon->cb)(evcon, evcon->cb_arg);
+}
+
+/**
+ * Advance the connection state.
+ * - If this is an outgoing connection, we've just processed the response;
+ * idle or close the connection.
+ * - If this is an incoming connection, we've just processed the request;
+ * respond.
+ */
+static void
+evhttp_connection_done(struct evhttp_connection *evcon)
+{
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+ int con_outgoing = evcon->flags & EVHTTP_CON_OUTGOING;
+ int free_evcon = 0;
+
+ if (con_outgoing) {
+ /* idle or close the connection */
+ int need_close = evhttp_is_request_connection_close(req);
+ TAILQ_REMOVE(&evcon->requests, req, next);
+ req->evcon = NULL;
+
+ evcon->state = EVCON_IDLE;
+
+ /* check if we got asked to close the connection */
+ if (need_close)
+ evhttp_connection_reset_(evcon);
+
+ if (TAILQ_FIRST(&evcon->requests) != NULL) {
+ /*
+ * We have more requests; reset the connection
+ * and deal with the next request.
+ */
+ if (!evhttp_connected(evcon))
+ evhttp_connection_connect_(evcon);
+ else
+ evhttp_request_dispatch(evcon);
+ } else if (!need_close) {
+ /*
+ * The connection is going to be persistent, but we
+ * need to detect if the other side closes it.
+ */
+ evhttp_connection_start_detectclose(evcon);
+ } else if ((evcon->flags & EVHTTP_CON_AUTOFREE)) {
+ /*
+ * If we have no more requests that need completion
+ * and we're not waiting for the connection to close
+ */
+ free_evcon = 1;
+ }
+ } else {
+ /*
+ * incoming connection - we need to leave the request on the
+ * connection so that we can reply to it.
+ */
+ evcon->state = EVCON_WRITING;
+ }
+
+ /* notify the user of the request */
+ (*req->cb)(req, req->cb_arg);
+
+ /* if this was an outgoing request, we own and it's done. so free it. */
+ if (con_outgoing) {
+ evhttp_request_free_auto(req);
+ }
+
+ /* If this was the last request of an outgoing connection and we're
+ * not waiting to receive a connection close event and we want to
+ * automatically free the connection. We check to ensure our request
+ * list is empty one last time just in case our callback added a
+ * new request.
+ */
+ if (free_evcon && TAILQ_FIRST(&evcon->requests) == NULL) {
+ evhttp_connection_free(evcon);
+ }
+}
+
+/*
+ * Handles reading from a chunked request.
+ * return ALL_DATA_READ:
+ * all data has been read
+ * return MORE_DATA_EXPECTED:
+ * more data is expected
+ * return DATA_CORRUPTED:
+ * data is corrupted
+ * return REQUEST_CANCELED:
+ * request was canceled by the user calling evhttp_cancel_request
+ * return DATA_TOO_LONG:
+ * ran over the maximum limit
+ */
+
+static enum message_read_status
+evhttp_handle_chunked_read(struct evhttp_request *req, struct evbuffer *buf)
+{
+ if (req == NULL || buf == NULL) {
+ return DATA_CORRUPTED;
+ }
+
+ while (1) {
+ size_t buflen;
+
+ if ((buflen = evbuffer_get_length(buf)) == 0) {
+ break;
+ }
+
+ /* evbuffer_get_length returns size_t, but len variable is ssize_t,
+ * check for overflow conditions */
+ if (buflen > EV_SSIZE_MAX) {
+ return DATA_CORRUPTED;
+ }
+
+ if (req->ntoread < 0) {
+ /* Read chunk size */
+ ev_int64_t ntoread;
+ char *p = evbuffer_readln(buf, NULL, EVBUFFER_EOL_CRLF);
+ char *endp;
+ int error;
+ if (p == NULL)
+ break;
+ /* the last chunk is on a new line? */
+ if (strlen(p) == 0) {
+ mm_free(p);
+ continue;
+ }
+ ntoread = evutil_strtoll(p, &endp, 16);
+ error = (*p == '\0' ||
+ (*endp != '\0' && *endp != ' ') ||
+ ntoread < 0);
+ mm_free(p);
+ if (error) {
+ /* could not get chunk size */
+ return (DATA_CORRUPTED);
+ }
+
+ /* ntoread is signed int64, body_size is unsigned size_t, check for under/overflow conditions */
+ if ((ev_uint64_t)ntoread > EV_SIZE_MAX - req->body_size) {
+ return DATA_CORRUPTED;
+ }
+
+ if (req->body_size + (size_t)ntoread > req->evcon->max_body_size) {
+ /* failed body length test */
+ event_debug(("Request body is too long"));
+ return (DATA_TOO_LONG);
+ }
+
+ req->body_size += (size_t)ntoread;
+ req->ntoread = ntoread;
+ if (req->ntoread == 0) {
+ /* Last chunk */
+ return (ALL_DATA_READ);
+ }
+ continue;
+ }
+
+ /* req->ntoread is signed int64, len is ssize_t, based on arch,
+ * ssize_t could only be 32b, check for these conditions */
+ if (req->ntoread > EV_SSIZE_MAX) {
+ return DATA_CORRUPTED;
+ }
+
+ /* don't have enough to complete a chunk; wait for more */
+ if (req->ntoread > 0 && buflen < (ev_uint64_t)req->ntoread)
+ return (MORE_DATA_EXPECTED);
+
+ /* Completed chunk */
+ evbuffer_remove_buffer(buf, req->input_buffer, (size_t)req->ntoread);
+ req->ntoread = -1;
+ if (req->chunk_cb != NULL) {
+ req->flags |= EVHTTP_REQ_DEFER_FREE;
+ (*req->chunk_cb)(req, req->cb_arg);
+ evbuffer_drain(req->input_buffer,
+ evbuffer_get_length(req->input_buffer));
+ req->flags &= ~EVHTTP_REQ_DEFER_FREE;
+ if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
+ return (REQUEST_CANCELED);
+ }
+ }
+ }
+
+ return (MORE_DATA_EXPECTED);
+}
+
+static void
+evhttp_read_trailer(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+ struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
+
+ switch (evhttp_parse_headers_(req, buf)) {
+ case DATA_CORRUPTED:
+ case DATA_TOO_LONG:
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
+ break;
+ case ALL_DATA_READ:
+ bufferevent_disable(evcon->bufev, EV_READ);
+ evhttp_connection_done(evcon);
+ break;
+ case MORE_DATA_EXPECTED:
+ case REQUEST_CANCELED: /* ??? */
+ default:
+ break;
+ }
+}
+
+static void
+evhttp_lingering_close(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
+
+ size_t n = evbuffer_get_length(buf);
+ if (n > (size_t) req->ntoread)
+ n = (size_t) req->ntoread;
+ req->ntoread -= n;
+ req->body_size += n;
+
+ event_debug(("Request body is too long, left " EV_I64_FMT,
+ EV_I64_ARG(req->ntoread)));
+
+ evbuffer_drain(buf, n);
+ if (!req->ntoread)
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
+}
+static void
+evhttp_lingering_fail(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ if (evcon->flags & EVHTTP_CON_LINGERING_CLOSE)
+ evhttp_lingering_close(evcon, req);
+ else
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_DATA_TOO_LONG);
+}
+
+static void
+evhttp_read_body(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+ struct evbuffer *buf = bufferevent_get_input(evcon->bufev);
+
+ if (req->chunked) {
+ switch (evhttp_handle_chunked_read(req, buf)) {
+ case ALL_DATA_READ:
+ /* finished last chunk */
+ evcon->state = EVCON_READING_TRAILER;
+ evhttp_read_trailer(evcon, req);
+ return;
+ case DATA_CORRUPTED:
+ case DATA_TOO_LONG:
+ /* corrupted data */
+ evhttp_connection_fail_(evcon,
+ EVREQ_HTTP_DATA_TOO_LONG);
+ return;
+ case REQUEST_CANCELED:
+ /* request canceled */
+ evhttp_request_free_auto(req);
+ return;
+ case MORE_DATA_EXPECTED:
+ default:
+ break;
+ }
+ } else if (req->ntoread < 0) {
+ /* Read until connection close. */
+ if ((size_t)(req->body_size + evbuffer_get_length(buf)) < req->body_size) {
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
+ return;
+ }
+
+ req->body_size += evbuffer_get_length(buf);
+ evbuffer_add_buffer(req->input_buffer, buf);
+ } else if (req->chunk_cb != NULL || evbuffer_get_length(buf) >= (size_t)req->ntoread) {
+ /* XXX: the above get_length comparison has to be fixed for overflow conditions! */
+ /* We've postponed moving the data until now, but we're
+ * about to use it. */
+ size_t n = evbuffer_get_length(buf);
+
+ if (n > (size_t) req->ntoread)
+ n = (size_t) req->ntoread;
+ req->ntoread -= n;
+ req->body_size += n;
+ evbuffer_remove_buffer(buf, req->input_buffer, n);
+ }
+
+ if (req->body_size > req->evcon->max_body_size ||
+ (!req->chunked && req->ntoread >= 0 &&
+ (size_t)req->ntoread > req->evcon->max_body_size)) {
+ /* XXX: The above casted comparison must checked for overflow */
+ /* failed body length test */
+
+ evhttp_lingering_fail(evcon, req);
+ return;
+ }
+
+ if (evbuffer_get_length(req->input_buffer) > 0 && req->chunk_cb != NULL) {
+ req->flags |= EVHTTP_REQ_DEFER_FREE;
+ (*req->chunk_cb)(req, req->cb_arg);
+ req->flags &= ~EVHTTP_REQ_DEFER_FREE;
+ evbuffer_drain(req->input_buffer,
+ evbuffer_get_length(req->input_buffer));
+ if ((req->flags & EVHTTP_REQ_NEEDS_FREE) != 0) {
+ evhttp_request_free_auto(req);
+ return;
+ }
+ }
+
+ if (!req->ntoread) {
+ bufferevent_disable(evcon->bufev, EV_READ);
+ /* Completed content length */
+ evhttp_connection_done(evcon);
+ return;
+ }
+}
+
+#define get_deferred_queue(evcon) \
+ ((evcon)->base)
+
+/*
+ * Gets called when more data becomes available
+ */
+
+static void
+evhttp_read_cb(struct bufferevent *bufev, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+ /* Cancel if it's pending. */
+ event_deferred_cb_cancel_(get_deferred_queue(evcon),
+ &evcon->read_more_deferred_cb);
+
+ switch (evcon->state) {
+ case EVCON_READING_FIRSTLINE:
+ evhttp_read_firstline(evcon, req);
+ /* note the request may have been freed in
+ * evhttp_read_body */
+ break;
+ case EVCON_READING_HEADERS:
+ evhttp_read_header(evcon, req);
+ /* note the request may have been freed in
+ * evhttp_read_body */
+ break;
+ case EVCON_READING_BODY:
+ evhttp_read_body(evcon, req);
+ /* note the request may have been freed in
+ * evhttp_read_body */
+ break;
+ case EVCON_READING_TRAILER:
+ evhttp_read_trailer(evcon, req);
+ break;
+ case EVCON_IDLE:
+ {
+#ifdef USE_DEBUG
+ struct evbuffer *input;
+ size_t total_len;
+
+ input = bufferevent_get_input(evcon->bufev);
+ total_len = evbuffer_get_length(input);
+ event_debug(("%s: read "EV_SIZE_FMT
+ " bytes in EVCON_IDLE state,"
+ " resetting connection",
+ __func__, EV_SIZE_ARG(total_len)));
+#endif
+
+ evhttp_connection_reset_(evcon);
+ }
+ break;
+ case EVCON_DISCONNECTED:
+ case EVCON_CONNECTING:
+ case EVCON_WRITING:
+ default:
+ event_errx(1, "%s: illegal connection state %d",
+ __func__, evcon->state);
+ }
+}
+
+static void
+evhttp_deferred_read_cb(struct event_callback *cb, void *data)
+{
+ struct evhttp_connection *evcon = data;
+ struct bufferevent *bev = evcon->bufev;
+ if (bev->readcb)
+ (bev->readcb)(evcon->bufev, evcon);
+}
+
+static void
+evhttp_write_connectioncb(struct evhttp_connection *evcon, void *arg)
+{
+ /* This is after writing the request to the server */
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+ struct evbuffer *output = bufferevent_get_output(evcon->bufev);
+ EVUTIL_ASSERT(req != NULL);
+
+ EVUTIL_ASSERT(evcon->state == EVCON_WRITING);
+
+ /* We need to wait until we've written all of our output data before we can
+ * continue */
+ if (evbuffer_get_length(output) > 0)
+ return;
+
+ /* We are done writing our header and are now expecting the response */
+ req->kind = EVHTTP_RESPONSE;
+
+ evhttp_start_read_(evcon);
+}
+
+/*
+ * Clean up a connection object
+ */
+
+void
+evhttp_connection_free(struct evhttp_connection *evcon)
+{
+ struct evhttp_request *req;
+ int need_close = 0;
+
+ /* notify interested parties that this connection is going down */
+ if (evcon->fd != -1) {
+ if (evhttp_connected(evcon) && evcon->closecb != NULL)
+ (*evcon->closecb)(evcon, evcon->closecb_arg);
+ }
+
+ /* remove all requests that might be queued on this
+ * connection. for server connections, this should be empty.
+ * because it gets dequeued either in evhttp_connection_done or
+ * evhttp_connection_fail_.
+ */
+ while ((req = TAILQ_FIRST(&evcon->requests)) != NULL) {
+ evhttp_request_free_(evcon, req);
+ }
+
+ if (evcon->http_server != NULL) {
+ struct evhttp *http = evcon->http_server;
+ TAILQ_REMOVE(&http->connections, evcon, next);
+ }
+
+ if (event_initialized(&evcon->retry_ev)) {
+ event_del(&evcon->retry_ev);
+ event_debug_unassign(&evcon->retry_ev);
+ }
+
+ event_deferred_cb_cancel_(get_deferred_queue(evcon),
+ &evcon->read_more_deferred_cb);
+
+ if (evcon->bufev != NULL) {
+ need_close =
+ !(bufferevent_get_options_(evcon->bufev) & BEV_OPT_CLOSE_ON_FREE);
+ if (evcon->fd == -1)
+ evcon->fd = bufferevent_getfd(evcon->bufev);
+
+ bufferevent_free(evcon->bufev);
+ }
+
+ if (evcon->fd != -1) {
+ shutdown(evcon->fd, EVUTIL_SHUT_WR);
+ if (need_close)
+ evutil_closesocket(evcon->fd);
+ }
+
+ if (evcon->bind_address != NULL)
+ mm_free(evcon->bind_address);
+
+ if (evcon->address != NULL)
+ mm_free(evcon->address);
+
+ mm_free(evcon);
+}
+
+void
+evhttp_connection_free_on_completion(struct evhttp_connection *evcon) {
+ evcon->flags |= EVHTTP_CON_AUTOFREE;
+}
+
+void
+evhttp_connection_set_local_address(struct evhttp_connection *evcon,
+ const char *address)
+{
+ EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+ if (evcon->bind_address)
+ mm_free(evcon->bind_address);
+ if ((evcon->bind_address = mm_strdup(address)) == NULL)
+ event_warn("%s: strdup", __func__);
+}
+
+void
+evhttp_connection_set_local_port(struct evhttp_connection *evcon,
+ ev_uint16_t port)
+{
+ EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+ evcon->bind_port = port;
+}
+
+static void
+evhttp_request_dispatch(struct evhttp_connection* evcon)
+{
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+ /* this should not usually happy but it's possible */
+ if (req == NULL)
+ return;
+
+ EVUTIL_ASSERT(req->kind == EVHTTP_REQUEST);
+
+ /* delete possible close detection events */
+ evhttp_connection_stop_detectclose(evcon);
+
+ /* we assume that the connection is connected already */
+ EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
+
+ evcon->state = EVCON_WRITING;
+
+ /* Create the header from the store arguments */
+ evhttp_make_header(evcon, req);
+
+ evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
+}
+
+/* Reset our connection state: disables reading/writing, closes our fd (if
+* any), clears out buffers, and puts us in state DISCONNECTED. */
+void
+evhttp_connection_reset_(struct evhttp_connection *evcon)
+{
+ struct evbuffer *tmp;
+ int err;
+
+ bufferevent_setcb(evcon->bufev, NULL, NULL, NULL, NULL);
+
+ /* XXXX This is not actually an optimal fix. Instead we ought to have
+ an API for "stop connecting", or use bufferevent_setfd to turn off
+ connecting. But for Libevent 2.0, this seems like a minimal change
+ least likely to disrupt the rest of the bufferevent and http code.
+
+ Why is this here? If the fd is set in the bufferevent, and the
+ bufferevent is connecting, then you can't actually stop the
+ bufferevent from trying to connect with bufferevent_disable(). The
+ connect will never trigger, since we close the fd, but the timeout
+ might. That caused an assertion failure in evhttp_connection_fail_.
+ */
+ bufferevent_disable_hard_(evcon->bufev, EV_READ|EV_WRITE);
+
+ if (evcon->fd == -1)
+ evcon->fd = bufferevent_getfd(evcon->bufev);
+
+ if (evcon->fd != -1) {
+ /* inform interested parties about connection close */
+ if (evhttp_connected(evcon) && evcon->closecb != NULL)
+ (*evcon->closecb)(evcon, evcon->closecb_arg);
+
+ shutdown(evcon->fd, EVUTIL_SHUT_WR);
+ evutil_closesocket(evcon->fd);
+ evcon->fd = -1;
+ }
+ err = bufferevent_setfd(evcon->bufev, -1);
+ EVUTIL_ASSERT(!err && "setfd");
+
+ /* we need to clean up any buffered data */
+ tmp = bufferevent_get_output(evcon->bufev);
+ err = evbuffer_drain(tmp, -1);
+ EVUTIL_ASSERT(!err && "drain output");
+ tmp = bufferevent_get_input(evcon->bufev);
+ err = evbuffer_drain(tmp, -1);
+ EVUTIL_ASSERT(!err && "drain input");
+
+ evcon->flags &= ~EVHTTP_CON_READING_ERROR;
+
+ evcon->state = EVCON_DISCONNECTED;
+}
+
+static void
+evhttp_connection_start_detectclose(struct evhttp_connection *evcon)
+{
+ evcon->flags |= EVHTTP_CON_CLOSEDETECT;
+ bufferevent_enable(evcon->bufev, EV_READ);
+}
+
+static void
+evhttp_connection_stop_detectclose(struct evhttp_connection *evcon)
+{
+ evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
+ bufferevent_disable(evcon->bufev, EV_READ);
+}
+
+static void
+evhttp_connection_retry(evutil_socket_t fd, short what, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+
+ evcon->state = EVCON_DISCONNECTED;
+ evhttp_connection_connect_(evcon);
+}
+
+static void
+evhttp_connection_cb_cleanup(struct evhttp_connection *evcon)
+{
+ struct evcon_requestq requests;
+
+ evhttp_connection_reset_(evcon);
+ if (evcon->retry_max < 0 || evcon->retry_cnt < evcon->retry_max) {
+ struct timeval tv_retry = evcon->initial_retry_timeout;
+ int i;
+ evtimer_assign(&evcon->retry_ev, evcon->base, evhttp_connection_retry, evcon);
+ /* XXXX handle failure from evhttp_add_event */
+ for (i=0; i < evcon->retry_cnt; ++i) {
+ tv_retry.tv_usec *= 2;
+ if (tv_retry.tv_usec > 1000000) {
+ tv_retry.tv_usec -= 1000000;
+ tv_retry.tv_sec += 1;
+ }
+ tv_retry.tv_sec *= 2;
+ if (tv_retry.tv_sec > 3600) {
+ tv_retry.tv_sec = 3600;
+ tv_retry.tv_usec = 0;
+ }
+ }
+ event_add(&evcon->retry_ev, &tv_retry);
+ evcon->retry_cnt++;
+ return;
+ }
+
+ /*
+ * User callback can do evhttp_make_request() on the same
+ * evcon so new request will be added to evcon->requests. To
+ * avoid freeing it prematurely we iterate over the copy of
+ * the queue.
+ */
+ TAILQ_INIT(&requests);
+ while (TAILQ_FIRST(&evcon->requests) != NULL) {
+ struct evhttp_request *request = TAILQ_FIRST(&evcon->requests);
+ TAILQ_REMOVE(&evcon->requests, request, next);
+ TAILQ_INSERT_TAIL(&requests, request, next);
+ }
+
+ /* for now, we just signal all requests by executing their callbacks */
+ while (TAILQ_FIRST(&requests) != NULL) {
+ struct evhttp_request *request = TAILQ_FIRST(&requests);
+ TAILQ_REMOVE(&requests, request, next);
+ request->evcon = NULL;
+
+ /* we might want to set an error here */
+ request->cb(request, request->cb_arg);
+ evhttp_request_free_auto(request);
+ }
+}
+
+static void
+evhttp_connection_read_on_write_error(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ struct evbuffer *buf;
+
+ /** Second time, we can't read anything */
+ if (evcon->flags & EVHTTP_CON_READING_ERROR) {
+ evcon->flags &= ~EVHTTP_CON_READING_ERROR;
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
+ return;
+ }
+
+ req->kind = EVHTTP_RESPONSE;
+
+ buf = bufferevent_get_output(evcon->bufev);
+ evbuffer_unfreeze(buf, 1);
+ evbuffer_drain(buf, evbuffer_get_length(buf));
+ evbuffer_freeze(buf, 1);
+
+ evhttp_start_read_(evcon);
+ evcon->flags |= EVHTTP_CON_READING_ERROR;
+}
+
+static void
+evhttp_error_cb(struct bufferevent *bufev, short what, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+
+ if (evcon->fd == -1)
+ evcon->fd = bufferevent_getfd(bufev);
+
+ switch (evcon->state) {
+ case EVCON_CONNECTING:
+ if (what & BEV_EVENT_TIMEOUT) {
+ event_debug(("%s: connection timeout for \"%s:%d\" on "
+ EV_SOCK_FMT,
+ __func__, evcon->address, evcon->port,
+ EV_SOCK_ARG(evcon->fd)));
+ evhttp_connection_cb_cleanup(evcon);
+ return;
+ }
+ break;
+
+ case EVCON_READING_BODY:
+ if (!req->chunked && req->ntoread < 0
+ && what == (BEV_EVENT_READING|BEV_EVENT_EOF)) {
+ /* EOF on read can be benign */
+ evhttp_connection_done(evcon);
+ return;
+ }
+ break;
+
+ case EVCON_DISCONNECTED:
+ case EVCON_IDLE:
+ case EVCON_READING_FIRSTLINE:
+ case EVCON_READING_HEADERS:
+ case EVCON_READING_TRAILER:
+ case EVCON_WRITING:
+ default:
+ break;
+ }
+
+ /* when we are in close detect mode, a read error means that
+ * the other side closed their connection.
+ */
+ if (evcon->flags & EVHTTP_CON_CLOSEDETECT) {
+ evcon->flags &= ~EVHTTP_CON_CLOSEDETECT;
+ EVUTIL_ASSERT(evcon->http_server == NULL);
+ /* For connections from the client, we just
+ * reset the connection so that it becomes
+ * disconnected.
+ */
+ EVUTIL_ASSERT(evcon->state == EVCON_IDLE);
+ evhttp_connection_reset_(evcon);
+
+ /*
+ * If we have no more requests that need completion
+ * and we want to auto-free the connection when all
+ * requests have been completed.
+ */
+ if (TAILQ_FIRST(&evcon->requests) == NULL
+ && (evcon->flags & EVHTTP_CON_OUTGOING)
+ && (evcon->flags & EVHTTP_CON_AUTOFREE)) {
+ evhttp_connection_free(evcon);
+ }
+ return;
+ }
+
+ if (what & BEV_EVENT_TIMEOUT) {
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_TIMEOUT);
+ } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+ if (what & BEV_EVENT_WRITING &&
+ evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR) {
+ evhttp_connection_read_on_write_error(evcon, req);
+ return;
+ }
+
+ if (what & BEV_EVENT_READING &&
+ evcon->flags & EVHTTP_CON_READ_ON_WRITE_ERROR &&
+ evbuffer_get_length(bufferevent_get_input(bufev))) {
+ event_deferred_cb_schedule_(get_deferred_queue(evcon),
+ &evcon->read_more_deferred_cb);
+ return;
+ }
+
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
+ } else if (what == BEV_EVENT_CONNECTED) {
+ } else {
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_BUFFER_ERROR);
+ }
+}
+
+/*
+ * Event callback for asynchronous connection attempt.
+ */
+static void
+evhttp_connection_cb(struct bufferevent *bufev, short what, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ int error;
+ ev_socklen_t errsz = sizeof(error);
+
+ if (evcon->fd == -1)
+ evcon->fd = bufferevent_getfd(bufev);
+
+ if (!(what & BEV_EVENT_CONNECTED)) {
+ /* some operating systems return ECONNREFUSED immediately
+ * when connecting to a local address. the cleanup is going
+ * to reschedule this function call.
+ */
+#ifndef _WIN32
+ if (errno == ECONNREFUSED)
+ goto cleanup;
+#endif
+ evhttp_error_cb(bufev, what, arg);
+ return;
+ }
+
+ if (evcon->fd == -1) {
+ event_debug(("%s: bufferevent_getfd returned -1",
+ __func__));
+ goto cleanup;
+ }
+
+ /* Check if the connection completed */
+ if (getsockopt(evcon->fd, SOL_SOCKET, SO_ERROR, (void*)&error,
+ &errsz) == -1) {
+ event_debug(("%s: getsockopt for \"%s:%d\" on "EV_SOCK_FMT,
+ __func__, evcon->address, evcon->port,
+ EV_SOCK_ARG(evcon->fd)));
+ goto cleanup;
+ }
+
+ if (error) {
+ event_debug(("%s: connect failed for \"%s:%d\" on "
+ EV_SOCK_FMT": %s",
+ __func__, evcon->address, evcon->port,
+ EV_SOCK_ARG(evcon->fd),
+ evutil_socket_error_to_string(error)));
+ goto cleanup;
+ }
+
+ /* We are connected to the server now */
+ event_debug(("%s: connected to \"%s:%d\" on "EV_SOCK_FMT"\n",
+ __func__, evcon->address, evcon->port,
+ EV_SOCK_ARG(evcon->fd)));
+
+ /* Reset the retry count as we were successful in connecting */
+ evcon->retry_cnt = 0;
+ evcon->state = EVCON_IDLE;
+
+ /* reset the bufferevent cbs */
+ bufferevent_setcb(evcon->bufev,
+ evhttp_read_cb,
+ evhttp_write_cb,
+ evhttp_error_cb,
+ evcon);
+
+ if (!evutil_timerisset(&evcon->timeout)) {
+ const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
+ const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
+ bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
+ } else {
+ bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
+ }
+
+ /* try to start requests that have queued up on this connection */
+ evhttp_request_dispatch(evcon);
+ return;
+
+ cleanup:
+ evhttp_connection_cb_cleanup(evcon);
+}
+
+/*
+ * Check if we got a valid response code.
+ */
+
+static int
+evhttp_valid_response_code(int code)
+{
+ if (code == 0)
+ return (0);
+
+ return (1);
+}
+
+static int
+evhttp_parse_http_version(const char *version, struct evhttp_request *req)
+{
+ int major, minor;
+ char ch;
+ int n = sscanf(version, "HTTP/%d.%d%c", &major, &minor, &ch);
+ if (n != 2 || major > 1) {
+ event_debug(("%s: bad version %s on message %p from %s",
+ __func__, version, req, req->remote_host));
+ return (-1);
+ }
+ req->major = major;
+ req->minor = minor;
+ return (0);
+}
+
+/* Parses the status line of a web server */
+
+static int
+evhttp_parse_response_line(struct evhttp_request *req, char *line)
+{
+ char *protocol;
+ char *number;
+ const char *readable = "";
+
+ protocol = strsep(&line, " ");
+ if (line == NULL)
+ return (-1);
+ number = strsep(&line, " ");
+ if (line != NULL)
+ readable = line;
+
+ if (evhttp_parse_http_version(protocol, req) < 0)
+ return (-1);
+
+ req->response_code = atoi(number);
+ if (!evhttp_valid_response_code(req->response_code)) {
+ event_debug(("%s: bad response code \"%s\"",
+ __func__, number));
+ return (-1);
+ }
+
+ if (req->response_code_line != NULL)
+ mm_free(req->response_code_line);
+ if ((req->response_code_line = mm_strdup(readable)) == NULL) {
+ event_warn("%s: strdup", __func__);
+ return (-1);
+ }
+
+ return (0);
+}
+
+/* Parse the first line of a HTTP request */
+
+static int
+evhttp_parse_request_line(struct evhttp_request *req, char *line, size_t len)
+{
+ char *eos = line + len;
+ char *method;
+ char *uri;
+ char *version;
+ const char *hostname;
+ const char *scheme;
+ size_t method_len;
+ enum evhttp_cmd_type type;
+
+ while (eos > line && *(eos-1) == ' ') {
+ *(eos-1) = '\0';
+ --eos;
+ --len;
+ }
+ if (len < strlen("GET / HTTP/1.0"))
+ return -1;
+
+ /* Parse the request line */
+ method = strsep(&line, " ");
+ if (!line)
+ return -1;
+ uri = line;
+ version = strrchr(uri, ' ');
+ if (!version || uri == version)
+ return -1;
+ *version = '\0';
+ version++;
+
+ method_len = (uri - method) - 1;
+ type = EVHTTP_REQ_UNKNOWN_;
+
+ /* First line */
+ switch (method_len) {
+ case 3:
+ /* The length of the method string is 3, meaning it can only be one of two methods: GET or PUT */
+
+ /* Since both GET and PUT share the same character 'T' at the end,
+ * if the string doesn't have 'T', we can immediately determine this
+ * is an invalid HTTP method */
+
+ if (method[2] != 'T') {
+ break;
+ }
+
+ switch (*method) {
+ case 'G':
+ /* This first byte is 'G', so make sure the next byte is
+ * 'E', if it isn't then this isn't a valid method */
+
+ if (method[1] == 'E') {
+ type = EVHTTP_REQ_GET;
+ }
+
+ break;
+ case 'P':
+ /* First byte is P, check second byte for 'U', if not,
+ * we know it's an invalid method */
+ if (method[1] == 'U') {
+ type = EVHTTP_REQ_PUT;
+ }
+ break;
+ default:
+ break;
+ }
+ break;
+ case 4:
+ /* The method length is 4 bytes, leaving only the methods "POST" and "HEAD" */
+ switch (*method) {
+ case 'P':
+ if (method[3] == 'T' && method[2] == 'S' && method[1] == 'O') {
+ type = EVHTTP_REQ_POST;
+ }
+ break;
+ case 'H':
+ if (method[3] == 'D' && method[2] == 'A' && method[1] == 'E') {
+ type = EVHTTP_REQ_HEAD;
+ }
+ break;
+ default:
+ break;
+ }
+ break;
+ case 5:
+ /* Method length is 5 bytes, which can only encompass PATCH and TRACE */
+ switch (*method) {
+ case 'P':
+ if (method[4] == 'H' && method[3] == 'C' && method[2] == 'T' && method[1] == 'A') {
+ type = EVHTTP_REQ_PATCH;
+ }
+ break;
+ case 'T':
+ if (method[4] == 'E' && method[3] == 'C' && method[2] == 'A' && method[1] == 'R') {
+ type = EVHTTP_REQ_TRACE;
+ }
+
+ break;
+ default:
+ break;
+ }
+ break;
+ case 6:
+ /* Method length is 6, only valid method 6 bytes in length is DELEte */
+
+ /* If the first byte isn't 'D' then it's invalid */
+ if (*method != 'D') {
+ break;
+ }
+
+ if (method[5] == 'E' && method[4] == 'T' && method[3] == 'E' && method[2] == 'L' && method[1] == 'E') {
+ type = EVHTTP_REQ_DELETE;
+ }
+
+ break;
+ case 7:
+ /* Method length is 7, only valid methods are "OPTIONS" and "CONNECT" */
+ switch (*method) {
+ case 'O':
+ if (method[6] == 'S' && method[5] == 'N' && method[4] == 'O' &&
+ method[3] == 'I' && method[2] == 'T' && method[1] == 'P') {
+ type = EVHTTP_REQ_OPTIONS;
+ }
+
+ break;
+ case 'C':
+ if (method[6] == 'T' && method[5] == 'C' && method[4] == 'E' &&
+ method[3] == 'N' && method[2] == 'N' && method[1] == 'O') {
+ type = EVHTTP_REQ_CONNECT;
+ }
+
+ break;
+ default:
+ break;
+ }
+ break;
+ } /* switch */
+
+ if ((int)type == EVHTTP_REQ_UNKNOWN_) {
+ event_debug(("%s: bad method %s on request %p from %s",
+ __func__, method, req, req->remote_host));
+ /* No error yet; we'll give a better error later when
+ * we see that req->type is unsupported. */
+ }
+
+ req->type = type;
+
+ if (evhttp_parse_http_version(version, req) < 0)
+ return -1;
+
+ if ((req->uri = mm_strdup(uri)) == NULL) {
+ event_debug(("%s: mm_strdup", __func__));
+ return -1;
+ }
+
+ if (type == EVHTTP_REQ_CONNECT) {
+ if ((req->uri_elems = evhttp_uri_parse_authority(req->uri)) == NULL) {
+ return -1;
+ }
+ } else {
+ if ((req->uri_elems = evhttp_uri_parse_with_flags(req->uri,
+ EVHTTP_URI_NONCONFORMANT)) == NULL) {
+ return -1;
+ }
+ }
+
+ /* If we have an absolute-URI, check to see if it is an http request
+ for a known vhost or server alias. If we don't know about this
+ host, we consider it a proxy request. */
+ scheme = evhttp_uri_get_scheme(req->uri_elems);
+ hostname = evhttp_uri_get_host(req->uri_elems);
+ if (scheme && (!evutil_ascii_strcasecmp(scheme, "http") ||
+ !evutil_ascii_strcasecmp(scheme, "https")) &&
+ hostname &&
+ !evhttp_find_vhost(req->evcon->http_server, NULL, hostname))
+ req->flags |= EVHTTP_PROXY_REQUEST;
+
+ return 0;
+}
+
+const char *
+evhttp_find_header(const struct evkeyvalq *headers, const char *key)
+{
+ struct evkeyval *header;
+
+ TAILQ_FOREACH(header, headers, next) {
+ if (evutil_ascii_strcasecmp(header->key, key) == 0)
+ return (header->value);
+ }
+
+ return (NULL);
+}
+
+void
+evhttp_clear_headers(struct evkeyvalq *headers)
+{
+ struct evkeyval *header;
+
+ for (header = TAILQ_FIRST(headers);
+ header != NULL;
+ header = TAILQ_FIRST(headers)) {
+ TAILQ_REMOVE(headers, header, next);
+ mm_free(header->key);
+ mm_free(header->value);
+ mm_free(header);
+ }
+}
+
+/*
+ * Returns 0, if the header was successfully removed.
+ * Returns -1, if the header could not be found.
+ */
+
+int
+evhttp_remove_header(struct evkeyvalq *headers, const char *key)
+{
+ struct evkeyval *header;
+
+ TAILQ_FOREACH(header, headers, next) {
+ if (evutil_ascii_strcasecmp(header->key, key) == 0)
+ break;
+ }
+
+ if (header == NULL)
+ return (-1);
+
+ /* Free and remove the header that we found */
+ TAILQ_REMOVE(headers, header, next);
+ mm_free(header->key);
+ mm_free(header->value);
+ mm_free(header);
+
+ return (0);
+}
+
+static int
+evhttp_header_is_valid_value(const char *value)
+{
+ const char *p = value;
+
+ while ((p = strpbrk(p, "\r\n")) != NULL) {
+ /* we really expect only one new line */
+ p += strspn(p, "\r\n");
+ /* we expect a space or tab for continuation */
+ if (*p != ' ' && *p != '\t')
+ return (0);
+ }
+ return (1);
+}
+
+int
+evhttp_add_header(struct evkeyvalq *headers,
+ const char *key, const char *value)
+{
+ event_debug(("%s: key: %s val: %s\n", __func__, key, value));
+
+ if (strchr(key, '\r') != NULL || strchr(key, '\n') != NULL) {
+ /* drop illegal headers */
+ event_debug(("%s: dropping illegal header key\n", __func__));
+ return (-1);
+ }
+
+ if (!evhttp_header_is_valid_value(value)) {
+ event_debug(("%s: dropping illegal header value\n", __func__));
+ return (-1);
+ }
+
+ return (evhttp_add_header_internal(headers, key, value));
+}
+
+static int
+evhttp_add_header_internal(struct evkeyvalq *headers,
+ const char *key, const char *value)
+{
+ struct evkeyval *header = mm_calloc(1, sizeof(struct evkeyval));
+ if (header == NULL) {
+ event_warn("%s: calloc", __func__);
+ return (-1);
+ }
+ if ((header->key = mm_strdup(key)) == NULL) {
+ mm_free(header);
+ event_warn("%s: strdup", __func__);
+ return (-1);
+ }
+ if ((header->value = mm_strdup(value)) == NULL) {
+ mm_free(header->key);
+ mm_free(header);
+ event_warn("%s: strdup", __func__);
+ return (-1);
+ }
+
+ TAILQ_INSERT_TAIL(headers, header, next);
+
+ return (0);
+}
+
+/*
+ * Parses header lines from a request or a response into the specified
+ * request object given an event buffer.
+ *
+ * Returns
+ * DATA_CORRUPTED on error
+ * MORE_DATA_EXPECTED when we need to read more headers
+ * ALL_DATA_READ when all headers have been read.
+ */
+
+enum message_read_status
+evhttp_parse_firstline_(struct evhttp_request *req, struct evbuffer *buffer)
+{
+ char *line;
+ enum message_read_status status = ALL_DATA_READ;
+
+ size_t len;
+ /* XXX try */
+ line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF);
+ if (line == NULL) {
+ if (req->evcon != NULL &&
+ evbuffer_get_length(buffer) > req->evcon->max_headers_size)
+ return (DATA_TOO_LONG);
+ else
+ return (MORE_DATA_EXPECTED);
+ }
+
+ if (req->evcon != NULL && len > req->evcon->max_headers_size) {
+ mm_free(line);
+ return (DATA_TOO_LONG);
+ }
+
+ req->headers_size = len;
+
+ switch (req->kind) {
+ case EVHTTP_REQUEST:
+ if (evhttp_parse_request_line(req, line, len) == -1)
+ status = DATA_CORRUPTED;
+ break;
+ case EVHTTP_RESPONSE:
+ if (evhttp_parse_response_line(req, line) == -1)
+ status = DATA_CORRUPTED;
+ break;
+ default:
+ status = DATA_CORRUPTED;
+ }
+
+ mm_free(line);
+ return (status);
+}
+
+static int
+evhttp_append_to_last_header(struct evkeyvalq *headers, char *line)
+{
+ struct evkeyval *header = TAILQ_LAST(headers, evkeyvalq);
+ char *newval;
+ size_t old_len, line_len;
+
+ if (header == NULL)
+ return (-1);
+
+ old_len = strlen(header->value);
+
+ /* Strip space from start and end of line. */
+ while (*line == ' ' || *line == '\t')
+ ++line;
+ evutil_rtrim_lws_(line);
+
+ line_len = strlen(line);
+
+ newval = mm_realloc(header->value, old_len + line_len + 2);
+ if (newval == NULL)
+ return (-1);
+
+ newval[old_len] = ' ';
+ memcpy(newval + old_len + 1, line, line_len + 1);
+ header->value = newval;
+
+ return (0);
+}
+
+enum message_read_status
+evhttp_parse_headers_(struct evhttp_request *req, struct evbuffer* buffer)
+{
+ enum message_read_status errcode = DATA_CORRUPTED;
+ char *line;
+ enum message_read_status status = MORE_DATA_EXPECTED;
+
+ struct evkeyvalq* headers = req->input_headers;
+ size_t len;
+ while ((line = evbuffer_readln(buffer, &len, EVBUFFER_EOL_CRLF))
+ != NULL) {
+ char *skey, *svalue;
+
+ req->headers_size += len;
+
+ if (req->evcon != NULL &&
+ req->headers_size > req->evcon->max_headers_size) {
+ errcode = DATA_TOO_LONG;
+ goto error;
+ }
+
+ if (*line == '\0') { /* Last header - Done */
+ status = ALL_DATA_READ;
+ mm_free(line);
+ break;
+ }
+
+ /* Check if this is a continuation line */
+ if (*line == ' ' || *line == '\t') {
+ if (evhttp_append_to_last_header(headers, line) == -1)
+ goto error;
+ mm_free(line);
+ continue;
+ }
+
+ /* Processing of header lines */
+ svalue = line;
+ skey = strsep(&svalue, ":");
+ if (svalue == NULL)
+ goto error;
+
+ svalue += strspn(svalue, " ");
+ evutil_rtrim_lws_(svalue);
+
+ if (evhttp_add_header(headers, skey, svalue) == -1)
+ goto error;
+
+ mm_free(line);
+ }
+
+ if (status == MORE_DATA_EXPECTED) {
+ if (req->evcon != NULL &&
+ req->headers_size + evbuffer_get_length(buffer) > req->evcon->max_headers_size)
+ return (DATA_TOO_LONG);
+ }
+
+ return (status);
+
+ error:
+ mm_free(line);
+ return (errcode);
+}
+
+static int
+evhttp_get_body_length(struct evhttp_request *req)
+{
+ struct evkeyvalq *headers = req->input_headers;
+ const char *content_length;
+ const char *connection;
+
+ content_length = evhttp_find_header(headers, "Content-Length");
+ connection = evhttp_find_header(headers, "Connection");
+
+ if (content_length == NULL && connection == NULL)
+ req->ntoread = -1;
+ else if (content_length == NULL &&
+ evutil_ascii_strcasecmp(connection, "Close") != 0) {
+ req->ntoread = 0;
+ } else if (content_length == NULL) {
+ req->ntoread = -1;
+ } else {
+ char *endp;
+ ev_int64_t ntoread = evutil_strtoll(content_length, &endp, 10);
+ if (*content_length == '\0' || *endp != '\0' || ntoread < 0) {
+ event_debug(("%s: illegal content length: %s",
+ __func__, content_length));
+ return (-1);
+ }
+ req->ntoread = ntoread;
+ }
+
+ event_debug(("%s: bytes to read: "EV_I64_FMT" (in buffer "EV_SIZE_FMT")\n",
+ __func__, EV_I64_ARG(req->ntoread),
+ EV_SIZE_ARG(evbuffer_get_length(bufferevent_get_input(req->evcon->bufev)))));
+
+ return (0);
+}
+
+static int
+evhttp_method_may_have_body(enum evhttp_cmd_type type)
+{
+ switch (type) {
+ case EVHTTP_REQ_POST:
+ case EVHTTP_REQ_PUT:
+ case EVHTTP_REQ_PATCH:
+
+ case EVHTTP_REQ_GET:
+ case EVHTTP_REQ_DELETE:
+ case EVHTTP_REQ_OPTIONS:
+ case EVHTTP_REQ_CONNECT:
+ return 1;
+
+ case EVHTTP_REQ_TRACE:
+ case EVHTTP_REQ_HEAD:
+ default:
+ return 0;
+ }
+}
+
+static void
+evhttp_get_body(struct evhttp_connection *evcon, struct evhttp_request *req)
+{
+ const char *xfer_enc;
+
+ /* If this is a request without a body, then we are done */
+ if (req->kind == EVHTTP_REQUEST &&
+ !evhttp_method_may_have_body(req->type)) {
+ evhttp_connection_done(evcon);
+ return;
+ }
+ evcon->state = EVCON_READING_BODY;
+ xfer_enc = evhttp_find_header(req->input_headers, "Transfer-Encoding");
+ if (xfer_enc != NULL && evutil_ascii_strcasecmp(xfer_enc, "chunked") == 0) {
+ req->chunked = 1;
+ req->ntoread = -1;
+ } else {
+ if (evhttp_get_body_length(req) == -1) {
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
+ return;
+ }
+ if (req->kind == EVHTTP_REQUEST && req->ntoread < 1) {
+ /* An incoming request with no content-length and no
+ * transfer-encoding has no body. */
+ evhttp_connection_done(evcon);
+ return;
+ }
+ }
+
+ /* Should we send a 100 Continue status line? */
+ switch (evhttp_have_expect(req, 1)) {
+ case CONTINUE:
+ /* XXX It would be nice to do some sanity
+ checking here. Does the resource exist?
+ Should the resource accept post requests? If
+ no, we should respond with an error. For
+ now, just optimistically tell the client to
+ send their message body. */
+ if (req->ntoread > 0) {
+ /* ntoread is ev_int64_t, max_body_size is ev_uint64_t */
+ if ((req->evcon->max_body_size <= EV_INT64_MAX) &&
+ (ev_uint64_t)req->ntoread > req->evcon->max_body_size) {
+ evhttp_lingering_fail(evcon, req);
+ return;
+ }
+ }
+ if (!evbuffer_get_length(bufferevent_get_input(evcon->bufev)))
+ evhttp_send_continue(evcon, req);
+ break;
+ case OTHER:
+ evhttp_send_error(req, HTTP_EXPECTATIONFAILED, NULL);
+ return;
+ case NO: break;
+ }
+
+ evhttp_read_body(evcon, req);
+ /* note the request may have been freed in evhttp_read_body */
+}
+
+static void
+evhttp_read_firstline(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ enum message_read_status res;
+
+ res = evhttp_parse_firstline_(req, bufferevent_get_input(evcon->bufev));
+ if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
+ /* Error while reading, terminate */
+ event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
+ __func__, EV_SOCK_ARG(evcon->fd)));
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
+ return;
+ } else if (res == MORE_DATA_EXPECTED) {
+ /* Need more header lines */
+ return;
+ }
+
+ evcon->state = EVCON_READING_HEADERS;
+ evhttp_read_header(evcon, req);
+}
+
+static void
+evhttp_read_header(struct evhttp_connection *evcon,
+ struct evhttp_request *req)
+{
+ enum message_read_status res;
+ evutil_socket_t fd = evcon->fd;
+
+ res = evhttp_parse_headers_(req, bufferevent_get_input(evcon->bufev));
+ if (res == DATA_CORRUPTED || res == DATA_TOO_LONG) {
+ /* Error while reading, terminate */
+ event_debug(("%s: bad header lines on "EV_SOCK_FMT"\n",
+ __func__, EV_SOCK_ARG(fd)));
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
+ return;
+ } else if (res == MORE_DATA_EXPECTED) {
+ /* Need more header lines */
+ return;
+ }
+
+ /* Callback can shut down connection with negative return value */
+ if (req->header_cb != NULL) {
+ if ((*req->header_cb)(req, req->cb_arg) < 0) {
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_EOF);
+ return;
+ }
+ }
+
+ /* Done reading headers, do the real work */
+ switch (req->kind) {
+ case EVHTTP_REQUEST:
+ event_debug(("%s: checking for post data on "EV_SOCK_FMT"\n",
+ __func__, EV_SOCK_ARG(fd)));
+ evhttp_get_body(evcon, req);
+ /* note the request may have been freed in evhttp_get_body */
+ break;
+
+ case EVHTTP_RESPONSE:
+ /* Start over if we got a 100 Continue response. */
+ if (req->response_code == 100) {
+ struct evbuffer *output = bufferevent_get_output(evcon->bufev);
+ evbuffer_add_buffer(output, req->output_buffer);
+ evhttp_start_write_(evcon);
+ return;
+ }
+ if (!evhttp_response_needs_body(req)) {
+ event_debug(("%s: skipping body for code %d\n",
+ __func__, req->response_code));
+ evhttp_connection_done(evcon);
+ } else {
+ event_debug(("%s: start of read body for %s on "
+ EV_SOCK_FMT"\n",
+ __func__, req->remote_host, EV_SOCK_ARG(fd)));
+ evhttp_get_body(evcon, req);
+ /* note the request may have been freed in
+ * evhttp_get_body */
+ }
+ break;
+
+ default:
+ event_warnx("%s: bad header on "EV_SOCK_FMT, __func__,
+ EV_SOCK_ARG(fd));
+ evhttp_connection_fail_(evcon, EVREQ_HTTP_INVALID_HEADER);
+ break;
+ }
+ /* request may have been freed above */
+}
+
+/*
+ * Creates a TCP connection to the specified port and executes a callback
+ * when finished. Failure or success is indicate by the passed connection
+ * object.
+ *
+ * Although this interface accepts a hostname, it is intended to take
+ * only numeric hostnames so that non-blocking DNS resolution can
+ * happen elsewhere.
+ */
+
+struct evhttp_connection *
+evhttp_connection_new(const char *address, ev_uint16_t port)
+{
+ return (evhttp_connection_base_new(NULL, NULL, address, port));
+}
+
+struct evhttp_connection *
+evhttp_connection_base_bufferevent_new(struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev,
+ const char *address, ev_uint16_t port)
+{
+ struct evhttp_connection *evcon = NULL;
+
+ event_debug(("Attempting connection to %s:%d\n", address, port));
+
+ if ((evcon = mm_calloc(1, sizeof(struct evhttp_connection))) == NULL) {
+ event_warn("%s: calloc failed", __func__);
+ goto error;
+ }
+
+ evcon->fd = -1;
+ evcon->port = port;
+
+ evcon->max_headers_size = EV_SIZE_MAX;
+ evcon->max_body_size = EV_SIZE_MAX;
+
+ evutil_timerclear(&evcon->timeout);
+ evcon->retry_cnt = evcon->retry_max = 0;
+
+ if ((evcon->address = mm_strdup(address)) == NULL) {
+ event_warn("%s: strdup failed", __func__);
+ goto error;
+ }
+
+ if (bev == NULL) {
+ if (!(bev = bufferevent_socket_new(base, -1, 0))) {
+ event_warn("%s: bufferevent_socket_new failed", __func__);
+ goto error;
+ }
+ }
+
+ bufferevent_setcb(bev, evhttp_read_cb, evhttp_write_cb, evhttp_error_cb, evcon);
+ evcon->bufev = bev;
+
+ evcon->state = EVCON_DISCONNECTED;
+ TAILQ_INIT(&evcon->requests);
+
+ evcon->initial_retry_timeout.tv_sec = 2;
+ evcon->initial_retry_timeout.tv_usec = 0;
+
+ if (base != NULL) {
+ evcon->base = base;
+ if (bufferevent_get_base(bev) != base)
+ bufferevent_base_set(base, evcon->bufev);
+ }
+
+ event_deferred_cb_init_(
+ &evcon->read_more_deferred_cb,
+ bufferevent_get_priority(bev),
+ evhttp_deferred_read_cb, evcon);
+
+ evcon->dns_base = dnsbase;
+ evcon->ai_family = AF_UNSPEC;
+
+ return (evcon);
+
+ error:
+ if (evcon != NULL)
+ evhttp_connection_free(evcon);
+ return (NULL);
+}
+
+struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon)
+{
+ return evcon->bufev;
+}
+
+struct evhttp *
+evhttp_connection_get_server(struct evhttp_connection *evcon)
+{
+ return evcon->http_server;
+}
+
+struct evhttp_connection *
+evhttp_connection_base_new(struct event_base *base, struct evdns_base *dnsbase,
+ const char *address, ev_uint16_t port)
+{
+ return evhttp_connection_base_bufferevent_new(base, dnsbase, NULL, address, port);
+}
+
+void evhttp_connection_set_family(struct evhttp_connection *evcon,
+ int family)
+{
+ evcon->ai_family = family;
+}
+
+int evhttp_connection_set_flags(struct evhttp_connection *evcon,
+ int flags)
+{
+ int avail_flags = 0;
+ avail_flags |= EVHTTP_CON_REUSE_CONNECTED_ADDR;
+ avail_flags |= EVHTTP_CON_READ_ON_WRITE_ERROR;
+
+ if (flags & ~avail_flags || flags > EVHTTP_CON_PUBLIC_FLAGS_END)
+ return 1;
+ evcon->flags &= ~avail_flags;
+
+ evcon->flags |= flags;
+
+ return 0;
+}
+
+void
+evhttp_connection_set_base(struct evhttp_connection *evcon,
+ struct event_base *base)
+{
+ EVUTIL_ASSERT(evcon->base == NULL);
+ EVUTIL_ASSERT(evcon->state == EVCON_DISCONNECTED);
+ evcon->base = base;
+ bufferevent_base_set(base, evcon->bufev);
+}
+
+void
+evhttp_connection_set_timeout(struct evhttp_connection *evcon,
+ int timeout_in_secs)
+{
+ if (timeout_in_secs == -1)
+ evhttp_connection_set_timeout_tv(evcon, NULL);
+ else {
+ struct timeval tv;
+ tv.tv_sec = timeout_in_secs;
+ tv.tv_usec = 0;
+ evhttp_connection_set_timeout_tv(evcon, &tv);
+ }
+}
+
+void
+evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
+ const struct timeval* tv)
+{
+ if (tv) {
+ evcon->timeout = *tv;
+ bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
+ } else {
+ const struct timeval read_tv = { HTTP_READ_TIMEOUT, 0 };
+ const struct timeval write_tv = { HTTP_WRITE_TIMEOUT, 0 };
+ evutil_timerclear(&evcon->timeout);
+ bufferevent_set_timeouts(evcon->bufev, &read_tv, &write_tv);
+ }
+}
+
+void
+evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
+ const struct timeval *tv)
+{
+ if (tv) {
+ evcon->initial_retry_timeout = *tv;
+ } else {
+ evutil_timerclear(&evcon->initial_retry_timeout);
+ evcon->initial_retry_timeout.tv_sec = 2;
+ }
+}
+
+void
+evhttp_connection_set_retries(struct evhttp_connection *evcon,
+ int retry_max)
+{
+ evcon->retry_max = retry_max;
+}
+
+void
+evhttp_connection_set_closecb(struct evhttp_connection *evcon,
+ void (*cb)(struct evhttp_connection *, void *), void *cbarg)
+{
+ evcon->closecb = cb;
+ evcon->closecb_arg = cbarg;
+}
+
+void
+evhttp_connection_get_peer(struct evhttp_connection *evcon,
+ char **address, ev_uint16_t *port)
+{
+ *address = evcon->address;
+ *port = evcon->port;
+}
+
+const struct sockaddr*
+evhttp_connection_get_addr(struct evhttp_connection *evcon)
+{
+ return bufferevent_socket_get_conn_address_(evcon->bufev);
+}
+
+int
+evhttp_connection_connect_(struct evhttp_connection *evcon)
+{
+ int old_state = evcon->state;
+ const char *address = evcon->address;
+ const struct sockaddr *sa = evhttp_connection_get_addr(evcon);
+ int ret;
+
+ if (evcon->state == EVCON_CONNECTING)
+ return (0);
+
+ evhttp_connection_reset_(evcon);
+
+ EVUTIL_ASSERT(!(evcon->flags & EVHTTP_CON_INCOMING));
+ evcon->flags |= EVHTTP_CON_OUTGOING;
+
+ if (evcon->bind_address || evcon->bind_port) {
+ evcon->fd = bind_socket(
+ evcon->bind_address, evcon->bind_port, 0 /*reuse*/);
+ if (evcon->fd == -1) {
+ event_debug(("%s: failed to bind to \"%s\"",
+ __func__, evcon->bind_address));
+ return (-1);
+ }
+
+ if (bufferevent_setfd(evcon->bufev, evcon->fd))
+ return (-1);
+ } else {
+ if (bufferevent_setfd(evcon->bufev, -1))
+ return (-1);
+ }
+
+ /* Set up a callback for successful connection setup */
+ bufferevent_setcb(evcon->bufev,
+ NULL /* evhttp_read_cb */,
+ NULL /* evhttp_write_cb */,
+ evhttp_connection_cb,
+ evcon);
+ if (!evutil_timerisset(&evcon->timeout)) {
+ const struct timeval conn_tv = { HTTP_CONNECT_TIMEOUT, 0 };
+ bufferevent_set_timeouts(evcon->bufev, &conn_tv, &conn_tv);
+ } else {
+ bufferevent_set_timeouts(evcon->bufev, &evcon->timeout, &evcon->timeout);
+ }
+ /* make sure that we get a write callback */
+ if (bufferevent_enable(evcon->bufev, EV_WRITE))
+ return (-1);
+
+ evcon->state = EVCON_CONNECTING;
+
+ if (evcon->flags & EVHTTP_CON_REUSE_CONNECTED_ADDR &&
+ sa &&
+ (sa->sa_family == AF_INET || sa->sa_family == AF_INET6)) {
+ int socklen = sizeof(struct sockaddr_in);
+ if (sa->sa_family == AF_INET6) {
+ socklen = sizeof(struct sockaddr_in6);
+ }
+ ret = bufferevent_socket_connect(evcon->bufev, sa, socklen);
+ } else {
+ ret = bufferevent_socket_connect_hostname(evcon->bufev,
+ evcon->dns_base, evcon->ai_family, address, evcon->port);
+ }
+
+ if (ret < 0) {
+ evcon->state = old_state;
+ event_sock_warn(evcon->fd, "%s: connection to \"%s\" failed",
+ __func__, evcon->address);
+ /* some operating systems return ECONNREFUSED immediately
+ * when connecting to a local address. the cleanup is going
+ * to reschedule this function call.
+ */
+ evhttp_connection_cb_cleanup(evcon);
+ return (0);
+ }
+
+ return (0);
+}
+
+/*
+ * Starts an HTTP request on the provided evhttp_connection object.
+ * If the connection object is not connected to the web server already,
+ * this will start the connection.
+ */
+
+int
+evhttp_make_request(struct evhttp_connection *evcon,
+ struct evhttp_request *req,
+ enum evhttp_cmd_type type, const char *uri)
+{
+ /* We are making a request */
+ req->kind = EVHTTP_REQUEST;
+ req->type = type;
+ if (req->uri != NULL)
+ mm_free(req->uri);
+ if ((req->uri = mm_strdup(uri)) == NULL) {
+ event_warn("%s: strdup", __func__);
+ evhttp_request_free_auto(req);
+ return (-1);
+ }
+
+ /* Set the protocol version if it is not supplied */
+ if (!req->major && !req->minor) {
+ req->major = 1;
+ req->minor = 1;
+ }
+
+ EVUTIL_ASSERT(req->evcon == NULL);
+ req->evcon = evcon;
+ EVUTIL_ASSERT(!(req->flags & EVHTTP_REQ_OWN_CONNECTION));
+
+ TAILQ_INSERT_TAIL(&evcon->requests, req, next);
+
+ /* We do not want to conflict with retry_ev */
+ if (evcon->retry_cnt)
+ return (0);
+
+ /* If the connection object is not connected; make it so */
+ if (!evhttp_connected(evcon)) {
+ int res = evhttp_connection_connect_(evcon);
+ /* evhttp_connection_fail_(), which is called through
+ * evhttp_connection_connect_(), assumes that req lies in
+ * evcon->requests. Thus, enqueue the request in advance and
+ * remove it in the error case. */
+ if (res != 0)
+ TAILQ_REMOVE(&evcon->requests, req, next);
+
+ return (res);
+ }
+
+ /*
+ * If it's connected already and we are the first in the queue,
+ * then we can dispatch this request immediately. Otherwise, it
+ * will be dispatched once the pending requests are completed.
+ */
+ if (TAILQ_FIRST(&evcon->requests) == req)
+ evhttp_request_dispatch(evcon);
+
+ return (0);
+}
+
+void
+evhttp_cancel_request(struct evhttp_request *req)
+{
+ struct evhttp_connection *evcon = req->evcon;
+ if (evcon != NULL) {
+ /* We need to remove it from the connection */
+ if (TAILQ_FIRST(&evcon->requests) == req) {
+ /* it's currently being worked on, so reset
+ * the connection.
+ */
+ evhttp_connection_fail_(evcon,
+ EVREQ_HTTP_REQUEST_CANCEL);
+
+ /* connection fail freed the request */
+ return;
+ } else {
+ /* otherwise, we can just remove it from the
+ * queue
+ */
+ TAILQ_REMOVE(&evcon->requests, req, next);
+ }
+ }
+
+ evhttp_request_free_auto(req);
+}
+
+/*
+ * Reads data from file descriptor into request structure
+ * Request structure needs to be set up correctly.
+ */
+
+void
+evhttp_start_read_(struct evhttp_connection *evcon)
+{
+ bufferevent_disable(evcon->bufev, EV_WRITE);
+ bufferevent_enable(evcon->bufev, EV_READ);
+
+ evcon->state = EVCON_READING_FIRSTLINE;
+ /* Reset the bufferevent callbacks */
+ bufferevent_setcb(evcon->bufev,
+ evhttp_read_cb,
+ evhttp_write_cb,
+ evhttp_error_cb,
+ evcon);
+
+ /* If there's still data pending, process it next time through the
+ * loop. Don't do it now; that could get recusive. */
+ if (evbuffer_get_length(bufferevent_get_input(evcon->bufev))) {
+ event_deferred_cb_schedule_(get_deferred_queue(evcon),
+ &evcon->read_more_deferred_cb);
+ }
+}
+
+void
+evhttp_start_write_(struct evhttp_connection *evcon)
+{
+ bufferevent_disable(evcon->bufev, EV_WRITE);
+ bufferevent_enable(evcon->bufev, EV_READ);
+
+ evcon->state = EVCON_WRITING;
+ evhttp_write_buffer(evcon, evhttp_write_connectioncb, NULL);
+}
+
+static void
+evhttp_send_done(struct evhttp_connection *evcon, void *arg)
+{
+ int need_close;
+ struct evhttp_request *req = TAILQ_FIRST(&evcon->requests);
+ TAILQ_REMOVE(&evcon->requests, req, next);
+
+ if (req->on_complete_cb != NULL) {
+ req->on_complete_cb(req, req->on_complete_cb_arg);
+ }
+
+ need_close =
+ (REQ_VERSION_BEFORE(req, 1, 1) &&
+ !evhttp_is_connection_keepalive(req->input_headers)) ||
+ evhttp_is_request_connection_close(req);
+
+ EVUTIL_ASSERT(req->flags & EVHTTP_REQ_OWN_CONNECTION);
+ evhttp_request_free(req);
+
+ if (need_close) {
+ evhttp_connection_free(evcon);
+ return;
+ }
+
+ /* we have a persistent connection; try to accept another request. */
+ if (evhttp_associate_new_request_with_connection(evcon) == -1) {
+ evhttp_connection_free(evcon);
+ }
+}
+
+/*
+ * Returns an error page.
+ */
+
+void
+evhttp_send_error(struct evhttp_request *req, int error, const char *reason)
+{
+
+#define ERR_FORMAT "<HTML><HEAD>\n" \
+ "<TITLE>%d %s</TITLE>\n" \
+ "</HEAD><BODY>\n" \
+ "<H1>%s</H1>\n" \
+ "</BODY></HTML>\n"
+
+ struct evbuffer *buf = evbuffer_new();
+ if (buf == NULL) {
+ /* if we cannot allocate memory; we just drop the connection */
+ evhttp_connection_free(req->evcon);
+ return;
+ }
+ if (reason == NULL) {
+ reason = evhttp_response_phrase_internal(error);
+ }
+
+ evhttp_response_code_(req, error, reason);
+
+ evbuffer_add_printf(buf, ERR_FORMAT, error, reason, reason);
+
+ evhttp_send_page_(req, buf);
+
+ evbuffer_free(buf);
+#undef ERR_FORMAT
+}
+
+/* Requires that headers and response code are already set up */
+
+static inline void
+evhttp_send(struct evhttp_request *req, struct evbuffer *databuf)
+{
+ struct evhttp_connection *evcon = req->evcon;
+
+ if (evcon == NULL) {
+ evhttp_request_free(req);
+ return;
+ }
+
+ EVUTIL_ASSERT(TAILQ_FIRST(&evcon->requests) == req);
+
+ /* we expect no more calls form the user on this request */
+ req->userdone = 1;
+
+ /* xxx: not sure if we really should expose the data buffer this way */
+ if (databuf != NULL)
+ evbuffer_add_buffer(req->output_buffer, databuf);
+
+ /* Adds headers to the response */
+ evhttp_make_header(evcon, req);
+
+ evhttp_write_buffer(evcon, evhttp_send_done, NULL);
+}
+
+void
+evhttp_send_reply(struct evhttp_request *req, int code, const char *reason,
+ struct evbuffer *databuf)
+{
+ evhttp_response_code_(req, code, reason);
+
+ evhttp_send(req, databuf);
+}
+
+void
+evhttp_send_reply_start(struct evhttp_request *req, int code,
+ const char *reason)
+{
+ evhttp_response_code_(req, code, reason);
+
+ if (req->evcon == NULL)
+ return;
+
+ if (evhttp_find_header(req->output_headers, "Content-Length") == NULL &&
+ REQ_VERSION_ATLEAST(req, 1, 1) &&
+ evhttp_response_needs_body(req)) {
+ /*
+ * prefer HTTP/1.1 chunked encoding to closing the connection;
+ * note RFC 2616 section 4.4 forbids it with Content-Length:
+ * and it's not necessary then anyway.
+ */
+ evhttp_add_header(req->output_headers, "Transfer-Encoding",
+ "chunked");
+ req->chunked = 1;
+ } else {
+ req->chunked = 0;
+ }
+ evhttp_make_header(req->evcon, req);
+ evhttp_write_buffer(req->evcon, NULL, NULL);
+}
+
+void
+evhttp_send_reply_chunk_with_cb(struct evhttp_request *req, struct evbuffer *databuf,
+ void (*cb)(struct evhttp_connection *, void *), void *arg)
+{
+ struct evhttp_connection *evcon = req->evcon;
+ struct evbuffer *output;
+
+ if (evcon == NULL)
+ return;
+
+ output = bufferevent_get_output(evcon->bufev);
+
+ if (evbuffer_get_length(databuf) == 0)
+ return;
+ if (!evhttp_response_needs_body(req))
+ return;
+ if (req->chunked) {
+ evbuffer_add_printf(output, "%x\r\n",
+ (unsigned)evbuffer_get_length(databuf));
+ }
+ evbuffer_add_buffer(output, databuf);
+ if (req->chunked) {
+ evbuffer_add(output, "\r\n", 2);
+ }
+ evhttp_write_buffer(evcon, cb, arg);
+}
+
+void
+evhttp_send_reply_chunk(struct evhttp_request *req, struct evbuffer *databuf)
+{
+ evhttp_send_reply_chunk_with_cb(req, databuf, NULL, NULL);
+}
+void
+evhttp_send_reply_end(struct evhttp_request *req)
+{
+ struct evhttp_connection *evcon = req->evcon;
+ struct evbuffer *output;
+
+ if (evcon == NULL) {
+ evhttp_request_free(req);
+ return;
+ }
+
+ output = bufferevent_get_output(evcon->bufev);
+
+ /* we expect no more calls form the user on this request */
+ req->userdone = 1;
+
+ if (req->chunked) {
+ evbuffer_add(output, "0\r\n\r\n", 5);
+ evhttp_write_buffer(req->evcon, evhttp_send_done, NULL);
+ req->chunked = 0;
+ } else if (evbuffer_get_length(output) == 0) {
+ /* let the connection know that we are done with the request */
+ evhttp_send_done(evcon, NULL);
+ } else {
+ /* make the callback execute after all data has been written */
+ evcon->cb = evhttp_send_done;
+ evcon->cb_arg = NULL;
+ }
+}
+
+static const char *informational_phrases[] = {
+ /* 100 */ "Continue",
+ /* 101 */ "Switching Protocols"
+};
+
+static const char *success_phrases[] = {
+ /* 200 */ "OK",
+ /* 201 */ "Created",
+ /* 202 */ "Accepted",
+ /* 203 */ "Non-Authoritative Information",
+ /* 204 */ "No Content",
+ /* 205 */ "Reset Content",
+ /* 206 */ "Partial Content"
+};
+
+static const char *redirection_phrases[] = {
+ /* 300 */ "Multiple Choices",
+ /* 301 */ "Moved Permanently",
+ /* 302 */ "Found",
+ /* 303 */ "See Other",
+ /* 304 */ "Not Modified",
+ /* 305 */ "Use Proxy",
+ /* 307 */ "Temporary Redirect"
+};
+
+static const char *client_error_phrases[] = {
+ /* 400 */ "Bad Request",
+ /* 401 */ "Unauthorized",
+ /* 402 */ "Payment Required",
+ /* 403 */ "Forbidden",
+ /* 404 */ "Not Found",
+ /* 405 */ "Method Not Allowed",
+ /* 406 */ "Not Acceptable",
+ /* 407 */ "Proxy Authentication Required",
+ /* 408 */ "Request Time-out",
+ /* 409 */ "Conflict",
+ /* 410 */ "Gone",
+ /* 411 */ "Length Required",
+ /* 412 */ "Precondition Failed",
+ /* 413 */ "Request Entity Too Large",
+ /* 414 */ "Request-URI Too Large",
+ /* 415 */ "Unsupported Media Type",
+ /* 416 */ "Requested range not satisfiable",
+ /* 417 */ "Expectation Failed"
+};
+
+static const char *server_error_phrases[] = {
+ /* 500 */ "Internal Server Error",
+ /* 501 */ "Not Implemented",
+ /* 502 */ "Bad Gateway",
+ /* 503 */ "Service Unavailable",
+ /* 504 */ "Gateway Time-out",
+ /* 505 */ "HTTP Version not supported"
+};
+
+struct response_class {
+ const char *name;
+ size_t num_responses;
+ const char **responses;
+};
+
+#ifndef MEMBERSOF
+#define MEMBERSOF(x) (sizeof(x)/sizeof(x[0]))
+#endif
+
+static const struct response_class response_classes[] = {
+ /* 1xx */ { "Informational", MEMBERSOF(informational_phrases), informational_phrases },
+ /* 2xx */ { "Success", MEMBERSOF(success_phrases), success_phrases },
+ /* 3xx */ { "Redirection", MEMBERSOF(redirection_phrases), redirection_phrases },
+ /* 4xx */ { "Client Error", MEMBERSOF(client_error_phrases), client_error_phrases },
+ /* 5xx */ { "Server Error", MEMBERSOF(server_error_phrases), server_error_phrases }
+};
+
+static const char *
+evhttp_response_phrase_internal(int code)
+{
+ int klass = code / 100 - 1;
+ int subcode = code % 100;
+
+ /* Unknown class - can't do any better here */
+ if (klass < 0 || klass >= (int) MEMBERSOF(response_classes))
+ return "Unknown Status Class";
+
+ /* Unknown sub-code, return class name at least */
+ if (subcode >= (int) response_classes[klass].num_responses)
+ return response_classes[klass].name;
+
+ return response_classes[klass].responses[subcode];
+}
+
+void
+evhttp_response_code_(struct evhttp_request *req, int code, const char *reason)
+{
+ req->kind = EVHTTP_RESPONSE;
+ req->response_code = code;
+ if (req->response_code_line != NULL)
+ mm_free(req->response_code_line);
+ if (reason == NULL)
+ reason = evhttp_response_phrase_internal(code);
+ req->response_code_line = mm_strdup(reason);
+ if (req->response_code_line == NULL) {
+ event_warn("%s: strdup", __func__);
+ /* XXX what else can we do? */
+ }
+}
+
+void
+evhttp_send_page_(struct evhttp_request *req, struct evbuffer *databuf)
+{
+ if (!req->major || !req->minor) {
+ req->major = 1;
+ req->minor = 1;
+ }
+
+ if (req->kind != EVHTTP_RESPONSE)
+ evhttp_response_code_(req, 200, "OK");
+
+ evhttp_clear_headers(req->output_headers);
+ evhttp_add_header(req->output_headers, "Content-Type", "text/html");
+ evhttp_add_header(req->output_headers, "Connection", "close");
+
+ evhttp_send(req, databuf);
+}
+
+static const char uri_chars[256] = {
+ /* 0 */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ /* 64 */
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0,
+ /* 128 */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ /* 192 */
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+};
+
+#define CHAR_IS_UNRESERVED(c) \
+ (uri_chars[(unsigned char)(c)])
+
+/*
+ * Helper functions to encode/decode a string for inclusion in a URI.
+ * The returned string must be freed by the caller.
+ */
+char *
+evhttp_uriencode(const char *uri, ev_ssize_t len, int space_as_plus)
+{
+ struct evbuffer *buf = evbuffer_new();
+ const char *p, *end;
+ char *result = NULL;
+
+ if (!buf) {
+ goto out;
+ }
+
+ if (len >= 0) {
+ if (uri + len < uri) {
+ goto out;
+ }
+
+ end = uri + len;
+ } else {
+ size_t slen = strlen(uri);
+
+ if (slen >= EV_SSIZE_MAX) {
+ /* we don't want to mix signed and unsigned */
+ goto out;
+ }
+
+ if (uri + slen < uri) {
+ goto out;
+ }
+
+ end = uri + slen;
+ }
+
+ for (p = uri; p < end; p++) {
+ if (CHAR_IS_UNRESERVED(*p)) {
+ evbuffer_add(buf, p, 1);
+ } else if (*p == ' ' && space_as_plus) {
+ evbuffer_add(buf, "+", 1);
+ } else {
+ evbuffer_add_printf(buf, "%%%02X", (unsigned char)(*p));
+ }
+ }
+
+ evbuffer_add(buf, "", 1); /* NUL-terminator. */
+ result = mm_malloc(evbuffer_get_length(buf));
+
+ if (result)
+ evbuffer_remove(buf, result, evbuffer_get_length(buf));
+
+out:
+ if (buf)
+ evbuffer_free(buf);
+ return result;
+}
+
+char *
+evhttp_encode_uri(const char *str)
+{
+ return evhttp_uriencode(str, -1, 0);
+}
+
+/*
+ * @param decode_plus_ctl: if 1, we decode plus into space. If 0, we don't.
+ * If -1, when true we transform plus to space only after we've seen
+ * a ?. -1 is deprecated.
+ * @return the number of bytes written to 'ret'.
+ */
+int
+evhttp_decode_uri_internal(
+ const char *uri, size_t length, char *ret, int decode_plus_ctl)
+{
+ char c;
+ int j;
+ int decode_plus = (decode_plus_ctl == 1) ? 1: 0;
+ unsigned i;
+
+ for (i = j = 0; i < length; i++) {
+ c = uri[i];
+ if (c == '?') {
+ if (decode_plus_ctl < 0)
+ decode_plus = 1;
+ } else if (c == '+' && decode_plus) {
+ c = ' ';
+ } else if ((i + 2) < length && c == '%' &&
+ EVUTIL_ISXDIGIT_(uri[i+1]) && EVUTIL_ISXDIGIT_(uri[i+2])) {
+ char tmp[3];
+ tmp[0] = uri[i+1];
+ tmp[1] = uri[i+2];
+ tmp[2] = '\0';
+ c = (char)strtol(tmp, NULL, 16);
+ i += 2;
+ }
+ ret[j++] = c;
+ }
+ ret[j] = '\0';
+
+ return (j);
+}
+
+/* deprecated */
+char *
+evhttp_decode_uri(const char *uri)
+{
+ char *ret;
+
+ if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
+ event_warn("%s: malloc(%lu)", __func__,
+ (unsigned long)(strlen(uri) + 1));
+ return (NULL);
+ }
+
+ evhttp_decode_uri_internal(uri, strlen(uri),
+ ret, -1 /*always_decode_plus*/);
+
+ return (ret);
+}
+
+char *
+evhttp_uridecode(const char *uri, int decode_plus, size_t *size_out)
+{
+ char *ret;
+ int n;
+
+ if ((ret = mm_malloc(strlen(uri) + 1)) == NULL) {
+ event_warn("%s: malloc(%lu)", __func__,
+ (unsigned long)(strlen(uri) + 1));
+ return (NULL);
+ }
+
+ n = evhttp_decode_uri_internal(uri, strlen(uri),
+ ret, !!decode_plus/*always_decode_plus*/);
+
+ if (size_out) {
+ EVUTIL_ASSERT(n >= 0);
+ *size_out = (size_t)n;
+ }
+
+ return (ret);
+}
+
+/*
+ * Helper function to parse out arguments in a query.
+ * The arguments are separated by key and value.
+ */
+
+static int
+evhttp_parse_query_impl(const char *str, struct evkeyvalq *headers,
+ int is_whole_uri)
+{
+ char *line=NULL;
+ char *argument;
+ char *p;
+ const char *query_part;
+ int result = -1;
+ struct evhttp_uri *uri=NULL;
+
+ TAILQ_INIT(headers);
+
+ if (is_whole_uri) {
+ uri = evhttp_uri_parse(str);
+ if (!uri)
+ goto error;
+ query_part = evhttp_uri_get_query(uri);
+ } else {
+ query_part = str;
+ }
+
+ /* No arguments - we are done */
+ if (!query_part || !strlen(query_part)) {
+ result = 0;
+ goto done;
+ }
+
+ if ((line = mm_strdup(query_part)) == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto error;
+ }
+
+ p = argument = line;
+ while (p != NULL && *p != '\0') {
+ char *key, *value, *decoded_value;
+ int err;
+ argument = strsep(&p, "&");
+
+ value = argument;
+ key = strsep(&value, "=");
+ if (value == NULL || *key == '\0') {
+ goto error;
+ }
+
+ if ((decoded_value = mm_malloc(strlen(value) + 1)) == NULL) {
+ event_warn("%s: mm_malloc", __func__);
+ goto error;
+ }
+ evhttp_decode_uri_internal(value, strlen(value),
+ decoded_value, 1 /*always_decode_plus*/);
+ event_debug(("Query Param: %s -> %s\n", key, decoded_value));
+ err = evhttp_add_header_internal(headers, key, decoded_value);
+ mm_free(decoded_value);
+ if (err)
+ goto error;
+ }
+
+ result = 0;
+ goto done;
+error:
+ evhttp_clear_headers(headers);
+done:
+ if (line)
+ mm_free(line);
+ if (uri)
+ evhttp_uri_free(uri);
+ return result;
+}
+
+int
+evhttp_parse_query(const char *uri, struct evkeyvalq *headers)
+{
+ return evhttp_parse_query_impl(uri, headers, 1);
+}
+int
+evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers)
+{
+ return evhttp_parse_query_impl(uri, headers, 0);
+}
+
+static struct evhttp_cb *
+evhttp_dispatch_callback(struct httpcbq *callbacks, struct evhttp_request *req)
+{
+ struct evhttp_cb *cb;
+ size_t offset = 0;
+ char *translated;
+ const char *path;
+
+ /* Test for different URLs */
+ path = evhttp_uri_get_path(req->uri_elems);
+ offset = strlen(path);
+ if ((translated = mm_malloc(offset + 1)) == NULL)
+ return (NULL);
+ evhttp_decode_uri_internal(path, offset, translated,
+ 0 /* decode_plus */);
+
+ TAILQ_FOREACH(cb, callbacks, next) {
+ if (!strcmp(cb->what, translated)) {
+ mm_free(translated);
+ return (cb);
+ }
+ }
+
+ mm_free(translated);
+ return (NULL);
+}
+
+
+static int
+prefix_suffix_match(const char *pattern, const char *name, int ignorecase)
+{
+ char c;
+
+ while (1) {
+ switch (c = *pattern++) {
+ case '\0':
+ return *name == '\0';
+
+ case '*':
+ while (*name != '\0') {
+ if (prefix_suffix_match(pattern, name,
+ ignorecase))
+ return (1);
+ ++name;
+ }
+ return (0);
+ default:
+ if (c != *name) {
+ if (!ignorecase ||
+ EVUTIL_TOLOWER_(c) != EVUTIL_TOLOWER_(*name))
+ return (0);
+ }
+ ++name;
+ }
+ }
+ /* NOTREACHED */
+}
+
+/*
+ Search the vhost hierarchy beginning with http for a server alias
+ matching hostname. If a match is found, and outhttp is non-null,
+ outhttp is set to the matching http object and 1 is returned.
+*/
+
+static int
+evhttp_find_alias(struct evhttp *http, struct evhttp **outhttp,
+ const char *hostname)
+{
+ struct evhttp_server_alias *alias;
+ struct evhttp *vhost;
+
+ TAILQ_FOREACH(alias, &http->aliases, next) {
+ /* XXX Do we need to handle IP addresses? */
+ if (!evutil_ascii_strcasecmp(alias->alias, hostname)) {
+ if (outhttp)
+ *outhttp = http;
+ return 1;
+ }
+ }
+
+ /* XXX It might be good to avoid recursion here, but I don't
+ see a way to do that w/o a list. */
+ TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
+ if (evhttp_find_alias(vhost, outhttp, hostname))
+ return 1;
+ }
+
+ return 0;
+}
+
+/*
+ Attempts to find the best http object to handle a request for a hostname.
+ All aliases for the root http object and vhosts are searched for an exact
+ match. Then, the vhost hierarchy is traversed again for a matching
+ pattern.
+
+ If an alias or vhost is matched, 1 is returned, and outhttp, if non-null,
+ is set with the best matching http object. If there are no matches, the
+ root http object is stored in outhttp and 0 is returned.
+*/
+
+static int
+evhttp_find_vhost(struct evhttp *http, struct evhttp **outhttp,
+ const char *hostname)
+{
+ struct evhttp *vhost;
+ struct evhttp *oldhttp;
+ int match_found = 0;
+
+ if (evhttp_find_alias(http, outhttp, hostname))
+ return 1;
+
+ do {
+ oldhttp = http;
+ TAILQ_FOREACH(vhost, &http->virtualhosts, next_vhost) {
+ if (prefix_suffix_match(vhost->vhost_pattern,
+ hostname, 1 /* ignorecase */)) {
+ http = vhost;
+ match_found = 1;
+ break;
+ }
+ }
+ } while (oldhttp != http);
+
+ if (outhttp)
+ *outhttp = http;
+
+ return match_found;
+}
+
+static void
+evhttp_handle_request(struct evhttp_request *req, void *arg)
+{
+ struct evhttp *http = arg;
+ struct evhttp_cb *cb = NULL;
+ const char *hostname;
+
+ /* we have a new request on which the user needs to take action */
+ req->userdone = 0;
+
+ bufferevent_disable(req->evcon->bufev, EV_READ);
+
+ if (req->type == 0 || req->uri == NULL) {
+ evhttp_send_error(req, req->response_code, NULL);
+ return;
+ }
+
+ if ((http->allowed_methods & req->type) == 0) {
+ event_debug(("Rejecting disallowed method %x (allowed: %x)\n",
+ (unsigned)req->type, (unsigned)http->allowed_methods));
+ evhttp_send_error(req, HTTP_NOTIMPLEMENTED, NULL);
+ return;
+ }
+
+ /* handle potential virtual hosts */
+ hostname = evhttp_request_get_host(req);
+ if (hostname != NULL) {
+ evhttp_find_vhost(http, &http, hostname);
+ }
+
+ if ((cb = evhttp_dispatch_callback(&http->callbacks, req)) != NULL) {
+ (*cb->cb)(req, cb->cbarg);
+ return;
+ }
+
+ /* Generic call back */
+ if (http->gencb) {
+ (*http->gencb)(req, http->gencbarg);
+ return;
+ } else {
+ /* We need to send a 404 here */
+#define ERR_FORMAT "<html><head>" \
+ "<title>404 Not Found</title>" \
+ "</head><body>" \
+ "<h1>Not Found</h1>" \
+ "<p>The requested URL %s was not found on this server.</p>"\
+ "</body></html>\n"
+
+ char *escaped_html;
+ struct evbuffer *buf;
+
+ if ((escaped_html = evhttp_htmlescape(req->uri)) == NULL) {
+ evhttp_connection_free(req->evcon);
+ return;
+ }
+
+ if ((buf = evbuffer_new()) == NULL) {
+ mm_free(escaped_html);
+ evhttp_connection_free(req->evcon);
+ return;
+ }
+
+ evhttp_response_code_(req, HTTP_NOTFOUND, "Not Found");
+
+ evbuffer_add_printf(buf, ERR_FORMAT, escaped_html);
+
+ mm_free(escaped_html);
+
+ evhttp_send_page_(req, buf);
+
+ evbuffer_free(buf);
+#undef ERR_FORMAT
+ }
+}
+
+/* Listener callback when a connection arrives at a server. */
+static void
+accept_socket_cb(struct evconnlistener *listener, evutil_socket_t nfd, struct sockaddr *peer_sa, int peer_socklen, void *arg)
+{
+ struct evhttp *http = arg;
+
+ evhttp_get_request(http, nfd, peer_sa, peer_socklen);
+}
+
+int
+evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port)
+{
+ struct evhttp_bound_socket *bound =
+ evhttp_bind_socket_with_handle(http, address, port);
+ if (bound == NULL)
+ return (-1);
+ return (0);
+}
+
+struct evhttp_bound_socket *
+evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port)
+{
+ evutil_socket_t fd;
+ struct evhttp_bound_socket *bound;
+ int serrno;
+
+ if ((fd = bind_socket(address, port, 1 /*reuse*/)) == -1)
+ return (NULL);
+
+ if (listen(fd, 128) == -1) {
+ serrno = EVUTIL_SOCKET_ERROR();
+ event_sock_warn(fd, "%s: listen", __func__);
+ evutil_closesocket(fd);
+ EVUTIL_SET_SOCKET_ERROR(serrno);
+ return (NULL);
+ }
+
+ bound = evhttp_accept_socket_with_handle(http, fd);
+
+ if (bound != NULL) {
+ event_debug(("Bound to port %d - Awaiting connections ... ",
+ port));
+ return (bound);
+ }
+
+ return (NULL);
+}
+
+int
+evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd)
+{
+ struct evhttp_bound_socket *bound =
+ evhttp_accept_socket_with_handle(http, fd);
+ if (bound == NULL)
+ return (-1);
+ return (0);
+}
+
+void
+evhttp_foreach_bound_socket(struct evhttp *http,
+ evhttp_bound_socket_foreach_fn *function,
+ void *argument)
+{
+ struct evhttp_bound_socket *bound;
+
+ TAILQ_FOREACH(bound, &http->sockets, next)
+ function(bound, argument);
+}
+
+struct evhttp_bound_socket *
+evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd)
+{
+ struct evhttp_bound_socket *bound;
+ struct evconnlistener *listener;
+ const int flags =
+ LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_CLOSE_ON_FREE;
+
+ listener = evconnlistener_new(http->base, NULL, NULL,
+ flags,
+ 0, /* Backlog is '0' because we already said 'listen' */
+ fd);
+ if (!listener)
+ return (NULL);
+
+ bound = evhttp_bind_listener(http, listener);
+ if (!bound) {
+ evconnlistener_free(listener);
+ return (NULL);
+ }
+ return (bound);
+}
+
+struct evhttp_bound_socket *
+evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener)
+{
+ struct evhttp_bound_socket *bound;
+
+ bound = mm_malloc(sizeof(struct evhttp_bound_socket));
+ if (bound == NULL)
+ return (NULL);
+
+ bound->listener = listener;
+ TAILQ_INSERT_TAIL(&http->sockets, bound, next);
+
+ evconnlistener_set_cb(listener, accept_socket_cb, http);
+ return bound;
+}
+
+evutil_socket_t
+evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound)
+{
+ return evconnlistener_get_fd(bound->listener);
+}
+
+struct evconnlistener *
+evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound)
+{
+ return bound->listener;
+}
+
+void
+evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound)
+{
+ TAILQ_REMOVE(&http->sockets, bound, next);
+ evconnlistener_free(bound->listener);
+ mm_free(bound);
+}
+
+static struct evhttp*
+evhttp_new_object(void)
+{
+ struct evhttp *http = NULL;
+
+ if ((http = mm_calloc(1, sizeof(struct evhttp))) == NULL) {
+ event_warn("%s: calloc", __func__);
+ return (NULL);
+ }
+
+ evutil_timerclear(&http->timeout);
+ evhttp_set_max_headers_size(http, EV_SIZE_MAX);
+ evhttp_set_max_body_size(http, EV_SIZE_MAX);
+ evhttp_set_default_content_type(http, "text/html; charset=ISO-8859-1");
+ evhttp_set_allowed_methods(http,
+ EVHTTP_REQ_GET |
+ EVHTTP_REQ_POST |
+ EVHTTP_REQ_HEAD |
+ EVHTTP_REQ_PUT |
+ EVHTTP_REQ_DELETE);
+
+ TAILQ_INIT(&http->sockets);
+ TAILQ_INIT(&http->callbacks);
+ TAILQ_INIT(&http->connections);
+ TAILQ_INIT(&http->virtualhosts);
+ TAILQ_INIT(&http->aliases);
+
+ return (http);
+}
+
+struct evhttp *
+evhttp_new(struct event_base *base)
+{
+ struct evhttp *http = NULL;
+
+ http = evhttp_new_object();
+ if (http == NULL)
+ return (NULL);
+ http->base = base;
+
+ return (http);
+}
+
+/*
+ * Start a web server on the specified address and port.
+ */
+
+struct evhttp *
+evhttp_start(const char *address, ev_uint16_t port)
+{
+ struct evhttp *http = NULL;
+
+ http = evhttp_new_object();
+ if (http == NULL)
+ return (NULL);
+ if (evhttp_bind_socket(http, address, port) == -1) {
+ mm_free(http);
+ return (NULL);
+ }
+
+ return (http);
+}
+
+void
+evhttp_free(struct evhttp* http)
+{
+ struct evhttp_cb *http_cb;
+ struct evhttp_connection *evcon;
+ struct evhttp_bound_socket *bound;
+ struct evhttp* vhost;
+ struct evhttp_server_alias *alias;
+
+ /* Remove the accepting part */
+ while ((bound = TAILQ_FIRST(&http->sockets)) != NULL) {
+ TAILQ_REMOVE(&http->sockets, bound, next);
+
+ evconnlistener_free(bound->listener);
+
+ mm_free(bound);
+ }
+
+ while ((evcon = TAILQ_FIRST(&http->connections)) != NULL) {
+ /* evhttp_connection_free removes the connection */
+ evhttp_connection_free(evcon);
+ }
+
+ while ((http_cb = TAILQ_FIRST(&http->callbacks)) != NULL) {
+ TAILQ_REMOVE(&http->callbacks, http_cb, next);
+ mm_free(http_cb->what);
+ mm_free(http_cb);
+ }
+
+ while ((vhost = TAILQ_FIRST(&http->virtualhosts)) != NULL) {
+ TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
+
+ evhttp_free(vhost);
+ }
+
+ if (http->vhost_pattern != NULL)
+ mm_free(http->vhost_pattern);
+
+ while ((alias = TAILQ_FIRST(&http->aliases)) != NULL) {
+ TAILQ_REMOVE(&http->aliases, alias, next);
+ mm_free(alias->alias);
+ mm_free(alias);
+ }
+
+ mm_free(http);
+}
+
+int
+evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
+ struct evhttp* vhost)
+{
+ /* a vhost can only be a vhost once and should not have bound sockets */
+ if (vhost->vhost_pattern != NULL ||
+ TAILQ_FIRST(&vhost->sockets) != NULL)
+ return (-1);
+
+ vhost->vhost_pattern = mm_strdup(pattern);
+ if (vhost->vhost_pattern == NULL)
+ return (-1);
+
+ TAILQ_INSERT_TAIL(&http->virtualhosts, vhost, next_vhost);
+
+ return (0);
+}
+
+int
+evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost)
+{
+ if (vhost->vhost_pattern == NULL)
+ return (-1);
+
+ TAILQ_REMOVE(&http->virtualhosts, vhost, next_vhost);
+
+ mm_free(vhost->vhost_pattern);
+ vhost->vhost_pattern = NULL;
+
+ return (0);
+}
+
+int
+evhttp_add_server_alias(struct evhttp *http, const char *alias)
+{
+ struct evhttp_server_alias *evalias;
+
+ evalias = mm_calloc(1, sizeof(*evalias));
+ if (!evalias)
+ return -1;
+
+ evalias->alias = mm_strdup(alias);
+ if (!evalias->alias) {
+ mm_free(evalias);
+ return -1;
+ }
+
+ TAILQ_INSERT_TAIL(&http->aliases, evalias, next);
+
+ return 0;
+}
+
+int
+evhttp_remove_server_alias(struct evhttp *http, const char *alias)
+{
+ struct evhttp_server_alias *evalias;
+
+ TAILQ_FOREACH(evalias, &http->aliases, next) {
+ if (evutil_ascii_strcasecmp(evalias->alias, alias) == 0) {
+ TAILQ_REMOVE(&http->aliases, evalias, next);
+ mm_free(evalias->alias);
+ mm_free(evalias);
+ return 0;
+ }
+ }
+
+ return -1;
+}
+
+void
+evhttp_set_timeout(struct evhttp* http, int timeout_in_secs)
+{
+ if (timeout_in_secs == -1) {
+ evhttp_set_timeout_tv(http, NULL);
+ } else {
+ struct timeval tv;
+ tv.tv_sec = timeout_in_secs;
+ tv.tv_usec = 0;
+ evhttp_set_timeout_tv(http, &tv);
+ }
+}
+
+void
+evhttp_set_timeout_tv(struct evhttp* http, const struct timeval* tv)
+{
+ if (tv) {
+ http->timeout = *tv;
+ } else {
+ evutil_timerclear(&http->timeout);
+ }
+}
+
+int evhttp_set_flags(struct evhttp *http, int flags)
+{
+ int avail_flags = 0;
+ avail_flags |= EVHTTP_SERVER_LINGERING_CLOSE;
+
+ if (flags & ~avail_flags)
+ return 1;
+ http->flags &= ~avail_flags;
+
+ http->flags |= flags;
+
+ return 0;
+}
+
+void
+evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size)
+{
+ if (max_headers_size < 0)
+ http->default_max_headers_size = EV_SIZE_MAX;
+ else
+ http->default_max_headers_size = max_headers_size;
+}
+
+void
+evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size)
+{
+ if (max_body_size < 0)
+ http->default_max_body_size = EV_UINT64_MAX;
+ else
+ http->default_max_body_size = max_body_size;
+}
+
+void
+evhttp_set_default_content_type(struct evhttp *http,
+ const char *content_type) {
+ http->default_content_type = content_type;
+}
+
+void
+evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods)
+{
+ http->allowed_methods = methods;
+}
+
+int
+evhttp_set_cb(struct evhttp *http, const char *uri,
+ void (*cb)(struct evhttp_request *, void *), void *cbarg)
+{
+ struct evhttp_cb *http_cb;
+
+ TAILQ_FOREACH(http_cb, &http->callbacks, next) {
+ if (strcmp(http_cb->what, uri) == 0)
+ return (-1);
+ }
+
+ if ((http_cb = mm_calloc(1, sizeof(struct evhttp_cb))) == NULL) {
+ event_warn("%s: calloc", __func__);
+ return (-2);
+ }
+
+ http_cb->what = mm_strdup(uri);
+ if (http_cb->what == NULL) {
+ event_warn("%s: strdup", __func__);
+ mm_free(http_cb);
+ return (-3);
+ }
+ http_cb->cb = cb;
+ http_cb->cbarg = cbarg;
+
+ TAILQ_INSERT_TAIL(&http->callbacks, http_cb, next);
+
+ return (0);
+}
+
+int
+evhttp_del_cb(struct evhttp *http, const char *uri)
+{
+ struct evhttp_cb *http_cb;
+
+ TAILQ_FOREACH(http_cb, &http->callbacks, next) {
+ if (strcmp(http_cb->what, uri) == 0)
+ break;
+ }
+ if (http_cb == NULL)
+ return (-1);
+
+ TAILQ_REMOVE(&http->callbacks, http_cb, next);
+ mm_free(http_cb->what);
+ mm_free(http_cb);
+
+ return (0);
+}
+
+void
+evhttp_set_gencb(struct evhttp *http,
+ void (*cb)(struct evhttp_request *, void *), void *cbarg)
+{
+ http->gencb = cb;
+ http->gencbarg = cbarg;
+}
+
+void
+evhttp_set_bevcb(struct evhttp *http,
+ struct bufferevent* (*cb)(struct event_base *, void *), void *cbarg)
+{
+ http->bevcb = cb;
+ http->bevcbarg = cbarg;
+}
+
+/*
+ * Request related functions
+ */
+
+struct evhttp_request *
+evhttp_request_new(void (*cb)(struct evhttp_request *, void *), void *arg)
+{
+ struct evhttp_request *req = NULL;
+
+ /* Allocate request structure */
+ if ((req = mm_calloc(1, sizeof(struct evhttp_request))) == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto error;
+ }
+
+ req->headers_size = 0;
+ req->body_size = 0;
+
+ req->kind = EVHTTP_RESPONSE;
+ req->input_headers = mm_calloc(1, sizeof(struct evkeyvalq));
+ if (req->input_headers == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto error;
+ }
+ TAILQ_INIT(req->input_headers);
+
+ req->output_headers = mm_calloc(1, sizeof(struct evkeyvalq));
+ if (req->output_headers == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto error;
+ }
+ TAILQ_INIT(req->output_headers);
+
+ if ((req->input_buffer = evbuffer_new()) == NULL) {
+ event_warn("%s: evbuffer_new", __func__);
+ goto error;
+ }
+
+ if ((req->output_buffer = evbuffer_new()) == NULL) {
+ event_warn("%s: evbuffer_new", __func__);
+ goto error;
+ }
+
+ req->cb = cb;
+ req->cb_arg = arg;
+
+ return (req);
+
+ error:
+ if (req != NULL)
+ evhttp_request_free(req);
+ return (NULL);
+}
+
+void
+evhttp_request_free(struct evhttp_request *req)
+{
+ if ((req->flags & EVHTTP_REQ_DEFER_FREE) != 0) {
+ req->flags |= EVHTTP_REQ_NEEDS_FREE;
+ return;
+ }
+
+ if (req->remote_host != NULL)
+ mm_free(req->remote_host);
+ if (req->uri != NULL)
+ mm_free(req->uri);
+ if (req->uri_elems != NULL)
+ evhttp_uri_free(req->uri_elems);
+ if (req->response_code_line != NULL)
+ mm_free(req->response_code_line);
+ if (req->host_cache != NULL)
+ mm_free(req->host_cache);
+
+ evhttp_clear_headers(req->input_headers);
+ mm_free(req->input_headers);
+
+ evhttp_clear_headers(req->output_headers);
+ mm_free(req->output_headers);
+
+ if (req->input_buffer != NULL)
+ evbuffer_free(req->input_buffer);
+
+ if (req->output_buffer != NULL)
+ evbuffer_free(req->output_buffer);
+
+ mm_free(req);
+}
+
+void
+evhttp_request_own(struct evhttp_request *req)
+{
+ req->flags |= EVHTTP_USER_OWNED;
+}
+
+int
+evhttp_request_is_owned(struct evhttp_request *req)
+{
+ return (req->flags & EVHTTP_USER_OWNED) != 0;
+}
+
+struct evhttp_connection *
+evhttp_request_get_connection(struct evhttp_request *req)
+{
+ return req->evcon;
+}
+
+struct event_base *
+evhttp_connection_get_base(struct evhttp_connection *conn)
+{
+ return conn->base;
+}
+
+void
+evhttp_request_set_chunked_cb(struct evhttp_request *req,
+ void (*cb)(struct evhttp_request *, void *))
+{
+ req->chunk_cb = cb;
+}
+
+void
+evhttp_request_set_header_cb(struct evhttp_request *req,
+ int (*cb)(struct evhttp_request *, void *))
+{
+ req->header_cb = cb;
+}
+
+void
+evhttp_request_set_error_cb(struct evhttp_request *req,
+ void (*cb)(enum evhttp_request_error, void *))
+{
+ req->error_cb = cb;
+}
+
+void
+evhttp_request_set_on_complete_cb(struct evhttp_request *req,
+ void (*cb)(struct evhttp_request *, void *), void *cb_arg)
+{
+ req->on_complete_cb = cb;
+ req->on_complete_cb_arg = cb_arg;
+}
+
+/*
+ * Allows for inspection of the request URI
+ */
+
+const char *
+evhttp_request_get_uri(const struct evhttp_request *req) {
+ if (req->uri == NULL)
+ event_debug(("%s: request %p has no uri\n", __func__, req));
+ return (req->uri);
+}
+
+const struct evhttp_uri *
+evhttp_request_get_evhttp_uri(const struct evhttp_request *req) {
+ if (req->uri_elems == NULL)
+ event_debug(("%s: request %p has no uri elems\n",
+ __func__, req));
+ return (req->uri_elems);
+}
+
+const char *
+evhttp_request_get_host(struct evhttp_request *req)
+{
+ const char *host = NULL;
+
+ if (req->host_cache)
+ return req->host_cache;
+
+ if (req->uri_elems)
+ host = evhttp_uri_get_host(req->uri_elems);
+ if (!host && req->input_headers) {
+ const char *p;
+ size_t len;
+
+ host = evhttp_find_header(req->input_headers, "Host");
+ /* The Host: header may include a port. Remove it here
+ to be consistent with uri_elems case above. */
+ if (host) {
+ p = host + strlen(host) - 1;
+ while (p > host && EVUTIL_ISDIGIT_(*p))
+ --p;
+ if (p > host && *p == ':') {
+ len = p - host;
+ req->host_cache = mm_malloc(len + 1);
+ if (!req->host_cache) {
+ event_warn("%s: malloc", __func__);
+ return NULL;
+ }
+ memcpy(req->host_cache, host, len);
+ req->host_cache[len] = '\0';
+ host = req->host_cache;
+ }
+ }
+ }
+
+ return host;
+}
+
+enum evhttp_cmd_type
+evhttp_request_get_command(const struct evhttp_request *req) {
+ return (req->type);
+}
+
+int
+evhttp_request_get_response_code(const struct evhttp_request *req)
+{
+ return req->response_code;
+}
+
+const char *
+evhttp_request_get_response_code_line(const struct evhttp_request *req)
+{
+ return req->response_code_line;
+}
+
+/** Returns the input headers */
+struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req)
+{
+ return (req->input_headers);
+}
+
+/** Returns the output headers */
+struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req)
+{
+ return (req->output_headers);
+}
+
+/** Returns the input buffer */
+struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req)
+{
+ return (req->input_buffer);
+}
+
+/** Returns the output buffer */
+struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req)
+{
+ return (req->output_buffer);
+}
+
+
+/*
+ * Takes a file descriptor to read a request from.
+ * The callback is executed once the whole request has been read.
+ */
+
+static struct evhttp_connection*
+evhttp_get_request_connection(
+ struct evhttp* http,
+ evutil_socket_t fd, struct sockaddr *sa, ev_socklen_t salen)
+{
+ struct evhttp_connection *evcon;
+ char *hostname = NULL, *portname = NULL;
+ struct bufferevent* bev = NULL;
+
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
+ if (sa->sa_family == AF_UNIX) {
+ struct sockaddr_un *sa_un = (struct sockaddr_un *)sa;
+ sa_un->sun_path[0] = '\0';
+ }
+#endif
+
+ name_from_addr(sa, salen, &hostname, &portname);
+ if (hostname == NULL || portname == NULL) {
+ if (hostname) mm_free(hostname);
+ if (portname) mm_free(portname);
+ return (NULL);
+ }
+
+ event_debug(("%s: new request from %s:%s on "EV_SOCK_FMT"\n",
+ __func__, hostname, portname, EV_SOCK_ARG(fd)));
+
+ /* we need a connection object to put the http request on */
+ if (http->bevcb != NULL) {
+ bev = (*http->bevcb)(http->base, http->bevcbarg);
+ }
+ evcon = evhttp_connection_base_bufferevent_new(
+ http->base, NULL, bev, hostname, atoi(portname));
+ mm_free(hostname);
+ mm_free(portname);
+ if (evcon == NULL)
+ return (NULL);
+
+ evcon->max_headers_size = http->default_max_headers_size;
+ evcon->max_body_size = http->default_max_body_size;
+ if (http->flags & EVHTTP_SERVER_LINGERING_CLOSE)
+ evcon->flags |= EVHTTP_CON_LINGERING_CLOSE;
+
+ evcon->flags |= EVHTTP_CON_INCOMING;
+ evcon->state = EVCON_READING_FIRSTLINE;
+
+ evcon->fd = fd;
+
+ if (bufferevent_setfd(evcon->bufev, fd))
+ goto err;
+ if (bufferevent_enable(evcon->bufev, EV_READ))
+ goto err;
+ if (bufferevent_disable(evcon->bufev, EV_WRITE))
+ goto err;
+ bufferevent_socket_set_conn_address_(evcon->bufev, sa, salen);
+
+ return (evcon);
+
+err:
+ evhttp_connection_free(evcon);
+ return (NULL);
+}
+
+static int
+evhttp_associate_new_request_with_connection(struct evhttp_connection *evcon)
+{
+ struct evhttp *http = evcon->http_server;
+ struct evhttp_request *req;
+ if ((req = evhttp_request_new(evhttp_handle_request, http)) == NULL)
+ return (-1);
+
+ if ((req->remote_host = mm_strdup(evcon->address)) == NULL) {
+ event_warn("%s: strdup", __func__);
+ evhttp_request_free(req);
+ return (-1);
+ }
+ req->remote_port = evcon->port;
+
+ req->evcon = evcon; /* the request ends up owning the connection */
+ req->flags |= EVHTTP_REQ_OWN_CONNECTION;
+
+ /* We did not present the request to the user user yet, so treat it as
+ * if the user was done with the request. This allows us to free the
+ * request on a persistent connection if the client drops it without
+ * sending a request.
+ */
+ req->userdone = 1;
+
+ TAILQ_INSERT_TAIL(&evcon->requests, req, next);
+
+ req->kind = EVHTTP_REQUEST;
+
+
+ evhttp_start_read_(evcon);
+
+ return (0);
+}
+
+static void
+evhttp_get_request(struct evhttp *http, evutil_socket_t fd,
+ struct sockaddr *sa, ev_socklen_t salen)
+{
+ struct evhttp_connection *evcon;
+
+ evcon = evhttp_get_request_connection(http, fd, sa, salen);
+ if (evcon == NULL) {
+ event_sock_warn(fd, "%s: cannot get connection on "EV_SOCK_FMT,
+ __func__, EV_SOCK_ARG(fd));
+ evutil_closesocket(fd);
+ return;
+ }
+
+ /* the timeout can be used by the server to close idle connections */
+ if (evutil_timerisset(&http->timeout))
+ evhttp_connection_set_timeout_tv(evcon, &http->timeout);
+
+ /*
+ * if we want to accept more than one request on a connection,
+ * we need to know which http server it belongs to.
+ */
+ evcon->http_server = http;
+ TAILQ_INSERT_TAIL(&http->connections, evcon, next);
+
+ if (evhttp_associate_new_request_with_connection(evcon) == -1)
+ evhttp_connection_free(evcon);
+}
+
+
+/*
+ * Network helper functions that we do not want to export to the rest of
+ * the world.
+ */
+
+static void
+name_from_addr(struct sockaddr *sa, ev_socklen_t salen,
+ char **phost, char **pport)
+{
+ char ntop[NI_MAXHOST];
+ char strport[NI_MAXSERV];
+ int ni_result;
+
+#ifdef EVENT__HAVE_GETNAMEINFO
+ ni_result = getnameinfo(sa, salen,
+ ntop, sizeof(ntop), strport, sizeof(strport),
+ NI_NUMERICHOST|NI_NUMERICSERV);
+
+ if (ni_result != 0) {
+#ifdef EAI_SYSTEM
+ /* Windows doesn't have an EAI_SYSTEM. */
+ if (ni_result == EAI_SYSTEM)
+ event_err(1, "getnameinfo failed");
+ else
+#endif
+ event_errx(1, "getnameinfo failed: %s", gai_strerror(ni_result));
+ return;
+ }
+#else
+ ni_result = fake_getnameinfo(sa, salen,
+ ntop, sizeof(ntop), strport, sizeof(strport),
+ NI_NUMERICHOST|NI_NUMERICSERV);
+ if (ni_result != 0)
+ return;
+#endif
+
+ *phost = mm_strdup(ntop);
+ *pport = mm_strdup(strport);
+}
+
+/* Create a non-blocking socket and bind it */
+static evutil_socket_t
+create_bind_socket_nonblock(struct evutil_addrinfo *ai, int reuse)
+{
+ evutil_socket_t fd;
+
+ int on = 1, r;
+ int serrno;
+
+ /* Create listen socket */
+ fd = evutil_socket_(ai ? ai->ai_family : AF_INET,
+ SOCK_STREAM|EVUTIL_SOCK_NONBLOCK|EVUTIL_SOCK_CLOEXEC, 0);
+ if (fd == -1) {
+ event_sock_warn(-1, "socket");
+ return (-1);
+ }
+
+ if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&on, sizeof(on))<0)
+ goto out;
+ if (reuse) {
+ if (evutil_make_listen_socket_reuseable(fd) < 0)
+ goto out;
+ }
+
+ if (ai != NULL) {
+ r = bind(fd, ai->ai_addr, (ev_socklen_t)ai->ai_addrlen);
+ if (r == -1)
+ goto out;
+ }
+
+ return (fd);
+
+ out:
+ serrno = EVUTIL_SOCKET_ERROR();
+ evutil_closesocket(fd);
+ EVUTIL_SET_SOCKET_ERROR(serrno);
+ return (-1);
+}
+
+static struct evutil_addrinfo *
+make_addrinfo(const char *address, ev_uint16_t port)
+{
+ struct evutil_addrinfo *ai = NULL;
+
+ struct evutil_addrinfo hints;
+ char strport[NI_MAXSERV];
+ int ai_result;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ /* turn NULL hostname into INADDR_ANY, and skip looking up any address
+ * types we don't have an interface to connect to. */
+ hints.ai_flags = EVUTIL_AI_PASSIVE|EVUTIL_AI_ADDRCONFIG;
+ evutil_snprintf(strport, sizeof(strport), "%d", port);
+ if ((ai_result = evutil_getaddrinfo(address, strport, &hints, &ai))
+ != 0) {
+ if (ai_result == EVUTIL_EAI_SYSTEM)
+ event_warn("getaddrinfo");
+ else
+ event_warnx("getaddrinfo: %s",
+ evutil_gai_strerror(ai_result));
+ return (NULL);
+ }
+
+ return (ai);
+}
+
+static evutil_socket_t
+bind_socket(const char *address, ev_uint16_t port, int reuse)
+{
+ evutil_socket_t fd;
+ struct evutil_addrinfo *aitop = NULL;
+
+ /* just create an unbound socket */
+ if (address == NULL && port == 0)
+ return create_bind_socket_nonblock(NULL, 0);
+
+ aitop = make_addrinfo(address, port);
+
+ if (aitop == NULL)
+ return (-1);
+
+ fd = create_bind_socket_nonblock(aitop, reuse);
+
+ evutil_freeaddrinfo(aitop);
+
+ return (fd);
+}
+
+struct evhttp_uri {
+ unsigned flags;
+ char *scheme; /* scheme; e.g http, ftp etc */
+ char *userinfo; /* userinfo (typically username:pass), or NULL */
+ char *host; /* hostname, IP address, or NULL */
+ int port; /* port, or zero */
+ char *path; /* path, or "". */
+ char *query; /* query, or NULL */
+ char *fragment; /* fragment or NULL */
+};
+
+struct evhttp_uri *
+evhttp_uri_new(void)
+{
+ struct evhttp_uri *uri = mm_calloc(sizeof(struct evhttp_uri), 1);
+ if (uri)
+ uri->port = -1;
+ return uri;
+}
+
+void
+evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags)
+{
+ uri->flags = flags;
+}
+
+/* Return true if the string starting at s and ending immediately before eos
+ * is a valid URI scheme according to RFC3986
+ */
+static int
+scheme_ok(const char *s, const char *eos)
+{
+ /* scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) */
+ EVUTIL_ASSERT(eos >= s);
+ if (s == eos)
+ return 0;
+ if (!EVUTIL_ISALPHA_(*s))
+ return 0;
+ while (++s < eos) {
+ if (! EVUTIL_ISALNUM_(*s) &&
+ *s != '+' && *s != '-' && *s != '.')
+ return 0;
+ }
+ return 1;
+}
+
+#define SUBDELIMS "!$&'()*+,;="
+
+/* Return true iff [s..eos) is a valid userinfo */
+static int
+userinfo_ok(const char *s, const char *eos)
+{
+ while (s < eos) {
+ if (CHAR_IS_UNRESERVED(*s) ||
+ strchr(SUBDELIMS, *s) ||
+ *s == ':')
+ ++s;
+ else if (*s == '%' && s+2 < eos &&
+ EVUTIL_ISXDIGIT_(s[1]) &&
+ EVUTIL_ISXDIGIT_(s[2]))
+ s += 3;
+ else
+ return 0;
+ }
+ return 1;
+}
+
+static int
+regname_ok(const char *s, const char *eos)
+{
+ while (s && s<eos) {
+ if (CHAR_IS_UNRESERVED(*s) ||
+ strchr(SUBDELIMS, *s))
+ ++s;
+ else if (*s == '%' &&
+ EVUTIL_ISXDIGIT_(s[1]) &&
+ EVUTIL_ISXDIGIT_(s[2]))
+ s += 3;
+ else
+ return 0;
+ }
+ return 1;
+}
+
+static int
+parse_port(const char *s, const char *eos)
+{
+ int portnum = 0;
+ while (s < eos) {
+ if (! EVUTIL_ISDIGIT_(*s))
+ return -1;
+ portnum = (portnum * 10) + (*s - '0');
+ if (portnum < 0)
+ return -1;
+ if (portnum > 65535)
+ return -1;
+ ++s;
+ }
+ return portnum;
+}
+
+/* returns 0 for bad, 1 for ipv6, 2 for IPvFuture */
+static int
+bracket_addr_ok(const char *s, const char *eos)
+{
+ if (s + 3 > eos || *s != '[' || *(eos-1) != ']')
+ return 0;
+ if (s[1] == 'v') {
+ /* IPvFuture, or junk.
+ "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" )
+ */
+ s += 2; /* skip [v */
+ --eos;
+ if (!EVUTIL_ISXDIGIT_(*s)) /*require at least one*/
+ return 0;
+ while (s < eos && *s != '.') {
+ if (EVUTIL_ISXDIGIT_(*s))
+ ++s;
+ else
+ return 0;
+ }
+ if (*s != '.')
+ return 0;
+ ++s;
+ while (s < eos) {
+ if (CHAR_IS_UNRESERVED(*s) ||
+ strchr(SUBDELIMS, *s) ||
+ *s == ':')
+ ++s;
+ else
+ return 0;
+ }
+ return 2;
+ } else {
+ /* IPv6, or junk */
+ char buf[64];
+ ev_ssize_t n_chars = eos-s-2;
+ struct in6_addr in6;
+ if (n_chars >= 64) /* way too long */
+ return 0;
+ memcpy(buf, s+1, n_chars);
+ buf[n_chars]='\0';
+ return (evutil_inet_pton(AF_INET6,buf,&in6)==1) ? 1 : 0;
+ }
+}
+
+static int
+parse_authority(struct evhttp_uri *uri, char *s, char *eos)
+{
+ char *cp, *port;
+ EVUTIL_ASSERT(eos);
+ if (eos == s) {
+ uri->host = mm_strdup("");
+ if (uri->host == NULL) {
+ event_warn("%s: strdup", __func__);
+ return -1;
+ }
+ return 0;
+ }
+
+ /* Optionally, we start with "userinfo@" */
+
+ cp = strchr(s, '@');
+ if (cp && cp < eos) {
+ if (! userinfo_ok(s,cp))
+ return -1;
+ *cp++ = '\0';
+ uri->userinfo = mm_strdup(s);
+ if (uri->userinfo == NULL) {
+ event_warn("%s: strdup", __func__);
+ return -1;
+ }
+ } else {
+ cp = s;
+ }
+ /* Optionally, we end with ":port" */
+ for (port=eos-1; port >= cp && EVUTIL_ISDIGIT_(*port); --port)
+ ;
+ if (port >= cp && *port == ':') {
+ if (port+1 == eos) /* Leave port unspecified; the RFC allows a
+ * nil port */
+ uri->port = -1;
+ else if ((uri->port = parse_port(port+1, eos))<0)
+ return -1;
+ eos = port;
+ }
+ /* Now, cp..eos holds the "host" port, which can be an IPv4Address,
+ * an IP-Literal, or a reg-name */
+ EVUTIL_ASSERT(eos >= cp);
+ if (*cp == '[' && eos >= cp+2 && *(eos-1) == ']') {
+ /* IPv6address, IP-Literal, or junk. */
+ if (! bracket_addr_ok(cp, eos))
+ return -1;
+ } else {
+ /* Make sure the host part is ok. */
+ if (! regname_ok(cp,eos)) /* Match IPv4Address or reg-name */
+ return -1;
+ }
+ uri->host = mm_malloc(eos-cp+1);
+ if (uri->host == NULL) {
+ event_warn("%s: malloc", __func__);
+ return -1;
+ }
+ memcpy(uri->host, cp, eos-cp);
+ uri->host[eos-cp] = '\0';
+ return 0;
+
+}
+
+static char *
+end_of_authority(char *cp)
+{
+ while (*cp) {
+ if (*cp == '?' || *cp == '#' || *cp == '/')
+ return cp;
+ ++cp;
+ }
+ return cp;
+}
+
+enum uri_part {
+ PART_PATH,
+ PART_QUERY,
+ PART_FRAGMENT
+};
+
+/* Return the character after the longest prefix of 'cp' that matches...
+ * *pchar / "/" if allow_qchars is false, or
+ * *(pchar / "/" / "?") if allow_qchars is true.
+ */
+static char *
+end_of_path(char *cp, enum uri_part part, unsigned flags)
+{
+ if (flags & EVHTTP_URI_NONCONFORMANT) {
+ /* If NONCONFORMANT:
+ * Path is everything up to a # or ? or nul.
+ * Query is everything up a # or nul
+ * Fragment is everything up to a nul.
+ */
+ switch (part) {
+ case PART_PATH:
+ while (*cp && *cp != '#' && *cp != '?')
+ ++cp;
+ break;
+ case PART_QUERY:
+ while (*cp && *cp != '#')
+ ++cp;
+ break;
+ case PART_FRAGMENT:
+ cp += strlen(cp);
+ break;
+ };
+ return cp;
+ }
+
+ while (*cp) {
+ if (CHAR_IS_UNRESERVED(*cp) ||
+ strchr(SUBDELIMS, *cp) ||
+ *cp == ':' || *cp == '@' || *cp == '/')
+ ++cp;
+ else if (*cp == '%' && EVUTIL_ISXDIGIT_(cp[1]) &&
+ EVUTIL_ISXDIGIT_(cp[2]))
+ cp += 3;
+ else if (*cp == '?' && part != PART_PATH)
+ ++cp;
+ else
+ return cp;
+ }
+ return cp;
+}
+
+static int
+path_matches_noscheme(const char *cp)
+{
+ while (*cp) {
+ if (*cp == ':')
+ return 0;
+ else if (*cp == '/')
+ return 1;
+ ++cp;
+ }
+ return 1;
+}
+
+struct evhttp_uri *
+evhttp_uri_parse(const char *source_uri)
+{
+ return evhttp_uri_parse_with_flags(source_uri, 0);
+}
+
+struct evhttp_uri *
+evhttp_uri_parse_with_flags(const char *source_uri, unsigned flags)
+{
+ char *readbuf = NULL, *readp = NULL, *token = NULL, *query = NULL;
+ char *path = NULL, *fragment = NULL;
+ int got_authority = 0;
+
+ struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
+ if (uri == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto err;
+ }
+ uri->port = -1;
+ uri->flags = flags;
+
+ readbuf = mm_strdup(source_uri);
+ if (readbuf == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+
+ readp = readbuf;
+ token = NULL;
+
+ /* We try to follow RFC3986 here as much as we can, and match
+ the productions
+
+ URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
+
+ relative-ref = relative-part [ "?" query ] [ "#" fragment ]
+ */
+
+ /* 1. scheme: */
+ token = strchr(readp, ':');
+ if (token && scheme_ok(readp,token)) {
+ *token = '\0';
+ uri->scheme = mm_strdup(readp);
+ if (uri->scheme == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+ readp = token+1; /* eat : */
+ }
+
+ /* 2. Optionally, "//" then an 'authority' part. */
+ if (readp[0]=='/' && readp[1] == '/') {
+ char *authority;
+ readp += 2;
+ authority = readp;
+ path = end_of_authority(readp);
+ if (parse_authority(uri, authority, path) < 0)
+ goto err;
+ readp = path;
+ got_authority = 1;
+ }
+
+ /* 3. Query: path-abempty, path-absolute, path-rootless, or path-empty
+ */
+ path = readp;
+ readp = end_of_path(path, PART_PATH, flags);
+
+ /* Query */
+ if (*readp == '?') {
+ *readp = '\0';
+ ++readp;
+ query = readp;
+ readp = end_of_path(readp, PART_QUERY, flags);
+ }
+ /* fragment */
+ if (*readp == '#') {
+ *readp = '\0';
+ ++readp;
+ fragment = readp;
+ readp = end_of_path(readp, PART_FRAGMENT, flags);
+ }
+ if (*readp != '\0') {
+ goto err;
+ }
+
+ /* These next two cases may be unreachable; I'm leaving them
+ * in to be defensive. */
+ /* If you didn't get an authority, the path can't begin with "//" */
+ if (!got_authority && path[0]=='/' && path[1]=='/')
+ goto err;
+ /* If you did get an authority, the path must begin with "/" or be
+ * empty. */
+ if (got_authority && path[0] != '/' && path[0] != '\0')
+ goto err;
+ /* (End of maybe-unreachable cases) */
+
+ /* If there was no scheme, the first part of the path (if any) must
+ * have no colon in it. */
+ if (! uri->scheme && !path_matches_noscheme(path))
+ goto err;
+
+ EVUTIL_ASSERT(path);
+ uri->path = mm_strdup(path);
+ if (uri->path == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+
+ if (query) {
+ uri->query = mm_strdup(query);
+ if (uri->query == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+ }
+ if (fragment) {
+ uri->fragment = mm_strdup(fragment);
+ if (uri->fragment == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+ }
+
+ mm_free(readbuf);
+
+ return uri;
+err:
+ if (uri)
+ evhttp_uri_free(uri);
+ if (readbuf)
+ mm_free(readbuf);
+ return NULL;
+}
+
+static struct evhttp_uri *
+evhttp_uri_parse_authority(char *source_uri)
+{
+ struct evhttp_uri *uri = mm_calloc(1, sizeof(struct evhttp_uri));
+ char *end;
+
+ if (uri == NULL) {
+ event_warn("%s: calloc", __func__);
+ goto err;
+ }
+ uri->port = -1;
+ uri->flags = 0;
+
+ end = end_of_authority(source_uri);
+ if (parse_authority(uri, source_uri, end) < 0)
+ goto err;
+
+ uri->path = mm_strdup("");
+ if (uri->path == NULL) {
+ event_warn("%s: strdup", __func__);
+ goto err;
+ }
+
+ return uri;
+err:
+ if (uri)
+ evhttp_uri_free(uri);
+ return NULL;
+}
+
+void
+evhttp_uri_free(struct evhttp_uri *uri)
+{
+#define URI_FREE_STR_(f) \
+ if (uri->f) { \
+ mm_free(uri->f); \
+ }
+
+ URI_FREE_STR_(scheme);
+ URI_FREE_STR_(userinfo);
+ URI_FREE_STR_(host);
+ URI_FREE_STR_(path);
+ URI_FREE_STR_(query);
+ URI_FREE_STR_(fragment);
+
+ mm_free(uri);
+#undef URI_FREE_STR_
+}
+
+char *
+evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit)
+{
+ struct evbuffer *tmp = 0;
+ size_t joined_size = 0;
+ char *output = NULL;
+
+#define URI_ADD_(f) evbuffer_add(tmp, uri->f, strlen(uri->f))
+
+ if (!uri || !buf || !limit)
+ return NULL;
+
+ tmp = evbuffer_new();
+ if (!tmp)
+ return NULL;
+
+ if (uri->scheme) {
+ URI_ADD_(scheme);
+ evbuffer_add(tmp, ":", 1);
+ }
+ if (uri->host) {
+ evbuffer_add(tmp, "//", 2);
+ if (uri->userinfo)
+ evbuffer_add_printf(tmp,"%s@", uri->userinfo);
+ URI_ADD_(host);
+ if (uri->port >= 0)
+ evbuffer_add_printf(tmp,":%d", uri->port);
+
+ if (uri->path && uri->path[0] != '/' && uri->path[0] != '\0')
+ goto err;
+ }
+
+ if (uri->path)
+ URI_ADD_(path);
+
+ if (uri->query) {
+ evbuffer_add(tmp, "?", 1);
+ URI_ADD_(query);
+ }
+
+ if (uri->fragment) {
+ evbuffer_add(tmp, "#", 1);
+ URI_ADD_(fragment);
+ }
+
+ evbuffer_add(tmp, "\0", 1); /* NUL */
+
+ joined_size = evbuffer_get_length(tmp);
+
+ if (joined_size > limit) {
+ /* It doesn't fit. */
+ evbuffer_free(tmp);
+ return NULL;
+ }
+ evbuffer_remove(tmp, buf, joined_size);
+
+ output = buf;
+err:
+ evbuffer_free(tmp);
+
+ return output;
+#undef URI_ADD_
+}
+
+const char *
+evhttp_uri_get_scheme(const struct evhttp_uri *uri)
+{
+ return uri->scheme;
+}
+const char *
+evhttp_uri_get_userinfo(const struct evhttp_uri *uri)
+{
+ return uri->userinfo;
+}
+const char *
+evhttp_uri_get_host(const struct evhttp_uri *uri)
+{
+ return uri->host;
+}
+int
+evhttp_uri_get_port(const struct evhttp_uri *uri)
+{
+ return uri->port;
+}
+const char *
+evhttp_uri_get_path(const struct evhttp_uri *uri)
+{
+ return uri->path;
+}
+const char *
+evhttp_uri_get_query(const struct evhttp_uri *uri)
+{
+ return uri->query;
+}
+const char *
+evhttp_uri_get_fragment(const struct evhttp_uri *uri)
+{
+ return uri->fragment;
+}
+
+#define URI_SET_STR_(f) do { \
+ if (uri->f) \
+ mm_free(uri->f); \
+ if (f) { \
+ if ((uri->f = mm_strdup(f)) == NULL) { \
+ event_warn("%s: strdup()", __func__); \
+ return -1; \
+ } \
+ } else { \
+ uri->f = NULL; \
+ } \
+ } while(0)
+
+int
+evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme)
+{
+ if (scheme && !scheme_ok(scheme, scheme+strlen(scheme)))
+ return -1;
+
+ URI_SET_STR_(scheme);
+ return 0;
+}
+int
+evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo)
+{
+ if (userinfo && !userinfo_ok(userinfo, userinfo+strlen(userinfo)))
+ return -1;
+ URI_SET_STR_(userinfo);
+ return 0;
+}
+int
+evhttp_uri_set_host(struct evhttp_uri *uri, const char *host)
+{
+ if (host) {
+ if (host[0] == '[') {
+ if (! bracket_addr_ok(host, host+strlen(host)))
+ return -1;
+ } else {
+ if (! regname_ok(host, host+strlen(host)))
+ return -1;
+ }
+ }
+
+ URI_SET_STR_(host);
+ return 0;
+}
+int
+evhttp_uri_set_port(struct evhttp_uri *uri, int port)
+{
+ if (port < -1)
+ return -1;
+ uri->port = port;
+ return 0;
+}
+#define end_of_cpath(cp,p,f) \
+ ((const char*)(end_of_path(((char*)(cp)), (p), (f))))
+
+int
+evhttp_uri_set_path(struct evhttp_uri *uri, const char *path)
+{
+ if (path && end_of_cpath(path, PART_PATH, uri->flags) != path+strlen(path))
+ return -1;
+
+ URI_SET_STR_(path);
+ return 0;
+}
+int
+evhttp_uri_set_query(struct evhttp_uri *uri, const char *query)
+{
+ if (query && end_of_cpath(query, PART_QUERY, uri->flags) != query+strlen(query))
+ return -1;
+ URI_SET_STR_(query);
+ return 0;
+}
+int
+evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment)
+{
+ if (fragment && end_of_cpath(fragment, PART_FRAGMENT, uri->flags) != fragment+strlen(fragment))
+ return -1;
+ URI_SET_STR_(fragment);
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/include/evdns.h b/ipc/chromium/src/third_party/libevent/include/evdns.h
new file mode 100644
index 0000000000..8672db0369
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/evdns.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT1_EVDNS_H_INCLUDED_
+#define EVENT1_EVDNS_H_INCLUDED_
+
+/** @file evdns.h
+
+ A dns subsystem for Libevent.
+
+ The <evdns.h> header is deprecated in Libevent 2.0 and later; please
+ use <event2/evdns.h> instead. Depending on what functionality you
+ need, you may also want to include more of the other <event2/...>
+ headers.
+ */
+
+#include <event.h>
+#include <event2/dns.h>
+#include <event2/dns_compat.h>
+#include <event2/dns_struct.h>
+
+#endif /* EVENT1_EVDNS_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event.h b/ipc/chromium/src/third_party/libevent/include/event.h
new file mode 100644
index 0000000000..ba5186713b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT1_EVENT_H_INCLUDED_
+#define EVENT1_EVENT_H_INCLUDED_
+
+/** @file event.h
+
+ A library for writing event-driven network servers.
+
+ The <event.h> header is deprecated in Libevent 2.0 and later; please
+ use <event2/event.h> instead. Depending on what functionality you
+ need, you may also want to include more of the other event2/
+ headers.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_STDINT_H
+#include <stdint.h>
+#endif
+#include <stdarg.h>
+
+/* For int types. */
+#include <evutil.h>
+
+#ifdef _WIN32
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+
+#include <event2/event_struct.h>
+#include <event2/event.h>
+#include <event2/event_compat.h>
+#include <event2/buffer.h>
+#include <event2/buffer_compat.h>
+#include <event2/bufferevent.h>
+#include <event2/bufferevent_struct.h>
+#include <event2/bufferevent_compat.h>
+#include <event2/tag.h>
+#include <event2/tag_compat.h>
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT1_EVENT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/buffer.h b/ipc/chromium/src/third_party/libevent/include/event2/buffer.h
new file mode 100644
index 0000000000..88af3ae141
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/buffer.h
@@ -0,0 +1,1077 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_BUFFER_H_INCLUDED_
+#define EVENT2_BUFFER_H_INCLUDED_
+
+/** @file event2/buffer.h
+
+ Functions for buffering data for network sending or receiving.
+
+ An evbuffer can be used for preparing data before sending it to
+ the network or conversely for reading data from the network.
+ Evbuffers try to avoid memory copies as much as possible. As a
+ result, evbuffers can be used to pass data around without actually
+ incurring the overhead of copying the data.
+
+ A new evbuffer can be allocated with evbuffer_new(), and can be
+ freed with evbuffer_free(). Most users will be using evbuffers via
+ the bufferevent interface. To access a bufferevent's evbuffers, use
+ bufferevent_get_input() and bufferevent_get_output().
+
+ There are several guidelines for using evbuffers.
+
+ - if you already know how much data you are going to add as a result
+ of calling evbuffer_add() multiple times, it makes sense to use
+ evbuffer_expand() first to make sure that enough memory is allocated
+ before hand.
+
+ - evbuffer_add_buffer() adds the contents of one buffer to the other
+ without incurring any unnecessary memory copies.
+
+ - evbuffer_add() and evbuffer_add_buffer() do not mix very well:
+ if you use them, you will wind up with fragmented memory in your
+ buffer.
+
+ - For high-performance code, you may want to avoid copying data into and out
+ of buffers. You can skip the copy step by using
+ evbuffer_reserve_space()/evbuffer_commit_space() when writing into a
+ buffer, and evbuffer_peek() when reading.
+
+ In Libevent 2.0 and later, evbuffers are represented using a linked
+ list of memory chunks, with pointers to the first and last chunk in
+ the chain.
+
+ As the contents of an evbuffer can be stored in multiple different
+ memory blocks, it cannot be accessed directly. Instead, evbuffer_pullup()
+ can be used to force a specified number of bytes to be contiguous. This
+ will cause memory reallocation and memory copies if the data is split
+ across multiple blocks. It is more efficient, however, to use
+ evbuffer_peek() if you don't require that the memory to be contiguous.
+ */
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#include <stdarg.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+#include <event2/util.h>
+
+/**
+ An evbuffer is an opaque data type for efficiently buffering data to be
+ sent or received on the network.
+
+ @see event2/event.h for more information
+*/
+struct evbuffer
+#ifdef EVENT_IN_DOXYGEN_
+{}
+#endif
+;
+
+/**
+ Pointer to a position within an evbuffer.
+
+ Used when repeatedly searching through a buffer. Calling any function
+ that modifies or re-packs the buffer contents may invalidate all
+ evbuffer_ptrs for that buffer. Do not modify or contruct these values
+ except with evbuffer_ptr_set.
+
+ An evbuffer_ptr can represent any position from the start of a buffer up
+ to a position immediately after the end of a buffer.
+
+ @see evbuffer_ptr_set()
+ */
+struct evbuffer_ptr {
+ ev_ssize_t pos;
+
+ /* Do not alter or rely on the values of fields: they are for internal
+ * use */
+ struct {
+ void *chain;
+ size_t pos_in_chain;
+ } internal_;
+};
+
+/** Describes a single extent of memory inside an evbuffer. Used for
+ direct-access functions.
+
+ @see evbuffer_reserve_space, evbuffer_commit_space, evbuffer_peek
+ */
+#ifdef EVENT__HAVE_SYS_UIO_H
+#define evbuffer_iovec iovec
+/* Internal use -- defined only if we are using the native struct iovec */
+#define EVBUFFER_IOVEC_IS_NATIVE_
+#else
+struct evbuffer_iovec {
+ /** The start of the extent of memory. */
+ void *iov_base;
+ /** The length of the extent of memory. */
+ size_t iov_len;
+};
+#endif
+
+/**
+ Allocate storage for a new evbuffer.
+
+ @return a pointer to a newly allocated evbuffer struct, or NULL if an error
+ occurred
+ */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *evbuffer_new(void);
+/**
+ Deallocate storage for an evbuffer.
+
+ @param buf pointer to the evbuffer to be freed
+ */
+EVENT2_EXPORT_SYMBOL
+void evbuffer_free(struct evbuffer *buf);
+
+/**
+ Enable locking on an evbuffer so that it can safely be used by multiple
+ threads at the same time.
+
+ NOTE: when locking is enabled, the lock will be held when callbacks are
+ invoked. This could result in deadlock if you aren't careful. Plan
+ accordingly!
+
+ @param buf An evbuffer to make lockable.
+ @param lock A lock object, or NULL if we should allocate our own.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_enable_locking(struct evbuffer *buf, void *lock);
+
+/**
+ Acquire the lock on an evbuffer. Has no effect if locking was not enabled
+ with evbuffer_enable_locking.
+*/
+EVENT2_EXPORT_SYMBOL
+void evbuffer_lock(struct evbuffer *buf);
+
+/**
+ Release the lock on an evbuffer. Has no effect if locking was not enabled
+ with evbuffer_enable_locking.
+*/
+EVENT2_EXPORT_SYMBOL
+void evbuffer_unlock(struct evbuffer *buf);
+
+
+/** If this flag is set, then we will not use evbuffer_peek(),
+ * evbuffer_remove(), evbuffer_remove_buffer(), and so on to read bytes
+ * from this buffer: we'll only take bytes out of this buffer by
+ * writing them to the network (as with evbuffer_write_atmost), by
+ * removing them without observing them (as with evbuffer_drain),
+ * or by copying them all out at once (as with evbuffer_add_buffer).
+ *
+ * Using this option allows the implementation to use sendfile-based
+ * operations for evbuffer_add_file(); see that function for more
+ * information.
+ *
+ * This flag is on by default for bufferevents that can take advantage
+ * of it; you should never actually need to set it on a bufferevent's
+ * output buffer.
+ */
+#define EVBUFFER_FLAG_DRAINS_TO_FD 1
+
+/** Change the flags that are set for an evbuffer by adding more.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_set_flags(struct evbuffer *buf, ev_uint64_t flags);
+/** Change the flags that are set for an evbuffer by removing some.
+ *
+ * @param buffer the evbuffer that the callback is watching.
+ * @param cb the callback whose status we want to change.
+ * @param flags One or more EVBUFFER_FLAG_* options
+ * @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_clear_flags(struct evbuffer *buf, ev_uint64_t flags);
+
+/**
+ Returns the total number of bytes stored in the evbuffer
+
+ @param buf pointer to the evbuffer
+ @return the number of bytes stored in the evbuffer
+*/
+EVENT2_EXPORT_SYMBOL
+size_t evbuffer_get_length(const struct evbuffer *buf);
+
+/**
+ Returns the number of contiguous available bytes in the first buffer chain.
+
+ This is useful when processing data that might be split into multiple
+ chains, or that might all be in the first chain. Calls to
+ evbuffer_pullup() that cause reallocation and copying of data can thus be
+ avoided.
+
+ @param buf pointer to the evbuffer
+ @return 0 if no data is available, otherwise the number of available bytes
+ in the first buffer chain.
+*/
+EVENT2_EXPORT_SYMBOL
+size_t evbuffer_get_contiguous_space(const struct evbuffer *buf);
+
+/**
+ Expands the available space in an evbuffer.
+
+ Expands the available space in the evbuffer to at least datlen, so that
+ appending datlen additional bytes will not require any new allocations.
+
+ @param buf the evbuffer to be expanded
+ @param datlen the new minimum length requirement
+ @return 0 if successful, or -1 if an error occurred
+*/
+EVENT2_EXPORT_SYMBOL
+int evbuffer_expand(struct evbuffer *buf, size_t datlen);
+
+/**
+ Reserves space in the last chain or chains of an evbuffer.
+
+ Makes space available in the last chain or chains of an evbuffer that can
+ be arbitrarily written to by a user. The space does not become
+ available for reading until it has been committed with
+ evbuffer_commit_space().
+
+ The space is made available as one or more extents, represented by
+ an initial pointer and a length. You can force the memory to be
+ available as only one extent. Allowing more extents, however, makes the
+ function more efficient.
+
+ Multiple subsequent calls to this function will make the same space
+ available until evbuffer_commit_space() has been called.
+
+ It is an error to do anything that moves around the buffer's internal
+ memory structures before committing the space.
+
+ NOTE: The code currently does not ever use more than two extents.
+ This may change in future versions.
+
+ @param buf the evbuffer in which to reserve space.
+ @param size how much space to make available, at minimum. The
+ total length of the extents may be greater than the requested
+ length.
+ @param vec an array of one or more evbuffer_iovec structures to
+ hold pointers to the reserved extents of memory.
+ @param n_vec The length of the vec array. Must be at least 1;
+ 2 is more efficient.
+ @return the number of provided extents, or -1 on error.
+ @see evbuffer_commit_space()
+*/
+EVENT2_EXPORT_SYMBOL
+int
+evbuffer_reserve_space(struct evbuffer *buf, ev_ssize_t size,
+ struct evbuffer_iovec *vec, int n_vec);
+
+/**
+ Commits previously reserved space.
+
+ Commits some of the space previously reserved with
+ evbuffer_reserve_space(). It then becomes available for reading.
+
+ This function may return an error if the pointer in the extents do
+ not match those returned from evbuffer_reserve_space, or if data
+ has been added to the buffer since the space was reserved.
+
+ If you want to commit less data than you got reserved space for,
+ modify the iov_len pointer of the appropriate extent to a smaller
+ value. Note that you may have received more space than you
+ requested if it was available!
+
+ @param buf the evbuffer in which to reserve space.
+ @param vec one or two extents returned by evbuffer_reserve_space.
+ @param n_vecs the number of extents.
+ @return 0 on success, -1 on error
+ @see evbuffer_reserve_space()
+*/
+EVENT2_EXPORT_SYMBOL
+int evbuffer_commit_space(struct evbuffer *buf,
+ struct evbuffer_iovec *vec, int n_vecs);
+
+/**
+ Append data to the end of an evbuffer.
+
+ @param buf the evbuffer to be appended to
+ @param data pointer to the beginning of the data buffer
+ @param datlen the number of bytes to be copied from the data buffer
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add(struct evbuffer *buf, const void *data, size_t datlen);
+
+
+/**
+ Read data from an evbuffer and drain the bytes read.
+
+ If more bytes are requested than are available in the evbuffer, we
+ only extract as many bytes as were available.
+
+ @param buf the evbuffer to be read from
+ @param data the destination buffer to store the result
+ @param datlen the maximum size of the destination buffer
+ @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_remove(struct evbuffer *buf, void *data, size_t datlen);
+
+/**
+ Read data from an evbuffer, and leave the buffer unchanged.
+
+ If more bytes are requested than are available in the evbuffer, we
+ only extract as many bytes as were available.
+
+ @param buf the evbuffer to be read from
+ @param data_out the destination buffer to store the result
+ @param datlen the maximum size of the destination buffer
+ @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t evbuffer_copyout(struct evbuffer *buf, void *data_out, size_t datlen);
+
+/**
+ Read data from the middle of an evbuffer, and leave the buffer unchanged.
+
+ If more bytes are requested than are available in the evbuffer, we
+ only extract as many bytes as were available.
+
+ @param buf the evbuffer to be read from
+ @param pos the position to start reading from
+ @param data_out the destination buffer to store the result
+ @param datlen the maximum size of the destination buffer
+ @return the number of bytes read, or -1 if we can't drain the buffer.
+ */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t evbuffer_copyout_from(struct evbuffer *buf, const struct evbuffer_ptr *pos, void *data_out, size_t datlen);
+
+/**
+ Read data from an evbuffer into another evbuffer, draining
+ the bytes from the source buffer. This function avoids copy
+ operations to the extent possible.
+
+ If more bytes are requested than are available in src, the src
+ buffer is drained completely.
+
+ @param src the evbuffer to be read from
+ @param dst the destination evbuffer to store the result into
+ @param datlen the maximum numbers of bytes to transfer
+ @return the number of bytes read
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_remove_buffer(struct evbuffer *src, struct evbuffer *dst,
+ size_t datlen);
+
+/** Used to tell evbuffer_readln what kind of line-ending to look for.
+ */
+enum evbuffer_eol_style {
+ /** Any sequence of CR and LF characters is acceptable as an
+ * EOL.
+ *
+ * Note that this style can produce ambiguous results: the
+ * sequence "CRLF" will be treated as a single EOL if it is
+ * all in the buffer at once, but if you first read a CR from
+ * the network and later read an LF from the network, it will
+ * be treated as two EOLs.
+ */
+ EVBUFFER_EOL_ANY,
+ /** An EOL is an LF, optionally preceded by a CR. This style is
+ * most useful for implementing text-based internet protocols. */
+ EVBUFFER_EOL_CRLF,
+ /** An EOL is a CR followed by an LF. */
+ EVBUFFER_EOL_CRLF_STRICT,
+ /** An EOL is a LF. */
+ EVBUFFER_EOL_LF,
+ /** An EOL is a NUL character (that is, a single byte with value 0) */
+ EVBUFFER_EOL_NUL
+};
+
+/**
+ * Read a single line from an evbuffer.
+ *
+ * Reads a line terminated by an EOL as determined by the evbuffer_eol_style
+ * argument. Returns a newly allocated nul-terminated string; the caller must
+ * free the returned value. The EOL is not included in the returned string.
+ *
+ * @param buffer the evbuffer to read from
+ * @param n_read_out if non-NULL, points to a size_t that is set to the
+ * number of characters in the returned string. This is useful for
+ * strings that can contain NUL characters.
+ * @param eol_style the style of line-ending to use.
+ * @return pointer to a single line, or NULL if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+char *evbuffer_readln(struct evbuffer *buffer, size_t *n_read_out,
+ enum evbuffer_eol_style eol_style);
+
+/**
+ Move all data from one evbuffer into another evbuffer.
+
+ This is a destructive add. The data from one buffer moves into
+ the other buffer. However, no unnecessary memory copies occur.
+
+ @param outbuf the output buffer
+ @param inbuf the input buffer
+ @return 0 if successful, or -1 if an error occurred
+
+ @see evbuffer_remove_buffer()
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_buffer(struct evbuffer *outbuf, struct evbuffer *inbuf);
+
+/**
+ Copy data from one evbuffer into another evbuffer.
+
+ This is a non-destructive add. The data from one buffer is copied
+ into the other buffer. However, no unnecessary memory copies occur.
+
+ Note that buffers already containing buffer references can't be added
+ to other buffers.
+
+ @param outbuf the output buffer
+ @param inbuf the input buffer
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_buffer_reference(struct evbuffer *outbuf,
+ struct evbuffer *inbuf);
+
+/**
+ A cleanup function for a piece of memory added to an evbuffer by
+ reference.
+
+ @see evbuffer_add_reference()
+ */
+typedef void (*evbuffer_ref_cleanup_cb)(const void *data,
+ size_t datalen, void *extra);
+
+/**
+ Reference memory into an evbuffer without copying.
+
+ The memory needs to remain valid until all the added data has been
+ read. This function keeps just a reference to the memory without
+ actually incurring the overhead of a copy.
+
+ @param outbuf the output buffer
+ @param data the memory to reference
+ @param datlen how memory to reference
+ @param cleanupfn callback to be invoked when the memory is no longer
+ referenced by this evbuffer.
+ @param cleanupfn_arg optional argument to the cleanup callback
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_reference(struct evbuffer *outbuf,
+ const void *data, size_t datlen,
+ evbuffer_ref_cleanup_cb cleanupfn, void *cleanupfn_arg);
+
+/**
+ Copy data from a file into the evbuffer for writing to a socket.
+
+ This function avoids unnecessary data copies between userland and
+ kernel. If sendfile is available and the EVBUFFER_FLAG_DRAINS_TO_FD
+ flag is set, it uses those functions. Otherwise, it tries to use
+ mmap (or CreateFileMapping on Windows).
+
+ The function owns the resulting file descriptor and will close it
+ when finished transferring data.
+
+ The results of using evbuffer_remove() or evbuffer_pullup() on
+ evbuffers whose data was added using this function are undefined.
+
+ For more fine-grained control, use evbuffer_add_file_segment.
+
+ @param outbuf the output buffer
+ @param fd the file descriptor
+ @param offset the offset from which to read data
+ @param length how much data to read, or -1 to read as much as possible.
+ (-1 requires that 'fd' support fstat.)
+ @return 0 if successful, or -1 if an error occurred
+*/
+
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_file(struct evbuffer *outbuf, int fd, ev_off_t offset,
+ ev_off_t length);
+
+/**
+ An evbuffer_file_segment holds a reference to a range of a file --
+ possibly the whole file! -- for use in writing from an evbuffer to a
+ socket. It could be implemented with mmap, sendfile, splice, or (if all
+ else fails) by just pulling all the data into RAM. A single
+ evbuffer_file_segment can be added more than once, and to more than one
+ evbuffer.
+ */
+struct evbuffer_file_segment;
+
+/**
+ Flag for creating evbuffer_file_segment: If this flag is set, then when
+ the evbuffer_file_segment is freed and no longer in use by any
+ evbuffer, the underlying fd is closed.
+ */
+#define EVBUF_FS_CLOSE_ON_FREE 0x01
+/**
+ Flag for creating evbuffer_file_segment: Disable memory-map based
+ implementations.
+ */
+#define EVBUF_FS_DISABLE_MMAP 0x02
+/**
+ Flag for creating evbuffer_file_segment: Disable direct fd-to-fd
+ implementations (including sendfile and splice).
+
+ You might want to use this option if data needs to be taken from the
+ evbuffer by any means other than writing it to the network: the sendfile
+ backend is fast, but it only works for sending files directly to the
+ network.
+ */
+#define EVBUF_FS_DISABLE_SENDFILE 0x04
+/**
+ Flag for creating evbuffer_file_segment: Do not allocate a lock for this
+ segment. If this option is set, then neither the segment nor any
+ evbuffer it is added to may ever be accessed from more than one thread
+ at a time.
+ */
+#define EVBUF_FS_DISABLE_LOCKING 0x08
+
+/**
+ A cleanup function for a evbuffer_file_segment added to an evbuffer
+ for reference.
+ */
+typedef void (*evbuffer_file_segment_cleanup_cb)(
+ struct evbuffer_file_segment const* seg, int flags, void* arg);
+
+/**
+ Create and return a new evbuffer_file_segment for reading data from a
+ file and sending it out via an evbuffer.
+
+ This function avoids unnecessary data copies between userland and
+ kernel. Where available, it uses sendfile or splice.
+
+ The file descriptor must not be closed so long as any evbuffer is using
+ this segment.
+
+ The results of using evbuffer_remove() or evbuffer_pullup() or any other
+ function that reads bytes from an evbuffer on any evbuffer containing
+ the newly returned segment are undefined, unless you pass the
+ EVBUF_FS_DISABLE_SENDFILE flag to this function.
+
+ @param fd an open file to read from.
+ @param offset an index within the file at which to start reading
+ @param length how much data to read, or -1 to read as much as possible.
+ (-1 requires that 'fd' support fstat.)
+ @param flags any number of the EVBUF_FS_* flags
+ @return a new evbuffer_file_segment, or NULL on failure.
+ **/
+EVENT2_EXPORT_SYMBOL
+struct evbuffer_file_segment *evbuffer_file_segment_new(
+ int fd, ev_off_t offset, ev_off_t length, unsigned flags);
+
+/**
+ Free an evbuffer_file_segment
+
+ It is safe to call this function even if the segment has been added to
+ one or more evbuffers. The evbuffer_file_segment will not be freed
+ until no more references to it exist.
+ */
+EVENT2_EXPORT_SYMBOL
+void evbuffer_file_segment_free(struct evbuffer_file_segment *seg);
+
+/**
+ Add cleanup callback and argument for the callback to an
+ evbuffer_file_segment.
+
+ The cleanup callback will be invoked when no more references to the
+ evbuffer_file_segment exist.
+ **/
+EVENT2_EXPORT_SYMBOL
+void evbuffer_file_segment_add_cleanup_cb(struct evbuffer_file_segment *seg,
+ evbuffer_file_segment_cleanup_cb cb, void* arg);
+
+/**
+ Insert some or all of an evbuffer_file_segment at the end of an evbuffer
+
+ Note that the offset and length parameters of this function have a
+ different meaning from those provided to evbuffer_file_segment_new: When
+ you create the segment, the offset is the offset _within the file_, and
+ the length is the length _of the segment_, whereas when you add a
+ segment to an evbuffer, the offset is _within the segment_ and the
+ length is the length of the _part of the segment you want to use.
+
+ In other words, if you have a 10 KiB file, and you create an
+ evbuffer_file_segment for it with offset 20 and length 1000, it will
+ refer to bytes 20..1019 inclusive. If you then pass this segment to
+ evbuffer_add_file_segment and specify an offset of 20 and a length of
+ 50, you will be adding bytes 40..99 inclusive.
+
+ @param buf the evbuffer to append to
+ @param seg the segment to add
+ @param offset the offset within the segment to start from
+ @param length the amount of data to add, or -1 to add it all.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_file_segment(struct evbuffer *buf,
+ struct evbuffer_file_segment *seg, ev_off_t offset, ev_off_t length);
+
+/**
+ Append a formatted string to the end of an evbuffer.
+
+ The string is formated as printf.
+
+ @param buf the evbuffer that will be appended to
+ @param fmt a format string
+ @param ... arguments that will be passed to printf(3)
+ @return The number of bytes added if successful, or -1 if an error occurred.
+
+ @see evutil_printf(), evbuffer_add_vprintf()
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_printf(struct evbuffer *buf, const char *fmt, ...)
+#ifdef __GNUC__
+ __attribute__((format(printf, 2, 3)))
+#endif
+;
+
+/**
+ Append a va_list formatted string to the end of an evbuffer.
+
+ @param buf the evbuffer that will be appended to
+ @param fmt a format string
+ @param ap a varargs va_list argument array that will be passed to vprintf(3)
+ @return The number of bytes added if successful, or -1 if an error occurred.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_add_vprintf(struct evbuffer *buf, const char *fmt, va_list ap)
+#ifdef __GNUC__
+ __attribute__((format(printf, 2, 0)))
+#endif
+;
+
+
+/**
+ Remove a specified number of bytes data from the beginning of an evbuffer.
+
+ @param buf the evbuffer to be drained
+ @param len the number of bytes to drain from the beginning of the buffer
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_drain(struct evbuffer *buf, size_t len);
+
+
+/**
+ Write the contents of an evbuffer to a file descriptor.
+
+ The evbuffer will be drained after the bytes have been successfully written.
+
+ @param buffer the evbuffer to be written and drained
+ @param fd the file descriptor to be written to
+ @return the number of bytes written, or -1 if an error occurred
+ @see evbuffer_read()
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_write(struct evbuffer *buffer, evutil_socket_t fd);
+
+/**
+ Write some of the contents of an evbuffer to a file descriptor.
+
+ The evbuffer will be drained after the bytes have been successfully written.
+
+ @param buffer the evbuffer to be written and drained
+ @param fd the file descriptor to be written to
+ @param howmuch the largest allowable number of bytes to write, or -1
+ to write as many bytes as we can.
+ @return the number of bytes written, or -1 if an error occurred
+ @see evbuffer_read()
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_write_atmost(struct evbuffer *buffer, evutil_socket_t fd,
+ ev_ssize_t howmuch);
+
+/**
+ Read from a file descriptor and store the result in an evbuffer.
+
+ @param buffer the evbuffer to store the result
+ @param fd the file descriptor to read from
+ @param howmuch the number of bytes to be read. If the given number is negative
+ or out of maximum bytes per one read, as many bytes as we can will be read.
+ @return the number of bytes read, or -1 if an error occurred
+ @see evbuffer_write()
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_read(struct evbuffer *buffer, evutil_socket_t fd, int howmuch);
+
+/**
+ Search for a string within an evbuffer.
+
+ @param buffer the evbuffer to be searched
+ @param what the string to be searched for
+ @param len the length of the search string
+ @param start NULL or a pointer to a valid struct evbuffer_ptr.
+ @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+ first occurrence of the string in the buffer after 'start'. The 'pos'
+ field of the result is -1 if the string was not found.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer_ptr evbuffer_search(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start);
+
+/**
+ Search for a string within part of an evbuffer.
+
+ @param buffer the evbuffer to be searched
+ @param what the string to be searched for
+ @param len the length of the search string
+ @param start NULL or a pointer to a valid struct evbuffer_ptr that
+ indicates where we should start searching.
+ @param end NULL or a pointer to a valid struct evbuffer_ptr that
+ indicates where we should stop searching.
+ @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+ first occurrence of the string in the buffer after 'start'. The 'pos'
+ field of the result is -1 if the string was not found.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer_ptr evbuffer_search_range(struct evbuffer *buffer, const char *what, size_t len, const struct evbuffer_ptr *start, const struct evbuffer_ptr *end);
+
+/**
+ Defines how to adjust an evbuffer_ptr by evbuffer_ptr_set()
+
+ @see evbuffer_ptr_set() */
+enum evbuffer_ptr_how {
+ /** Sets the pointer to the position; can be called on with an
+ uninitialized evbuffer_ptr. */
+ EVBUFFER_PTR_SET,
+ /** Advances the pointer by adding to the current position. */
+ EVBUFFER_PTR_ADD
+};
+
+/**
+ Sets the search pointer in the buffer to position.
+
+ There are two ways to use this function: you can call
+ evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_SET)
+ to move 'pos' to a position 'N' bytes after the start of the buffer, or
+ evbuffer_ptr_set(buf, &pos, N, EVBUFFER_PTR_ADD)
+ to move 'pos' forward by 'N' bytes.
+
+ If evbuffer_ptr is not initialized, this function can only be called
+ with EVBUFFER_PTR_SET.
+
+ An evbuffer_ptr can represent any position from the start of the buffer to
+ a position immediately after the end of the buffer.
+
+ @param buffer the evbuffer to be search
+ @param ptr a pointer to a struct evbuffer_ptr
+ @param position the position at which to start the next search
+ @param how determines how the pointer should be manipulated.
+ @returns 0 on success or -1 otherwise
+*/
+EVENT2_EXPORT_SYMBOL
+int
+evbuffer_ptr_set(struct evbuffer *buffer, struct evbuffer_ptr *ptr,
+ size_t position, enum evbuffer_ptr_how how);
+
+/**
+ Search for an end-of-line string within an evbuffer.
+
+ @param buffer the evbuffer to be searched
+ @param start NULL or a pointer to a valid struct evbuffer_ptr to start
+ searching at.
+ @param eol_len_out If non-NULL, the pointed-to value will be set to
+ the length of the end-of-line string.
+ @param eol_style The kind of EOL to look for; see evbuffer_readln() for
+ more information
+ @return a struct evbuffer_ptr whose 'pos' field has the offset of the
+ first occurrence EOL in the buffer after 'start'. The 'pos'
+ field of the result is -1 if the string was not found.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer_ptr evbuffer_search_eol(struct evbuffer *buffer,
+ struct evbuffer_ptr *start, size_t *eol_len_out,
+ enum evbuffer_eol_style eol_style);
+
+/** Function to peek at data inside an evbuffer without removing it or
+ copying it out.
+
+ Pointers to the data are returned by filling the 'vec_out' array
+ with pointers to one or more extents of data inside the buffer.
+
+ The total data in the extents that you get back may be more than
+ you requested (if there is more data last extent than you asked
+ for), or less (if you do not provide enough evbuffer_iovecs, or if
+ the buffer does not have as much data as you asked to see).
+
+ @param buffer the evbuffer to peek into,
+ @param len the number of bytes to try to peek. If len is negative, we
+ will try to fill as much of vec_out as we can. If len is negative
+ and vec_out is not provided, we return the number of evbuffer_iovecs
+ that would be needed to get all the data in the buffer.
+ @param start_at an evbuffer_ptr indicating the point at which we
+ should start looking for data. NULL means, "At the start of the
+ buffer."
+ @param vec_out an array of evbuffer_iovec
+ @param n_vec the length of vec_out. If 0, we only count how many
+ extents would be necessary to point to the requested amount of
+ data.
+ @return The number of extents needed. This may be less than n_vec
+ if we didn't need all the evbuffer_iovecs we were given, or more
+ than n_vec if we would need more to return all the data that was
+ requested.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_peek(struct evbuffer *buffer, ev_ssize_t len,
+ struct evbuffer_ptr *start_at,
+ struct evbuffer_iovec *vec_out, int n_vec);
+
+
+/** Structure passed to an evbuffer_cb_func evbuffer callback
+
+ @see evbuffer_cb_func, evbuffer_add_cb()
+ */
+struct evbuffer_cb_info {
+ /** The number of bytes in this evbuffer when callbacks were last
+ * invoked. */
+ size_t orig_size;
+ /** The number of bytes added since callbacks were last invoked. */
+ size_t n_added;
+ /** The number of bytes removed since callbacks were last invoked. */
+ size_t n_deleted;
+};
+
+/** Type definition for a callback that is invoked whenever data is added or
+ removed from an evbuffer.
+
+ An evbuffer may have one or more callbacks set at a time. The order
+ in which they are executed is undefined.
+
+ A callback function may add more callbacks, or remove itself from the
+ list of callbacks, or add or remove data from the buffer. It may not
+ remove another callback from the list.
+
+ If a callback adds or removes data from the buffer or from another
+ buffer, this can cause a recursive invocation of your callback or
+ other callbacks. If you ask for an infinite loop, you might just get
+ one: watch out!
+
+ @param buffer the buffer whose size has changed
+ @param info a structure describing how the buffer changed.
+ @param arg a pointer to user data
+*/
+typedef void (*evbuffer_cb_func)(struct evbuffer *buffer, const struct evbuffer_cb_info *info, void *arg);
+
+struct evbuffer_cb_entry;
+/** Add a new callback to an evbuffer.
+
+ Subsequent calls to evbuffer_add_cb() add new callbacks. To remove this
+ callback, call evbuffer_remove_cb or evbuffer_remove_cb_entry.
+
+ @param buffer the evbuffer to be monitored
+ @param cb the callback function to invoke when the evbuffer is modified,
+ or NULL to remove all callbacks.
+ @param cbarg an argument to be provided to the callback function
+ @return a handle to the callback on success, or NULL on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer_cb_entry *evbuffer_add_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
+
+/** Remove a callback from an evbuffer, given a handle returned from
+ evbuffer_add_cb.
+
+ Calling this function invalidates the handle.
+
+ @return 0 if a callback was removed, or -1 if no matching callback was
+ found.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_remove_cb_entry(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *ent);
+
+/** Remove a callback from an evbuffer, given the function and argument
+ used to add it.
+
+ @return 0 if a callback was removed, or -1 if no matching callback was
+ found.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_remove_cb(struct evbuffer *buffer, evbuffer_cb_func cb, void *cbarg);
+
+/** If this flag is not set, then a callback is temporarily disabled, and
+ * should not be invoked.
+ *
+ * @see evbuffer_cb_set_flags(), evbuffer_cb_clear_flags()
+ */
+#define EVBUFFER_CB_ENABLED 1
+
+/** Change the flags that are set for a callback on a buffer by adding more.
+
+ @param buffer the evbuffer that the callback is watching.
+ @param cb the callback whose status we want to change.
+ @param flags EVBUFFER_CB_ENABLED to re-enable the callback.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_cb_set_flags(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *cb, ev_uint32_t flags);
+
+/** Change the flags that are set for a callback on a buffer by removing some
+
+ @param buffer the evbuffer that the callback is watching.
+ @param cb the callback whose status we want to change.
+ @param flags EVBUFFER_CB_ENABLED to disable the callback.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_cb_clear_flags(struct evbuffer *buffer,
+ struct evbuffer_cb_entry *cb, ev_uint32_t flags);
+
+#if 0
+/** Postpone calling a given callback until unsuspend is called later.
+
+ This is different from disabling the callback, since the callback will get
+ invoked later if the buffer size changes between now and when we unsuspend
+ it.
+
+ @param the buffer that the callback is watching.
+ @param cb the callback we want to suspend.
+ */
+EVENT2_EXPORT_SYMBOL
+void evbuffer_cb_suspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
+/** Stop postponing a callback that we postponed with evbuffer_cb_suspend.
+
+ If data was added to or removed from the buffer while the callback was
+ suspended, the callback will get called once now.
+
+ @param the buffer that the callback is watching.
+ @param cb the callback we want to stop suspending.
+ */
+EVENT2_EXPORT_SYMBOL
+void evbuffer_cb_unsuspend(struct evbuffer *buffer, struct evbuffer_cb_entry *cb);
+#endif
+
+/**
+ Makes the data at the beginning of an evbuffer contiguous.
+
+ @param buf the evbuffer to make contiguous
+ @param size the number of bytes to make contiguous, or -1 to make the
+ entire buffer contiguous.
+ @return a pointer to the contiguous memory array, or NULL if param size
+ requested more data than is present in the buffer.
+*/
+
+EVENT2_EXPORT_SYMBOL
+unsigned char *evbuffer_pullup(struct evbuffer *buf, ev_ssize_t size);
+
+/**
+ Prepends data to the beginning of the evbuffer
+
+ @param buf the evbuffer to which to prepend data
+ @param data a pointer to the memory to prepend
+ @param size the number of bytes to prepend
+ @return 0 if successful, or -1 otherwise
+*/
+
+EVENT2_EXPORT_SYMBOL
+int evbuffer_prepend(struct evbuffer *buf, const void *data, size_t size);
+
+/**
+ Prepends all data from the src evbuffer to the beginning of the dst
+ evbuffer.
+
+ @param dst the evbuffer to which to prepend data
+ @param src the evbuffer to prepend; it will be emptied as a result
+ @return 0 if successful, or -1 otherwise
+*/
+EVENT2_EXPORT_SYMBOL
+int evbuffer_prepend_buffer(struct evbuffer *dst, struct evbuffer* src);
+
+/**
+ Prevent calls that modify an evbuffer from succeeding. A buffer may
+ frozen at the front, at the back, or at both the front and the back.
+
+ If the front of a buffer is frozen, operations that drain data from
+ the front of the buffer, or that prepend data to the buffer, will
+ fail until it is unfrozen. If the back a buffer is frozen, operations
+ that append data from the buffer will fail until it is unfrozen.
+
+ @param buf The buffer to freeze
+ @param at_front If true, we freeze the front of the buffer. If false,
+ we freeze the back.
+ @return 0 on success, -1 on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+int evbuffer_freeze(struct evbuffer *buf, int at_front);
+/**
+ Re-enable calls that modify an evbuffer.
+
+ @param buf The buffer to un-freeze
+ @param at_front If true, we unfreeze the front of the buffer. If false,
+ we unfreeze the back.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_unfreeze(struct evbuffer *buf, int at_front);
+
+struct event_base;
+/**
+ Force all the callbacks on an evbuffer to be run, not immediately after
+ the evbuffer is altered, but instead from inside the event loop.
+
+ This can be used to serialize all the callbacks to a single thread
+ of execution.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_defer_callbacks(struct evbuffer *buffer, struct event_base *base);
+
+/**
+ Append data from 1 or more iovec's to an evbuffer
+
+ Calculates the number of bytes needed for an iovec structure and guarantees
+ all data will fit into a single chain. Can be used in lieu of functionality
+ which calls evbuffer_add() constantly before being used to increase
+ performance.
+
+ @param buffer the destination buffer
+ @param vec the source iovec
+ @param n_vec the number of iovec structures.
+ @return the number of bytes successfully written to the output buffer.
+*/
+EVENT2_EXPORT_SYMBOL
+size_t evbuffer_add_iovec(struct evbuffer * buffer, struct evbuffer_iovec * vec, int n_vec);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_BUFFER_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/buffer_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/buffer_compat.h
new file mode 100644
index 0000000000..0ce1025448
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/buffer_compat.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef EVENT2_BUFFER_COMPAT_H_INCLUDED_
+#define EVENT2_BUFFER_COMPAT_H_INCLUDED_
+
+#include <event2/visibility.h>
+
+/** @file event2/buffer_compat.h
+
+ Obsolete and deprecated versions of the functions in buffer.h: provided
+ only for backward compatibility.
+ */
+
+
+/**
+ Obsolete alias for evbuffer_readln(buffer, NULL, EVBUFFER_EOL_ANY).
+
+ @deprecated This function is deprecated because its behavior is not correct
+ for almost any protocol, and also because it's wholly subsumed by
+ evbuffer_readln().
+
+ @param buffer the evbuffer to read from
+ @return pointer to a single line, or NULL if an error occurred
+
+*/
+EVENT2_EXPORT_SYMBOL
+char *evbuffer_readline(struct evbuffer *buffer);
+
+/** Type definition for a callback that is invoked whenever data is added or
+ removed from an evbuffer.
+
+ An evbuffer may have one or more callbacks set at a time. The order
+ in which they are executed is undefined.
+
+ A callback function may add more callbacks, or remove itself from the
+ list of callbacks, or add or remove data from the buffer. It may not
+ remove another callback from the list.
+
+ If a callback adds or removes data from the buffer or from another
+ buffer, this can cause a recursive invocation of your callback or
+ other callbacks. If you ask for an infinite loop, you might just get
+ one: watch out!
+
+ @param buffer the buffer whose size has changed
+ @param old_len the previous length of the buffer
+ @param new_len the current length of the buffer
+ @param arg a pointer to user data
+*/
+typedef void (*evbuffer_cb)(struct evbuffer *buffer, size_t old_len, size_t new_len, void *arg);
+
+/**
+ Replace all callbacks on an evbuffer with a single new callback, or
+ remove them.
+
+ Subsequent calls to evbuffer_setcb() replace callbacks set by previous
+ calls. Setting the callback to NULL removes any previously set callback.
+
+ @deprecated This function is deprecated because it clears all previous
+ callbacks set on the evbuffer, which can cause confusing behavior if
+ multiple parts of the code all want to add their own callbacks on a
+ buffer. Instead, use evbuffer_add(), evbuffer_del(), and
+ evbuffer_setflags() to manage your own evbuffer callbacks without
+ interfering with callbacks set by others.
+
+ @param buffer the evbuffer to be monitored
+ @param cb the callback function to invoke when the evbuffer is modified,
+ or NULL to remove all callbacks.
+ @param cbarg an argument to be provided to the callback function
+ @return 0 if successful, or -1 on error
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_setcb(struct evbuffer *buffer, evbuffer_cb cb, void *cbarg);
+
+
+/**
+ Find a string within an evbuffer.
+
+ @param buffer the evbuffer to be searched
+ @param what the string to be searched for
+ @param len the length of the search string
+ @return a pointer to the beginning of the search string, or NULL if the search failed.
+ */
+EVENT2_EXPORT_SYMBOL
+unsigned char *evbuffer_find(struct evbuffer *buffer, const unsigned char *what, size_t len);
+
+/** deprecated in favor of calling the functions directly */
+#define EVBUFFER_LENGTH(x) evbuffer_get_length(x)
+/** deprecated in favor of calling the functions directly */
+#define EVBUFFER_DATA(x) evbuffer_pullup((x), -1)
+
+#endif
+
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/bufferevent.h b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent.h
new file mode 100644
index 0000000000..48cd153563
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent.h
@@ -0,0 +1,1024 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_BUFFEREVENT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_H_INCLUDED_
+
+/**
+ @file event2/bufferevent.h
+
+ Functions for buffering data for network sending or receiving. Bufferevents
+ are higher level than evbuffers: each has an underlying evbuffer for reading
+ and one for writing, and callbacks that are invoked under certain
+ circumstances.
+
+ A bufferevent provides input and output buffers that get filled and
+ drained automatically. The user of a bufferevent no longer deals
+ directly with the I/O, but instead is reading from input and writing
+ to output buffers.
+
+ Once initialized, the bufferevent structure can be used repeatedly
+ with bufferevent_enable() and bufferevent_disable().
+
+ When reading is enabled, the bufferevent will try to read from the
+ file descriptor onto its input buffer, and call the read callback.
+ When writing is enabled, the bufferevent will try to write data onto its
+ file descriptor when the output buffer has enough data, and call the write
+ callback when the output buffer is sufficiently drained.
+
+ Bufferevents come in several flavors, including:
+
+ <dl>
+ <dt>Socket-based bufferevents</dt>
+ <dd>A bufferevent that reads and writes data onto a network
+ socket. Created with bufferevent_socket_new().</dd>
+
+ <dt>Paired bufferevents</dt>
+ <dd>A pair of bufferevents that send and receive data to one
+ another without touching the network. Created with
+ bufferevent_pair_new().</dd>
+
+ <dt>Filtering bufferevents</dt>
+ <dd>A bufferevent that transforms data, and sends or receives it
+ over another underlying bufferevent. Created with
+ bufferevent_filter_new().</dd>
+
+ <dt>SSL-backed bufferevents</dt>
+ <dd>A bufferevent that uses the openssl library to send and
+ receive data over an encrypted connection. Created with
+ bufferevent_openssl_socket_new() or
+ bufferevent_openssl_filter_new().</dd>
+ </dl>
+ */
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/** @name Bufferevent event codes
+
+ These flags are passed as arguments to a bufferevent's event callback.
+
+ @{
+*/
+#define BEV_EVENT_READING 0x01 /**< error encountered while reading */
+#define BEV_EVENT_WRITING 0x02 /**< error encountered while writing */
+#define BEV_EVENT_EOF 0x10 /**< eof file reached */
+#define BEV_EVENT_ERROR 0x20 /**< unrecoverable error encountered */
+#define BEV_EVENT_TIMEOUT 0x40 /**< user-specified timeout reached */
+#define BEV_EVENT_CONNECTED 0x80 /**< connect operation finished. */
+/**@}*/
+
+/**
+ An opaque type for handling buffered IO
+
+ @see event2/bufferevent.h
+ */
+struct bufferevent
+#ifdef EVENT_IN_DOXYGEN_
+{}
+#endif
+;
+struct event_base;
+struct evbuffer;
+struct sockaddr;
+
+/**
+ A read or write callback for a bufferevent.
+
+ The read callback is triggered when new data arrives in the input
+ buffer and the amount of readable data exceed the low watermark
+ which is 0 by default.
+
+ The write callback is triggered if the write buffer has been
+ exhausted or fell below its low watermark.
+
+ @param bev the bufferevent that triggered the callback
+ @param ctx the user-specified context for this bufferevent
+ */
+typedef void (*bufferevent_data_cb)(struct bufferevent *bev, void *ctx);
+
+/**
+ An event/error callback for a bufferevent.
+
+ The event callback is triggered if either an EOF condition or another
+ unrecoverable error was encountered.
+
+ For bufferevents with deferred callbacks, this is a bitwise OR of all errors
+ that have happened on the bufferevent since the last callback invocation.
+
+ @param bev the bufferevent for which the error condition was reached
+ @param what a conjunction of flags: BEV_EVENT_READING or BEV_EVENT_WRITING
+ to indicate if the error was encountered on the read or write path,
+ and one of the following flags: BEV_EVENT_EOF, BEV_EVENT_ERROR,
+ BEV_EVENT_TIMEOUT, BEV_EVENT_CONNECTED.
+
+ @param ctx the user-specified context for this bufferevent
+*/
+typedef void (*bufferevent_event_cb)(struct bufferevent *bev, short what, void *ctx);
+
+/** Options that can be specified when creating a bufferevent */
+enum bufferevent_options {
+ /** If set, we close the underlying file
+ * descriptor/bufferevent/whatever when this bufferevent is freed. */
+ BEV_OPT_CLOSE_ON_FREE = (1<<0),
+
+ /** If set, and threading is enabled, operations on this bufferevent
+ * are protected by a lock */
+ BEV_OPT_THREADSAFE = (1<<1),
+
+ /** If set, callbacks are run deferred in the event loop. */
+ BEV_OPT_DEFER_CALLBACKS = (1<<2),
+
+ /** If set, callbacks are executed without locks being held on the
+ * bufferevent. This option currently requires that
+ * BEV_OPT_DEFER_CALLBACKS also be set; a future version of Libevent
+ * might remove the requirement.*/
+ BEV_OPT_UNLOCK_CALLBACKS = (1<<3)
+};
+
+/**
+ Create a new socket bufferevent over an existing socket.
+
+ @param base the event base to associate with the new bufferevent.
+ @param fd the file descriptor from which data is read and written to.
+ This file descriptor is not allowed to be a pipe(2).
+ It is safe to set the fd to -1, so long as you later
+ set it with bufferevent_setfd or bufferevent_socket_connect().
+ @param options Zero or more BEV_OPT_* flags
+ @return a pointer to a newly allocated bufferevent struct, or NULL if an
+ error occurred
+ @see bufferevent_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *bufferevent_socket_new(struct event_base *base, evutil_socket_t fd, int options);
+
+/**
+ Launch a connect() attempt with a socket-based bufferevent.
+
+ When the connect succeeds, the eventcb will be invoked with
+ BEV_EVENT_CONNECTED set.
+
+ If the bufferevent does not already have a socket set, we allocate a new
+ socket here and make it nonblocking before we begin.
+
+ If no address is provided, we assume that the socket is already connecting,
+ and configure the bufferevent so that a BEV_EVENT_CONNECTED event will be
+ yielded when it is done connecting.
+
+ @param bufev an existing bufferevent allocated with
+ bufferevent_socket_new().
+ @param addr the address we should connect to
+ @param socklen The length of the address
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_socket_connect(struct bufferevent *, const struct sockaddr *, int);
+
+struct evdns_base;
+/**
+ Resolve the hostname 'hostname' and connect to it as with
+ bufferevent_socket_connect().
+
+ @param bufev An existing bufferevent allocated with bufferevent_socket_new()
+ @param evdns_base Optionally, an evdns_base to use for resolving hostnames
+ asynchronously. May be set to NULL for a blocking resolve.
+ @param family A preferred address family to resolve addresses to, or
+ AF_UNSPEC for no preference. Only AF_INET, AF_INET6, and AF_UNSPEC are
+ supported.
+ @param hostname The hostname to resolve; see below for notes on recognized
+ formats
+ @param port The port to connect to on the resolved address.
+ @return 0 if successful, -1 on failure.
+
+ Recognized hostname formats are:
+
+ www.example.com (hostname)
+ 1.2.3.4 (ipv4address)
+ ::1 (ipv6address)
+ [::1] ([ipv6address])
+
+ Performance note: If you do not provide an evdns_base, this function
+ may block while it waits for a DNS response. This is probably not
+ what you want.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_socket_connect_hostname(struct bufferevent *,
+ struct evdns_base *, int, const char *, int);
+
+/**
+ Return the error code for the last failed DNS lookup attempt made by
+ bufferevent_socket_connect_hostname().
+
+ @param bev The bufferevent object.
+ @return DNS error code.
+ @see evutil_gai_strerror()
+*/
+EVENT2_EXPORT_SYMBOL
+int bufferevent_socket_get_dns_error(struct bufferevent *bev);
+
+/**
+ Assign a bufferevent to a specific event_base.
+
+ NOTE that only socket bufferevents support this function.
+
+ @param base an event_base returned by event_init()
+ @param bufev a bufferevent struct returned by bufferevent_new()
+ or bufferevent_socket_new()
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_new()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_base_set(struct event_base *base, struct bufferevent *bufev);
+
+/**
+ Return the event_base used by a bufferevent
+*/
+EVENT2_EXPORT_SYMBOL
+struct event_base *bufferevent_get_base(struct bufferevent *bev);
+
+/**
+ Assign a priority to a bufferevent.
+
+ Only supported for socket bufferevents.
+
+ @param bufev a bufferevent struct
+ @param pri the priority to be assigned
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_priority_set(struct bufferevent *bufev, int pri);
+
+/**
+ Return the priority of a bufferevent.
+
+ Only supported for socket bufferevents
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_get_priority(const struct bufferevent *bufev);
+
+/**
+ Deallocate the storage associated with a bufferevent structure.
+
+ If there is pending data to write on the bufferevent, it probably won't be
+ flushed before the bufferevent is freed.
+
+ @param bufev the bufferevent structure to be freed.
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_free(struct bufferevent *bufev);
+
+
+/**
+ Changes the callbacks for a bufferevent.
+
+ @param bufev the bufferevent object for which to change callbacks
+ @param readcb callback to invoke when there is data to be read, or NULL if
+ no callback is desired
+ @param writecb callback to invoke when the file descriptor is ready for
+ writing, or NULL if no callback is desired
+ @param eventcb callback to invoke when there is an event on the file
+ descriptor
+ @param cbarg an argument that will be supplied to each of the callbacks
+ (readcb, writecb, and errorcb)
+ @see bufferevent_new()
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_setcb(struct bufferevent *bufev,
+ bufferevent_data_cb readcb, bufferevent_data_cb writecb,
+ bufferevent_event_cb eventcb, void *cbarg);
+
+/**
+ Retrieves the callbacks for a bufferevent.
+
+ @param bufev the bufferevent to examine.
+ @param readcb_ptr if readcb_ptr is nonnull, *readcb_ptr is set to the current
+ read callback for the bufferevent.
+ @param writecb_ptr if writecb_ptr is nonnull, *writecb_ptr is set to the
+ current write callback for the bufferevent.
+ @param eventcb_ptr if eventcb_ptr is nonnull, *eventcb_ptr is set to the
+ current event callback for the bufferevent.
+ @param cbarg_ptr if cbarg_ptr is nonnull, *cbarg_ptr is set to the current
+ callback argument for the bufferevent.
+ @see buffervent_setcb()
+*/
+EVENT2_EXPORT_SYMBOL
+void bufferevent_getcb(struct bufferevent *bufev,
+ bufferevent_data_cb *readcb_ptr,
+ bufferevent_data_cb *writecb_ptr,
+ bufferevent_event_cb *eventcb_ptr,
+ void **cbarg_ptr);
+
+/**
+ Changes the file descriptor on which the bufferevent operates.
+ Not supported for all bufferevent types.
+
+ @param bufev the bufferevent object for which to change the file descriptor
+ @param fd the file descriptor to operate on
+*/
+EVENT2_EXPORT_SYMBOL
+int bufferevent_setfd(struct bufferevent *bufev, evutil_socket_t fd);
+
+/**
+ Returns the file descriptor associated with a bufferevent, or -1 if
+ no file descriptor is associated with the bufferevent.
+ */
+EVENT2_EXPORT_SYMBOL
+evutil_socket_t bufferevent_getfd(struct bufferevent *bufev);
+
+/**
+ Returns the underlying bufferevent associated with a bufferevent (if
+ the bufferevent is a wrapper), or NULL if there is no underlying bufferevent.
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *bufferevent_get_underlying(struct bufferevent *bufev);
+
+/**
+ Write data to a bufferevent buffer.
+
+ The bufferevent_write() function can be used to write data to the file
+ descriptor. The data is appended to the output buffer and written to the
+ descriptor automatically as it becomes available for writing.
+
+ @param bufev the bufferevent to be written to
+ @param data a pointer to the data to be written
+ @param size the length of the data, in bytes
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_write_buffer()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_write(struct bufferevent *bufev,
+ const void *data, size_t size);
+
+
+/**
+ Write data from an evbuffer to a bufferevent buffer. The evbuffer is
+ being drained as a result.
+
+ @param bufev the bufferevent to be written to
+ @param buf the evbuffer to be written
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_write()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_write_buffer(struct bufferevent *bufev, struct evbuffer *buf);
+
+
+/**
+ Read data from a bufferevent buffer.
+
+ The bufferevent_read() function is used to read data from the input buffer.
+
+ @param bufev the bufferevent to be read from
+ @param data pointer to a buffer that will store the data
+ @param size the size of the data buffer, in bytes
+ @return the amount of data read, in bytes.
+ */
+EVENT2_EXPORT_SYMBOL
+size_t bufferevent_read(struct bufferevent *bufev, void *data, size_t size);
+
+/**
+ Read data from a bufferevent buffer into an evbuffer. This avoids
+ memory copies.
+
+ @param bufev the bufferevent to be read from
+ @param buf the evbuffer to which to add data
+ @return 0 if successful, or -1 if an error occurred.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_read_buffer(struct bufferevent *bufev, struct evbuffer *buf);
+
+/**
+ Returns the input buffer.
+
+ The user MUST NOT set the callback on this buffer.
+
+ @param bufev the bufferevent from which to get the evbuffer
+ @return the evbuffer object for the input buffer
+ */
+
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *bufferevent_get_input(struct bufferevent *bufev);
+
+/**
+ Returns the output buffer.
+
+ The user MUST NOT set the callback on this buffer.
+
+ When filters are being used, the filters need to be manually
+ triggered if the output buffer was manipulated.
+
+ @param bufev the bufferevent from which to get the evbuffer
+ @return the evbuffer object for the output buffer
+ */
+
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *bufferevent_get_output(struct bufferevent *bufev);
+
+/**
+ Enable a bufferevent.
+
+ @param bufev the bufferevent to be enabled
+ @param event any combination of EV_READ | EV_WRITE.
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_disable()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_enable(struct bufferevent *bufev, short event);
+
+/**
+ Disable a bufferevent.
+
+ @param bufev the bufferevent to be disabled
+ @param event any combination of EV_READ | EV_WRITE.
+ @return 0 if successful, or -1 if an error occurred
+ @see bufferevent_enable()
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_disable(struct bufferevent *bufev, short event);
+
+/**
+ Return the events that are enabled on a given bufferevent.
+
+ @param bufev the bufferevent to inspect
+ @return A combination of EV_READ | EV_WRITE
+ */
+EVENT2_EXPORT_SYMBOL
+short bufferevent_get_enabled(struct bufferevent *bufev);
+
+/**
+ Set the read and write timeout for a bufferevent.
+
+ A bufferevent's timeout will fire the first time that the indicated
+ amount of time has elapsed since a successful read or write operation,
+ during which the bufferevent was trying to read or write.
+
+ (In other words, if reading or writing is disabled, or if the
+ bufferevent's read or write operation has been suspended because
+ there's no data to write, or not enough bandwidth, or so on, the
+ timeout isn't active. The timeout only becomes active when we we're
+ willing to actually read or write.)
+
+ Calling bufferevent_enable or setting a timeout for a bufferevent
+ whose timeout is already pending resets its timeout.
+
+ If the timeout elapses, the corresponding operation (EV_READ or
+ EV_WRITE) becomes disabled until you re-enable it again. The
+ bufferevent's event callback is called with the
+ BEV_EVENT_TIMEOUT|BEV_EVENT_READING or
+ BEV_EVENT_TIMEOUT|BEV_EVENT_WRITING.
+
+ @param bufev the bufferevent to be modified
+ @param timeout_read the read timeout, or NULL
+ @param timeout_write the write timeout, or NULL
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_set_timeouts(struct bufferevent *bufev,
+ const struct timeval *timeout_read, const struct timeval *timeout_write);
+
+/**
+ Sets the watermarks for read and write events.
+
+ On input, a bufferevent does not invoke the user read callback unless
+ there is at least low watermark data in the buffer. If the read buffer
+ is beyond the high watermark, the bufferevent stops reading from the network.
+ But be aware that bufferevent input/read buffer can overrun high watermark
+ limit (typical example is openssl bufferevent), so you should not relay in
+ this.
+
+ On output, the user write callback is invoked whenever the buffered data
+ falls below the low watermark. Filters that write to this bufev will try
+ not to write more bytes to this buffer than the high watermark would allow,
+ except when flushing.
+
+ @param bufev the bufferevent to be modified
+ @param events EV_READ, EV_WRITE or both
+ @param lowmark the lower watermark to set
+ @param highmark the high watermark to set
+*/
+
+EVENT2_EXPORT_SYMBOL
+void bufferevent_setwatermark(struct bufferevent *bufev, short events,
+ size_t lowmark, size_t highmark);
+
+/**
+ Retrieves the watermarks for read or write events.
+ Returns non-zero if events contains not only EV_READ or EV_WRITE.
+ Returns zero if events equal EV_READ or EV_WRITE
+
+ @param bufev the bufferevent to be examined
+ @param events EV_READ or EV_WRITE
+ @param lowmark receives the lower watermark if not NULL
+ @param highmark receives the high watermark if not NULL
+*/
+EVENT2_EXPORT_SYMBOL
+int bufferevent_getwatermark(struct bufferevent *bufev, short events,
+ size_t *lowmark, size_t *highmark);
+
+/**
+ Acquire the lock on a bufferevent. Has no effect if locking was not
+ enabled with BEV_OPT_THREADSAFE.
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_lock(struct bufferevent *bufev);
+
+/**
+ Release the lock on a bufferevent. Has no effect if locking was not
+ enabled with BEV_OPT_THREADSAFE.
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_unlock(struct bufferevent *bufev);
+
+
+/**
+ * Public interface to manually increase the reference count of a bufferevent
+ * this is useful in situations where a user may reference the bufferevent
+ * somewhere else (unknown to libevent)
+ *
+ * @param bufev the bufferevent to increase the refcount on
+ *
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_incref(struct bufferevent *bufev);
+
+/**
+ * Public interface to manually decrement the reference count of a bufferevent
+ *
+ * Warning: make sure you know what you're doing. This is mainly used in
+ * conjunction with bufferevent_incref(). This will free up all data associated
+ * with a bufferevent if the reference count hits 0.
+ *
+ * @param bufev the bufferevent to decrement the refcount on
+ *
+ * @return 1 if the bufferevent was freed, otherwise 0 (still referenced)
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decref(struct bufferevent *bufev);
+
+/**
+ Flags that can be passed into filters to let them know how to
+ deal with the incoming data.
+*/
+enum bufferevent_flush_mode {
+ /** usually set when processing data */
+ BEV_NORMAL = 0,
+
+ /** want to checkpoint all data sent. */
+ BEV_FLUSH = 1,
+
+ /** encountered EOF on read or done sending data */
+ BEV_FINISHED = 2
+};
+
+/**
+ Triggers the bufferevent to produce more data if possible.
+
+ @param bufev the bufferevent object
+ @param iotype either EV_READ or EV_WRITE or both.
+ @param mode either BEV_NORMAL or BEV_FLUSH or BEV_FINISHED
+ @return -1 on failure, 0 if no data was produces, 1 if data was produced
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_flush(struct bufferevent *bufev,
+ short iotype,
+ enum bufferevent_flush_mode mode);
+
+/**
+ Flags for bufferevent_trigger(_event) that modify when and how to trigger
+ the callback.
+*/
+enum bufferevent_trigger_options {
+ /** trigger the callback regardless of the watermarks */
+ BEV_TRIG_IGNORE_WATERMARKS = (1<<16),
+
+ /** defer even if the callbacks are not */
+ BEV_TRIG_DEFER_CALLBACKS = BEV_OPT_DEFER_CALLBACKS
+
+ /* (Note: for internal reasons, these need to be disjoint from
+ * bufferevent_options, except when they mean the same thing. */
+};
+
+/**
+ Triggers bufferevent data callbacks.
+
+ The function will honor watermarks unless options contain
+ BEV_TRIG_IGNORE_WATERMARKS. If the options contain BEV_OPT_DEFER_CALLBACKS,
+ the callbacks are deferred.
+
+ @param bufev the bufferevent object
+ @param iotype either EV_READ or EV_WRITE or both.
+ @param options
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_trigger(struct bufferevent *bufev, short iotype,
+ int options);
+
+/**
+ Triggers the bufferevent event callback.
+
+ If the options contain BEV_OPT_DEFER_CALLBACKS, the callbacks are deferred.
+
+ @param bufev the bufferevent object
+ @param what the flags to pass onto the event callback
+ @param options
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_trigger_event(struct bufferevent *bufev, short what,
+ int options);
+
+/**
+ @name Filtering support
+
+ @{
+*/
+/**
+ Values that filters can return.
+ */
+enum bufferevent_filter_result {
+ /** everything is okay */
+ BEV_OK = 0,
+
+ /** the filter needs to read more data before output */
+ BEV_NEED_MORE = 1,
+
+ /** the filter encountered a critical error, no further data
+ can be processed. */
+ BEV_ERROR = 2
+};
+
+/** A callback function to implement a filter for a bufferevent.
+
+ @param src An evbuffer to drain data from.
+ @param dst An evbuffer to add data to.
+ @param limit A suggested upper bound of bytes to write to dst.
+ The filter may ignore this value, but doing so means that
+ it will overflow the high-water mark associated with dst.
+ -1 means "no limit".
+ @param mode Whether we should write data as may be convenient
+ (BEV_NORMAL), or flush as much data as we can (BEV_FLUSH),
+ or flush as much as we can, possibly including an end-of-stream
+ marker (BEV_FINISH).
+ @param ctx A user-supplied pointer.
+
+ @return BEV_OK if we wrote some data; BEV_NEED_MORE if we can't
+ produce any more output until we get some input; and BEV_ERROR
+ on an error.
+ */
+typedef enum bufferevent_filter_result (*bufferevent_filter_cb)(
+ struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit,
+ enum bufferevent_flush_mode mode, void *ctx);
+
+/**
+ Allocate a new filtering bufferevent on top of an existing bufferevent.
+
+ @param underlying the underlying bufferevent.
+ @param input_filter The filter to apply to data we read from the underlying
+ bufferevent
+ @param output_filter The filer to apply to data we write to the underlying
+ bufferevent
+ @param options A bitfield of bufferevent options.
+ @param free_context A function to use to free the filter context when
+ this bufferevent is freed.
+ @param ctx A context pointer to pass to the filter functions.
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *
+bufferevent_filter_new(struct bufferevent *underlying,
+ bufferevent_filter_cb input_filter,
+ bufferevent_filter_cb output_filter,
+ int options,
+ void (*free_context)(void *),
+ void *ctx);
+/**@}*/
+
+/**
+ Allocate a pair of linked bufferevents. The bufferevents behave as would
+ two bufferevent_sock instances connected to opposite ends of a
+ socketpair(), except that no internal socketpair is allocated.
+
+ @param base The event base to associate with the socketpair.
+ @param options A set of options for this bufferevent
+ @param pair A pointer to an array to hold the two new bufferevent objects.
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_pair_new(struct event_base *base, int options,
+ struct bufferevent *pair[2]);
+
+/**
+ Given one bufferevent returned by bufferevent_pair_new(), returns the
+ other one if it still exists. Otherwise returns NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *bufferevent_pair_get_partner(struct bufferevent *bev);
+
+/**
+ Abstract type used to configure rate-limiting on a bufferevent or a group
+ of bufferevents.
+ */
+struct ev_token_bucket_cfg;
+
+/**
+ A group of bufferevents which are configured to respect the same rate
+ limit.
+*/
+struct bufferevent_rate_limit_group;
+
+/** Maximum configurable rate- or burst-limit. */
+#define EV_RATE_LIMIT_MAX EV_SSIZE_MAX
+
+/**
+ Initialize and return a new object to configure the rate-limiting behavior
+ of bufferevents.
+
+ @param read_rate The maximum number of bytes to read per tick on
+ average.
+ @param read_burst The maximum number of bytes to read in any single tick.
+ @param write_rate The maximum number of bytes to write per tick on
+ average.
+ @param write_burst The maximum number of bytes to write in any single tick.
+ @param tick_len The length of a single tick. Defaults to one second.
+ Any fractions of a millisecond are ignored.
+
+ Note that all rate-limits hare are currently best-effort: future versions
+ of Libevent may implement them more tightly.
+ */
+EVENT2_EXPORT_SYMBOL
+struct ev_token_bucket_cfg *ev_token_bucket_cfg_new(
+ size_t read_rate, size_t read_burst,
+ size_t write_rate, size_t write_burst,
+ const struct timeval *tick_len);
+
+/** Free all storage held in 'cfg'.
+
+ Note: 'cfg' is not currently reference-counted; it is not safe to free it
+ until no bufferevent is using it.
+ */
+EVENT2_EXPORT_SYMBOL
+void ev_token_bucket_cfg_free(struct ev_token_bucket_cfg *cfg);
+
+/**
+ Set the rate-limit of a the bufferevent 'bev' to the one specified in
+ 'cfg'. If 'cfg' is NULL, disable any per-bufferevent rate-limiting on
+ 'bev'.
+
+ Note that only some bufferevent types currently respect rate-limiting.
+ They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
+ bufferevents.
+
+ Return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_set_rate_limit(struct bufferevent *bev,
+ struct ev_token_bucket_cfg *cfg);
+
+/**
+ Create a new rate-limit group for bufferevents. A rate-limit group
+ constrains the maximum number of bytes sent and received, in toto,
+ by all of its bufferevents.
+
+ @param base An event_base to run any necessary timeouts for the group.
+ Note that all bufferevents in the group do not necessarily need to share
+ this event_base.
+ @param cfg The rate-limit for this group.
+
+ Note that all rate-limits hare are currently best-effort: future versions
+ of Libevent may implement them more tightly.
+
+ Note also that only some bufferevent types currently respect rate-limiting.
+ They are: socket-based bufferevents (normal and IOCP-based), and SSL-based
+ bufferevents.
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent_rate_limit_group *bufferevent_rate_limit_group_new(
+ struct event_base *base,
+ const struct ev_token_bucket_cfg *cfg);
+/**
+ Change the rate-limiting settings for a given rate-limiting group.
+
+ Return 0 on success, -1 on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+int bufferevent_rate_limit_group_set_cfg(
+ struct bufferevent_rate_limit_group *,
+ const struct ev_token_bucket_cfg *);
+
+/**
+ Change the smallest quantum we're willing to allocate to any single
+ bufferevent in a group for reading or writing at a time.
+
+ The rationale is that, because of TCP/IP protocol overheads and kernel
+ behavior, if a rate-limiting group is so tight on bandwidth that you're
+ only willing to send 1 byte per tick per bufferevent, you might instead
+ want to batch up the reads and writes so that you send N bytes per
+ 1/N of the bufferevents (chosen at random) each tick, so you still wind
+ up send 1 byte per tick per bufferevent on average, but you don't send
+ so many tiny packets.
+
+ The default min-share is currently 64 bytes.
+
+ Returns 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_rate_limit_group_set_min_share(
+ struct bufferevent_rate_limit_group *, size_t);
+
+/**
+ Free a rate-limiting group. The group must have no members when
+ this function is called.
+*/
+EVENT2_EXPORT_SYMBOL
+void bufferevent_rate_limit_group_free(struct bufferevent_rate_limit_group *);
+
+/**
+ Add 'bev' to the list of bufferevents whose aggregate reading and writing
+ is restricted by 'g'. If 'g' is NULL, remove 'bev' from its current group.
+
+ A bufferevent may belong to no more than one rate-limit group at a time.
+ If 'bev' is already a member of a group, it will be removed from its old
+ group before being added to 'g'.
+
+ Return 0 on success and -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_add_to_rate_limit_group(struct bufferevent *bev,
+ struct bufferevent_rate_limit_group *g);
+
+/** Remove 'bev' from its current rate-limit group (if any). */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_remove_from_rate_limit_group(struct bufferevent *bev);
+
+/**
+ Set the size limit for single read operation.
+
+ Set to 0 for a reasonable default.
+
+ Return 0 on success and -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_set_max_single_read(struct bufferevent *bev, size_t size);
+
+/**
+ Set the size limit for single write operation.
+
+ Set to 0 for a reasonable default.
+
+ Return 0 on success and -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_set_max_single_write(struct bufferevent *bev, size_t size);
+
+/** Get the current size limit for single read operation. */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_max_single_read(struct bufferevent *bev);
+
+/** Get the current size limit for single write operation. */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_max_single_write(struct bufferevent *bev);
+
+/**
+ @name Rate limit inspection
+
+ Return the current read or write bucket size for a bufferevent.
+ If it is not configured with a per-bufferevent ratelimit, return
+ EV_SSIZE_MAX. This function does not inspect the group limit, if any.
+ Note that it can return a negative value if the bufferevent has been
+ made to read or write more than its limit.
+
+ @{
+ */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_read_limit(struct bufferevent *bev);
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_write_limit(struct bufferevent *bev);
+/*@}*/
+
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_max_to_read(struct bufferevent *bev);
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_get_max_to_write(struct bufferevent *bev);
+
+EVENT2_EXPORT_SYMBOL
+const struct ev_token_bucket_cfg *bufferevent_get_token_bucket_cfg(const struct bufferevent * bev);
+
+/**
+ @name Group Rate limit inspection
+
+ Return the read or write bucket size for a bufferevent rate limit
+ group. Note that it can return a negative value if bufferevents in
+ the group have been made to read or write more than their limits.
+
+ @{
+ */
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_rate_limit_group_get_read_limit(
+ struct bufferevent_rate_limit_group *);
+EVENT2_EXPORT_SYMBOL
+ev_ssize_t bufferevent_rate_limit_group_get_write_limit(
+ struct bufferevent_rate_limit_group *);
+/*@}*/
+
+/**
+ @name Rate limit manipulation
+
+ Subtract a number of bytes from a bufferevent's read or write bucket.
+ The decrement value can be negative, if you want to manually refill
+ the bucket. If the change puts the bucket above or below zero, the
+ bufferevent will resume or suspend reading writing as appropriate.
+ These functions make no change in the buckets for the bufferevent's
+ group, if any.
+
+ Returns 0 on success, -1 on internal error.
+
+ @{
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr);
+EVENT2_EXPORT_SYMBOL
+int bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr);
+/*@}*/
+
+/**
+ @name Group rate limit manipulation
+
+ Subtract a number of bytes from a bufferevent rate-limiting group's
+ read or write bucket. The decrement value can be negative, if you
+ want to manually refill the bucket. If the change puts the bucket
+ above or below zero, the bufferevents in the group will resume or
+ suspend reading writing as appropriate.
+
+ Returns 0 on success, -1 on internal error.
+
+ @{
+ */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_rate_limit_group_decrement_read(
+ struct bufferevent_rate_limit_group *, ev_ssize_t);
+EVENT2_EXPORT_SYMBOL
+int bufferevent_rate_limit_group_decrement_write(
+ struct bufferevent_rate_limit_group *, ev_ssize_t);
+/*@}*/
+
+
+/**
+ * Inspect the total bytes read/written on a group.
+ *
+ * Set the variable pointed to by total_read_out to the total number of bytes
+ * ever read on grp, and the variable pointed to by total_written_out to the
+ * total number of bytes ever written on grp. */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_rate_limit_group_get_totals(
+ struct bufferevent_rate_limit_group *grp,
+ ev_uint64_t *total_read_out, ev_uint64_t *total_written_out);
+
+/**
+ * Reset the total bytes read/written on a group.
+ *
+ * Reset the number of bytes read or written on grp as given by
+ * bufferevent_rate_limit_group_reset_totals(). */
+EVENT2_EXPORT_SYMBOL
+void
+bufferevent_rate_limit_group_reset_totals(
+ struct bufferevent_rate_limit_group *grp);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_BUFFEREVENT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_compat.h
new file mode 100644
index 0000000000..a5a3c7207d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_compat.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos, Nick Mathewson
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_COMPAT_H_INCLUDED_
+
+#include <event2/visibility.h>
+
+#define evbuffercb bufferevent_data_cb
+#define everrorcb bufferevent_event_cb
+
+/**
+ Create a new bufferevent for an fd.
+
+ This function is deprecated. Use bufferevent_socket_new and
+ bufferevent_set_callbacks instead.
+
+ Libevent provides an abstraction on top of the regular event callbacks.
+ This abstraction is called a buffered event. A buffered event provides
+ input and output buffers that get filled and drained automatically. The
+ user of a buffered event no longer deals directly with the I/O, but
+ instead is reading from input and writing to output buffers.
+
+ Once initialized, the bufferevent structure can be used repeatedly with
+ bufferevent_enable() and bufferevent_disable().
+
+ When read enabled the bufferevent will try to read from the file descriptor
+ and call the read callback. The write callback is executed whenever the
+ output buffer is drained below the write low watermark, which is 0 by
+ default.
+
+ If multiple bases are in use, bufferevent_base_set() must be called before
+ enabling the bufferevent for the first time.
+
+ @deprecated This function is deprecated because it uses the current
+ event base, and as such can be error prone for multithreaded programs.
+ Use bufferevent_socket_new() instead.
+
+ @param fd the file descriptor from which data is read and written to.
+ This file descriptor is not allowed to be a pipe(2).
+ @param readcb callback to invoke when there is data to be read, or NULL if
+ no callback is desired
+ @param writecb callback to invoke when the file descriptor is ready for
+ writing, or NULL if no callback is desired
+ @param errorcb callback to invoke when there is an error on the file
+ descriptor
+ @param cbarg an argument that will be supplied to each of the callbacks
+ (readcb, writecb, and errorcb)
+ @return a pointer to a newly allocated bufferevent struct, or NULL if an
+ error occurred
+ @see bufferevent_base_set(), bufferevent_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *bufferevent_new(evutil_socket_t fd,
+ evbuffercb readcb, evbuffercb writecb, everrorcb errorcb, void *cbarg);
+
+
+/**
+ Set the read and write timeout for a buffered event.
+
+ @param bufev the bufferevent to be modified
+ @param timeout_read the read timeout
+ @param timeout_write the write timeout
+ */
+EVENT2_EXPORT_SYMBOL
+void bufferevent_settimeout(struct bufferevent *bufev,
+ int timeout_read, int timeout_write);
+
+#define EVBUFFER_READ BEV_EVENT_READING
+#define EVBUFFER_WRITE BEV_EVENT_WRITING
+#define EVBUFFER_EOF BEV_EVENT_EOF
+#define EVBUFFER_ERROR BEV_EVENT_ERROR
+#define EVBUFFER_TIMEOUT BEV_EVENT_TIMEOUT
+
+/** macro for getting access to the input buffer of a bufferevent */
+#define EVBUFFER_INPUT(x) bufferevent_get_input(x)
+/** macro for getting access to the output buffer of a bufferevent */
+#define EVBUFFER_OUTPUT(x) bufferevent_get_output(x)
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_ssl.h b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_ssl.h
new file mode 100644
index 0000000000..bf39b844a9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_ssl.h
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_SSL_H_INCLUDED_
+
+/** @file event2/bufferevent_ssl.h
+
+ OpenSSL support for bufferevents.
+ */
+#include <event2/visibility.h>
+#include <event2/event-config.h>
+#include <event2/bufferevent.h>
+#include <event2/util.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* This is what openssl's SSL objects are underneath. */
+struct ssl_st;
+
+/**
+ The state of an SSL object to be used when creating a new
+ SSL bufferevent.
+ */
+enum bufferevent_ssl_state {
+ BUFFEREVENT_SSL_OPEN = 0,
+ BUFFEREVENT_SSL_CONNECTING = 1,
+ BUFFEREVENT_SSL_ACCEPTING = 2
+};
+
+#if defined(EVENT__HAVE_OPENSSL) || defined(EVENT_IN_DOXYGEN_)
+/**
+ Create a new SSL bufferevent to send its data over another bufferevent.
+
+ @param base An event_base to use to detect reading and writing. It
+ must also be the base for the underlying bufferevent.
+ @param underlying A socket to use for this SSL
+ @param ssl A SSL* object from openssl.
+ @param state The current state of the SSL connection
+ @param options One or more bufferevent_options
+ @return A new bufferevent on success, or NULL on failure
+*/
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *
+bufferevent_openssl_filter_new(struct event_base *base,
+ struct bufferevent *underlying,
+ struct ssl_st *ssl,
+ enum bufferevent_ssl_state state,
+ int options);
+
+/**
+ Create a new SSL bufferevent to send its data over an SSL * on a socket.
+
+ @param base An event_base to use to detect reading and writing
+ @param fd A socket to use for this SSL
+ @param ssl A SSL* object from openssl.
+ @param state The current state of the SSL connection
+ @param options One or more bufferevent_options
+ @return A new bufferevent on success, or NULL on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *
+bufferevent_openssl_socket_new(struct event_base *base,
+ evutil_socket_t fd,
+ struct ssl_st *ssl,
+ enum bufferevent_ssl_state state,
+ int options);
+
+/** Control how to report dirty SSL shutdowns.
+
+ If the peer (or the network, or an attacker) closes the TCP
+ connection before closing the SSL channel, and the protocol is SSL >= v3,
+ this is a "dirty" shutdown. If allow_dirty_shutdown is 0 (default),
+ this is reported as BEV_EVENT_ERROR.
+
+ If instead allow_dirty_shutdown=1, a dirty shutdown is reported as
+ BEV_EVENT_EOF.
+
+ (Note that if the protocol is < SSLv3, you will always receive
+ BEV_EVENT_EOF, since SSL 2 and earlier cannot distinguish a secure
+ connection close from a dirty one. This is one reason (among many)
+ not to use SSL 2.)
+*/
+
+EVENT2_EXPORT_SYMBOL
+int bufferevent_openssl_get_allow_dirty_shutdown(struct bufferevent *bev);
+EVENT2_EXPORT_SYMBOL
+void bufferevent_openssl_set_allow_dirty_shutdown(struct bufferevent *bev,
+ int allow_dirty_shutdown);
+
+/** Return the underlying openssl SSL * object for an SSL bufferevent. */
+EVENT2_EXPORT_SYMBOL
+struct ssl_st *
+bufferevent_openssl_get_ssl(struct bufferevent *bufev);
+
+/** Tells a bufferevent to begin SSL renegotiation. */
+EVENT2_EXPORT_SYMBOL
+int bufferevent_ssl_renegotiate(struct bufferevent *bev);
+
+/** Return the most recent OpenSSL error reported on an SSL bufferevent. */
+EVENT2_EXPORT_SYMBOL
+unsigned long bufferevent_get_openssl_error(struct bufferevent *bev);
+
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_BUFFEREVENT_SSL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_struct.h
new file mode 100644
index 0000000000..e84c082c30
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/bufferevent_struct.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
+#define EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_
+
+/** @file event2/bufferevent_struct.h
+
+ Data structures for bufferevents. Using these structures may hurt forward
+ compatibility with later versions of Libevent: be careful!
+
+ @deprecated Use of bufferevent_struct.h is completely deprecated; these
+ structures are only exposed for backward compatibility with programs
+ written before Libevent 2.0 that used them.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+/* For struct event */
+#include <event2/event_struct.h>
+
+struct event_watermark {
+ size_t low;
+ size_t high;
+};
+
+/**
+ Shared implementation of a bufferevent.
+
+ This type is exposed only because it was exposed in previous versions,
+ and some people's code may rely on manipulating it. Otherwise, you
+ should really not rely on the layout, size, or contents of this structure:
+ it is fairly volatile, and WILL change in future versions of the code.
+**/
+struct bufferevent {
+ /** Event base for which this bufferevent was created. */
+ struct event_base *ev_base;
+ /** Pointer to a table of function pointers to set up how this
+ bufferevent behaves. */
+ const struct bufferevent_ops *be_ops;
+
+ /** A read event that triggers when a timeout has happened or a socket
+ is ready to read data. Only used by some subtypes of
+ bufferevent. */
+ struct event ev_read;
+ /** A write event that triggers when a timeout has happened or a socket
+ is ready to write data. Only used by some subtypes of
+ bufferevent. */
+ struct event ev_write;
+
+ /** An input buffer. Only the bufferevent is allowed to add data to
+ this buffer, though the user is allowed to drain it. */
+ struct evbuffer *input;
+
+ /** An input buffer. Only the bufferevent is allowed to drain data
+ from this buffer, though the user is allowed to add it. */
+ struct evbuffer *output;
+
+ struct event_watermark wm_read;
+ struct event_watermark wm_write;
+
+ bufferevent_data_cb readcb;
+ bufferevent_data_cb writecb;
+ /* This should be called 'eventcb', but renaming it would break
+ * backward compatibility */
+ bufferevent_event_cb errorcb;
+ void *cbarg;
+
+ struct timeval timeout_read;
+ struct timeval timeout_write;
+
+ /** Events that are currently enabled: currently EV_READ and EV_WRITE
+ are supported. */
+ short enabled;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_BUFFEREVENT_STRUCT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/dns.h b/ipc/chromium/src/third_party/libevent/include/event2/dns.h
new file mode 100644
index 0000000000..13ce027e4a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/dns.h
@@ -0,0 +1,751 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/*
+ * The original DNS code is due to Adam Langley with heavy
+ * modifications by Nick Mathewson. Adam put his DNS software in the
+ * public domain. You can find his original copyright below. Please,
+ * aware that the code as part of Libevent is governed by the 3-clause
+ * BSD license above.
+ *
+ * This software is Public Domain. To view a copy of the public domain dedication,
+ * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
+ * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
+ *
+ * I ask and expect, but do not require, that all derivative works contain an
+ * attribution similar to:
+ * Parts developed by Adam Langley <agl@imperialviolet.org>
+ *
+ * You may wish to replace the word "Parts" with something else depending on
+ * the amount of original code.
+ *
+ * (Derivative works does not include programs which link against, run or include
+ * the source verbatim in their source distributions)
+ */
+
+/** @file event2/dns.h
+ *
+ * Welcome, gentle reader
+ *
+ * Async DNS lookups are really a whole lot harder than they should be,
+ * mostly stemming from the fact that the libc resolver has never been
+ * very good at them. Before you use this library you should see if libc
+ * can do the job for you with the modern async call getaddrinfo_a
+ * (see http://www.imperialviolet.org/page25.html#e498). Otherwise,
+ * please continue.
+ *
+ * The library keeps track of the state of nameservers and will avoid
+ * them when they go down. Otherwise it will round robin between them.
+ *
+ * Quick start guide:
+ * #include "evdns.h"
+ * void callback(int result, char type, int count, int ttl,
+ * void *addresses, void *arg);
+ * evdns_resolv_conf_parse(DNS_OPTIONS_ALL, "/etc/resolv.conf");
+ * evdns_resolve("www.hostname.com", 0, callback, NULL);
+ *
+ * When the lookup is complete the callback function is called. The
+ * first argument will be one of the DNS_ERR_* defines in evdns.h.
+ * Hopefully it will be DNS_ERR_NONE, in which case type will be
+ * DNS_IPv4_A, count will be the number of IP addresses, ttl is the time
+ * which the data can be cached for (in seconds), addresses will point
+ * to an array of uint32_t's and arg will be whatever you passed to
+ * evdns_resolve.
+ *
+ * Searching:
+ *
+ * In order for this library to be a good replacement for glibc's resolver it
+ * supports searching. This involves setting a list of default domains, in
+ * which names will be queried for. The number of dots in the query name
+ * determines the order in which this list is used.
+ *
+ * Searching appears to be a single lookup from the point of view of the API,
+ * although many DNS queries may be generated from a single call to
+ * evdns_resolve. Searching can also drastically slow down the resolution
+ * of names.
+ *
+ * To disable searching:
+ * 1. Never set it up. If you never call evdns_resolv_conf_parse or
+ * evdns_search_add then no searching will occur.
+ *
+ * 2. If you do call evdns_resolv_conf_parse then don't pass
+ * DNS_OPTION_SEARCH (or DNS_OPTIONS_ALL, which implies it).
+ *
+ * 3. When calling evdns_resolve, pass the DNS_QUERY_NO_SEARCH flag.
+ *
+ * The order of searches depends on the number of dots in the name. If the
+ * number is greater than the ndots setting then the names is first tried
+ * globally. Otherwise each search domain is appended in turn.
+ *
+ * The ndots setting can either be set from a resolv.conf, or by calling
+ * evdns_search_ndots_set.
+ *
+ * For example, with ndots set to 1 (the default) and a search domain list of
+ * ["myhome.net"]:
+ * Query: www
+ * Order: www.myhome.net, www.
+ *
+ * Query: www.abc
+ * Order: www.abc., www.abc.myhome.net
+ *
+ * Internals:
+ *
+ * Requests are kept in two queues. The first is the inflight queue. In
+ * this queue requests have an allocated transaction id and nameserver.
+ * They will soon be transmitted if they haven't already been.
+ *
+ * The second is the waiting queue. The size of the inflight ring is
+ * limited and all other requests wait in waiting queue for space. This
+ * bounds the number of concurrent requests so that we don't flood the
+ * nameserver. Several algorithms require a full walk of the inflight
+ * queue and so bounding its size keeps thing going nicely under huge
+ * (many thousands of requests) loads.
+ *
+ * If a nameserver loses too many requests it is considered down and we
+ * try not to use it. After a while we send a probe to that nameserver
+ * (a lookup for google.com) and, if it replies, we consider it working
+ * again. If the nameserver fails a probe we wait longer to try again
+ * with the next probe.
+ */
+
+#ifndef EVENT2_DNS_H_INCLUDED_
+#define EVENT2_DNS_H_INCLUDED_
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* For integer types. */
+#include <event2/util.h>
+
+/** Error codes 0-5 are as described in RFC 1035. */
+#define DNS_ERR_NONE 0
+/** The name server was unable to interpret the query */
+#define DNS_ERR_FORMAT 1
+/** The name server was unable to process this query due to a problem with the
+ * name server */
+#define DNS_ERR_SERVERFAILED 2
+/** The domain name does not exist */
+#define DNS_ERR_NOTEXIST 3
+/** The name server does not support the requested kind of query */
+#define DNS_ERR_NOTIMPL 4
+/** The name server refuses to reform the specified operation for policy
+ * reasons */
+#define DNS_ERR_REFUSED 5
+/** The reply was truncated or ill-formatted */
+#define DNS_ERR_TRUNCATED 65
+/** An unknown error occurred */
+#define DNS_ERR_UNKNOWN 66
+/** Communication with the server timed out */
+#define DNS_ERR_TIMEOUT 67
+/** The request was canceled because the DNS subsystem was shut down. */
+#define DNS_ERR_SHUTDOWN 68
+/** The request was canceled via a call to evdns_cancel_request */
+#define DNS_ERR_CANCEL 69
+/** There were no answers and no error condition in the DNS packet.
+ * This can happen when you ask for an address that exists, but a record
+ * type that doesn't. */
+#define DNS_ERR_NODATA 70
+
+#define DNS_IPv4_A 1
+#define DNS_PTR 2
+#define DNS_IPv6_AAAA 3
+
+#define DNS_QUERY_NO_SEARCH 1
+
+/* Allow searching */
+#define DNS_OPTION_SEARCH 1
+/* Parse "nameserver" and add default if no such section */
+#define DNS_OPTION_NAMESERVERS 2
+/* Parse additional options like:
+ * - timeout:
+ * - getaddrinfo-allow-skew:
+ * - max-timeouts:
+ * - max-inflight:
+ * - attempts:
+ * - randomize-case:
+ * - initial-probe-timeout:
+ */
+#define DNS_OPTION_MISC 4
+/* Load hosts file (i.e. "/etc/hosts") */
+#define DNS_OPTION_HOSTSFILE 8
+/**
+ * All above:
+ * - DNS_OPTION_SEARCH
+ * - DNS_OPTION_NAMESERVERS
+ * - DNS_OPTION_MISC
+ * - DNS_OPTION_HOSTSFILE
+ */
+#define DNS_OPTIONS_ALL ( \
+ DNS_OPTION_SEARCH | \
+ DNS_OPTION_NAMESERVERS | \
+ DNS_OPTION_MISC | \
+ DNS_OPTION_HOSTSFILE | \
+ 0 \
+)
+/* Do not "default" nameserver (i.e. "127.0.0.1:53") if there is no nameservers
+ * in resolv.conf, (iff DNS_OPTION_NAMESERVERS is set) */
+#define DNS_OPTION_NAMESERVERS_NO_DEFAULT 16
+
+/* Obsolete name for DNS_QUERY_NO_SEARCH */
+#define DNS_NO_SEARCH DNS_QUERY_NO_SEARCH
+
+/**
+ * The callback that contains the results from a lookup.
+ * - result is one of the DNS_ERR_* values (DNS_ERR_NONE for success)
+ * - type is either DNS_IPv4_A or DNS_PTR or DNS_IPv6_AAAA
+ * - count contains the number of addresses of form type
+ * - ttl is the number of seconds the resolution may be cached for.
+ * - addresses needs to be cast according to type. It will be an array of
+ * 4-byte sequences for ipv4, or an array of 16-byte sequences for ipv6,
+ * or a nul-terminated string for PTR.
+ */
+typedef void (*evdns_callback_type) (int result, char type, int count, int ttl, void *addresses, void *arg);
+
+struct evdns_base;
+struct event_base;
+
+/** Flag for evdns_base_new: process resolv.conf. */
+#define EVDNS_BASE_INITIALIZE_NAMESERVERS 1
+/** Flag for evdns_base_new: Do not prevent the libevent event loop from
+ * exiting when we have no active dns requests. */
+#define EVDNS_BASE_DISABLE_WHEN_INACTIVE 0x8000
+/** Flag for evdns_base_new: If EVDNS_BASE_INITIALIZE_NAMESERVERS isset, do not
+ * add default nameserver if there are no nameservers in resolv.conf
+ * @see DNS_OPTION_NAMESERVERS_NO_DEFAULT */
+#define EVDNS_BASE_NAMESERVERS_NO_DEFAULT 0x10000
+
+/**
+ Initialize the asynchronous DNS library.
+
+ This function initializes support for non-blocking name resolution by
+ calling evdns_resolv_conf_parse() on UNIX and
+ evdns_config_windows_nameservers() on Windows.
+
+ @param event_base the event base to associate the dns client with
+ @param flags any of EVDNS_BASE_INITIALIZE_NAMESERVERS|
+ EVDNS_BASE_DISABLE_WHEN_INACTIVE|EVDNS_BASE_NAMESERVERS_NO_DEFAULT
+ @return evdns_base object if successful, or NULL if an error occurred.
+ @see evdns_base_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_base * evdns_base_new(struct event_base *event_base, int initialize_nameservers);
+
+
+/**
+ Shut down the asynchronous DNS resolver and terminate all active requests.
+
+ If the 'fail_requests' option is enabled, all active requests will return
+ an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
+ the requests will be silently discarded.
+
+ @param evdns_base the evdns base to free
+ @param fail_requests if zero, active requests will be aborted; if non-zero,
+ active requests will return DNS_ERR_SHUTDOWN.
+ @see evdns_base_new()
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_base_free(struct evdns_base *base, int fail_requests);
+
+/**
+ Remove all hosts entries that have been loaded into the event_base via
+ evdns_base_load_hosts or via event_base_resolv_conf_parse.
+
+ @param evdns_base the evdns base to remove outdated host addresses from
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_base_clear_host_addresses(struct evdns_base *base);
+
+/**
+ Convert a DNS error code to a string.
+
+ @param err the DNS error code
+ @return a string containing an explanation of the error code
+*/
+EVENT2_EXPORT_SYMBOL
+const char *evdns_err_to_string(int err);
+
+
+/**
+ Add a nameserver.
+
+ The address should be an IPv4 address in network byte order.
+ The type of address is chosen so that it matches in_addr.s_addr.
+
+ @param base the evdns_base to which to add the name server
+ @param address an IP address in network byte order
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_base_nameserver_ip_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_nameserver_add(struct evdns_base *base,
+ unsigned long int address);
+
+/**
+ Get the number of configured nameservers.
+
+ This returns the number of configured nameservers (not necessarily the
+ number of running nameservers). This is useful for double-checking
+ whether our calls to the various nameserver configuration functions
+ have been successful.
+
+ @param base the evdns_base to which to apply this operation
+ @return the number of configured nameservers
+ @see evdns_base_nameserver_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_count_nameservers(struct evdns_base *base);
+
+/**
+ Remove all configured nameservers, and suspend all pending resolves.
+
+ Resolves will not necessarily be re-attempted until evdns_base_resume() is called.
+
+ @param base the evdns_base to which to apply this operation
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_base_resume()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_clear_nameservers_and_suspend(struct evdns_base *base);
+
+
+/**
+ Resume normal operation and continue any suspended resolve requests.
+
+ Re-attempt resolves left in limbo after an earlier call to
+ evdns_base_clear_nameservers_and_suspend().
+
+ @param base the evdns_base to which to apply this operation
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_base_clear_nameservers_and_suspend()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_resume(struct evdns_base *base);
+
+/**
+ Add a nameserver by string address.
+
+ This function parses a n IPv4 or IPv6 address from a string and adds it as a
+ nameserver. It supports the following formats:
+ - [IPv6Address]:port
+ - [IPv6Address]
+ - IPv6Address
+ - IPv4Address:port
+ - IPv4Address
+
+ If no port is specified, it defaults to 53.
+
+ @param base the evdns_base to which to apply this operation
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_base_nameserver_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_nameserver_ip_add(struct evdns_base *base,
+ const char *ip_as_string);
+
+/**
+ Add a nameserver by sockaddr.
+ **/
+EVENT2_EXPORT_SYMBOL
+int
+evdns_base_nameserver_sockaddr_add(struct evdns_base *base,
+ const struct sockaddr *sa, ev_socklen_t len, unsigned flags);
+
+struct evdns_request;
+
+/**
+ Lookup an A record for a given name.
+
+ @param base the evdns_base to which to apply this operation
+ @param name a DNS hostname
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return an evdns_request object if successful, or NULL if an error occurred.
+ @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_request *evdns_base_resolve_ipv4(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+ Lookup an AAAA record for a given name.
+
+ @param base the evdns_base to which to apply this operation
+ @param name a DNS hostname
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return an evdns_request object if successful, or NULL if an error occurred.
+ @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_request *evdns_base_resolve_ipv6(struct evdns_base *base, const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+struct in_addr;
+struct in6_addr;
+
+/**
+ Lookup a PTR record for a given IP address.
+
+ @param base the evdns_base to which to apply this operation
+ @param in an IPv4 address
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return an evdns_request object if successful, or NULL if an error occurred.
+ @see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_request *evdns_base_resolve_reverse(struct evdns_base *base, const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+
+/**
+ Lookup a PTR record for a given IPv6 address.
+
+ @param base the evdns_base to which to apply this operation
+ @param in an IPv6 address
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return an evdns_request object if successful, or NULL if an error occurred.
+ @see evdns_resolve_reverse_ipv6(), evdns_cancel_request()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_request *evdns_base_resolve_reverse_ipv6(struct evdns_base *base, const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+ Cancels a pending DNS resolution request.
+
+ @param base the evdns_base that was used to make the request
+ @param req the evdns_request that was returned by calling a resolve function
+ @see evdns_base_resolve_ipv4(), evdns_base_resolve_ipv6, evdns_base_resolve_reverse
+*/
+EVENT2_EXPORT_SYMBOL
+void evdns_cancel_request(struct evdns_base *base, struct evdns_request *req);
+
+/**
+ Set the value of a configuration option.
+
+ The currently available configuration options are:
+
+ ndots, timeout, max-timeouts, max-inflight, attempts, randomize-case,
+ bind-to, initial-probe-timeout, getaddrinfo-allow-skew,
+ so-rcvbuf, so-sndbuf.
+
+ In versions before Libevent 2.0.3-alpha, the option name needed to end with
+ a colon.
+
+ @param base the evdns_base to which to apply this operation
+ @param option the name of the configuration option to be modified
+ @param val the value to be set
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_set_option(struct evdns_base *base, const char *option, const char *val);
+
+
+/**
+ Parse a resolv.conf file.
+
+ The 'flags' parameter determines what information is parsed from the
+ resolv.conf file. See the man page for resolv.conf for the format of this
+ file.
+
+ The following directives are not parsed from the file: sortlist, rotate,
+ no-check-names, inet6, debug.
+
+ If this function encounters an error, the possible return values are: 1 =
+ failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
+ memory, 5 = short read from file, 6 = no nameservers listed in the file
+
+ @param base the evdns_base to which to apply this operation
+ @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
+ DNS_OPTION_HOSTSFILE|DNS_OPTIONS_ALL|DNS_OPTION_NAMESERVERS_NO_DEFAULT
+ @param filename the path to the resolv.conf file
+ @return 0 if successful, or various positive error codes if an error
+ occurred (see above)
+ @see resolv.conf(3), evdns_config_windows_nameservers()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_resolv_conf_parse(struct evdns_base *base, int flags, const char *const filename);
+
+/**
+ Load an /etc/hosts-style file from 'hosts_fname' into 'base'.
+
+ If hosts_fname is NULL, add minimal entries for localhost, and nothing
+ else.
+
+ Note that only evdns_getaddrinfo uses the /etc/hosts entries.
+
+ This function does not replace previously loaded hosts entries; to do that,
+ call evdns_base_clear_host_addresses first.
+
+ Return 0 on success, negative on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+int evdns_base_load_hosts(struct evdns_base *base, const char *hosts_fname);
+
+#if defined(EVENT_IN_DOXYGEN_) || defined(_WIN32)
+/**
+ Obtain nameserver information using the Windows API.
+
+ Attempt to configure a set of nameservers based on platform settings on
+ a win32 host. Preferentially tries to use GetNetworkParams; if that fails,
+ looks in the registry.
+
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resolv_conf_parse()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_config_windows_nameservers(struct evdns_base *);
+#define EVDNS_BASE_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
+#endif
+
+
+/**
+ Clear the list of search domains.
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_base_search_clear(struct evdns_base *base);
+
+
+/**
+ Add a domain to the list of search domains
+
+ @param domain the domain to be added to the search list
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_base_search_add(struct evdns_base *base, const char *domain);
+
+
+/**
+ Set the 'ndots' parameter for searches.
+
+ Sets the number of dots which, when found in a name, causes
+ the first query to be without any search domain.
+
+ @param ndots the new ndots parameter
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_base_search_ndots_set(struct evdns_base *base, const int ndots);
+
+/**
+ A callback that is invoked when a log message is generated
+
+ @param is_warning indicates if the log message is a 'warning'
+ @param msg the content of the log message
+ */
+typedef void (*evdns_debug_log_fn_type)(int is_warning, const char *msg);
+
+
+/**
+ Set the callback function to handle DNS log messages. If this
+ callback is not set, evdns log messages are handled with the regular
+ Libevent logging system.
+
+ @param fn the callback to be invoked when a log message is generated
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_set_log_fn(evdns_debug_log_fn_type fn);
+
+/**
+ Set a callback that will be invoked to generate transaction IDs. By
+ default, we pick transaction IDs based on the current clock time, which
+ is bad for security.
+
+ @param fn the new callback, or NULL to use the default.
+
+ NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
+ since Libevent now provides its own secure RNG.
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_set_transaction_id_fn(ev_uint16_t (*fn)(void));
+
+/**
+ Set a callback used to generate random bytes. By default, we use
+ the same function as passed to evdns_set_transaction_id_fn to generate
+ bytes two at a time. If a function is provided here, it's also used
+ to generate transaction IDs.
+
+ NOTE: This function has no effect in Libevent 2.0.4-alpha and later,
+ since Libevent now provides its own secure RNG.
+*/
+EVENT2_EXPORT_SYMBOL
+void evdns_set_random_bytes_fn(void (*fn)(char *, size_t));
+
+/*
+ * Functions used to implement a DNS server.
+ */
+
+struct evdns_server_request;
+struct evdns_server_question;
+
+/**
+ A callback to implement a DNS server. The callback function receives a DNS
+ request. It should then optionally add a number of answers to the reply
+ using the evdns_server_request_add_*_reply functions, before calling either
+ evdns_server_request_respond to send the reply back, or
+ evdns_server_request_drop to decline to answer the request.
+
+ @param req A newly received request
+ @param user_data A pointer that was passed to
+ evdns_add_server_port_with_base().
+ */
+typedef void (*evdns_request_callback_fn_type)(struct evdns_server_request *, void *);
+#define EVDNS_ANSWER_SECTION 0
+#define EVDNS_AUTHORITY_SECTION 1
+#define EVDNS_ADDITIONAL_SECTION 2
+
+#define EVDNS_TYPE_A 1
+#define EVDNS_TYPE_NS 2
+#define EVDNS_TYPE_CNAME 5
+#define EVDNS_TYPE_SOA 6
+#define EVDNS_TYPE_PTR 12
+#define EVDNS_TYPE_MX 15
+#define EVDNS_TYPE_TXT 16
+#define EVDNS_TYPE_AAAA 28
+
+#define EVDNS_QTYPE_AXFR 252
+#define EVDNS_QTYPE_ALL 255
+
+#define EVDNS_CLASS_INET 1
+
+/* flags that can be set in answers; as part of the err parameter */
+#define EVDNS_FLAGS_AA 0x400
+#define EVDNS_FLAGS_RD 0x080
+
+/** Create a new DNS server port.
+
+ @param base The event base to handle events for the server port.
+ @param socket A UDP socket to accept DNS requests.
+ @param flags Always 0 for now.
+ @param callback A function to invoke whenever we get a DNS request
+ on the socket.
+ @param user_data Data to pass to the callback.
+ @return an evdns_server_port structure for this server port or NULL if
+ an error occurred.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_server_port *evdns_add_server_port_with_base(struct event_base *base, evutil_socket_t socket, int flags, evdns_request_callback_fn_type callback, void *user_data);
+/** Close down a DNS server port, and free associated structures. */
+EVENT2_EXPORT_SYMBOL
+void evdns_close_server_port(struct evdns_server_port *port);
+
+/** Sets some flags in a reply we're building.
+ Allows setting of the AA or RD flags
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_server_request_set_flags(struct evdns_server_request *req, int flags);
+
+/* Functions to add an answer to an in-progress DNS reply.
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_add_reply(struct evdns_server_request *req, int section, const char *name, int type, int dns_class, int ttl, int datalen, int is_name, const char *data);
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_add_a_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_add_aaaa_reply(struct evdns_server_request *req, const char *name, int n, const void *addrs, int ttl);
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_add_ptr_reply(struct evdns_server_request *req, struct in_addr *in, const char *inaddr_name, const char *hostname, int ttl);
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_add_cname_reply(struct evdns_server_request *req, const char *name, const char *cname, int ttl);
+
+/**
+ Send back a response to a DNS request, and free the request structure.
+*/
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_respond(struct evdns_server_request *req, int err);
+/**
+ Free a DNS request without sending back a reply.
+*/
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_drop(struct evdns_server_request *req);
+struct sockaddr;
+/**
+ Get the address that made a DNS request.
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_server_request_get_requesting_addr(struct evdns_server_request *req, struct sockaddr *sa, int addr_len);
+
+/** Callback for evdns_getaddrinfo. */
+typedef void (*evdns_getaddrinfo_cb)(int result, struct evutil_addrinfo *res, void *arg);
+
+struct evdns_base;
+struct evdns_getaddrinfo_request;
+/** Make a non-blocking getaddrinfo request using the dns_base in 'dns_base'.
+ *
+ * If we can answer the request immediately (with an error or not!), then we
+ * invoke cb immediately and return NULL. Otherwise we return
+ * an evdns_getaddrinfo_request and invoke cb later.
+ *
+ * When the callback is invoked, we pass as its first argument the error code
+ * that getaddrinfo would return (or 0 for no error). As its second argument,
+ * we pass the evutil_addrinfo structures we found (or NULL on error). We
+ * pass 'arg' as the third argument.
+ *
+ * Limitations:
+ *
+ * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
+ * - For ai_socktype, we only handle SOCKTYPE_STREAM, SOCKTYPE_UDP, and 0.
+ * - For ai_protocol, we only handle IPPROTO_TCP, IPPROTO_UDP, and 0.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_getaddrinfo_request *evdns_getaddrinfo(
+ struct evdns_base *dns_base,
+ const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in,
+ evdns_getaddrinfo_cb cb, void *arg);
+
+/* Cancel an in-progress evdns_getaddrinfo. This MUST NOT be called after the
+ * getaddrinfo's callback has been invoked. The resolves will be canceled,
+ * and the callback will be invoked with the error EVUTIL_EAI_CANCEL. */
+EVENT2_EXPORT_SYMBOL
+void evdns_getaddrinfo_cancel(struct evdns_getaddrinfo_request *req);
+
+/**
+ Retrieve the address of the 'idx'th configured nameserver.
+
+ @param base The evdns_base to examine.
+ @param idx The index of the nameserver to get the address of.
+ @param sa A location to receive the server's address.
+ @param len The number of bytes available at sa.
+
+ @return the number of bytes written into sa on success. On failure, returns
+ -1 if idx is greater than the number of configured nameservers, or a
+ value greater than 'len' if len was not high enough.
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_base_get_nameserver_addr(struct evdns_base *base, int idx,
+ struct sockaddr *sa, ev_socklen_t len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* !EVENT2_DNS_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/dns_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/dns_compat.h
new file mode 100644
index 0000000000..a58c4b2937
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/dns_compat.h
@@ -0,0 +1,358 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_DNS_COMPAT_H_INCLUDED_
+#define EVENT2_DNS_COMPAT_H_INCLUDED_
+
+/** @file event2/dns_compat.h
+
+ Potentially non-threadsafe versions of the functions in dns.h: provided
+ only for backwards compatibility.
+
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+#include <event2/visibility.h>
+
+/**
+ Initialize the asynchronous DNS library.
+
+ This function initializes support for non-blocking name resolution by
+ calling evdns_resolv_conf_parse() on UNIX and
+ evdns_config_windows_nameservers() on Windows.
+
+ @deprecated This function is deprecated because it always uses the current
+ event base, and is easily confused by multiple calls to event_init(), and
+ so is not safe for multithreaded use. Additionally, it allocates a global
+ structure that only one thread can use. The replacement is
+ evdns_base_new().
+
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_shutdown()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_init(void);
+
+struct evdns_base;
+/**
+ Return the global evdns_base created by event_init() and used by the other
+ deprecated functions.
+
+ @deprecated This function is deprecated because use of the global
+ evdns_base is error-prone.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evdns_base *evdns_get_global_base(void);
+
+/**
+ Shut down the asynchronous DNS resolver and terminate all active requests.
+
+ If the 'fail_requests' option is enabled, all active requests will return
+ an empty result with the error flag set to DNS_ERR_SHUTDOWN. Otherwise,
+ the requests will be silently discarded.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_shutdown().
+
+ @param fail_requests if zero, active requests will be aborted; if non-zero,
+ active requests will return DNS_ERR_SHUTDOWN.
+ @see evdns_init()
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_shutdown(int fail_requests);
+
+/**
+ Add a nameserver.
+
+ The address should be an IPv4 address in network byte order.
+ The type of address is chosen so that it matches in_addr.s_addr.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_nameserver_add().
+
+ @param address an IP address in network byte order
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_nameserver_ip_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_nameserver_add(unsigned long int address);
+
+/**
+ Get the number of configured nameservers.
+
+ This returns the number of configured nameservers (not necessarily the
+ number of running nameservers). This is useful for double-checking
+ whether our calls to the various nameserver configuration functions
+ have been successful.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_count_nameservers().
+
+ @return the number of configured nameservers
+ @see evdns_nameserver_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_count_nameservers(void);
+
+/**
+ Remove all configured nameservers, and suspend all pending resolves.
+
+ Resolves will not necessarily be re-attempted until evdns_resume() is called.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_clear_nameservers_and_suspend().
+
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resume()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_clear_nameservers_and_suspend(void);
+
+/**
+ Resume normal operation and continue any suspended resolve requests.
+
+ Re-attempt resolves left in limbo after an earlier call to
+ evdns_clear_nameservers_and_suspend().
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_resume().
+
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_clear_nameservers_and_suspend()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resume(void);
+
+/**
+ Add a nameserver.
+
+ This wraps the evdns_nameserver_add() function by parsing a string as an IP
+ address and adds it as a nameserver.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_nameserver_ip_add().
+
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_nameserver_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_nameserver_ip_add(const char *ip_as_string);
+
+/**
+ Lookup an A record for a given name.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_resolve_ipv4().
+
+ @param name a DNS hostname
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resolve_ipv6(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resolve_ipv4(const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+ Lookup an AAAA record for a given name.
+
+ @param name a DNS hostname
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resolve_ipv4(), evdns_resolve_reverse(), evdns_resolve_reverse_ipv6()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resolve_ipv6(const char *name, int flags, evdns_callback_type callback, void *ptr);
+
+struct in_addr;
+struct in6_addr;
+
+/**
+ Lookup a PTR record for a given IP address.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_resolve_reverse().
+
+ @param in an IPv4 address
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resolve_reverse_ipv6()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resolve_reverse(const struct in_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+ Lookup a PTR record for a given IPv6 address.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_resolve_reverse_ipv6().
+
+ @param in an IPv6 address
+ @param flags either 0, or DNS_QUERY_NO_SEARCH to disable searching for this query.
+ @param callback a callback function to invoke when the request is completed
+ @param ptr an argument to pass to the callback function
+ @return 0 if successful, or -1 if an error occurred
+ @see evdns_resolve_reverse_ipv6()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resolve_reverse_ipv6(const struct in6_addr *in, int flags, evdns_callback_type callback, void *ptr);
+
+/**
+ Set the value of a configuration option.
+
+ The currently available configuration options are:
+
+ ndots, timeout, max-timeouts, max-inflight, and attempts
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_set_option().
+
+ @param option the name of the configuration option to be modified
+ @param val the value to be set
+ @param flags Ignored.
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_set_option(const char *option, const char *val, int flags);
+
+/**
+ Parse a resolv.conf file.
+
+ The 'flags' parameter determines what information is parsed from the
+ resolv.conf file. See the man page for resolv.conf for the format of this
+ file.
+
+ The following directives are not parsed from the file: sortlist, rotate,
+ no-check-names, inet6, debug.
+
+ If this function encounters an error, the possible return values are: 1 =
+ failed to open file, 2 = failed to stat file, 3 = file too large, 4 = out of
+ memory, 5 = short read from file, 6 = no nameservers listed in the file
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_resolv_conf_parse().
+
+ @param flags any of DNS_OPTION_NAMESERVERS|DNS_OPTION_SEARCH|DNS_OPTION_MISC|
+ DNS_OPTIONS_ALL
+ @param filename the path to the resolv.conf file
+ @return 0 if successful, or various positive error codes if an error
+ occurred (see above)
+ @see resolv.conf(3), evdns_config_windows_nameservers()
+ */
+EVENT2_EXPORT_SYMBOL
+int evdns_resolv_conf_parse(int flags, const char *const filename);
+
+/**
+ Clear the list of search domains.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_search_clear().
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_search_clear(void);
+
+/**
+ Add a domain to the list of search domains
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_search_add().
+
+ @param domain the domain to be added to the search list
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_search_add(const char *domain);
+
+/**
+ Set the 'ndots' parameter for searches.
+
+ Sets the number of dots which, when found in a name, causes
+ the first query to be without any search domain.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which evdns_base it applies to. The recommended
+ function is evdns_base_search_ndots_set().
+
+ @param ndots the new ndots parameter
+ */
+EVENT2_EXPORT_SYMBOL
+void evdns_search_ndots_set(const int ndots);
+
+/**
+ As evdns_server_new_with_base.
+
+ @deprecated This function is deprecated because it does not allow the
+ caller to specify which even_base it uses. The recommended
+ function is evdns_add_server_port_with_base().
+
+*/
+EVENT2_EXPORT_SYMBOL
+struct evdns_server_port *
+evdns_add_server_port(evutil_socket_t socket, int flags,
+ evdns_request_callback_fn_type callback, void *user_data);
+
+#ifdef _WIN32
+EVENT2_EXPORT_SYMBOL
+int evdns_config_windows_nameservers(void);
+#define EVDNS_CONFIG_WINDOWS_NAMESERVERS_IMPLEMENTED
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/dns_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/dns_struct.h
new file mode 100644
index 0000000000..593a8a70b6
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/dns_struct.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_DNS_STRUCT_H_INCLUDED_
+#define EVENT2_DNS_STRUCT_H_INCLUDED_
+
+/** @file event2/dns_struct.h
+
+ Data structures for dns. Using these structures may hurt forward
+ compatibility with later versions of Libevent: be careful!
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/*
+ * Structures used to implement a DNS server.
+ */
+
+struct evdns_server_request {
+ int flags;
+ int nquestions;
+ struct evdns_server_question **questions;
+};
+struct evdns_server_question {
+ int type;
+#ifdef __cplusplus
+ int dns_question_class;
+#else
+ /* You should refer to this field as "dns_question_class". The
+ * name "class" works in C for backward compatibility, and will be
+ * removed in a future version. (1.5 or later). */
+ int class;
+#define dns_question_class class
+#endif
+ char name[1];
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_DNS_STRUCT_H_INCLUDED_ */
+
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/event.h b/ipc/chromium/src/third_party/libevent/include/event2/event.h
new file mode 100644
index 0000000000..a6b6144a92
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/event.h
@@ -0,0 +1,1672 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_EVENT_H_INCLUDED_
+#define EVENT2_EVENT_H_INCLUDED_
+
+/**
+ @mainpage
+
+ @section intro Introduction
+
+ Libevent is an event notification library for developing scalable network
+ servers. The Libevent API provides a mechanism to execute a callback
+ function when a specific event occurs on a file descriptor or after a
+ timeout has been reached. Furthermore, Libevent also support callbacks due
+ to signals or regular timeouts.
+
+ Libevent is meant to replace the event loop found in event driven network
+ servers. An application just needs to call event_base_dispatch() and then add or
+ remove events dynamically without having to change the event loop.
+
+
+ Currently, Libevent supports /dev/poll, kqueue(2), select(2), poll(2),
+ epoll(4), and evports. The internal event mechanism is completely
+ independent of the exposed event API, and a simple update of Libevent can
+ provide new functionality without having to redesign the applications. As a
+ result, Libevent allows for portable application development and provides
+ the most scalable event notification mechanism available on an operating
+ system. Libevent can also be used for multithreaded programs. Libevent
+ should compile on Linux, *BSD, Mac OS X, Solaris and, Windows.
+
+ @section usage Standard usage
+
+ Every program that uses Libevent must include the <event2/event.h>
+ header, and pass the -levent flag to the linker. (You can instead link
+ -levent_core if you only want the main event and buffered IO-based code,
+ and don't want to link any protocol code.)
+
+ @section setup Library setup
+
+ Before you call any other Libevent functions, you need to set up the
+ library. If you're going to use Libevent from multiple threads in a
+ multithreaded application, you need to initialize thread support --
+ typically by using evthread_use_pthreads() or
+ evthread_use_windows_threads(). See <event2/thread.h> for more
+ information.
+
+ This is also the point where you can replace Libevent's memory
+ management functions with event_set_mem_functions, and enable debug mode
+ with event_enable_debug_mode().
+
+ @section base Creating an event base
+
+ Next, you need to create an event_base structure, using event_base_new()
+ or event_base_new_with_config(). The event_base is responsible for
+ keeping track of which events are "pending" (that is to say, being
+ watched to see if they become active) and which events are "active".
+ Every event is associated with a single event_base.
+
+ @section event Event notification
+
+ For each file descriptor that you wish to monitor, you must create an
+ event structure with event_new(). (You may also declare an event
+ structure and call event_assign() to initialize the members of the
+ structure.) To enable notification, you add the structure to the list
+ of monitored events by calling event_add(). The event structure must
+ remain allocated as long as it is active, so it should generally be
+ allocated on the heap.
+
+ @section loop Dispatching events.
+
+ Finally, you call event_base_dispatch() to loop and dispatch events.
+ You can also use event_base_loop() for more fine-grained control.
+
+ Currently, only one thread can be dispatching a given event_base at a
+ time. If you want to run events in multiple threads at once, you can
+ either have a single event_base whose events add work to a work queue,
+ or you can create multiple event_base objects.
+
+ @section bufferevent I/O Buffers
+
+ Libevent provides a buffered I/O abstraction on top of the regular event
+ callbacks. This abstraction is called a bufferevent. A bufferevent
+ provides input and output buffers that get filled and drained
+ automatically. The user of a buffered event no longer deals directly
+ with the I/O, but instead is reading from input and writing to output
+ buffers.
+
+ Once initialized via bufferevent_socket_new(), the bufferevent structure
+ can be used repeatedly with bufferevent_enable() and
+ bufferevent_disable(). Instead of reading and writing directly to a
+ socket, you would call bufferevent_read() and bufferevent_write().
+
+ When read enabled the bufferevent will try to read from the file descriptor
+ and call the read callback. The write callback is executed whenever the
+ output buffer is drained below the write low watermark, which is 0 by
+ default.
+
+ See <event2/bufferevent*.h> for more information.
+
+ @section timers Timers
+
+ Libevent can also be used to create timers that invoke a callback after a
+ certain amount of time has expired. The evtimer_new() macro returns
+ an event struct to use as a timer. To activate the timer, call
+ evtimer_add(). Timers can be deactivated by calling evtimer_del().
+ (These macros are thin wrappers around event_new(), event_add(),
+ and event_del(); you can also use those instead.)
+
+ @section evdns Asynchronous DNS resolution
+
+ Libevent provides an asynchronous DNS resolver that should be used instead
+ of the standard DNS resolver functions. See the <event2/dns.h>
+ functions for more detail.
+
+ @section evhttp Event-driven HTTP servers
+
+ Libevent provides a very simple event-driven HTTP server that can be
+ embedded in your program and used to service HTTP requests.
+
+ To use this capability, you need to include the <event2/http.h> header in your
+ program. See that header for more information.
+
+ @section evrpc A framework for RPC servers and clients
+
+ Libevent provides a framework for creating RPC servers and clients. It
+ takes care of marshaling and unmarshaling all data structures.
+
+ @section api API Reference
+
+ To browse the complete documentation of the libevent API, click on any of
+ the following links.
+
+ event2/event.h
+ The primary libevent header
+
+ event2/thread.h
+ Functions for use by multithreaded programs
+
+ event2/buffer.h and event2/bufferevent.h
+ Buffer management for network reading and writing
+
+ event2/util.h
+ Utility functions for portable nonblocking network code
+
+ event2/dns.h
+ Asynchronous DNS resolution
+
+ event2/http.h
+ An embedded libevent-based HTTP server
+
+ event2/rpc.h
+ A framework for creating RPC servers and clients
+
+ */
+
+/** @file event2/event.h
+
+ Core functions for waiting for and receiving events, and using event bases.
+*/
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#include <stdio.h>
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * Structure to hold information and state for a Libevent dispatch loop.
+ *
+ * The event_base lies at the center of Libevent; every application will
+ * have one. It keeps track of all pending and active events, and
+ * notifies your application of the active ones.
+ *
+ * This is an opaque structure; you can allocate one using
+ * event_base_new() or event_base_new_with_config().
+ *
+ * @see event_base_new(), event_base_free(), event_base_loop(),
+ * event_base_new_with_config()
+ */
+struct event_base
+#ifdef EVENT_IN_DOXYGEN_
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * @struct event
+ *
+ * Structure to represent a single event.
+ *
+ * An event can have some underlying condition it represents: a socket
+ * becoming readable or writeable (or both), or a signal becoming raised.
+ * (An event that represents no underlying condition is still useful: you
+ * can use one to implement a timer, or to communicate between threads.)
+ *
+ * Generally, you can create events with event_new(), then make them
+ * pending with event_add(). As your event_base runs, it will run the
+ * callbacks of an events whose conditions are triggered. When you no
+ * longer want the event, free it with event_free().
+ *
+ * In more depth:
+ *
+ * An event may be "pending" (one whose condition we are watching),
+ * "active" (one whose condition has triggered and whose callback is about
+ * to run), neither, or both. Events come into existence via
+ * event_assign() or event_new(), and are then neither active nor pending.
+ *
+ * To make an event pending, pass it to event_add(). When doing so, you
+ * can also set a timeout for the event.
+ *
+ * Events become active during an event_base_loop() call when either their
+ * condition has triggered, or when their timeout has elapsed. You can
+ * also activate an event manually using event_active(). The even_base
+ * loop will run the callbacks of active events; after it has done so, it
+ * marks them as no longer active.
+ *
+ * You can make an event non-pending by passing it to event_del(). This
+ * also makes the event non-active.
+ *
+ * Events can be "persistent" or "non-persistent". A non-persistent event
+ * becomes non-pending as soon as it is triggered: thus, it only runs at
+ * most once per call to event_add(). A persistent event remains pending
+ * even when it becomes active: you'll need to event_del() it manually in
+ * order to make it non-pending. When a persistent event with a timeout
+ * becomes active, its timeout is reset: this means you can use persistent
+ * events to implement periodic timeouts.
+ *
+ * This should be treated as an opaque structure; you should never read or
+ * write any of its fields directly. For backward compatibility with old
+ * code, it is defined in the event2/event_struct.h header; including this
+ * header may make your code incompatible with other versions of Libevent.
+ *
+ * @see event_new(), event_free(), event_assign(), event_get_assignment(),
+ * event_add(), event_del(), event_active(), event_pending(),
+ * event_get_fd(), event_get_base(), event_get_events(),
+ * event_get_callback(), event_get_callback_arg(),
+ * event_priority_set()
+ */
+struct event
+#ifdef EVENT_IN_DOXYGEN_
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * Configuration for an event_base.
+ *
+ * There are many options that can be used to alter the behavior and
+ * implementation of an event_base. To avoid having to pass them all in a
+ * complex many-argument constructor, we provide an abstract data type
+ * where you set up configuration information before passing it to
+ * event_base_new_with_config().
+ *
+ * @see event_config_new(), event_config_free(), event_base_new_with_config(),
+ * event_config_avoid_method(), event_config_require_features(),
+ * event_config_set_flag(), event_config_set_num_cpus_hint()
+ */
+struct event_config
+#ifdef EVENT_IN_DOXYGEN_
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+/**
+ * Enable some relatively expensive debugging checks in Libevent that
+ * would normally be turned off. Generally, these checks cause code that
+ * would otherwise crash mysteriously to fail earlier with an assertion
+ * failure. Note that this method MUST be called before any events or
+ * event_bases have been created.
+ *
+ * Debug mode can currently catch the following errors:
+ * An event is re-assigned while it is added
+ * Any function is called on a non-assigned event
+ *
+ * Note that debugging mode uses memory to track every event that has been
+ * initialized (via event_assign, event_set, or event_new) but not yet
+ * released (via event_free or event_debug_unassign). If you want to use
+ * debug mode, and you find yourself running out of memory, you will need
+ * to use event_debug_unassign to explicitly stop tracking events that
+ * are no longer considered set-up.
+ *
+ * @see event_debug_unassign()
+ */
+EVENT2_EXPORT_SYMBOL
+void event_enable_debug_mode(void);
+
+/**
+ * When debugging mode is enabled, informs Libevent that an event should no
+ * longer be considered as assigned. When debugging mode is not enabled, does
+ * nothing.
+ *
+ * This function must only be called on a non-added event.
+ *
+ * @see event_enable_debug_mode()
+ */
+EVENT2_EXPORT_SYMBOL
+void event_debug_unassign(struct event *);
+
+/**
+ * Create and return a new event_base to use with the rest of Libevent.
+ *
+ * @return a new event_base on success, or NULL on failure.
+ *
+ * @see event_base_free(), event_base_new_with_config()
+ */
+EVENT2_EXPORT_SYMBOL
+struct event_base *event_base_new(void);
+
+/**
+ Reinitialize the event base after a fork
+
+ Some event mechanisms do not survive across fork. The event base needs
+ to be reinitialized with the event_reinit() function.
+
+ @param base the event base that needs to be re-initialized
+ @return 0 if successful, or -1 if some events could not be re-added.
+ @see event_base_new()
+*/
+EVENT2_EXPORT_SYMBOL
+int event_reinit(struct event_base *base);
+
+/**
+ Event dispatching loop
+
+ This loop will run the event base until either there are no more pending or
+ active, or until something calls event_base_loopbreak() or
+ event_base_loopexit().
+
+ @param base the event_base structure returned by event_base_new() or
+ event_base_new_with_config()
+ @return 0 if successful, -1 if an error occurred, or 1 if we exited because
+ no events were pending or active.
+ @see event_base_loop()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_dispatch(struct event_base *);
+
+/**
+ Get the kernel event notification mechanism used by Libevent.
+
+ @param eb the event_base structure returned by event_base_new()
+ @return a string identifying the kernel event mechanism (kqueue, epoll, etc.)
+ */
+EVENT2_EXPORT_SYMBOL
+const char *event_base_get_method(const struct event_base *);
+
+/**
+ Gets all event notification mechanisms supported by Libevent.
+
+ This functions returns the event mechanism in order preferred by
+ Libevent. Note that this list will include all backends that
+ Libevent has compiled-in support for, and will not necessarily check
+ your OS to see whether it has the required resources.
+
+ @return an array with pointers to the names of support methods.
+ The end of the array is indicated by a NULL pointer. If an
+ error is encountered NULL is returned.
+*/
+EVENT2_EXPORT_SYMBOL
+const char **event_get_supported_methods(void);
+
+/** Query the current monotonic time from a the timer for a struct
+ * event_base.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_gettime_monotonic(struct event_base *base, struct timeval *tp);
+
+/**
+ @name event type flag
+
+ Flags to pass to event_base_get_num_events() to specify the kinds of events
+ we want to aggregate counts for
+*/
+/**@{*/
+/** count the number of active events, which have been triggered.*/
+#define EVENT_BASE_COUNT_ACTIVE 1U
+/** count the number of virtual events, which is used to represent an internal
+ * condition, other than a pending event, that keeps the loop from exiting. */
+#define EVENT_BASE_COUNT_VIRTUAL 2U
+/** count the number of events which have been added to event base, including
+ * internal events. */
+#define EVENT_BASE_COUNT_ADDED 4U
+/**@}*/
+
+/**
+ Gets the number of events in event_base, as specified in the flags.
+
+ Since event base has some internal events added to make some of its
+ functionalities work, EVENT_BASE_COUNT_ADDED may return more than the
+ number of events you added using event_add().
+
+ If you pass EVENT_BASE_COUNT_ACTIVE and EVENT_BASE_COUNT_ADDED together, an
+ active event will be counted twice. However, this might not be the case in
+ future libevent versions. The return value is an indication of the work
+ load, but the user shouldn't rely on the exact value as this may change in
+ the future.
+
+ @param eb the event_base structure returned by event_base_new()
+ @param flags a bitwise combination of the kinds of events to aggregate
+ counts for
+ @return the number of events specified in the flags
+*/
+EVENT2_EXPORT_SYMBOL
+int event_base_get_num_events(struct event_base *, unsigned int);
+
+/**
+ Get the maximum number of events in a given event_base as specified in the
+ flags.
+
+ @param eb the event_base structure returned by event_base_new()
+ @param flags a bitwise combination of the kinds of events to aggregate
+ counts for
+ @param clear option used to reset the maximum count.
+ @return the number of events specified in the flags
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_get_max_events(struct event_base *, unsigned int, int);
+
+/**
+ Allocates a new event configuration object.
+
+ The event configuration object can be used to change the behavior of
+ an event base.
+
+ @return an event_config object that can be used to store configuration, or
+ NULL if an error is encountered.
+ @see event_base_new_with_config(), event_config_free(), event_config
+*/
+EVENT2_EXPORT_SYMBOL
+struct event_config *event_config_new(void);
+
+/**
+ Deallocates all memory associated with an event configuration object
+
+ @param cfg the event configuration object to be freed.
+*/
+EVENT2_EXPORT_SYMBOL
+void event_config_free(struct event_config *cfg);
+
+/**
+ Enters an event method that should be avoided into the configuration.
+
+ This can be used to avoid event mechanisms that do not support certain
+ file descriptor types, or for debugging to avoid certain event
+ mechanisms. An application can make use of multiple event bases to
+ accommodate incompatible file descriptor types.
+
+ @param cfg the event configuration object
+ @param method the name of the event method to avoid
+ @return 0 on success, -1 on failure.
+*/
+EVENT2_EXPORT_SYMBOL
+int event_config_avoid_method(struct event_config *cfg, const char *method);
+
+/**
+ A flag used to describe which features an event_base (must) provide.
+
+ Because of OS limitations, not every Libevent backend supports every
+ possible feature. You can use this type with
+ event_config_require_features() to tell Libevent to only proceed if your
+ event_base implements a given feature, and you can receive this type from
+ event_base_get_features() to see which features are available.
+*/
+enum event_method_feature {
+ /** Require an event method that allows edge-triggered events with EV_ET. */
+ EV_FEATURE_ET = 0x01,
+ /** Require an event method where having one event triggered among
+ * many is [approximately] an O(1) operation. This excludes (for
+ * example) select and poll, which are approximately O(N) for N
+ * equal to the total number of possible events. */
+ EV_FEATURE_O1 = 0x02,
+ /** Require an event method that allows file descriptors as well as
+ * sockets. */
+ EV_FEATURE_FDS = 0x04,
+ /** Require an event method that allows you to use EV_CLOSED to detect
+ * connection close without the necessity of reading all the pending data.
+ *
+ * Methods that do support EV_CLOSED may not be able to provide support on
+ * all kernel versions.
+ **/
+ EV_FEATURE_EARLY_CLOSE = 0x08
+};
+
+/**
+ A flag passed to event_config_set_flag().
+
+ These flags change the behavior of an allocated event_base.
+
+ @see event_config_set_flag(), event_base_new_with_config(),
+ event_method_feature
+ */
+enum event_base_config_flag {
+ /** Do not allocate a lock for the event base, even if we have
+ locking set up.
+
+ Setting this option will make it unsafe and nonfunctional to call
+ functions on the base concurrently from multiple threads.
+ */
+ EVENT_BASE_FLAG_NOLOCK = 0x01,
+ /** Do not check the EVENT_* environment variables when configuring
+ an event_base */
+ EVENT_BASE_FLAG_IGNORE_ENV = 0x02,
+ /** Windows only: enable the IOCP dispatcher at startup
+
+ If this flag is set then bufferevent_socket_new() and
+ evconn_listener_new() will use IOCP-backed implementations
+ instead of the usual select-based one on Windows.
+ */
+ EVENT_BASE_FLAG_STARTUP_IOCP = 0x04,
+ /** Instead of checking the current time every time the event loop is
+ ready to run timeout callbacks, check after each timeout callback.
+ */
+ EVENT_BASE_FLAG_NO_CACHE_TIME = 0x08,
+
+ /** If we are using the epoll backend, this flag says that it is
+ safe to use Libevent's internal change-list code to batch up
+ adds and deletes in order to try to do as few syscalls as
+ possible. Setting this flag can make your code run faster, but
+ it may trigger a Linux bug: it is not safe to use this flag
+ if you have any fds cloned by dup() or its variants. Doing so
+ will produce strange and hard-to-diagnose bugs.
+
+ This flag can also be activated by setting the
+ EVENT_EPOLL_USE_CHANGELIST environment variable.
+
+ This flag has no effect if you wind up using a backend other than
+ epoll.
+ */
+ EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = 0x10,
+
+ /** Ordinarily, Libevent implements its time and timeout code using
+ the fastest monotonic timer that we have. If this flag is set,
+ however, we use less efficient more precise timer, assuming one is
+ present.
+ */
+ EVENT_BASE_FLAG_PRECISE_TIMER = 0x20
+};
+
+/**
+ Return a bitmask of the features implemented by an event base. This
+ will be a bitwise OR of one or more of the values of
+ event_method_feature
+
+ @see event_method_feature
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_get_features(const struct event_base *base);
+
+/**
+ Enters a required event method feature that the application demands.
+
+ Note that not every feature or combination of features is supported
+ on every platform. Code that requests features should be prepared
+ to handle the case where event_base_new_with_config() returns NULL, as in:
+ <pre>
+ event_config_require_features(cfg, EV_FEATURE_ET);
+ base = event_base_new_with_config(cfg);
+ if (base == NULL) {
+ // We can't get edge-triggered behavior here.
+ event_config_require_features(cfg, 0);
+ base = event_base_new_with_config(cfg);
+ }
+ </pre>
+
+ @param cfg the event configuration object
+ @param feature a bitfield of one or more event_method_feature values.
+ Replaces values from previous calls to this function.
+ @return 0 on success, -1 on failure.
+ @see event_method_feature, event_base_new_with_config()
+*/
+EVENT2_EXPORT_SYMBOL
+int event_config_require_features(struct event_config *cfg, int feature);
+
+/**
+ * Sets one or more flags to configure what parts of the eventual event_base
+ * will be initialized, and how they'll work.
+ *
+ * @see event_base_config_flags, event_base_new_with_config()
+ **/
+EVENT2_EXPORT_SYMBOL
+int event_config_set_flag(struct event_config *cfg, int flag);
+
+/**
+ * Records a hint for the number of CPUs in the system. This is used for
+ * tuning thread pools, etc, for optimal performance. In Libevent 2.0,
+ * it is only on Windows, and only when IOCP is in use.
+ *
+ * @param cfg the event configuration object
+ * @param cpus the number of cpus
+ * @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_config_set_num_cpus_hint(struct event_config *cfg, int cpus);
+
+/**
+ * Record an interval and/or a number of callbacks after which the event base
+ * should check for new events. By default, the event base will run as many
+ * events are as activated at the highest activated priority before checking
+ * for new events. If you configure it by setting max_interval, it will check
+ * the time after each callback, and not allow more than max_interval to
+ * elapse before checking for new events. If you configure it by setting
+ * max_callbacks to a value >= 0, it will run no more than max_callbacks
+ * callbacks before checking for new events.
+ *
+ * This option can decrease the latency of high-priority events, and
+ * avoid priority inversions where multiple low-priority events keep us from
+ * polling for high-priority events, but at the expense of slightly decreasing
+ * the throughput. Use it with caution!
+ *
+ * @param cfg The event_base configuration object.
+ * @param max_interval An interval after which Libevent should stop running
+ * callbacks and check for more events, or NULL if there should be
+ * no such interval.
+ * @param max_callbacks A number of callbacks after which Libevent should
+ * stop running callbacks and check for more events, or -1 if there
+ * should be no such limit.
+ * @param min_priority A priority below which max_interval and max_callbacks
+ * should not be enforced. If this is set to 0, they are enforced
+ * for events of every priority; if it's set to 1, they're enforced
+ * for events of priority 1 and above, and so on.
+ * @return 0 on success, -1 on failure.
+ **/
+EVENT2_EXPORT_SYMBOL
+int event_config_set_max_dispatch_interval(struct event_config *cfg,
+ const struct timeval *max_interval, int max_callbacks,
+ int min_priority);
+
+/**
+ Initialize the event API.
+
+ Use event_base_new_with_config() to initialize a new event base, taking
+ the specified configuration under consideration. The configuration object
+ can currently be used to avoid certain event notification mechanisms.
+
+ @param cfg the event configuration object
+ @return an initialized event_base that can be used to registering events,
+ or NULL if no event base can be created with the requested event_config.
+ @see event_base_new(), event_base_free(), event_init(), event_assign()
+*/
+EVENT2_EXPORT_SYMBOL
+struct event_base *event_base_new_with_config(const struct event_config *);
+
+/**
+ Deallocate all memory associated with an event_base, and free the base.
+
+ Note that this function will not close any fds or free any memory passed
+ to event_new as the argument to callback.
+
+ If there are any pending finalizer callbacks, this function will invoke
+ them.
+
+ @param eb an event_base to be freed
+ */
+EVENT2_EXPORT_SYMBOL
+void event_base_free(struct event_base *);
+
+/**
+ As event_base_free, but do not run finalizers.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_base_free_nofinalize(struct event_base *);
+
+/** @name Log severities
+ */
+/**@{*/
+#define EVENT_LOG_DEBUG 0
+#define EVENT_LOG_MSG 1
+#define EVENT_LOG_WARN 2
+#define EVENT_LOG_ERR 3
+/**@}*/
+
+/* Obsolete names: these are deprecated, but older programs might use them.
+ * They violate the reserved-identifier namespace. */
+#define _EVENT_LOG_DEBUG EVENT_LOG_DEBUG
+#define _EVENT_LOG_MSG EVENT_LOG_MSG
+#define _EVENT_LOG_WARN EVENT_LOG_WARN
+#define _EVENT_LOG_ERR EVENT_LOG_ERR
+
+/**
+ A callback function used to intercept Libevent's log messages.
+
+ @see event_set_log_callback
+ */
+typedef void (*event_log_cb)(int severity, const char *msg);
+/**
+ Redirect Libevent's log messages.
+
+ @param cb a function taking two arguments: an integer severity between
+ EVENT_LOG_DEBUG and EVENT_LOG_ERR, and a string. If cb is NULL,
+ then the default log is used.
+
+ NOTE: The function you provide *must not* call any other libevent
+ functionality. Doing so can produce undefined behavior.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_set_log_callback(event_log_cb cb);
+
+/**
+ A function to be called if Libevent encounters a fatal internal error.
+
+ @see event_set_fatal_callback
+ */
+typedef void (*event_fatal_cb)(int err);
+
+/**
+ Override Libevent's behavior in the event of a fatal internal error.
+
+ By default, Libevent will call exit(1) if a programming error makes it
+ impossible to continue correct operation. This function allows you to supply
+ another callback instead. Note that if the function is ever invoked,
+ something is wrong with your program, or with Libevent: any subsequent calls
+ to Libevent may result in undefined behavior.
+
+ Libevent will (almost) always log an EVENT_LOG_ERR message before calling
+ this function; look at the last log message to see why Libevent has died.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_set_fatal_callback(event_fatal_cb cb);
+
+#define EVENT_DBG_ALL 0xffffffffu
+#define EVENT_DBG_NONE 0
+
+/**
+ Turn on debugging logs and have them sent to the default log handler.
+
+ This is a global setting; if you are going to call it, you must call this
+ before any calls that create an event-base. You must call it before any
+ multithreaded use of Libevent.
+
+ Debug logs are verbose.
+
+ @param which Controls which debug messages are turned on. This option is
+ unused for now; for forward compatibility, you must pass in the constant
+ "EVENT_DBG_ALL" to turn debugging logs on, or "EVENT_DBG_NONE" to turn
+ debugging logs off.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_enable_debug_logging(ev_uint32_t which);
+
+/**
+ Associate a different event base with an event.
+
+ The event to be associated must not be currently active or pending.
+
+ @param eb the event base
+ @param ev the event
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_set(struct event_base *, struct event *);
+
+/** @name Loop flags
+
+ These flags control the behavior of event_base_loop().
+ */
+/**@{*/
+/** Block until we have an active event, then exit once all active events
+ * have had their callbacks run. */
+#define EVLOOP_ONCE 0x01
+/** Do not block: see which events are ready now, run the callbacks
+ * of the highest-priority ones, then exit. */
+#define EVLOOP_NONBLOCK 0x02
+/** Do not exit the loop because we have no pending events. Instead, keep
+ * running until event_base_loopexit() or event_base_loopbreak() makes us
+ * stop.
+ */
+#define EVLOOP_NO_EXIT_ON_EMPTY 0x04
+/**@}*/
+
+/**
+ Wait for events to become active, and run their callbacks.
+
+ This is a more flexible version of event_base_dispatch().
+
+ By default, this loop will run the event base until either there are no more
+ pending or active events, or until something calls event_base_loopbreak() or
+ event_base_loopexit(). You can override this behavior with the 'flags'
+ argument.
+
+ @param eb the event_base structure returned by event_base_new() or
+ event_base_new_with_config()
+ @param flags any combination of EVLOOP_ONCE | EVLOOP_NONBLOCK
+ @return 0 if successful, -1 if an error occurred, or 1 if we exited because
+ no events were pending or active.
+ @see event_base_loopexit(), event_base_dispatch(), EVLOOP_ONCE,
+ EVLOOP_NONBLOCK
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_loop(struct event_base *, int);
+
+/**
+ Exit the event loop after the specified time
+
+ The next event_base_loop() iteration after the given timer expires will
+ complete normally (handling all queued events) then exit without
+ blocking for events again.
+
+ Subsequent invocations of event_base_loop() will proceed normally.
+
+ @param eb the event_base structure returned by event_init()
+ @param tv the amount of time after which the loop should terminate,
+ or NULL to exit after running all currently active events.
+ @return 0 if successful, or -1 if an error occurred
+ @see event_base_loopbreak()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_loopexit(struct event_base *, const struct timeval *);
+
+/**
+ Abort the active event_base_loop() immediately.
+
+ event_base_loop() will abort the loop after the next event is completed;
+ event_base_loopbreak() is typically invoked from this event's callback.
+ This behavior is analogous to the "break;" statement.
+
+ Subsequent invocations of event_base_loop() will proceed normally.
+
+ @param eb the event_base structure returned by event_init()
+ @return 0 if successful, or -1 if an error occurred
+ @see event_base_loopexit()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_loopbreak(struct event_base *);
+
+/**
+ Tell the active event_base_loop() to scan for new events immediately.
+
+ Calling this function makes the currently active event_base_loop()
+ start the loop over again (scanning for new events) after the current
+ event callback finishes. If the event loop is not running, this
+ function has no effect.
+
+ event_base_loopbreak() is typically invoked from this event's callback.
+ This behavior is analogous to the "continue;" statement.
+
+ Subsequent invocations of event loop will proceed normally.
+
+ @param eb the event_base structure returned by event_init()
+ @return 0 if successful, or -1 if an error occurred
+ @see event_base_loopbreak()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_loopcontinue(struct event_base *);
+
+/**
+ Checks if the event loop was told to exit by event_base_loopexit().
+
+ This function will return true for an event_base at every point after
+ event_loopexit() is called, until the event loop is next entered.
+
+ @param eb the event_base structure returned by event_init()
+ @return true if event_base_loopexit() was called on this event base,
+ or 0 otherwise
+ @see event_base_loopexit()
+ @see event_base_got_break()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_got_exit(struct event_base *);
+
+/**
+ Checks if the event loop was told to abort immediately by event_base_loopbreak().
+
+ This function will return true for an event_base at every point after
+ event_base_loopbreak() is called, until the event loop is next entered.
+
+ @param eb the event_base structure returned by event_init()
+ @return true if event_base_loopbreak() was called on this event base,
+ or 0 otherwise
+ @see event_base_loopbreak()
+ @see event_base_got_exit()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_got_break(struct event_base *);
+
+/**
+ * @name event flags
+ *
+ * Flags to pass to event_new(), event_assign(), event_pending(), and
+ * anything else with an argument of the form "short events"
+ */
+/**@{*/
+/** Indicates that a timeout has occurred. It's not necessary to pass
+ * this flag to event_for new()/event_assign() to get a timeout. */
+#define EV_TIMEOUT 0x01
+/** Wait for a socket or FD to become readable */
+#define EV_READ 0x02
+/** Wait for a socket or FD to become writeable */
+#define EV_WRITE 0x04
+/** Wait for a POSIX signal to be raised*/
+#define EV_SIGNAL 0x08
+/**
+ * Persistent event: won't get removed automatically when activated.
+ *
+ * When a persistent event with a timeout becomes activated, its timeout
+ * is reset to 0.
+ */
+#define EV_PERSIST 0x10
+/** Select edge-triggered behavior, if supported by the backend. */
+#define EV_ET 0x20
+/**
+ * If this option is provided, then event_del() will not block in one thread
+ * while waiting for the event callback to complete in another thread.
+ *
+ * To use this option safely, you may need to use event_finalize() or
+ * event_free_finalize() in order to safely tear down an event in a
+ * multithreaded application. See those functions for more information.
+ **/
+#define EV_FINALIZE 0x40
+/**
+ * Detects connection close events. You can use this to detect when a
+ * connection has been closed, without having to read all the pending data
+ * from a connection.
+ *
+ * Not all backends support EV_CLOSED. To detect or require it, use the
+ * feature flag EV_FEATURE_EARLY_CLOSE.
+ **/
+#define EV_CLOSED 0x80
+/**@}*/
+
+/**
+ @name evtimer_* macros
+
+ Aliases for working with one-shot timer events
+ If you need EV_PERSIST timer use event_*() functions.
+ */
+/**@{*/
+#define evtimer_assign(ev, b, cb, arg) \
+ event_assign((ev), (b), -1, 0, (cb), (arg))
+#define evtimer_new(b, cb, arg) event_new((b), -1, 0, (cb), (arg))
+#define evtimer_add(ev, tv) event_add((ev), (tv))
+#define evtimer_del(ev) event_del(ev)
+#define evtimer_pending(ev, tv) event_pending((ev), EV_TIMEOUT, (tv))
+#define evtimer_initialized(ev) event_initialized(ev)
+/**@}*/
+
+/**
+ @name evsignal_* macros
+
+ Aliases for working with signal events
+ */
+/**@{*/
+#define evsignal_add(ev, tv) event_add((ev), (tv))
+#define evsignal_assign(ev, b, x, cb, arg) \
+ event_assign((ev), (b), (x), EV_SIGNAL|EV_PERSIST, cb, (arg))
+#define evsignal_new(b, x, cb, arg) \
+ event_new((b), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+#define evsignal_del(ev) event_del(ev)
+#define evsignal_pending(ev, tv) event_pending((ev), EV_SIGNAL, (tv))
+#define evsignal_initialized(ev) event_initialized(ev)
+/**@}*/
+
+/**
+ @name evuser_* macros
+
+ Aliases for working with user-triggered events
+ If you need EV_PERSIST event use event_*() functions.
+ */
+/**@{*/
+#define evuser_new(b, cb, arg) event_new((b), -1, 0, (cb), (arg))
+#define evuser_del(ev) event_del(ev)
+#define evuser_pending(ev, tv) event_pending((ev), 0, (tv))
+#define evuser_initialized(ev) event_initialized(ev)
+#define evuser_trigger(ev) event_active((ev), 0, 0)
+/**@}*/
+
+/**
+ A callback function for an event.
+
+ It receives three arguments:
+
+ @param fd An fd or signal
+ @param events One or more EV_* flags
+ @param arg A user-supplied argument.
+
+ @see event_new()
+ */
+typedef void (*event_callback_fn)(evutil_socket_t, short, void *);
+
+/**
+ Return a value used to specify that the event itself must be used as the callback argument.
+
+ The function event_new() takes a callback argument which is passed
+ to the event's callback function. To specify that the argument to be
+ passed to the callback function is the event that event_new() returns,
+ pass in the return value of event_self_cbarg() as the callback argument
+ for event_new().
+
+ For example:
+ <pre>
+ struct event *ev = event_new(base, sock, events, callback, %event_self_cbarg());
+ </pre>
+
+ For consistency with event_new(), it is possible to pass the return value
+ of this function as the callback argument for event_assign() &ndash; this
+ achieves the same result as passing the event in directly.
+
+ @return a value to be passed as the callback argument to event_new() or
+ event_assign().
+ @see event_new(), event_assign()
+ */
+EVENT2_EXPORT_SYMBOL
+void *event_self_cbarg(void);
+
+/**
+ Allocate and assign a new event structure, ready to be added.
+
+ The function event_new() returns a new event that can be used in
+ future calls to event_add() and event_del(). The fd and events
+ arguments determine which conditions will trigger the event; the
+ callback and callback_arg arguments tell Libevent what to do when the
+ event becomes active.
+
+ If events contains one of EV_READ, EV_WRITE, or EV_READ|EV_WRITE, then
+ fd is a file descriptor or socket that should get monitored for
+ readiness to read, readiness to write, or readiness for either operation
+ (respectively). If events contains EV_SIGNAL, then fd is a signal
+ number to wait for. If events contains none of those flags, then the
+ event can be triggered only by a timeout or by manual activation with
+ event_active(): In this case, fd must be -1.
+
+ The EV_PERSIST flag can also be passed in the events argument: it makes
+ event_add() persistent until event_del() is called.
+
+ The EV_ET flag is compatible with EV_READ and EV_WRITE, and supported
+ only by certain backends. It tells Libevent to use edge-triggered
+ events.
+
+ The EV_TIMEOUT flag has no effect here.
+
+ It is okay to have multiple events all listening on the same fds; but
+ they must either all be edge-triggered, or all not be edge triggered.
+
+ When the event becomes active, the event loop will run the provided
+ callback function, with three arguments. The first will be the provided
+ fd value. The second will be a bitfield of the events that triggered:
+ EV_READ, EV_WRITE, or EV_SIGNAL. Here the EV_TIMEOUT flag indicates
+ that a timeout occurred, and EV_ET indicates that an edge-triggered
+ event occurred. The third event will be the callback_arg pointer that
+ you provide.
+
+ @param base the event base to which the event should be attached.
+ @param fd the file descriptor or signal to be monitored, or -1.
+ @param events desired events to monitor: bitfield of EV_READ, EV_WRITE,
+ EV_SIGNAL, EV_PERSIST, EV_ET.
+ @param callback callback function to be invoked when the event occurs
+ @param callback_arg an argument to be passed to the callback function
+
+ @return a newly allocated struct event that must later be freed with
+ event_free() or NULL if an error occurred.
+ @see event_free(), event_add(), event_del(), event_assign()
+ */
+EVENT2_EXPORT_SYMBOL
+struct event *event_new(struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
+
+
+/**
+ Prepare a new, already-allocated event structure to be added.
+
+ The function event_assign() prepares the event structure ev to be used
+ in future calls to event_add() and event_del(). Unlike event_new(), it
+ doesn't allocate memory itself: it requires that you have already
+ allocated a struct event, probably on the heap. Doing this will
+ typically make your code depend on the size of the event structure, and
+ thereby create incompatibility with future versions of Libevent.
+
+ The easiest way to avoid this problem is just to use event_new() and
+ event_free() instead.
+
+ A slightly harder way to future-proof your code is to use
+ event_get_struct_event_size() to determine the required size of an event
+ at runtime.
+
+ Note that it is NOT safe to call this function on an event that is
+ active or pending. Doing so WILL corrupt internal data structures in
+ Libevent, and lead to strange, hard-to-diagnose bugs. You _can_ use
+ event_assign to change an existing event, but only if it is not active
+ or pending!
+
+ The arguments for this function, and the behavior of the events that it
+ makes, are as for event_new().
+
+ @param ev an event struct to be modified
+ @param base the event base to which ev should be attached.
+ @param fd the file descriptor to be monitored
+ @param events desired events to monitor; can be EV_READ and/or EV_WRITE
+ @param callback callback function to be invoked when the event occurs
+ @param callback_arg an argument to be passed to the callback function
+
+ @return 0 if success, or -1 on invalid arguments.
+
+ @see event_new(), event_add(), event_del(), event_base_once(),
+ event_get_struct_event_size()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_assign(struct event *, struct event_base *, evutil_socket_t, short, event_callback_fn, void *);
+
+/**
+ Deallocate a struct event * returned by event_new().
+
+ If the event is pending or active, this function makes it non-pending
+ and non-active first.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_free(struct event *);
+
+/**
+ * Callback type for event_finalize and event_free_finalize().
+ **/
+typedef void (*event_finalize_callback_fn)(struct event *, void *);
+/**
+ @name Finalization functions
+
+ These functions are used to safely tear down an event in a multithreaded
+ application. If you construct your events with EV_FINALIZE to avoid
+ deadlocks, you will need a way to remove an event in the certainty that
+ it will definitely not be running its callback when you deallocate it
+ and its callback argument.
+
+ To do this, call one of event_finalize() or event_free_finalize with
+ 0 for its first argument, the event to tear down as its second argument,
+ and a callback function as its third argument. The callback will be
+ invoked as part of the event loop, with the event's priority.
+
+ After you call a finalizer function, event_add() and event_active() will
+ no longer work on the event, and event_del() will produce a no-op. You
+ must not try to change the event's fields with event_assign() or
+ event_set() while the finalize callback is in progress. Once the
+ callback has been invoked, you should treat the event structure as
+ containing uninitialized memory.
+
+ The event_free_finalize() function frees the event after it's finalized;
+ event_finalize() does not.
+
+ A finalizer callback must not make events pending or active. It must not
+ add events, activate events, or attempt to "resuscitate" the event being
+ finalized in any way.
+
+ @return 0 on success, -1 on failure.
+ */
+/**@{*/
+EVENT2_EXPORT_SYMBOL
+int event_finalize(unsigned, struct event *, event_finalize_callback_fn);
+EVENT2_EXPORT_SYMBOL
+int event_free_finalize(unsigned, struct event *, event_finalize_callback_fn);
+/**@}*/
+
+/**
+ Schedule a one-time event
+
+ The function event_base_once() is similar to event_new(). However, it
+ schedules a callback to be called exactly once, and does not require the
+ caller to prepare an event structure.
+
+ Note that in Libevent 2.0 and earlier, if the event is never triggered, the
+ internal memory used to hold it will never be freed. In Libevent 2.1,
+ the internal memory will get freed by event_base_free() if the event
+ is never triggered. The 'arg' value, however, will not get freed in either
+ case--you'll need to free that on your own if you want it to go away.
+
+ @param base an event_base
+ @param fd a file descriptor to monitor, or -1 for no fd.
+ @param events event(s) to monitor; can be any of EV_READ |
+ EV_WRITE, or EV_TIMEOUT
+ @param callback callback function to be invoked when the event occurs
+ @param arg an argument to be passed to the callback function
+ @param timeout the maximum amount of time to wait for the event. NULL
+ makes an EV_READ/EV_WRITE event make forever; NULL makes an
+ EV_TIMEOUT event success immediately.
+ @return 0 if successful, or -1 if an error occurred
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_once(struct event_base *, evutil_socket_t, short, event_callback_fn, void *, const struct timeval *);
+
+/**
+ Add an event to the set of pending events.
+
+ The function event_add() schedules the execution of the event 'ev' when the
+ condition specified by event_assign() or event_new() occurs, or when the time
+ specified in timeout has elapsed. If a timeout is NULL, no timeout
+ occurs and the function will only be
+ called if a matching event occurs. The event in the
+ ev argument must be already initialized by event_assign() or event_new()
+ and may not be used
+ in calls to event_assign() until it is no longer pending.
+
+ If the event in the ev argument already has a scheduled timeout, calling
+ event_add() replaces the old timeout with the new one if tv is non-NULL.
+
+ @param ev an event struct initialized via event_assign() or event_new()
+ @param timeout the maximum amount of time to wait for the event, or NULL
+ to wait forever
+ @return 0 if successful, or -1 if an error occurred
+ @see event_del(), event_assign(), event_new()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_add(struct event *ev, const struct timeval *timeout);
+
+/**
+ Remove a timer from a pending event without removing the event itself.
+
+ If the event has a scheduled timeout, this function unschedules it but
+ leaves the event otherwise pending.
+
+ @param ev an event struct initialized via event_assign() or event_new()
+ @return 0 on success, or -1 if an error occurred.
+*/
+EVENT2_EXPORT_SYMBOL
+int event_remove_timer(struct event *ev);
+
+/**
+ Remove an event from the set of monitored events.
+
+ The function event_del() will cancel the event in the argument ev. If the
+ event has already executed or has never been added the call will have no
+ effect.
+
+ @param ev an event struct to be removed from the working set
+ @return 0 if successful, or -1 if an error occurred
+ @see event_add()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_del(struct event *);
+
+/**
+ As event_del(), but never blocks while the event's callback is running
+ in another thread, even if the event was constructed without the
+ EV_FINALIZE flag.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_del_noblock(struct event *ev);
+/**
+ As event_del(), but always blocks while the event's callback is running
+ in another thread, even if the event was constructed with the
+ EV_FINALIZE flag.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_del_block(struct event *ev);
+
+/**
+ Make an event active.
+
+ You can use this function on a pending or a non-pending event to make it
+ active, so that its callback will be run by event_base_dispatch() or
+ event_base_loop().
+
+ One common use in multithreaded programs is to wake the thread running
+ event_base_loop() from another thread.
+
+ @param ev an event to make active.
+ @param res a set of flags to pass to the event's callback.
+ @param ncalls an obsolete argument: this is ignored.
+ **/
+EVENT2_EXPORT_SYMBOL
+void event_active(struct event *ev, int res, short ncalls);
+
+/**
+ Checks if a specific event is pending or scheduled.
+
+ @param ev an event struct previously passed to event_add()
+ @param events the requested event type; any of EV_TIMEOUT|EV_READ|
+ EV_WRITE|EV_SIGNAL
+ @param tv if this field is not NULL, and the event has a timeout,
+ this field is set to hold the time at which the timeout will
+ expire.
+
+ @return true if the event is pending on any of the events in 'what', (that
+ is to say, it has been added), or 0 if the event is not added.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_pending(const struct event *ev, short events, struct timeval *tv);
+
+/**
+ If called from within the callback for an event, returns that event.
+
+ The behavior of this function is not defined when called from outside the
+ callback function for an event.
+ */
+EVENT2_EXPORT_SYMBOL
+struct event *event_base_get_running_event(struct event_base *base);
+
+/**
+ Test if an event structure might be initialized.
+
+ The event_initialized() function can be used to check if an event has been
+ initialized.
+
+ Warning: This function is only useful for distinguishing a zeroed-out
+ piece of memory from an initialized event, it can easily be confused by
+ uninitialized memory. Thus, it should ONLY be used to distinguish an
+ initialized event from zero.
+
+ @param ev an event structure to be tested
+ @return 1 if the structure might be initialized, or 0 if it has not been
+ initialized
+ */
+EVENT2_EXPORT_SYMBOL
+int event_initialized(const struct event *ev);
+
+/**
+ Get the signal number assigned to a signal event
+*/
+#define event_get_signal(ev) ((int)event_get_fd(ev))
+
+/**
+ Get the socket or signal assigned to an event, or -1 if the event has
+ no socket.
+*/
+EVENT2_EXPORT_SYMBOL
+evutil_socket_t event_get_fd(const struct event *ev);
+
+/**
+ Get the event_base associated with an event.
+*/
+EVENT2_EXPORT_SYMBOL
+struct event_base *event_get_base(const struct event *ev);
+
+/**
+ Return the events (EV_READ, EV_WRITE, etc) assigned to an event.
+*/
+EVENT2_EXPORT_SYMBOL
+short event_get_events(const struct event *ev);
+
+/**
+ Return the callback assigned to an event.
+*/
+EVENT2_EXPORT_SYMBOL
+event_callback_fn event_get_callback(const struct event *ev);
+
+/**
+ Return the callback argument assigned to an event.
+*/
+EVENT2_EXPORT_SYMBOL
+void *event_get_callback_arg(const struct event *ev);
+
+/**
+ Return the priority of an event.
+ @see event_priority_init(), event_get_priority()
+*/
+EVENT2_EXPORT_SYMBOL
+int event_get_priority(const struct event *ev);
+
+/**
+ Extract _all_ of arguments given to construct a given event. The
+ event_base is copied into *base_out, the fd is copied into *fd_out, and so
+ on.
+
+ If any of the "_out" arguments is NULL, it will be ignored.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_get_assignment(const struct event *event,
+ struct event_base **base_out, evutil_socket_t *fd_out, short *events_out,
+ event_callback_fn *callback_out, void **arg_out);
+
+/**
+ Return the size of struct event that the Libevent library was compiled
+ with.
+
+ This will be NO GREATER than sizeof(struct event) if you're running with
+ the same version of Libevent that your application was built with, but
+ otherwise might not.
+
+ Note that it might be SMALLER than sizeof(struct event) if some future
+ version of Libevent adds extra padding to the end of struct event.
+ We might do this to help ensure ABI-compatibility between different
+ versions of Libevent.
+ */
+EVENT2_EXPORT_SYMBOL
+size_t event_get_struct_event_size(void);
+
+/**
+ Get the Libevent version.
+
+ Note that this will give you the version of the library that you're
+ currently linked against, not the version of the headers that you've
+ compiled against.
+
+ @return a string containing the version number of Libevent
+*/
+EVENT2_EXPORT_SYMBOL
+const char *event_get_version(void);
+
+/**
+ Return a numeric representation of Libevent's version.
+
+ Note that this will give you the version of the library that you're
+ currently linked against, not the version of the headers you've used to
+ compile.
+
+ The format uses one byte each for the major, minor, and patchlevel parts of
+ the version number. The low-order byte is unused. For example, version
+ 2.0.1-alpha has a numeric representation of 0x02000100
+*/
+EVENT2_EXPORT_SYMBOL
+ev_uint32_t event_get_version_number(void);
+
+/** As event_get_version, but gives the version of Libevent's headers. */
+#define LIBEVENT_VERSION EVENT__VERSION
+/** As event_get_version_number, but gives the version number of Libevent's
+ * headers. */
+#define LIBEVENT_VERSION_NUMBER EVENT__NUMERIC_VERSION
+
+/** Largest number of priorities that Libevent can support. */
+#define EVENT_MAX_PRIORITIES 256
+/**
+ Set the number of different event priorities
+
+ By default Libevent schedules all active events with the same priority.
+ However, some time it is desirable to process some events with a higher
+ priority than others. For that reason, Libevent supports strict priority
+ queues. Active events with a lower priority are always processed before
+ events with a higher priority.
+
+ The number of different priorities can be set initially with the
+ event_base_priority_init() function. This function should be called
+ before the first call to event_base_dispatch(). The
+ event_priority_set() function can be used to assign a priority to an
+ event. By default, Libevent assigns the middle priority to all events
+ unless their priority is explicitly set.
+
+ Note that urgent-priority events can starve less-urgent events: after
+ running all urgent-priority callbacks, Libevent checks for more urgent
+ events again, before running less-urgent events. Less-urgent events
+ will not have their callbacks run until there are no events more urgent
+ than them that want to be active.
+
+ @param eb the event_base structure returned by event_base_new()
+ @param npriorities the maximum number of priorities
+ @return 0 if successful, or -1 if an error occurred
+ @see event_priority_set()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_priority_init(struct event_base *, int);
+
+/**
+ Get the number of different event priorities.
+
+ @param eb the event_base structure returned by event_base_new()
+ @return Number of different event priorities
+ @see event_base_priority_init()
+*/
+EVENT2_EXPORT_SYMBOL
+int event_base_get_npriorities(struct event_base *eb);
+
+/**
+ Assign a priority to an event.
+
+ @param ev an event struct
+ @param priority the new priority to be assigned
+ @return 0 if successful, or -1 if an error occurred
+ @see event_priority_init(), event_get_priority()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_priority_set(struct event *, int);
+
+/**
+ Prepare an event_base to use a large number of timeouts with the same
+ duration.
+
+ Libevent's default scheduling algorithm is optimized for having a large
+ number of timeouts with their durations more or less randomly
+ distributed. But if you have a large number of timeouts that all have
+ the same duration (for example, if you have a large number of
+ connections that all have a 10-second timeout), then you can improve
+ Libevent's performance by telling Libevent about it.
+
+ To do this, call this function with the common duration. It will return a
+ pointer to a different, opaque timeout value. (Don't depend on its actual
+ contents!) When you use this timeout value in event_add(), Libevent will
+ schedule the event more efficiently.
+
+ (This optimization probably will not be worthwhile until you have thousands
+ or tens of thousands of events with the same timeout.)
+ */
+EVENT2_EXPORT_SYMBOL
+const struct timeval *event_base_init_common_timeout(struct event_base *base,
+ const struct timeval *duration);
+
+#if !defined(EVENT__DISABLE_MM_REPLACEMENT) || defined(EVENT_IN_DOXYGEN_)
+/**
+ Override the functions that Libevent uses for memory management.
+
+ Usually, Libevent uses the standard libc functions malloc, realloc, and
+ free to allocate memory. Passing replacements for those functions to
+ event_set_mem_functions() overrides this behavior.
+
+ Note that all memory returned from Libevent will be allocated by the
+ replacement functions rather than by malloc() and realloc(). Thus, if you
+ have replaced those functions, it will not be appropriate to free() memory
+ that you get from Libevent. Instead, you must use the free_fn replacement
+ that you provided.
+
+ Note also that if you are going to call this function, you should do so
+ before any call to any Libevent function that does allocation.
+ Otherwise, those functions will allocate their memory using malloc(), but
+ then later free it using your provided free_fn.
+
+ @param malloc_fn A replacement for malloc.
+ @param realloc_fn A replacement for realloc
+ @param free_fn A replacement for free.
+ **/
+EVENT2_EXPORT_SYMBOL
+void event_set_mem_functions(
+ void *(*malloc_fn)(size_t sz),
+ void *(*realloc_fn)(void *ptr, size_t sz),
+ void (*free_fn)(void *ptr));
+/** This definition is present if Libevent was built with support for
+ event_set_mem_functions() */
+#define EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+#endif
+
+/**
+ Writes a human-readable description of all inserted and/or active
+ events to a provided stdio stream.
+
+ This is intended for debugging; its format is not guaranteed to be the same
+ between libevent versions.
+
+ @param base An event_base on which to scan the events.
+ @param output A stdio file to write on.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_base_dump_events(struct event_base *, FILE *);
+
+
+/**
+ Activates all pending events for the given fd and event mask.
+
+ This function activates pending events only. Events which have not been
+ added will not become active.
+
+ @param base the event_base on which to activate the events.
+ @param fd An fd to active events on.
+ @param events One or more of EV_{READ,WRITE,TIMEOUT}.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_base_active_by_fd(struct event_base *base, evutil_socket_t fd, short events);
+
+/**
+ Activates all pending signals with a given signal number
+
+ This function activates pending events only. Events which have not been
+ added will not become active.
+
+ @param base the event_base on which to activate the events.
+ @param fd The signal to active events on.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_base_active_by_signal(struct event_base *base, int sig);
+
+/**
+ * Callback for iterating events in an event base via event_base_foreach_event
+ */
+typedef int (*event_base_foreach_event_cb)(const struct event_base *, const struct event *, void *);
+
+/**
+ Iterate over all added or active events events in an event loop, and invoke
+ a given callback on each one.
+
+ The callback must not call any function that modifies the event base, that
+ modifies any event in the event base, or that adds or removes any event to
+ the event base. Doing so is unsupported and will lead to undefined
+ behavior -- likely, to crashes.
+
+ event_base_foreach_event() holds a lock on the event_base() for the whole
+ time it's running: slow callbacks are not advisable.
+
+ Note that Libevent adds some events of its own to make pieces of its
+ functionality work. You must not assume that the only events you'll
+ encounter will be the ones you added yourself.
+
+ The callback function must return 0 to continue iteration, or some other
+ integer to stop iterating.
+
+ @param base An event_base on which to scan the events.
+ @param fn A callback function to receive the events.
+ @param arg An argument passed to the callback function.
+ @return 0 if we iterated over every event, or the value returned by the
+ callback function if the loop exited early.
+*/
+EVENT2_EXPORT_SYMBOL
+int event_base_foreach_event(struct event_base *base, event_base_foreach_event_cb fn, void *arg);
+
+
+/** Sets 'tv' to the current time (as returned by gettimeofday()),
+ looking at the cached value in 'base' if possible, and calling
+ gettimeofday() or clock_gettime() as appropriate if there is no
+ cached time.
+
+ Generally, this value will only be cached while actually
+ processing event callbacks, and may be very inaccurate if your
+ callbacks take a long time to execute.
+
+ Returns 0 on success, negative on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_gettimeofday_cached(struct event_base *base,
+ struct timeval *tv);
+
+/** Update cached_tv in the 'base' to the current time
+ *
+ * You can use this function is useful for selectively increasing
+ * the accuracy of the cached time value in 'base' during callbacks
+ * that take a long time to execute.
+ *
+ * This function has no effect if the base is currently not in its
+ * event loop, or if timeval caching is disabled via
+ * EVENT_BASE_FLAG_NO_CACHE_TIME.
+ *
+ * @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int event_base_update_cache_time(struct event_base *base);
+
+/** Release up all globally-allocated resources allocated by Libevent.
+
+ This function does not free developer-controlled resources like
+ event_bases, events, bufferevents, listeners, and so on. It only releases
+ resources like global locks that there is no other way to free.
+
+ It is not actually necessary to call this function before exit: every
+ resource that it frees would be released anyway on exit. It mainly exists
+ so that resource-leak debugging tools don't see Libevent as holding
+ resources at exit.
+
+ You should only call this function when no other Libevent functions will
+ be invoked -- e.g., when cleanly exiting a program.
+ */
+EVENT2_EXPORT_SYMBOL
+void libevent_global_shutdown(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/event_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/event_compat.h
new file mode 100644
index 0000000000..5110175a1b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/event_compat.h
@@ -0,0 +1,230 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_EVENT_COMPAT_H_INCLUDED_
+#define EVENT2_EVENT_COMPAT_H_INCLUDED_
+
+/** @file event2/event_compat.h
+
+ Potentially non-threadsafe versions of the functions in event.h: provided
+ only for backwards compatibility.
+
+ In the oldest versions of Libevent, event_base was not a first-class
+ structure. Instead, there was a single event base that every function
+ manipulated. Later, when separate event bases were added, the old functions
+ that didn't take an event_base argument needed to work by manipulating the
+ "current" event base. This could lead to thread-safety issues, and obscure,
+ hard-to-diagnose bugs.
+
+ @deprecated All functions in this file are by definition deprecated.
+ */
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ Initialize the event API.
+
+ The event API needs to be initialized with event_init() before it can be
+ used. Sets the global current base that gets used for events that have no
+ base associated with them.
+
+ @deprecated This function is deprecated because it replaces the "current"
+ event_base, and is totally unsafe for multithreaded use. The replacement
+ is event_base_new().
+
+ @see event_base_set(), event_base_new()
+ */
+EVENT2_EXPORT_SYMBOL
+struct event_base *event_init(void);
+
+/**
+ Loop to process events.
+
+ Like event_base_dispatch(), but uses the "current" base.
+
+ @deprecated This function is deprecated because it is easily confused by
+ multiple calls to event_init(), and because it is not safe for
+ multithreaded use. The replacement is event_base_dispatch().
+
+ @see event_base_dispatch(), event_init()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_dispatch(void);
+
+/**
+ Handle events.
+
+ This function behaves like event_base_loop(), but uses the "current" base
+
+ @deprecated This function is deprecated because it uses the event base from
+ the last call to event_init, and is therefore not safe for multithreaded
+ use. The replacement is event_base_loop().
+
+ @see event_base_loop(), event_init()
+*/
+EVENT2_EXPORT_SYMBOL
+int event_loop(int);
+
+
+/**
+ Exit the event loop after the specified time.
+
+ This function behaves like event_base_loopexit(), except that it uses the
+ "current" base.
+
+ @deprecated This function is deprecated because it uses the event base from
+ the last call to event_init, and is therefore not safe for multithreaded
+ use. The replacement is event_base_loopexit().
+
+ @see event_init, event_base_loopexit()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_loopexit(const struct timeval *);
+
+
+/**
+ Abort the active event_loop() immediately.
+
+ This function behaves like event_base_loopbreakt(), except that it uses the
+ "current" base.
+
+ @deprecated This function is deprecated because it uses the event base from
+ the last call to event_init, and is therefore not safe for multithreaded
+ use. The replacement is event_base_loopbreak().
+
+ @see event_base_loopbreak(), event_init()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_loopbreak(void);
+
+/**
+ Schedule a one-time event to occur.
+
+ @deprecated This function is obsolete, and has been replaced by
+ event_base_once(). Its use is deprecated because it relies on the
+ "current" base configured by event_init().
+
+ @see event_base_once()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_once(evutil_socket_t , short,
+ void (*)(evutil_socket_t, short, void *), void *, const struct timeval *);
+
+
+/**
+ Get the kernel event notification mechanism used by Libevent.
+
+ @deprecated This function is obsolete, and has been replaced by
+ event_base_get_method(). Its use is deprecated because it relies on the
+ "current" base configured by event_init().
+
+ @see event_base_get_method()
+ */
+EVENT2_EXPORT_SYMBOL
+const char *event_get_method(void);
+
+
+/**
+ Set the number of different event priorities.
+
+ @deprecated This function is deprecated because it is easily confused by
+ multiple calls to event_init(), and because it is not safe for
+ multithreaded use. The replacement is event_base_priority_init().
+
+ @see event_base_priority_init()
+ */
+EVENT2_EXPORT_SYMBOL
+int event_priority_init(int);
+
+/**
+ Prepare an event structure to be added.
+
+ @deprecated event_set() is not recommended for new code, because it requires
+ a subsequent call to event_base_set() to be safe under most circumstances.
+ Use event_assign() or event_new() instead.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_set(struct event *, evutil_socket_t, short, void (*)(evutil_socket_t, short, void *), void *);
+
+#define evtimer_set(ev, cb, arg) event_set((ev), -1, 0, (cb), (arg))
+#define evsignal_set(ev, x, cb, arg) \
+ event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+
+
+/**
+ @name timeout_* macros
+
+ @deprecated These macros are deprecated because their naming is inconsistent
+ with the rest of Libevent. Use the evtimer_* macros instead.
+ @{
+ */
+#define timeout_add(ev, tv) event_add((ev), (tv))
+#define timeout_set(ev, cb, arg) event_set((ev), -1, 0, (cb), (arg))
+#define timeout_del(ev) event_del(ev)
+#define timeout_pending(ev, tv) event_pending((ev), EV_TIMEOUT, (tv))
+#define timeout_initialized(ev) event_initialized(ev)
+/**@}*/
+
+/**
+ @name signal_* macros
+
+ @deprecated These macros are deprecated because their naming is inconsistent
+ with the rest of Libevent. Use the evsignal_* macros instead.
+ @{
+ */
+#define signal_add(ev, tv) event_add((ev), (tv))
+#define signal_set(ev, x, cb, arg) \
+ event_set((ev), (x), EV_SIGNAL|EV_PERSIST, (cb), (arg))
+#define signal_del(ev) event_del(ev)
+#define signal_pending(ev, tv) event_pending((ev), EV_SIGNAL, (tv))
+#define signal_initialized(ev) event_initialized(ev)
+/**@}*/
+
+#ifndef EVENT_FD
+/* These macros are obsolete; use event_get_fd and event_get_signal instead. */
+#define EVENT_FD(ev) ((int)event_get_fd(ev))
+#define EVENT_SIGNAL(ev) event_get_signal(ev)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/event_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/event_struct.h
new file mode 100644
index 0000000000..1c8b71b6b0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/event_struct.h
@@ -0,0 +1,180 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_EVENT_STRUCT_H_INCLUDED_
+#define EVENT2_EVENT_STRUCT_H_INCLUDED_
+
+/** @file event2/event_struct.h
+
+ Structures used by event.h. Using these structures directly WILL harm
+ forward compatibility: be careful.
+
+ No field declared in this file should be used directly in user code. Except
+ for historical reasons, these fields would not be exposed at all.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/* For evkeyvalq */
+#include <event2/keyvalq_struct.h>
+
+#define EVLIST_TIMEOUT 0x01
+#define EVLIST_INSERTED 0x02
+#define EVLIST_SIGNAL 0x04
+#define EVLIST_ACTIVE 0x08
+#define EVLIST_INTERNAL 0x10
+#define EVLIST_ACTIVE_LATER 0x20
+#define EVLIST_FINALIZING 0x40
+#define EVLIST_INIT 0x80
+
+#define EVLIST_ALL 0xff
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+#ifndef TAILQ_ENTRY
+#define EVENT_DEFINED_TQENTRY_
+#define TAILQ_ENTRY(type) \
+struct { \
+ struct type *tqe_next; /* next element */ \
+ struct type **tqe_prev; /* address of previous next element */ \
+}
+#endif /* !TAILQ_ENTRY */
+
+#ifndef TAILQ_HEAD
+#define EVENT_DEFINED_TQHEAD_
+#define TAILQ_HEAD(name, type) \
+struct name { \
+ struct type *tqh_first; \
+ struct type **tqh_last; \
+}
+#endif
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+#ifndef LIST_ENTRY
+#define EVENT_DEFINED_LISTENTRY_
+#define LIST_ENTRY(type) \
+struct { \
+ struct type *le_next; /* next element */ \
+ struct type **le_prev; /* address of previous next element */ \
+}
+#endif /* !LIST_ENTRY */
+
+#ifndef LIST_HEAD
+#define EVENT_DEFINED_LISTHEAD_
+#define LIST_HEAD(name, type) \
+struct name { \
+ struct type *lh_first; /* first element */ \
+ }
+#endif /* !LIST_HEAD */
+
+struct event;
+
+struct event_callback {
+ TAILQ_ENTRY(event_callback) evcb_active_next;
+ short evcb_flags;
+ ev_uint8_t evcb_pri; /* smaller numbers are higher priority */
+ ev_uint8_t evcb_closure;
+ /* allows us to adopt for different types of events */
+ union {
+ void (*evcb_callback)(evutil_socket_t, short, void *);
+ void (*evcb_selfcb)(struct event_callback *, void *);
+ void (*evcb_evfinalize)(struct event *, void *);
+ void (*evcb_cbfinalize)(struct event_callback *, void *);
+ } evcb_cb_union;
+ void *evcb_arg;
+};
+
+struct event_base;
+struct event {
+ struct event_callback ev_evcallback;
+
+ /* for managing timeouts */
+ union {
+ TAILQ_ENTRY(event) ev_next_with_common_timeout;
+ int min_heap_idx;
+ } ev_timeout_pos;
+ evutil_socket_t ev_fd;
+
+ struct event_base *ev_base;
+
+ union {
+ /* used for io events */
+ struct {
+ LIST_ENTRY (event) ev_io_next;
+ struct timeval ev_timeout;
+ } ev_io;
+
+ /* used by signal events */
+ struct {
+ LIST_ENTRY (event) ev_signal_next;
+ short ev_ncalls;
+ /* Allows deletes in callback */
+ short *ev_pncalls;
+ } ev_signal;
+ } ev_;
+
+ short ev_events;
+ short ev_res; /* result passed to event callback */
+ struct timeval ev_timeout;
+};
+
+TAILQ_HEAD (event_list, event);
+
+#ifdef EVENT_DEFINED_TQENTRY_
+#undef TAILQ_ENTRY
+#endif
+
+#ifdef EVENT_DEFINED_TQHEAD_
+#undef TAILQ_HEAD
+#endif
+
+LIST_HEAD (event_dlist, event);
+
+#ifdef EVENT_DEFINED_LISTENTRY_
+#undef LIST_ENTRY
+#endif
+
+#ifdef EVENT_DEFINED_LISTHEAD_
+#undef LIST_HEAD
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_STRUCT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/http.h b/ipc/chromium/src/third_party/libevent/include/event2/http.h
new file mode 100644
index 0000000000..2a41303ede
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/http.h
@@ -0,0 +1,1192 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_HTTP_H_INCLUDED_
+#define EVENT2_HTTP_H_INCLUDED_
+
+/* For int types. */
+#include <event2/util.h>
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* In case we haven't included the right headers yet. */
+struct evbuffer;
+struct event_base;
+struct bufferevent;
+struct evhttp_connection;
+
+/** @file event2/http.h
+ *
+ * Basic support for HTTP serving.
+ *
+ * As Libevent is a library for dealing with event notification and most
+ * interesting applications are networked today, I have often found the
+ * need to write HTTP code. The following prototypes and definitions provide
+ * an application with a minimal interface for making HTTP requests and for
+ * creating a very simple HTTP server.
+ */
+
+/* Response codes */
+#define HTTP_OK 200 /**< request completed ok */
+#define HTTP_NOCONTENT 204 /**< request does not have content */
+#define HTTP_MOVEPERM 301 /**< the uri moved permanently */
+#define HTTP_MOVETEMP 302 /**< the uri moved temporarily */
+#define HTTP_NOTMODIFIED 304 /**< page was not modified from last */
+#define HTTP_BADREQUEST 400 /**< invalid http request was made */
+#define HTTP_NOTFOUND 404 /**< could not find content for uri */
+#define HTTP_BADMETHOD 405 /**< method not allowed for this uri */
+#define HTTP_ENTITYTOOLARGE 413 /**< */
+#define HTTP_EXPECTATIONFAILED 417 /**< we can't handle this expectation */
+#define HTTP_INTERNAL 500 /**< internal error */
+#define HTTP_NOTIMPLEMENTED 501 /**< not implemented */
+#define HTTP_SERVUNAVAIL 503 /**< the server is not available */
+
+struct evhttp;
+struct evhttp_request;
+struct evkeyvalq;
+struct evhttp_bound_socket;
+struct evconnlistener;
+struct evdns_base;
+
+/**
+ * Create a new HTTP server.
+ *
+ * @param base (optional) the event base to receive the HTTP events
+ * @return a pointer to a newly initialized evhttp server structure or NULL
+ * on error
+ * @see evhttp_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp *evhttp_new(struct event_base *base);
+
+/**
+ * Binds an HTTP server on the specified address and port.
+ *
+ * Can be called multiple times to bind the same http server
+ * to multiple different ports.
+ *
+ * @param http a pointer to an evhttp object
+ * @param address a string containing the IP address to listen(2) on
+ * @param port the port number to listen on
+ * @return 0 on success, -1 on failure.
+ * @see evhttp_accept_socket()
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_bind_socket(struct evhttp *http, const char *address, ev_uint16_t port);
+
+/**
+ * Like evhttp_bind_socket(), but returns a handle for referencing the socket.
+ *
+ * The returned pointer is not valid after \a http is freed.
+ *
+ * @param http a pointer to an evhttp object
+ * @param address a string containing the IP address to listen(2) on
+ * @param port the port number to listen on
+ * @return Handle for the socket on success, NULL on failure.
+ * @see evhttp_bind_socket(), evhttp_del_accept_socket()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_bound_socket *evhttp_bind_socket_with_handle(struct evhttp *http, const char *address, ev_uint16_t port);
+
+/**
+ * Makes an HTTP server accept connections on the specified socket.
+ *
+ * This may be useful to create a socket and then fork multiple instances
+ * of an http server, or when a socket has been communicated via file
+ * descriptor passing in situations where an http servers does not have
+ * permissions to bind to a low-numbered port.
+ *
+ * Can be called multiple times to have the http server listen to
+ * multiple different sockets.
+ *
+ * @param http a pointer to an evhttp object
+ * @param fd a socket fd that is ready for accepting connections
+ * @return 0 on success, -1 on failure.
+ * @see evhttp_bind_socket()
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_accept_socket(struct evhttp *http, evutil_socket_t fd);
+
+/**
+ * Like evhttp_accept_socket(), but returns a handle for referencing the socket.
+ *
+ * The returned pointer is not valid after \a http is freed.
+ *
+ * @param http a pointer to an evhttp object
+ * @param fd a socket fd that is ready for accepting connections
+ * @return Handle for the socket on success, NULL on failure.
+ * @see evhttp_accept_socket(), evhttp_del_accept_socket()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_bound_socket *evhttp_accept_socket_with_handle(struct evhttp *http, evutil_socket_t fd);
+
+/**
+ * The most low-level evhttp_bind/accept method: takes an evconnlistener, and
+ * returns an evhttp_bound_socket. The listener will be freed when the bound
+ * socket is freed.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_bound_socket *evhttp_bind_listener(struct evhttp *http, struct evconnlistener *listener);
+
+/**
+ * Return the listener used to implement a bound socket.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evconnlistener *evhttp_bound_socket_get_listener(struct evhttp_bound_socket *bound);
+
+typedef void evhttp_bound_socket_foreach_fn(struct evhttp_bound_socket *, void *);
+/**
+ * Applies the function specified in the first argument to all
+ * evhttp_bound_sockets associated with "http". The user must not
+ * attempt to free or remove any connections, sockets or listeners
+ * in the callback "function".
+ *
+ * @param http pointer to an evhttp object
+ * @param function function to apply to every bound socket
+ * @param argument pointer value passed to function for every socket iterated
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_foreach_bound_socket(struct evhttp *http, evhttp_bound_socket_foreach_fn *function, void *argument);
+
+/**
+ * Makes an HTTP server stop accepting connections on the specified socket
+ *
+ * This may be useful when a socket has been sent via file descriptor passing
+ * and is no longer needed by the current process.
+ *
+ * If you created this bound socket with evhttp_bind_socket_with_handle or
+ * evhttp_accept_socket_with_handle, this function closes the fd you provided.
+ * If you created this bound socket with evhttp_bind_listener, this function
+ * frees the listener you provided.
+ *
+ * \a bound_socket is an invalid pointer after this call returns.
+ *
+ * @param http a pointer to an evhttp object
+ * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
+ * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_del_accept_socket(struct evhttp *http, struct evhttp_bound_socket *bound_socket);
+
+/**
+ * Get the raw file descriptor referenced by an evhttp_bound_socket.
+ *
+ * @param bound_socket a handle returned by evhttp_{bind,accept}_socket_with_handle
+ * @return the file descriptor used by the bound socket
+ * @see evhttp_bind_socket_with_handle(), evhttp_accept_socket_with_handle()
+ */
+EVENT2_EXPORT_SYMBOL
+evutil_socket_t evhttp_bound_socket_get_fd(struct evhttp_bound_socket *bound_socket);
+
+/**
+ * Free the previously created HTTP server.
+ *
+ * Works only if no requests are currently being served.
+ *
+ * @param http the evhttp server object to be freed
+ * @see evhttp_start()
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_free(struct evhttp* http);
+
+/** XXX Document. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_max_headers_size(struct evhttp* http, ev_ssize_t max_headers_size);
+/** XXX Document. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_max_body_size(struct evhttp* http, ev_ssize_t max_body_size);
+
+/**
+ Set the value to use for the Content-Type header when none was provided. If
+ the content type string is NULL, the Content-Type header will not be
+ automatically added.
+
+ @param http the http server on which to set the default content type
+ @param content_type the value for the Content-Type header
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_default_content_type(struct evhttp *http,
+ const char *content_type);
+
+/**
+ Sets the what HTTP methods are supported in requests accepted by this
+ server, and passed to user callbacks.
+
+ If not supported they will generate a "405 Method not allowed" response.
+
+ By default this includes the following methods: GET, POST, HEAD, PUT, DELETE
+
+ @param http the http server on which to set the methods
+ @param methods bit mask constructed from evhttp_cmd_type values
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_allowed_methods(struct evhttp* http, ev_uint16_t methods);
+
+/**
+ Set a callback for a specified URI
+
+ @param http the http sever on which to set the callback
+ @param path the path for which to invoke the callback
+ @param cb the callback function that gets invoked on requesting path
+ @param cb_arg an additional context argument for the callback
+ @return 0 on success, -1 if the callback existed already, -2 on failure
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_set_cb(struct evhttp *http, const char *path,
+ void (*cb)(struct evhttp_request *, void *), void *cb_arg);
+
+/** Removes the callback for a specified URI */
+EVENT2_EXPORT_SYMBOL
+int evhttp_del_cb(struct evhttp *, const char *);
+
+/**
+ Set a callback for all requests that are not caught by specific callbacks
+
+ Invokes the specified callback for all requests that do not match any of
+ the previously specified request paths. This is catchall for requests not
+ specifically configured with evhttp_set_cb().
+
+ @param http the evhttp server object for which to set the callback
+ @param cb the callback to invoke for any unmatched requests
+ @param arg an context argument for the callback
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_gencb(struct evhttp *http,
+ void (*cb)(struct evhttp_request *, void *), void *arg);
+
+/**
+ Set a callback used to create new bufferevents for connections
+ to a given evhttp object.
+
+ You can use this to override the default bufferevent type -- for example,
+ to make this evhttp object use SSL bufferevents rather than unencrypted
+ ones.
+
+ New bufferevents must be allocated with no fd set on them.
+
+ @param http the evhttp server object for which to set the callback
+ @param cb the callback to invoke for incoming connections
+ @param arg an context argument for the callback
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_bevcb(struct evhttp *http,
+ struct bufferevent *(*cb)(struct event_base *, void *), void *arg);
+
+/**
+ Adds a virtual host to the http server.
+
+ A virtual host is a newly initialized evhttp object that has request
+ callbacks set on it via evhttp_set_cb() or evhttp_set_gencb(). It
+ most not have any listing sockets associated with it.
+
+ If the virtual host has not been removed by the time that evhttp_free()
+ is called on the main http server, it will be automatically freed, too.
+
+ It is possible to have hierarchical vhosts. For example: A vhost
+ with the pattern *.example.com may have other vhosts with patterns
+ foo.example.com and bar.example.com associated with it.
+
+ @param http the evhttp object to which to add a virtual host
+ @param pattern the glob pattern against which the hostname is matched.
+ The match is case insensitive and follows otherwise regular shell
+ matching.
+ @param vhost the virtual host to add the regular http server.
+ @return 0 on success, -1 on failure
+ @see evhttp_remove_virtual_host()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_add_virtual_host(struct evhttp* http, const char *pattern,
+ struct evhttp* vhost);
+
+/**
+ Removes a virtual host from the http server.
+
+ @param http the evhttp object from which to remove the virtual host
+ @param vhost the virtual host to remove from the regular http server.
+ @return 0 on success, -1 on failure
+ @see evhttp_add_virtual_host()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_remove_virtual_host(struct evhttp* http, struct evhttp* vhost);
+
+/**
+ Add a server alias to an http object. The http object can be a virtual
+ host or the main server.
+
+ @param http the evhttp object
+ @param alias the alias to add
+ @see evhttp_add_remove_alias()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_add_server_alias(struct evhttp *http, const char *alias);
+
+/**
+ Remove a server alias from an http object.
+
+ @param http the evhttp object
+ @param alias the alias to remove
+ @see evhttp_add_server_alias()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_remove_server_alias(struct evhttp *http, const char *alias);
+
+/**
+ * Set the timeout for an HTTP request.
+ *
+ * @param http an evhttp object
+ * @param timeout_in_secs the timeout, in seconds
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_timeout(struct evhttp *http, int timeout_in_secs);
+
+/**
+ * Set the timeout for an HTTP request.
+ *
+ * @param http an evhttp object
+ * @param tv the timeout, or NULL
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_set_timeout_tv(struct evhttp *http, const struct timeval* tv);
+
+/* Read all the clients body, and only after this respond with an error if the
+ * clients body exceed max_body_size */
+#define EVHTTP_SERVER_LINGERING_CLOSE 0x0001
+/**
+ * Set connection flags for HTTP server.
+ *
+ * @see EVHTTP_SERVER_*
+ * @return 0 on success, otherwise non zero (for example if flag doesn't
+ * supported).
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_set_flags(struct evhttp *http, int flags);
+
+/* Request/Response functionality */
+
+/**
+ * Send an HTML error message to the client.
+ *
+ * @param req a request object
+ * @param error the HTTP error code
+ * @param reason a brief explanation of the error. If this is NULL, we'll
+ * just use the standard meaning of the error code.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_error(struct evhttp_request *req, int error,
+ const char *reason);
+
+/**
+ * Send an HTML reply to the client.
+ *
+ * The body of the reply consists of the data in databuf. After calling
+ * evhttp_send_reply() databuf will be empty, but the buffer is still
+ * owned by the caller and needs to be deallocated by the caller if
+ * necessary.
+ *
+ * @param req a request object
+ * @param code the HTTP response code to send
+ * @param reason a brief message to send with the response code
+ * @param databuf the body of the response
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_reply(struct evhttp_request *req, int code,
+ const char *reason, struct evbuffer *databuf);
+
+/* Low-level response interface, for streaming/chunked replies */
+
+/**
+ Initiate a reply that uses Transfer-Encoding chunked.
+
+ This allows the caller to stream the reply back to the client and is
+ useful when either not all of the reply data is immediately available
+ or when sending very large replies.
+
+ The caller needs to supply data chunks with evhttp_send_reply_chunk()
+ and complete the reply by calling evhttp_send_reply_end().
+
+ @param req a request object
+ @param code the HTTP response code to send
+ @param reason a brief message to send with the response code
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_reply_start(struct evhttp_request *req, int code,
+ const char *reason);
+
+/**
+ Send another data chunk as part of an ongoing chunked reply.
+
+ The reply chunk consists of the data in databuf. After calling
+ evhttp_send_reply_chunk() databuf will be empty, but the buffer is
+ still owned by the caller and needs to be deallocated by the caller
+ if necessary.
+
+ @param req a request object
+ @param databuf the data chunk to send as part of the reply.
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_reply_chunk(struct evhttp_request *req,
+ struct evbuffer *databuf);
+
+/**
+ Send another data chunk as part of an ongoing chunked reply.
+
+ The reply chunk consists of the data in databuf. After calling
+ evhttp_send_reply_chunk() databuf will be empty, but the buffer is
+ still owned by the caller and needs to be deallocated by the caller
+ if necessary.
+
+ @param req a request object
+ @param databuf the data chunk to send as part of the reply.
+ @param cb callback funcion
+ @param call back's argument.
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_reply_chunk_with_cb(struct evhttp_request *, struct evbuffer *,
+ void (*cb)(struct evhttp_connection *, void *), void *arg);
+
+/**
+ Complete a chunked reply, freeing the request as appropriate.
+
+ @param req a request object
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_send_reply_end(struct evhttp_request *req);
+
+/*
+ * Interfaces for making requests
+ */
+
+/** The different request types supported by evhttp. These are as specified
+ * in RFC2616, except for PATCH which is specified by RFC5789.
+ *
+ * By default, only some of these methods are accepted and passed to user
+ * callbacks; use evhttp_set_allowed_methods() to change which methods
+ * are allowed.
+ */
+enum evhttp_cmd_type {
+ EVHTTP_REQ_GET = 1 << 0,
+ EVHTTP_REQ_POST = 1 << 1,
+ EVHTTP_REQ_HEAD = 1 << 2,
+ EVHTTP_REQ_PUT = 1 << 3,
+ EVHTTP_REQ_DELETE = 1 << 4,
+ EVHTTP_REQ_OPTIONS = 1 << 5,
+ EVHTTP_REQ_TRACE = 1 << 6,
+ EVHTTP_REQ_CONNECT = 1 << 7,
+ EVHTTP_REQ_PATCH = 1 << 8
+};
+
+/** a request object can represent either a request or a reply */
+enum evhttp_request_kind { EVHTTP_REQUEST, EVHTTP_RESPONSE };
+
+/**
+ * Create and return a connection object that can be used to for making HTTP
+ * requests. The connection object tries to resolve address and establish the
+ * connection when it is given an http request object.
+ *
+ * @param base the event_base to use for handling the connection
+ * @param dnsbase the dns_base to use for resolving host names; if not
+ * specified host name resolution will block.
+ * @param bev a bufferevent to use for connecting to the server; if NULL, a
+ * socket-based bufferevent will be created. This buffrevent will be freed
+ * when the connection closes. It must have no fd set on it.
+ * @param address the address to which to connect
+ * @param port the port to connect to
+ * @return an evhttp_connection object that can be used for making requests or
+ * NULL on error
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_connection *evhttp_connection_base_bufferevent_new(
+ struct event_base *base, struct evdns_base *dnsbase, struct bufferevent* bev, const char *address, ev_uint16_t port);
+
+/**
+ * Return the bufferevent that an evhttp_connection is using.
+ */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent* evhttp_connection_get_bufferevent(struct evhttp_connection *evcon);
+
+/**
+ * Return the HTTP server associated with this connection, or NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp *evhttp_connection_get_server(struct evhttp_connection *evcon);
+
+/**
+ * Creates a new request object that needs to be filled in with the request
+ * parameters. The callback is executed when the request completed or an
+ * error occurred.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_request *evhttp_request_new(
+ void (*cb)(struct evhttp_request *, void *), void *arg);
+
+/**
+ * Enable delivery of chunks to requestor.
+ * @param cb will be called after every read of data with the same argument
+ * as the completion callback. Will never be called on an empty
+ * response. May drain the input buffer; it will be drained
+ * automatically on return.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_set_chunked_cb(struct evhttp_request *,
+ void (*cb)(struct evhttp_request *, void *));
+
+/**
+ * Register callback for additional parsing of request headers.
+ * @param cb will be called after receiving and parsing the full header.
+ * It allows analyzing the header and possibly closing the connection
+ * by returning a value < 0.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_set_header_cb(struct evhttp_request *,
+ int (*cb)(struct evhttp_request *, void *));
+
+/**
+ * The different error types supported by evhttp
+ *
+ * @see evhttp_request_set_error_cb()
+ */
+enum evhttp_request_error {
+ /**
+ * Timeout reached, also @see evhttp_connection_set_timeout()
+ */
+ EVREQ_HTTP_TIMEOUT,
+ /**
+ * EOF reached
+ */
+ EVREQ_HTTP_EOF,
+ /**
+ * Error while reading header, or invalid header
+ */
+ EVREQ_HTTP_INVALID_HEADER,
+ /**
+ * Error encountered while reading or writing
+ */
+ EVREQ_HTTP_BUFFER_ERROR,
+ /**
+ * The evhttp_cancel_request() called on this request.
+ */
+ EVREQ_HTTP_REQUEST_CANCEL,
+ /**
+ * Body is greater then evhttp_connection_set_max_body_size()
+ */
+ EVREQ_HTTP_DATA_TOO_LONG
+};
+/**
+ * Set a callback for errors
+ * @see evhttp_request_error for error types.
+ *
+ * On error, both the error callback and the regular callback will be called,
+ * error callback is called before the regular callback.
+ **/
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_set_error_cb(struct evhttp_request *,
+ void (*)(enum evhttp_request_error, void *));
+
+/**
+ * Set a callback to be called on request completion of evhttp_send_* function.
+ *
+ * The callback function will be called on the completion of the request after
+ * the output data has been written and before the evhttp_request object
+ * is destroyed. This can be useful for tracking resources associated with a
+ * request (ex: timing metrics).
+ *
+ * @param req a request object
+ * @param cb callback function that will be called on request completion
+ * @param cb_arg an additional context argument for the callback
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_set_on_complete_cb(struct evhttp_request *req,
+ void (*cb)(struct evhttp_request *, void *), void *cb_arg);
+
+/** Frees the request object and removes associated events. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_free(struct evhttp_request *req);
+
+/**
+ * Create and return a connection object that can be used to for making HTTP
+ * requests. The connection object tries to resolve address and establish the
+ * connection when it is given an http request object.
+ *
+ * @param base the event_base to use for handling the connection
+ * @param dnsbase the dns_base to use for resolving host names; if not
+ * specified host name resolution will block.
+ * @param address the address to which to connect
+ * @param port the port to connect to
+ * @return an evhttp_connection object that can be used for making requests or
+ * NULL on error
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_connection *evhttp_connection_base_new(
+ struct event_base *base, struct evdns_base *dnsbase,
+ const char *address, ev_uint16_t port);
+
+/**
+ * Set family hint for DNS requests.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_family(struct evhttp_connection *evcon,
+ int family);
+
+/* reuse connection address on retry */
+#define EVHTTP_CON_REUSE_CONNECTED_ADDR 0x0008
+/* Try to read error, since server may already send and close
+ * connection, but if at that time we have some data to send then we
+ * can send get EPIPE and fail, while we can read that HTTP error. */
+#define EVHTTP_CON_READ_ON_WRITE_ERROR 0x0010
+/* @see EVHTTP_SERVER_LINGERING_CLOSE */
+#define EVHTTP_CON_LINGERING_CLOSE 0x0020
+/* Padding for public flags, @see EVHTTP_CON_* in http-internal.h */
+#define EVHTTP_CON_PUBLIC_FLAGS_END 0x100000
+/**
+ * Set connection flags.
+ *
+ * @see EVHTTP_CON_*
+ * @return 0 on success, otherwise non zero (for example if flag doesn't
+ * supported).
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_connection_set_flags(struct evhttp_connection *evcon,
+ int flags);
+
+/** Takes ownership of the request object
+ *
+ * Can be used in a request callback to keep onto the request until
+ * evhttp_request_free() is explicitly called by the user.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_request_own(struct evhttp_request *req);
+
+/** Returns 1 if the request is owned by the user */
+EVENT2_EXPORT_SYMBOL
+int evhttp_request_is_owned(struct evhttp_request *req);
+
+/**
+ * Returns the connection object associated with the request or NULL
+ *
+ * The user needs to either free the request explicitly or call
+ * evhttp_send_reply_end().
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_connection *evhttp_request_get_connection(struct evhttp_request *req);
+
+/**
+ * Returns the underlying event_base for this connection
+ */
+EVENT2_EXPORT_SYMBOL
+struct event_base *evhttp_connection_get_base(struct evhttp_connection *req);
+
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_max_headers_size(struct evhttp_connection *evcon,
+ ev_ssize_t new_max_headers_size);
+
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_max_body_size(struct evhttp_connection* evcon,
+ ev_ssize_t new_max_body_size);
+
+/** Frees an http connection */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_free(struct evhttp_connection *evcon);
+
+/** Disowns a given connection object
+ *
+ * Can be used to tell libevent to free the connection object after
+ * the last request has completed or failed.
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_free_on_completion(struct evhttp_connection *evcon);
+
+/** sets the ip address from which http connections are made */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_local_address(struct evhttp_connection *evcon,
+ const char *address);
+
+/** sets the local port from which http connections are made */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_local_port(struct evhttp_connection *evcon,
+ ev_uint16_t port);
+
+/** Sets the timeout in seconds for events related to this connection */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_timeout(struct evhttp_connection *evcon,
+ int timeout_in_secs);
+
+/** Sets the timeout for events related to this connection. Takes a struct
+ * timeval. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_timeout_tv(struct evhttp_connection *evcon,
+ const struct timeval *tv);
+
+/** Sets the delay before retrying requests on this connection. This is only
+ * used if evhttp_connection_set_retries is used to make the number of retries
+ * at least one. Each retry after the first is twice as long as the one before
+ * it. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_initial_retry_tv(struct evhttp_connection *evcon,
+ const struct timeval *tv);
+
+/** Sets the retry limit for this connection - -1 repeats indefinitely */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_retries(struct evhttp_connection *evcon,
+ int retry_max);
+
+/** Set a callback for connection close. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_closecb(struct evhttp_connection *evcon,
+ void (*)(struct evhttp_connection *, void *), void *);
+
+/** Get the remote address and port associated with this connection. */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_get_peer(struct evhttp_connection *evcon,
+ char **address, ev_uint16_t *port);
+
+/** Get the remote address associated with this connection.
+ * extracted from getpeername() OR from nameserver.
+ *
+ * @return NULL if getpeername() return non success,
+ * or connection is not connected,
+ * otherwise it return pointer to struct sockaddr_storage */
+EVENT2_EXPORT_SYMBOL
+const struct sockaddr*
+evhttp_connection_get_addr(struct evhttp_connection *evcon);
+
+/**
+ Make an HTTP request over the specified connection.
+
+ The connection gets ownership of the request. On failure, the
+ request object is no longer valid as it has been freed.
+
+ @param evcon the evhttp_connection object over which to send the request
+ @param req the previously created and configured request object
+ @param type the request type EVHTTP_REQ_GET, EVHTTP_REQ_POST, etc.
+ @param uri the URI associated with the request
+ @return 0 on success, -1 on failure
+ @see evhttp_cancel_request()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_make_request(struct evhttp_connection *evcon,
+ struct evhttp_request *req,
+ enum evhttp_cmd_type type, const char *uri);
+
+/**
+ Cancels a pending HTTP request.
+
+ Cancels an ongoing HTTP request. The callback associated with this request
+ is not executed and the request object is freed. If the request is
+ currently being processed, e.g. it is ongoing, the corresponding
+ evhttp_connection object is going to get reset.
+
+ A request cannot be canceled if its callback has executed already. A request
+ may be canceled reentrantly from its chunked callback.
+
+ @param req the evhttp_request to cancel; req becomes invalid after this call.
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_cancel_request(struct evhttp_request *req);
+
+/**
+ * A structure to hold a parsed URI or Relative-Ref conforming to RFC3986.
+ */
+struct evhttp_uri;
+
+/** Returns the request URI */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_request_get_uri(const struct evhttp_request *req);
+/** Returns the request URI (parsed) */
+EVENT2_EXPORT_SYMBOL
+const struct evhttp_uri *evhttp_request_get_evhttp_uri(const struct evhttp_request *req);
+/** Returns the request command */
+EVENT2_EXPORT_SYMBOL
+enum evhttp_cmd_type evhttp_request_get_command(const struct evhttp_request *req);
+
+EVENT2_EXPORT_SYMBOL
+int evhttp_request_get_response_code(const struct evhttp_request *req);
+EVENT2_EXPORT_SYMBOL
+const char * evhttp_request_get_response_code_line(const struct evhttp_request *req);
+
+/** Returns the input headers */
+EVENT2_EXPORT_SYMBOL
+struct evkeyvalq *evhttp_request_get_input_headers(struct evhttp_request *req);
+/** Returns the output headers */
+EVENT2_EXPORT_SYMBOL
+struct evkeyvalq *evhttp_request_get_output_headers(struct evhttp_request *req);
+/** Returns the input buffer */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *evhttp_request_get_input_buffer(struct evhttp_request *req);
+/** Returns the output buffer */
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *evhttp_request_get_output_buffer(struct evhttp_request *req);
+/** Returns the host associated with the request. If a client sends an absolute
+ URI, the host part of that is preferred. Otherwise, the input headers are
+ searched for a Host: header. NULL is returned if no absolute URI or Host:
+ header is provided. */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_request_get_host(struct evhttp_request *req);
+
+/* Interfaces for dealing with HTTP headers */
+
+/**
+ Finds the value belonging to a header.
+
+ @param headers the evkeyvalq object in which to find the header
+ @param key the name of the header to find
+ @returns a pointer to the value for the header or NULL if the header
+ could not be found.
+ @see evhttp_add_header(), evhttp_remove_header()
+*/
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_find_header(const struct evkeyvalq *headers,
+ const char *key);
+
+/**
+ Removes a header from a list of existing headers.
+
+ @param headers the evkeyvalq object from which to remove a header
+ @param key the name of the header to remove
+ @returns 0 if the header was removed, -1 otherwise.
+ @see evhttp_find_header(), evhttp_add_header()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_remove_header(struct evkeyvalq *headers, const char *key);
+
+/**
+ Adds a header to a list of existing headers.
+
+ @param headers the evkeyvalq object to which to add a header
+ @param key the name of the header
+ @param value the value belonging to the header
+ @returns 0 on success, -1 otherwise.
+ @see evhttp_find_header(), evhttp_clear_headers()
+*/
+EVENT2_EXPORT_SYMBOL
+int evhttp_add_header(struct evkeyvalq *headers, const char *key, const char *value);
+
+/**
+ Removes all headers from the header list.
+
+ @param headers the evkeyvalq object from which to remove all headers
+*/
+EVENT2_EXPORT_SYMBOL
+void evhttp_clear_headers(struct evkeyvalq *headers);
+
+/* Miscellaneous utility functions */
+
+
+/**
+ Helper function to encode a string for inclusion in a URI. All
+ characters are replaced by their hex-escaped (%22) equivalents,
+ except for characters explicitly unreserved by RFC3986 -- that is,
+ ASCII alphanumeric characters, hyphen, dot, underscore, and tilde.
+
+ The returned string must be freed by the caller.
+
+ @param str an unencoded string
+ @return a newly allocated URI-encoded string or NULL on failure
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_encode_uri(const char *str);
+
+/**
+ As evhttp_encode_uri, but if 'size' is nonnegative, treat the string
+ as being 'size' bytes long. This allows you to encode strings that
+ may contain 0-valued bytes.
+
+ The returned string must be freed by the caller.
+
+ @param str an unencoded string
+ @param size the length of the string to encode, or -1 if the string
+ is NUL-terminated
+ @param space_to_plus if true, space characters in 'str' are encoded
+ as +, not %20.
+ @return a newly allocate URI-encoded string, or NULL on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_uriencode(const char *str, ev_ssize_t size, int space_to_plus);
+
+/**
+ Helper function to sort of decode a URI-encoded string. Unlike
+ evhttp_uridecode, it decodes all plus characters that appear
+ _after_ the first question mark character, but no plusses that occur
+ before. This is not a good way to decode URIs in whole or in part.
+
+ The returned string must be freed by the caller
+
+ @deprecated This function is deprecated; you probably want to use
+ evhttp_uridecode instead.
+
+ @param uri an encoded URI
+ @return a newly allocated unencoded URI or NULL on failure
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_decode_uri(const char *uri);
+
+/**
+ Helper function to decode a URI-escaped string or HTTP parameter.
+
+ If 'decode_plus' is 1, then we decode the string as an HTTP parameter
+ value, and convert all plus ('+') characters to spaces. If
+ 'decode_plus' is 0, we leave all plus characters unchanged.
+
+ The returned string must be freed by the caller.
+
+ @param uri a URI-encode encoded URI
+ @param decode_plus determines whether we convert '+' to space.
+ @param size_out if size_out is not NULL, *size_out is set to the size of the
+ returned string
+ @return a newly allocated unencoded URI or NULL on failure
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_uridecode(const char *uri, int decode_plus,
+ size_t *size_out);
+
+/**
+ Helper function to parse out arguments in a query.
+
+ Parsing a URI like
+
+ http://foo.com/?q=test&s=some+thing
+
+ will result in two entries in the key value queue.
+
+ The first entry is: key="q", value="test"
+ The second entry is: key="s", value="some thing"
+
+ @deprecated This function is deprecated as of Libevent 2.0.9. Use
+ evhttp_uri_parse and evhttp_parse_query_str instead.
+
+ @param uri the request URI
+ @param headers the head of the evkeyval queue
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_parse_query(const char *uri, struct evkeyvalq *headers);
+
+/**
+ Helper function to parse out arguments from the query portion of an
+ HTTP URI.
+
+ Parsing a query string like
+
+ q=test&s=some+thing
+
+ will result in two entries in the key value queue.
+
+ The first entry is: key="q", value="test"
+ The second entry is: key="s", value="some thing"
+
+ @param query_parse the query portion of the URI
+ @param headers the head of the evkeyval queue
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evhttp_parse_query_str(const char *uri, struct evkeyvalq *headers);
+
+/**
+ * Escape HTML character entities in a string.
+ *
+ * Replaces <, >, ", ' and & with &lt;, &gt;, &quot;,
+ * &#039; and &amp; correspondingly.
+ *
+ * The returned string needs to be freed by the caller.
+ *
+ * @param html an unescaped HTML string
+ * @return an escaped HTML string or NULL on error
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_htmlescape(const char *html);
+
+/**
+ * Return a new empty evhttp_uri with no fields set.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_uri *evhttp_uri_new(void);
+
+/**
+ * Changes the flags set on a given URI. See EVHTTP_URI_* for
+ * a list of flags.
+ **/
+EVENT2_EXPORT_SYMBOL
+void evhttp_uri_set_flags(struct evhttp_uri *uri, unsigned flags);
+
+/** Return the scheme of an evhttp_uri, or NULL if there is no scheme has
+ * been set and the evhttp_uri contains a Relative-Ref. */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_scheme(const struct evhttp_uri *uri);
+/**
+ * Return the userinfo part of an evhttp_uri, or NULL if it has no userinfo
+ * set.
+ */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_userinfo(const struct evhttp_uri *uri);
+/**
+ * Return the host part of an evhttp_uri, or NULL if it has no host set.
+ * The host may either be a regular hostname (conforming to the RFC 3986
+ * "regname" production), or an IPv4 address, or the empty string, or a
+ * bracketed IPv6 address, or a bracketed 'IP-Future' address.
+ *
+ * Note that having a NULL host means that the URI has no authority
+ * section, but having an empty-string host means that the URI has an
+ * authority section with no host part. For example,
+ * "mailto:user@example.com" has a host of NULL, but "file:///etc/motd"
+ * has a host of "".
+ */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_host(const struct evhttp_uri *uri);
+/** Return the port part of an evhttp_uri, or -1 if there is no port set. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_get_port(const struct evhttp_uri *uri);
+/** Return the path part of an evhttp_uri, or NULL if it has no path set */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_path(const struct evhttp_uri *uri);
+/** Return the query part of an evhttp_uri (excluding the leading "?"), or
+ * NULL if it has no query set */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_query(const struct evhttp_uri *uri);
+/** Return the fragment part of an evhttp_uri (excluding the leading "#"),
+ * or NULL if it has no fragment set */
+EVENT2_EXPORT_SYMBOL
+const char *evhttp_uri_get_fragment(const struct evhttp_uri *uri);
+
+/** Set the scheme of an evhttp_uri, or clear the scheme if scheme==NULL.
+ * Returns 0 on success, -1 if scheme is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_scheme(struct evhttp_uri *uri, const char *scheme);
+/** Set the userinfo of an evhttp_uri, or clear the userinfo if userinfo==NULL.
+ * Returns 0 on success, -1 if userinfo is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_userinfo(struct evhttp_uri *uri, const char *userinfo);
+/** Set the host of an evhttp_uri, or clear the host if host==NULL.
+ * Returns 0 on success, -1 if host is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_host(struct evhttp_uri *uri, const char *host);
+/** Set the port of an evhttp_uri, or clear the port if port==-1.
+ * Returns 0 on success, -1 if port is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_port(struct evhttp_uri *uri, int port);
+/** Set the path of an evhttp_uri, or clear the path if path==NULL.
+ * Returns 0 on success, -1 if path is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_path(struct evhttp_uri *uri, const char *path);
+/** Set the query of an evhttp_uri, or clear the query if query==NULL.
+ * The query should not include a leading "?".
+ * Returns 0 on success, -1 if query is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_query(struct evhttp_uri *uri, const char *query);
+/** Set the fragment of an evhttp_uri, or clear the fragment if fragment==NULL.
+ * The fragment should not include a leading "#".
+ * Returns 0 on success, -1 if fragment is not well-formed. */
+EVENT2_EXPORT_SYMBOL
+int evhttp_uri_set_fragment(struct evhttp_uri *uri, const char *fragment);
+
+/**
+ * Helper function to parse a URI-Reference as specified by RFC3986.
+ *
+ * This function matches the URI-Reference production from RFC3986,
+ * which includes both URIs like
+ *
+ * scheme://[[userinfo]@]foo.com[:port]]/[path][?query][#fragment]
+ *
+ * and relative-refs like
+ *
+ * [path][?query][#fragment]
+ *
+ * Any optional elements portions not present in the original URI are
+ * left set to NULL in the resulting evhttp_uri. If no port is
+ * specified, the port is set to -1.
+ *
+ * Note that no decoding is performed on percent-escaped characters in
+ * the string; if you want to parse them, use evhttp_uridecode or
+ * evhttp_parse_query_str as appropriate.
+ *
+ * Note also that most URI schemes will have additional constraints that
+ * this function does not know about, and cannot check. For example,
+ * mailto://www.example.com/cgi-bin/fortune.pl is not a reasonable
+ * mailto url, http://www.example.com:99999/ is not a reasonable HTTP
+ * URL, and ftp:username@example.com is not a reasonable FTP URL.
+ * Nevertheless, all of these URLs conform to RFC3986, and this function
+ * accepts all of them as valid.
+ *
+ * @param source_uri the request URI
+ * @param flags Zero or more EVHTTP_URI_* flags to affect the behavior
+ * of the parser.
+ * @return uri container to hold parsed data, or NULL if there is error
+ * @see evhttp_uri_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_uri *evhttp_uri_parse_with_flags(const char *source_uri,
+ unsigned flags);
+
+/** Tolerate URIs that do not conform to RFC3986.
+ *
+ * Unfortunately, some HTTP clients generate URIs that, according to RFC3986,
+ * are not conformant URIs. If you need to support these URIs, you can
+ * do so by passing this flag to evhttp_uri_parse_with_flags.
+ *
+ * Currently, these changes are:
+ * <ul>
+ * <li> Nonconformant URIs are allowed to contain otherwise unreasonable
+ * characters in their path, query, and fragment components.
+ * </ul>
+ */
+#define EVHTTP_URI_NONCONFORMANT 0x01
+
+/** Alias for evhttp_uri_parse_with_flags(source_uri, 0) */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_uri *evhttp_uri_parse(const char *source_uri);
+
+/**
+ * Free all memory allocated for a parsed uri. Only use this for URIs
+ * generated by evhttp_uri_parse.
+ *
+ * @param uri container with parsed data
+ * @see evhttp_uri_parse()
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_uri_free(struct evhttp_uri *uri);
+
+/**
+ * Join together the uri parts from parsed data to form a URI-Reference.
+ *
+ * Note that no escaping of reserved characters is done on the members
+ * of the evhttp_uri, so the generated string might not be a valid URI
+ * unless the members of evhttp_uri are themselves valid.
+ *
+ * @param uri container with parsed data
+ * @param buf destination buffer
+ * @param limit destination buffer size
+ * @return an joined uri as string or NULL on error
+ * @see evhttp_uri_parse()
+ */
+EVENT2_EXPORT_SYMBOL
+char *evhttp_uri_join(struct evhttp_uri *uri, char *buf, size_t limit);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_HTTP_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/http_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/http_compat.h
new file mode 100644
index 0000000000..794a581083
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/http_compat.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_HTTP_COMPAT_H_INCLUDED_
+#define EVENT2_HTTP_COMPAT_H_INCLUDED_
+
+/** @file event2/http_compat.h
+
+ Potentially non-threadsafe versions of the functions in http.h: provided
+ only for backwards compatibility.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * Start an HTTP server on the specified address and port
+ *
+ * @deprecated It does not allow an event base to be specified
+ *
+ * @param address the address to which the HTTP server should be bound
+ * @param port the port number on which the HTTP server should listen
+ * @return a pointer to a newly initialized evhttp server structure
+ * or NULL on error
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp *evhttp_start(const char *address, ev_uint16_t port);
+
+/**
+ * A connection object that can be used to for making HTTP requests. The
+ * connection object tries to establish the connection when it is given an
+ * http request object.
+ *
+ * @deprecated It does not allow an event base to be specified
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_connection *evhttp_connection_new(
+ const char *address, ev_uint16_t port);
+
+/**
+ * Associates an event base with the connection - can only be called
+ * on a freshly created connection object that has not been used yet.
+ *
+ * @deprecated XXXX Why?
+ */
+EVENT2_EXPORT_SYMBOL
+void evhttp_connection_set_base(struct evhttp_connection *evcon,
+ struct event_base *base);
+
+
+/** Returns the request URI */
+#define evhttp_request_uri evhttp_request_get_uri
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/http_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/http_struct.h
new file mode 100644
index 0000000000..4bf5b1ff60
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/http_struct.h
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_HTTP_STRUCT_H_INCLUDED_
+#define EVENT2_HTTP_STRUCT_H_INCLUDED_
+
+/** @file event2/http_struct.h
+
+ Data structures for http. Using these structures may hurt forward
+ compatibility with later versions of Libevent: be careful!
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+/**
+ * the request structure that a server receives.
+ * WARNING: expect this structure to change. I will try to provide
+ * reasonable accessors.
+ */
+struct evhttp_request {
+#if defined(TAILQ_ENTRY)
+ TAILQ_ENTRY(evhttp_request) next;
+#else
+struct {
+ struct evhttp_request *tqe_next;
+ struct evhttp_request **tqe_prev;
+} next;
+#endif
+
+ /* the connection object that this request belongs to */
+ struct evhttp_connection *evcon;
+ int flags;
+/** The request obj owns the evhttp connection and needs to free it */
+#define EVHTTP_REQ_OWN_CONNECTION 0x0001
+/** Request was made via a proxy */
+#define EVHTTP_PROXY_REQUEST 0x0002
+/** The request object is owned by the user; the user must free it */
+#define EVHTTP_USER_OWNED 0x0004
+/** The request will be used again upstack; freeing must be deferred */
+#define EVHTTP_REQ_DEFER_FREE 0x0008
+/** The request should be freed upstack */
+#define EVHTTP_REQ_NEEDS_FREE 0x0010
+
+ struct evkeyvalq *input_headers;
+ struct evkeyvalq *output_headers;
+
+ /* address of the remote host and the port connection came from */
+ char *remote_host;
+ ev_uint16_t remote_port;
+
+ /* cache of the hostname for evhttp_request_get_host */
+ char *host_cache;
+
+ enum evhttp_request_kind kind;
+ enum evhttp_cmd_type type;
+
+ size_t headers_size;
+ size_t body_size;
+
+ char *uri; /* uri after HTTP request was parsed */
+ struct evhttp_uri *uri_elems; /* uri elements */
+
+ char major; /* HTTP Major number */
+ char minor; /* HTTP Minor number */
+
+ int response_code; /* HTTP Response code */
+ char *response_code_line; /* Readable response */
+
+ struct evbuffer *input_buffer; /* read data */
+ ev_int64_t ntoread;
+ unsigned chunked:1, /* a chunked request */
+ userdone:1; /* the user has sent all data */
+
+ struct evbuffer *output_buffer; /* outgoing post or data */
+
+ /* Callback */
+ void (*cb)(struct evhttp_request *, void *);
+ void *cb_arg;
+
+ /*
+ * Chunked data callback - call for each completed chunk if
+ * specified. If not specified, all the data is delivered via
+ * the regular callback.
+ */
+ void (*chunk_cb)(struct evhttp_request *, void *);
+
+ /*
+ * Callback added for forked-daapd so they can collect ICY
+ * (shoutcast) metadata from the http header. If return
+ * int is negative the connection will be closed.
+ */
+ int (*header_cb)(struct evhttp_request *, void *);
+
+ /*
+ * Error callback - called when error is occured.
+ * @see evhttp_request_error for error types.
+ *
+ * @see evhttp_request_set_error_cb()
+ */
+ void (*error_cb)(enum evhttp_request_error, void *);
+
+ /*
+ * Send complete callback - called when the request is actually
+ * sent and completed.
+ */
+ void (*on_complete_cb)(struct evhttp_request *, void *);
+ void *on_complete_cb_arg;
+};
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_HTTP_STRUCT_H_INCLUDED_ */
+
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/keyvalq_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/keyvalq_struct.h
new file mode 100644
index 0000000000..bffa54b3a7
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/keyvalq_struct.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
+#define EVENT2_KEYVALQ_STRUCT_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+/* XXXX This code is duplicated with event_struct.h */
+#ifndef TAILQ_ENTRY
+#define EVENT_DEFINED_TQENTRY_
+#define TAILQ_ENTRY(type) \
+struct { \
+ struct type *tqe_next; /* next element */ \
+ struct type **tqe_prev; /* address of previous next element */ \
+}
+#endif /* !TAILQ_ENTRY */
+
+#ifndef TAILQ_HEAD
+#define EVENT_DEFINED_TQHEAD_
+#define TAILQ_HEAD(name, type) \
+struct name { \
+ struct type *tqh_first; \
+ struct type **tqh_last; \
+}
+#endif
+
+/*
+ * Key-Value pairs. Can be used for HTTP headers but also for
+ * query argument parsing.
+ */
+struct evkeyval {
+ TAILQ_ENTRY(evkeyval) next;
+
+ char *key;
+ char *value;
+};
+
+TAILQ_HEAD (evkeyvalq, evkeyval);
+
+/* XXXX This code is duplicated with event_struct.h */
+#ifdef EVENT_DEFINED_TQENTRY_
+#undef TAILQ_ENTRY
+#endif
+
+#ifdef EVENT_DEFINED_TQHEAD_
+#undef TAILQ_HEAD
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/listener.h b/ipc/chromium/src/third_party/libevent/include/event2/listener.h
new file mode 100644
index 0000000000..789a27c2aa
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/listener.h
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_LISTENER_H_INCLUDED_
+#define EVENT2_LISTENER_H_INCLUDED_
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event.h>
+
+struct sockaddr;
+struct evconnlistener;
+
+/**
+ A callback that we invoke when a listener has a new connection.
+
+ @param listener The evconnlistener
+ @param fd The new file descriptor
+ @param addr The source address of the connection
+ @param socklen The length of addr
+ @param user_arg the pointer passed to evconnlistener_new()
+ */
+typedef void (*evconnlistener_cb)(struct evconnlistener *, evutil_socket_t, struct sockaddr *, int socklen, void *);
+
+/**
+ A callback that we invoke when a listener encounters a non-retriable error.
+
+ @param listener The evconnlistener
+ @param user_arg the pointer passed to evconnlistener_new()
+ */
+typedef void (*evconnlistener_errorcb)(struct evconnlistener *, void *);
+
+/** Flag: Indicates that we should not make incoming sockets nonblocking
+ * before passing them to the callback. */
+#define LEV_OPT_LEAVE_SOCKETS_BLOCKING (1u<<0)
+/** Flag: Indicates that freeing the listener should close the underlying
+ * socket. */
+#define LEV_OPT_CLOSE_ON_FREE (1u<<1)
+/** Flag: Indicates that we should set the close-on-exec flag, if possible */
+#define LEV_OPT_CLOSE_ON_EXEC (1u<<2)
+/** Flag: Indicates that we should disable the timeout (if any) between when
+ * this socket is closed and when we can listen again on the same port. */
+#define LEV_OPT_REUSEABLE (1u<<3)
+/** Flag: Indicates that the listener should be locked so it's safe to use
+ * from multiple threadcs at once. */
+#define LEV_OPT_THREADSAFE (1u<<4)
+/** Flag: Indicates that the listener should be created in disabled
+ * state. Use evconnlistener_enable() to enable it later. */
+#define LEV_OPT_DISABLED (1u<<5)
+/** Flag: Indicates that the listener should defer accept() until data is
+ * available, if possible. Ignored on platforms that do not support this.
+ *
+ * This option can help performance for protocols where the client transmits
+ * immediately after connecting. Do not use this option if your protocol
+ * _doesn't_ start out with the client transmitting data, since in that case
+ * this option will sometimes cause the kernel to never tell you about the
+ * connection.
+ *
+ * This option is only supported by evconnlistener_new_bind(): it can't
+ * work with evconnlistener_new_fd(), since the listener needs to be told
+ * to use the option before it is actually bound.
+ */
+#define LEV_OPT_DEFERRED_ACCEPT (1u<<6)
+/** Flag: Indicates that we ask to allow multiple servers (processes or
+ * threads) to bind to the same port if they each set the option.
+ *
+ * SO_REUSEPORT is what most people would expect SO_REUSEADDR to be, however
+ * SO_REUSEPORT does not imply SO_REUSEADDR.
+ *
+ * This is only available on Linux and kernel 3.9+
+ */
+#define LEV_OPT_REUSEABLE_PORT (1u<<7)
+/** Flag: Indicates that the listener wants to work only in IPv6 socket.
+ *
+ * According to RFC3493 and most Linux distributions, default value is to
+ * work in IPv4-mapped mode. If there is a requirement to bind same port
+ * on same ip addresses but different handlers for both IPv4 and IPv6,
+ * it is required to set IPV6_V6ONLY socket option to be sure that the
+ * code works as expected without affected by bindv6only sysctl setting in
+ * system.
+ *
+ * This socket option also supported by Windows.
+ */
+#define LEV_OPT_BIND_IPV6ONLY (1u<<8)
+
+/**
+ Allocate a new evconnlistener object to listen for incoming TCP connections
+ on a given file descriptor.
+
+ @param base The event base to associate the listener with.
+ @param cb A callback to be invoked when a new connection arrives. If the
+ callback is NULL, the listener will be treated as disabled until the
+ callback is set.
+ @param ptr A user-supplied pointer to give to the callback.
+ @param flags Any number of LEV_OPT_* flags
+ @param backlog Passed to the listen() call to determine the length of the
+ acceptable connection backlog. Set to -1 for a reasonable default.
+ Set to 0 if the socket is already listening.
+ @param fd The file descriptor to listen on. It must be a nonblocking
+ file descriptor, and it should already be bound to an appropriate
+ port and address.
+*/
+EVENT2_EXPORT_SYMBOL
+struct evconnlistener *evconnlistener_new(struct event_base *base,
+ evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+ evutil_socket_t fd);
+/**
+ Allocate a new evconnlistener object to listen for incoming TCP connections
+ on a given address.
+
+ @param base The event base to associate the listener with.
+ @param cb A callback to be invoked when a new connection arrives. If the
+ callback is NULL, the listener will be treated as disabled until the
+ callback is set.
+ @param ptr A user-supplied pointer to give to the callback.
+ @param flags Any number of LEV_OPT_* flags
+ @param backlog Passed to the listen() call to determine the length of the
+ acceptable connection backlog. Set to -1 for a reasonable default.
+ @param addr The address to listen for connections on.
+ @param socklen The length of the address.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evconnlistener *evconnlistener_new_bind(struct event_base *base,
+ evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+ const struct sockaddr *sa, int socklen);
+/**
+ Disable and deallocate an evconnlistener.
+ */
+EVENT2_EXPORT_SYMBOL
+void evconnlistener_free(struct evconnlistener *lev);
+/**
+ Re-enable an evconnlistener that has been disabled.
+ */
+EVENT2_EXPORT_SYMBOL
+int evconnlistener_enable(struct evconnlistener *lev);
+/**
+ Stop listening for connections on an evconnlistener.
+ */
+EVENT2_EXPORT_SYMBOL
+int evconnlistener_disable(struct evconnlistener *lev);
+
+/** Return an evconnlistener's associated event_base. */
+EVENT2_EXPORT_SYMBOL
+struct event_base *evconnlistener_get_base(struct evconnlistener *lev);
+
+/** Return the socket that an evconnlistner is listening on. */
+EVENT2_EXPORT_SYMBOL
+evutil_socket_t evconnlistener_get_fd(struct evconnlistener *lev);
+
+/** Change the callback on the listener to cb and its user_data to arg.
+ */
+EVENT2_EXPORT_SYMBOL
+void evconnlistener_set_cb(struct evconnlistener *lev,
+ evconnlistener_cb cb, void *arg);
+
+/** Set an evconnlistener's error callback. */
+EVENT2_EXPORT_SYMBOL
+void evconnlistener_set_error_cb(struct evconnlistener *lev,
+ evconnlistener_errorcb errorcb);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/rpc.h b/ipc/chromium/src/third_party/libevent/include/event2/rpc.h
new file mode 100644
index 0000000000..1bc31d5711
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/rpc.h
@@ -0,0 +1,626 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_RPC_H_INCLUDED_
+#define EVENT2_RPC_H_INCLUDED_
+
+/* For int types. */
+#include <event2/util.h>
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file rpc.h
+ *
+ * This header files provides basic support for an RPC server and client.
+ *
+ * To support RPCs in a server, every supported RPC command needs to be
+ * defined and registered.
+ *
+ * EVRPC_HEADER(SendCommand, Request, Reply);
+ *
+ * SendCommand is the name of the RPC command.
+ * Request is the name of a structure generated by event_rpcgen.py.
+ * It contains all parameters relating to the SendCommand RPC. The
+ * server needs to fill in the Reply structure.
+ * Reply is the name of a structure generated by event_rpcgen.py. It
+ * contains the answer to the RPC.
+ *
+ * To register an RPC with an HTTP server, you need to first create an RPC
+ * base with:
+ *
+ * struct evrpc_base *base = evrpc_init(http);
+ *
+ * A specific RPC can then be registered with
+ *
+ * EVRPC_REGISTER(base, SendCommand, Request, Reply, FunctionCB, arg);
+ *
+ * when the server receives an appropriately formatted RPC, the user callback
+ * is invoked. The callback needs to fill in the reply structure.
+ *
+ * void FunctionCB(EVRPC_STRUCT(SendCommand)* rpc, void *arg);
+ *
+ * To send the reply, call EVRPC_REQUEST_DONE(rpc);
+ *
+ * See the regression test for an example.
+ */
+
+/**
+ Determines if the member has been set in the message
+
+ @param msg the message to inspect
+ @param member the member variable to test for presences
+ @return 1 if it's present or 0 otherwise.
+*/
+#define EVTAG_HAS(msg, member) \
+ ((msg)->member##_set == 1)
+
+#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
+
+/**
+ Assigns a value to the member in the message.
+
+ @param msg the message to which to assign a value
+ @param member the name of the member variable
+ @param value the value to assign
+*/
+#define EVTAG_ASSIGN(msg, member, value) \
+ (*(msg)->base->member##_assign)((msg), (value))
+/**
+ Assigns a value to the member in the message.
+
+ @param msg the message to which to assign a value
+ @param member the name of the member variable
+ @param value the value to assign
+ @param len the length of the value
+*/
+#define EVTAG_ASSIGN_WITH_LEN(msg, member, value, len) \
+ (*(msg)->base->member##_assign)((msg), (value), (len))
+/**
+ Returns the value for a member.
+
+ @param msg the message from which to get the value
+ @param member the name of the member variable
+ @param pvalue a pointer to the variable to hold the value
+ @return 0 on success, -1 otherwise.
+*/
+#define EVTAG_GET(msg, member, pvalue) \
+ (*(msg)->base->member##_get)((msg), (pvalue))
+/**
+ Returns the value for a member.
+
+ @param msg the message from which to get the value
+ @param member the name of the member variable
+ @param pvalue a pointer to the variable to hold the value
+ @param plen a pointer to the length of the value
+ @return 0 on success, -1 otherwise.
+*/
+#define EVTAG_GET_WITH_LEN(msg, member, pvalue, plen) \
+ (*(msg)->base->member##_get)((msg), (pvalue), (plen))
+
+#endif /* EVENT2_RPC_COMPAT_H_INCLUDED_ */
+
+/**
+ Adds a value to an array.
+*/
+#define EVTAG_ARRAY_ADD_VALUE(msg, member, value) \
+ (*(msg)->base->member##_add)((msg), (value))
+/**
+ Allocates a new entry in the array and returns it.
+*/
+#define EVTAG_ARRAY_ADD(msg, member) \
+ (*(msg)->base->member##_add)(msg)
+/**
+ Gets a variable at the specified offset from the array.
+*/
+#define EVTAG_ARRAY_GET(msg, member, offset, pvalue) \
+ (*(msg)->base->member##_get)((msg), (offset), (pvalue))
+/**
+ Returns the number of entries in the array.
+*/
+#define EVTAG_ARRAY_LEN(msg, member) ((msg)->member##_length)
+
+
+struct evbuffer;
+struct event_base;
+struct evrpc_req_generic;
+struct evrpc_request_wrapper;
+struct evrpc;
+
+/** The type of a specific RPC Message
+ *
+ * @param rpcname the name of the RPC message
+ */
+#define EVRPC_STRUCT(rpcname) struct evrpc_req__##rpcname
+
+struct evhttp_request;
+struct evrpc_status;
+struct evrpc_hook_meta;
+
+/** Creates the definitions and prototypes for an RPC
+ *
+ * You need to use EVRPC_HEADER to create structures and function prototypes
+ * needed by the server and client implementation. The structures have to be
+ * defined in an .rpc file and converted to source code via event_rpcgen.py
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @see EVRPC_GENERATE()
+ */
+#define EVRPC_HEADER(rpcname, reqstruct, rplystruct) \
+EVRPC_STRUCT(rpcname) { \
+ struct evrpc_hook_meta *hook_meta; \
+ struct reqstruct* request; \
+ struct rplystruct* reply; \
+ struct evrpc* rpc; \
+ struct evhttp_request* http_req; \
+ struct evbuffer* rpc_data; \
+}; \
+EVENT2_EXPORT_SYMBOL \
+int evrpc_send_request_##rpcname(struct evrpc_pool *, \
+ struct reqstruct *, struct rplystruct *, \
+ void (*)(struct evrpc_status *, \
+ struct reqstruct *, struct rplystruct *, void *cbarg), \
+ void *);
+
+struct evrpc_pool;
+
+/** use EVRPC_GENERATE instead */
+EVENT2_EXPORT_SYMBOL
+struct evrpc_request_wrapper *evrpc_make_request_ctx(
+ struct evrpc_pool *pool, void *request, void *reply,
+ const char *rpcname,
+ void (*req_marshal)(struct evbuffer*, void *),
+ void (*rpl_clear)(void *),
+ int (*rpl_unmarshal)(void *, struct evbuffer *),
+ void (*cb)(struct evrpc_status *, void *, void *, void *),
+ void *cbarg);
+
+/** Creates a context structure that contains rpc specific information.
+ *
+ * EVRPC_MAKE_CTX is used to populate a RPC specific context that
+ * contains information about marshaling the RPC data types.
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @param pool the evrpc_pool over which to make the request
+ * @param request a pointer to the RPC request structure object
+ * @param reply a pointer to the RPC reply structure object
+ * @param cb the callback function to call when the RPC has completed
+ * @param cbarg the argument to supply to the callback
+ */
+#define EVRPC_MAKE_CTX(rpcname, reqstruct, rplystruct, \
+ pool, request, reply, cb, cbarg) \
+ evrpc_make_request_ctx(pool, request, reply, \
+ #rpcname, \
+ (void (*)(struct evbuffer *, void *))reqstruct##_marshal, \
+ (void (*)(void *))rplystruct##_clear, \
+ (int (*)(void *, struct evbuffer *))rplystruct##_unmarshal, \
+ (void (*)(struct evrpc_status *, void *, void *, void *))cb, \
+ cbarg)
+
+/** Generates the code for receiving and sending an RPC message
+ *
+ * EVRPC_GENERATE is used to create the code corresponding to sending
+ * and receiving a particular RPC message
+ *
+ * @param rpcname the name of the RPC
+ * @param reqstruct the name of the RPC request structure
+ * @param replystruct the name of the RPC reply structure
+ * @see EVRPC_HEADER()
+ */
+#define EVRPC_GENERATE(rpcname, reqstruct, rplystruct) \
+ int evrpc_send_request_##rpcname(struct evrpc_pool *pool, \
+ struct reqstruct *request, struct rplystruct *reply, \
+ void (*cb)(struct evrpc_status *, \
+ struct reqstruct *, struct rplystruct *, void *cbarg), \
+ void *cbarg) { \
+ return evrpc_send_request_generic(pool, request, reply, \
+ (void (*)(struct evrpc_status *, void *, void *, void *))cb, \
+ cbarg, \
+ #rpcname, \
+ (void (*)(struct evbuffer *, void *))reqstruct##_marshal, \
+ (void (*)(void *))rplystruct##_clear, \
+ (int (*)(void *, struct evbuffer *))rplystruct##_unmarshal); \
+}
+
+/** Provides access to the HTTP request object underlying an RPC
+ *
+ * Access to the underlying http object; can be used to look at headers or
+ * for getting the remote ip address
+ *
+ * @param rpc_req the rpc request structure provided to the server callback
+ * @return an struct evhttp_request object that can be inspected for
+ * HTTP headers or sender information.
+ */
+#define EVRPC_REQUEST_HTTP(rpc_req) (rpc_req)->http_req
+
+/** completes the server response to an rpc request */
+EVENT2_EXPORT_SYMBOL
+void evrpc_request_done(struct evrpc_req_generic *req);
+
+/** accessors for request and reply */
+EVENT2_EXPORT_SYMBOL
+void *evrpc_get_request(struct evrpc_req_generic *req);
+EVENT2_EXPORT_SYMBOL
+void *evrpc_get_reply(struct evrpc_req_generic *req);
+
+/** Creates the reply to an RPC request
+ *
+ * EVRPC_REQUEST_DONE is used to answer a request; the reply is expected
+ * to have been filled in. The request and reply pointers become invalid
+ * after this call has finished.
+ *
+ * @param rpc_req the rpc request structure provided to the server callback
+ */
+#define EVRPC_REQUEST_DONE(rpc_req) do { \
+ struct evrpc_req_generic *req_ = (struct evrpc_req_generic *)(rpc_req); \
+ evrpc_request_done(req_); \
+} while (0)
+
+
+struct evrpc_base;
+struct evhttp;
+
+/* functions to start up the rpc system */
+
+/** Creates a new rpc base from which RPC requests can be received
+ *
+ * @param server a pointer to an existing HTTP server
+ * @return a newly allocated evrpc_base struct or NULL if an error occurred
+ * @see evrpc_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evrpc_base *evrpc_init(struct evhttp *server);
+
+/**
+ * Frees the evrpc base
+ *
+ * For now, you are responsible for making sure that no rpcs are ongoing.
+ *
+ * @param base the evrpc_base object to be freed
+ * @see evrpc_init
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_free(struct evrpc_base *base);
+
+/** register RPCs with the HTTP Server
+ *
+ * registers a new RPC with the HTTP server, each RPC needs to have
+ * a unique name under which it can be identified.
+ *
+ * @param base the evrpc_base structure in which the RPC should be
+ * registered.
+ * @param name the name of the RPC
+ * @param request the name of the RPC request structure
+ * @param reply the name of the RPC reply structure
+ * @param callback the callback that should be invoked when the RPC
+ * is received. The callback has the following prototype
+ * void (*callback)(EVRPC_STRUCT(Message)* rpc, void *arg)
+ * @param cbarg an additional parameter that can be passed to the callback.
+ * The parameter can be used to carry around state.
+ */
+#define EVRPC_REGISTER(base, name, request, reply, callback, cbarg) \
+ evrpc_register_generic(base, #name, \
+ (void (*)(struct evrpc_req_generic *, void *))callback, cbarg, \
+ (void *(*)(void *))request##_new_with_arg, NULL, \
+ (void (*)(void *))request##_free, \
+ (int (*)(void *, struct evbuffer *))request##_unmarshal, \
+ (void *(*)(void *))reply##_new_with_arg, NULL, \
+ (void (*)(void *))reply##_free, \
+ (int (*)(void *))reply##_complete, \
+ (void (*)(struct evbuffer *, void *))reply##_marshal)
+
+/**
+ Low level function for registering an RPC with a server.
+
+ Use EVRPC_REGISTER() instead.
+
+ @see EVRPC_REGISTER()
+*/
+EVENT2_EXPORT_SYMBOL
+int evrpc_register_rpc(struct evrpc_base *, struct evrpc *,
+ void (*)(struct evrpc_req_generic*, void *), void *);
+
+/**
+ * Unregisters an already registered RPC
+ *
+ * @param base the evrpc_base object from which to unregister an RPC
+ * @param name the name of the rpc to unregister
+ * @return -1 on error or 0 when successful.
+ * @see EVRPC_REGISTER()
+ */
+#define EVRPC_UNREGISTER(base, name) evrpc_unregister_rpc((base), #name)
+
+EVENT2_EXPORT_SYMBOL
+int evrpc_unregister_rpc(struct evrpc_base *base, const char *name);
+
+/*
+ * Client-side RPC support
+ */
+
+struct evhttp_connection;
+struct evrpc_status;
+
+/** launches an RPC and sends it to the server
+ *
+ * EVRPC_MAKE_REQUEST() is used by the client to send an RPC to the server.
+ *
+ * @param name the name of the RPC
+ * @param pool the evrpc_pool that contains the connection objects over which
+ * the request should be sent.
+ * @param request a pointer to the RPC request structure - it contains the
+ * data to be sent to the server.
+ * @param reply a pointer to the RPC reply structure. It is going to be filled
+ * if the request was answered successfully
+ * @param cb the callback to invoke when the RPC request has been answered
+ * @param cbarg an additional argument to be passed to the client
+ * @return 0 on success, -1 on failure
+ */
+#define EVRPC_MAKE_REQUEST(name, pool, request, reply, cb, cbarg) \
+ evrpc_send_request_##name((pool), (request), (reply), (cb), (cbarg))
+
+/**
+ Makes an RPC request based on the provided context.
+
+ This is a low-level function and should not be used directly
+ unless a custom context object is provided. Use EVRPC_MAKE_REQUEST()
+ instead.
+
+ @param ctx a context from EVRPC_MAKE_CTX()
+ @returns 0 on success, -1 otherwise.
+ @see EVRPC_MAKE_REQUEST(), EVRPC_MAKE_CTX()
+*/
+EVENT2_EXPORT_SYMBOL
+int evrpc_make_request(struct evrpc_request_wrapper *ctx);
+
+/** creates an rpc connection pool
+ *
+ * a pool has a number of connections associated with it.
+ * rpc requests are always made via a pool.
+ *
+ * @param base a pointer to an struct event_based object; can be left NULL
+ * in singled-threaded applications
+ * @return a newly allocated struct evrpc_pool object or NULL if an error
+ * occurred
+ * @see evrpc_pool_free()
+ */
+EVENT2_EXPORT_SYMBOL
+struct evrpc_pool *evrpc_pool_new(struct event_base *base);
+/** frees an rpc connection pool
+ *
+ * @param pool a pointer to an evrpc_pool allocated via evrpc_pool_new()
+ * @see evrpc_pool_new()
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_pool_free(struct evrpc_pool *pool);
+
+/**
+ * Adds a connection over which rpc can be dispatched to the pool.
+ *
+ * The connection object must have been newly created.
+ *
+ * @param pool the pool to which to add the connection
+ * @param evcon the connection to add to the pool.
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_pool_add_connection(struct evrpc_pool *pool,
+ struct evhttp_connection *evcon);
+
+/**
+ * Removes a connection from the pool.
+ *
+ * The connection object must have been newly created.
+ *
+ * @param pool the pool from which to remove the connection
+ * @param evcon the connection to remove from the pool.
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_pool_remove_connection(struct evrpc_pool *pool,
+ struct evhttp_connection *evcon);
+
+/**
+ * Sets the timeout in secs after which a request has to complete. The
+ * RPC is completely aborted if it does not complete by then. Setting
+ * the timeout to 0 means that it never timeouts and can be used to
+ * implement callback type RPCs.
+ *
+ * Any connection already in the pool will be updated with the new
+ * timeout. Connections added to the pool after set_timeout has be
+ * called receive the pool timeout only if no timeout has been set
+ * for the connection itself.
+ *
+ * @param pool a pointer to a struct evrpc_pool object
+ * @param timeout_in_secs the number of seconds after which a request should
+ * timeout and a failure be returned to the callback.
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_pool_set_timeout(struct evrpc_pool *pool, int timeout_in_secs);
+
+/**
+ * Hooks for changing the input and output of RPCs; this can be used to
+ * implement compression, authentication, encryption, ...
+ */
+
+enum EVRPC_HOOK_TYPE {
+ EVRPC_INPUT, /**< apply the function to an input hook */
+ EVRPC_OUTPUT /**< apply the function to an output hook */
+};
+
+#ifndef _WIN32
+/** Deprecated alias for EVRPC_INPUT. Not available on windows, where it
+ * conflicts with platform headers. */
+#define INPUT EVRPC_INPUT
+/** Deprecated alias for EVRPC_OUTPUT. Not available on windows, where it
+ * conflicts with platform headers. */
+#define OUTPUT EVRPC_OUTPUT
+#endif
+
+/**
+ * Return value from hook processing functions
+ */
+
+enum EVRPC_HOOK_RESULT {
+ EVRPC_TERMINATE = -1, /**< indicates the rpc should be terminated */
+ EVRPC_CONTINUE = 0, /**< continue processing the rpc */
+ EVRPC_PAUSE = 1 /**< pause processing request until resumed */
+};
+
+/** adds a processing hook to either an rpc base or rpc pool
+ *
+ * If a hook returns TERMINATE, the processing is aborted. On CONTINUE,
+ * the request is immediately processed after the hook returns. If the
+ * hook returns PAUSE, request processing stops until evrpc_resume_request()
+ * has been called.
+ *
+ * The add functions return handles that can be used for removing hooks.
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param hook_type either INPUT or OUTPUT
+ * @param cb the callback to call when the hook is activated
+ * @param cb_arg an additional argument for the callback
+ * @return a handle to the hook so it can be removed later
+ * @see evrpc_remove_hook()
+ */
+EVENT2_EXPORT_SYMBOL
+void *evrpc_add_hook(void *vbase,
+ enum EVRPC_HOOK_TYPE hook_type,
+ int (*cb)(void *, struct evhttp_request *, struct evbuffer *, void *),
+ void *cb_arg);
+
+/** removes a previously added hook
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param hook_type either INPUT or OUTPUT
+ * @param handle a handle returned by evrpc_add_hook()
+ * @return 1 on success or 0 on failure
+ * @see evrpc_add_hook()
+ */
+EVENT2_EXPORT_SYMBOL
+int evrpc_remove_hook(void *vbase,
+ enum EVRPC_HOOK_TYPE hook_type,
+ void *handle);
+
+/** resume a paused request
+ *
+ * @param vbase a pointer to either struct evrpc_base or struct evrpc_pool
+ * @param ctx the context pointer provided to the original hook call
+ */
+EVENT2_EXPORT_SYMBOL
+int evrpc_resume_request(void *vbase, void *ctx, enum EVRPC_HOOK_RESULT res);
+
+/** adds meta data to request
+ *
+ * evrpc_hook_add_meta() allows hooks to add meta data to a request. for
+ * a client request, the meta data can be inserted by an outgoing request hook
+ * and retrieved by the incoming request hook.
+ *
+ * @param ctx the context provided to the hook call
+ * @param key a NUL-terminated c-string
+ * @param data the data to be associated with the key
+ * @param data_size the size of the data
+ */
+EVENT2_EXPORT_SYMBOL
+void evrpc_hook_add_meta(void *ctx, const char *key,
+ const void *data, size_t data_size);
+
+/** retrieves meta data previously associated
+ *
+ * evrpc_hook_find_meta() can be used to retrieve meta data associated to a
+ * request by a previous hook.
+ * @param ctx the context provided to the hook call
+ * @param key a NUL-terminated c-string
+ * @param data pointer to a data pointer that will contain the retrieved data
+ * @param data_size pointer to the size of the data
+ * @return 0 on success or -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evrpc_hook_find_meta(void *ctx, const char *key,
+ void **data, size_t *data_size);
+
+/**
+ * returns the connection object associated with the request
+ *
+ * @param ctx the context provided to the hook call
+ * @return a pointer to the evhttp_connection object or NULL if an error
+ * occurred
+ */
+EVENT2_EXPORT_SYMBOL
+struct evhttp_connection *evrpc_hook_get_connection(void *ctx);
+
+/**
+ Function for sending a generic RPC request.
+
+ Do not call this function directly, use EVRPC_MAKE_REQUEST() instead.
+
+ @see EVRPC_MAKE_REQUEST()
+ */
+EVENT2_EXPORT_SYMBOL
+int evrpc_send_request_generic(struct evrpc_pool *pool,
+ void *request, void *reply,
+ void (*cb)(struct evrpc_status *, void *, void *, void *),
+ void *cb_arg,
+ const char *rpcname,
+ void (*req_marshal)(struct evbuffer *, void *),
+ void (*rpl_clear)(void *),
+ int (*rpl_unmarshal)(void *, struct evbuffer *));
+
+/**
+ Function for registering a generic RPC with the RPC base.
+
+ Do not call this function directly, use EVRPC_REGISTER() instead.
+
+ @see EVRPC_REGISTER()
+ */
+EVENT2_EXPORT_SYMBOL
+int evrpc_register_generic(struct evrpc_base *base, const char *name,
+ void (*callback)(struct evrpc_req_generic *, void *), void *cbarg,
+ void *(*req_new)(void *), void *req_new_arg, void (*req_free)(void *),
+ int (*req_unmarshal)(void *, struct evbuffer *),
+ void *(*rpl_new)(void *), void *rpl_new_arg, void (*rpl_free)(void *),
+ int (*rpl_complete)(void *),
+ void (*rpl_marshal)(struct evbuffer *, void *));
+
+/** accessors for obscure and undocumented functionality */
+EVENT2_EXPORT_SYMBOL
+struct evrpc_pool* evrpc_request_get_pool(struct evrpc_request_wrapper *ctx);
+EVENT2_EXPORT_SYMBOL
+void evrpc_request_set_pool(struct evrpc_request_wrapper *ctx,
+ struct evrpc_pool *pool);
+EVENT2_EXPORT_SYMBOL
+void evrpc_request_set_cb(struct evrpc_request_wrapper *ctx,
+ void (*cb)(struct evrpc_status*, void *request, void *reply, void *arg),
+ void *cb_arg);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_RPC_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/rpc_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/rpc_compat.h
new file mode 100644
index 0000000000..8d8334d25f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/rpc_compat.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_RPC_COMPAT_H_INCLUDED_
+#define EVENT2_RPC_COMPAT_H_INCLUDED_
+
+/** @file event2/rpc_compat.h
+
+ Deprecated versions of the functions in rpc.h: provided only for
+ backwards compatibility.
+
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** backwards compatible accessors that work only with gcc */
+#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
+
+#undef EVTAG_ASSIGN
+#undef EVTAG_GET
+#undef EVTAG_ADD
+
+#define EVTAG_ASSIGN(msg, member, args...) \
+ (*(msg)->base->member##_assign)(msg, ## args)
+#define EVTAG_GET(msg, member, args...) \
+ (*(msg)->base->member##_get)(msg, ## args)
+#define EVTAG_ADD(msg, member, args...) \
+ (*(msg)->base->member##_add)(msg, ## args)
+#endif
+#define EVTAG_LEN(msg, member) ((msg)->member##_length)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_EVENT_COMPAT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/rpc_struct.h b/ipc/chromium/src/third_party/libevent/include/event2/rpc_struct.h
new file mode 100644
index 0000000000..f3cb460aed
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/rpc_struct.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2006-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_RPC_STRUCT_H_INCLUDED_
+#define EVENT2_RPC_STRUCT_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file event2/rpc_struct.h
+
+ Structures used by rpc.h. Using these structures directly may harm
+ forward compatibility: be careful!
+
+ */
+
+/* Fix so that people don't have to run with <sys/queue.h> */
+#ifndef TAILQ_ENTRY
+#define EVENT_DEFINED_TQENTRY_
+#define TAILQ_ENTRY(type) \
+struct { \
+ struct type *tqe_next; /* next element */ \
+ struct type **tqe_prev; /* address of previous next element */ \
+}
+#endif /* !TAILQ_ENTRY */
+
+/**
+ * provides information about the completed RPC request.
+ */
+struct evrpc_status {
+#define EVRPC_STATUS_ERR_NONE 0
+#define EVRPC_STATUS_ERR_TIMEOUT 1
+#define EVRPC_STATUS_ERR_BADPAYLOAD 2
+#define EVRPC_STATUS_ERR_UNSTARTED 3
+#define EVRPC_STATUS_ERR_HOOKABORTED 4
+ int error;
+
+ /* for looking at headers or other information */
+ struct evhttp_request *http_req;
+};
+
+/* the structure below needs to be synchronized with evrpc_req_generic */
+
+/* Encapsulates a request */
+struct evrpc {
+ TAILQ_ENTRY(evrpc) next;
+
+ /* the URI at which the request handler lives */
+ const char* uri;
+
+ /* creates a new request structure */
+ void *(*request_new)(void *);
+ void *request_new_arg;
+
+ /* frees the request structure */
+ void (*request_free)(void *);
+
+ /* unmarshals the buffer into the proper request structure */
+ int (*request_unmarshal)(void *, struct evbuffer *);
+
+ /* creates a new reply structure */
+ void *(*reply_new)(void *);
+ void *reply_new_arg;
+
+ /* frees the reply structure */
+ void (*reply_free)(void *);
+
+ /* verifies that the reply is valid */
+ int (*reply_complete)(void *);
+
+ /* marshals the reply into a buffer */
+ void (*reply_marshal)(struct evbuffer*, void *);
+
+ /* the callback invoked for each received rpc */
+ void (*cb)(struct evrpc_req_generic *, void *);
+ void *cb_arg;
+
+ /* reference for further configuration */
+ struct evrpc_base *base;
+};
+
+#ifdef EVENT_DEFINED_TQENTRY_
+#undef TAILQ_ENTRY
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_RPC_STRUCT_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/tag.h b/ipc/chromium/src/third_party/libevent/include/event2/tag.h
new file mode 100644
index 0000000000..2f73bfc00e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/tag.h
@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_TAG_H_INCLUDED_
+#define EVENT2_TAG_H_INCLUDED_
+
+/** @file event2/tag.h
+
+ Helper functions for reading and writing tagged data onto buffers.
+
+ */
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+/* For int types. */
+#include <event2/util.h>
+
+struct evbuffer;
+
+/*
+ * Marshaling tagged data - We assume that all tags are inserted in their
+ * numeric order - so that unknown tags will always be higher than the
+ * known ones - and we can just ignore the end of an event buffer.
+ */
+
+EVENT2_EXPORT_SYMBOL
+void evtag_init(void);
+
+/**
+ Unmarshals the header and returns the length of the payload
+
+ @param evbuf the buffer from which to unmarshal data
+ @param ptag a pointer in which the tag id is being stored
+ @returns -1 on failure or the number of bytes in the remaining payload.
+*/
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_header(struct evbuffer *evbuf, ev_uint32_t *ptag);
+
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal(struct evbuffer *evbuf, ev_uint32_t tag, const void *data,
+ ev_uint32_t len);
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal_buffer(struct evbuffer *evbuf, ev_uint32_t tag,
+ struct evbuffer *data);
+
+/**
+ Encode an integer and store it in an evbuffer.
+
+ We encode integers by nybbles; the first nibble contains the number
+ of significant nibbles - 1; this allows us to encode up to 64-bit
+ integers. This function is byte-order independent.
+
+ @param evbuf evbuffer to store the encoded number
+ @param number a 32-bit integer
+ */
+EVENT2_EXPORT_SYMBOL
+void evtag_encode_int(struct evbuffer *evbuf, ev_uint32_t number);
+EVENT2_EXPORT_SYMBOL
+void evtag_encode_int64(struct evbuffer *evbuf, ev_uint64_t number);
+
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal_int(struct evbuffer *evbuf, ev_uint32_t tag,
+ ev_uint32_t integer);
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal_int64(struct evbuffer *evbuf, ev_uint32_t tag,
+ ev_uint64_t integer);
+
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal_string(struct evbuffer *buf, ev_uint32_t tag,
+ const char *string);
+
+EVENT2_EXPORT_SYMBOL
+void evtag_marshal_timeval(struct evbuffer *evbuf, ev_uint32_t tag,
+ struct timeval *tv);
+
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal(struct evbuffer *src, ev_uint32_t *ptag,
+ struct evbuffer *dst);
+EVENT2_EXPORT_SYMBOL
+int evtag_peek(struct evbuffer *evbuf, ev_uint32_t *ptag);
+EVENT2_EXPORT_SYMBOL
+int evtag_peek_length(struct evbuffer *evbuf, ev_uint32_t *plength);
+EVENT2_EXPORT_SYMBOL
+int evtag_payload_length(struct evbuffer *evbuf, ev_uint32_t *plength);
+EVENT2_EXPORT_SYMBOL
+int evtag_consume(struct evbuffer *evbuf);
+
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_int(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ ev_uint32_t *pinteger);
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_int64(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ ev_uint64_t *pinteger);
+
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_fixed(struct evbuffer *src, ev_uint32_t need_tag,
+ void *data, size_t len);
+
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_string(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ char **pstring);
+
+EVENT2_EXPORT_SYMBOL
+int evtag_unmarshal_timeval(struct evbuffer *evbuf, ev_uint32_t need_tag,
+ struct timeval *ptv);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_TAG_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/tag_compat.h b/ipc/chromium/src/third_party/libevent/include/event2/tag_compat.h
new file mode 100644
index 0000000000..a276c0d35b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/tag_compat.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_TAG_COMPAT_H_INCLUDED_
+#define EVENT2_TAG_COMPAT_H_INCLUDED_
+
+/** @file event2/tag_compat.h
+
+ Obsolete/deprecated functions from tag.h; provided only for backwards
+ compatibility.
+ */
+
+/**
+ @name Misnamed functions
+
+ @deprecated These macros are deprecated because their names don't follow
+ Libevent's naming conventions. Use evtag_encode_int and
+ evtag_encode_int64 instead.
+
+ @{
+*/
+#define encode_int(evbuf, number) evtag_encode_int((evbuf), (number))
+#define encode_int64(evbuf, number) evtag_encode_int64((evbuf), (number))
+/**@}*/
+
+#endif /* EVENT2_TAG_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/thread.h b/ipc/chromium/src/third_party/libevent/include/event2/thread.h
new file mode 100644
index 0000000000..b51998631b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/thread.h
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_THREAD_H_INCLUDED_
+#define EVENT2_THREAD_H_INCLUDED_
+
+/** @file event2/thread.h
+
+ Functions for multi-threaded applications using Libevent.
+
+ When using a multi-threaded application in which multiple threads
+ add and delete events from a single event base, Libevent needs to
+ lock its data structures.
+
+ Like the memory-management function hooks, all of the threading functions
+ _must_ be set up before an event_base is created if you want the base to
+ use them.
+
+ Most programs will either be using Windows threads or Posix threads. You
+ can configure Libevent to use one of these event_use_windows_threads() or
+ event_use_pthreads() respectively. If you're using another threading
+ library, you'll need to configure threading functions manually using
+ evthread_set_lock_callbacks() and evthread_set_condition_callbacks().
+
+ */
+
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+
+/**
+ @name Flags passed to lock functions
+
+ @{
+*/
+/** A flag passed to a locking callback when the lock was allocated as a
+ * read-write lock, and we want to acquire or release the lock for writing. */
+#define EVTHREAD_WRITE 0x04
+/** A flag passed to a locking callback when the lock was allocated as a
+ * read-write lock, and we want to acquire or release the lock for reading. */
+#define EVTHREAD_READ 0x08
+/** A flag passed to a locking callback when we don't want to block waiting
+ * for the lock; if we can't get the lock immediately, we will instead
+ * return nonzero from the locking callback. */
+#define EVTHREAD_TRY 0x10
+/**@}*/
+
+#if !defined(EVENT__DISABLE_THREAD_SUPPORT) || defined(EVENT_IN_DOXYGEN_)
+
+#define EVTHREAD_LOCK_API_VERSION 1
+
+/**
+ @name Types of locks
+
+ @{*/
+/** A recursive lock is one that can be acquired multiple times at once by the
+ * same thread. No other process can allocate the lock until the thread that
+ * has been holding it has unlocked it as many times as it locked it. */
+#define EVTHREAD_LOCKTYPE_RECURSIVE 1
+/* A read-write lock is one that allows multiple simultaneous readers, but
+ * where any one writer excludes all other writers and readers. */
+#define EVTHREAD_LOCKTYPE_READWRITE 2
+/**@}*/
+
+/** This structure describes the interface a threading library uses for
+ * locking. It's used to tell evthread_set_lock_callbacks() how to use
+ * locking on this platform.
+ */
+struct evthread_lock_callbacks {
+ /** The current version of the locking API. Set this to
+ * EVTHREAD_LOCK_API_VERSION */
+ int lock_api_version;
+ /** Which kinds of locks does this version of the locking API
+ * support? A bitfield of EVTHREAD_LOCKTYPE_RECURSIVE and
+ * EVTHREAD_LOCKTYPE_READWRITE.
+ *
+ * (Note that RECURSIVE locks are currently mandatory, and
+ * READWRITE locks are not currently used.)
+ **/
+ unsigned supported_locktypes;
+ /** Function to allocate and initialize new lock of type 'locktype'.
+ * Returns NULL on failure. */
+ void *(*alloc)(unsigned locktype);
+ /** Funtion to release all storage held in 'lock', which was created
+ * with type 'locktype'. */
+ void (*free)(void *lock, unsigned locktype);
+ /** Acquire an already-allocated lock at 'lock' with mode 'mode'.
+ * Returns 0 on success, and nonzero on failure. */
+ int (*lock)(unsigned mode, void *lock);
+ /** Release a lock at 'lock' using mode 'mode'. Returns 0 on success,
+ * and nonzero on failure. */
+ int (*unlock)(unsigned mode, void *lock);
+};
+
+/** Sets a group of functions that Libevent should use for locking.
+ * For full information on the required callback API, see the
+ * documentation for the individual members of evthread_lock_callbacks.
+ *
+ * Note that if you're using Windows or the Pthreads threading library, you
+ * probably shouldn't call this function; instead, use
+ * evthread_use_windows_threads() or evthread_use_posix_threads() if you can.
+ */
+EVENT2_EXPORT_SYMBOL
+int evthread_set_lock_callbacks(const struct evthread_lock_callbacks *);
+
+#define EVTHREAD_CONDITION_API_VERSION 1
+
+struct timeval;
+
+/** This structure describes the interface a threading library uses for
+ * condition variables. It's used to tell evthread_set_condition_callbacks
+ * how to use locking on this platform.
+ */
+struct evthread_condition_callbacks {
+ /** The current version of the conditions API. Set this to
+ * EVTHREAD_CONDITION_API_VERSION */
+ int condition_api_version;
+ /** Function to allocate and initialize a new condition variable.
+ * Returns the condition variable on success, and NULL on failure.
+ * The 'condtype' argument will be 0 with this API version.
+ */
+ void *(*alloc_condition)(unsigned condtype);
+ /** Function to free a condition variable. */
+ void (*free_condition)(void *cond);
+ /** Function to signal a condition variable. If 'broadcast' is 1, all
+ * threads waiting on 'cond' should be woken; otherwise, only on one
+ * thread is worken. Should return 0 on success, -1 on failure.
+ * This function will only be called while holding the associated
+ * lock for the condition.
+ */
+ int (*signal_condition)(void *cond, int broadcast);
+ /** Function to wait for a condition variable. The lock 'lock'
+ * will be held when this function is called; should be released
+ * while waiting for the condition to be come signalled, and
+ * should be held again when this function returns.
+ * If timeout is provided, it is interval of seconds to wait for
+ * the event to become signalled; if it is NULL, the function
+ * should wait indefinitely.
+ *
+ * The function should return -1 on error; 0 if the condition
+ * was signalled, or 1 on a timeout. */
+ int (*wait_condition)(void *cond, void *lock,
+ const struct timeval *timeout);
+};
+
+/** Sets a group of functions that Libevent should use for condition variables.
+ * For full information on the required callback API, see the
+ * documentation for the individual members of evthread_condition_callbacks.
+ *
+ * Note that if you're using Windows or the Pthreads threading library, you
+ * probably shouldn't call this function; instead, use
+ * evthread_use_windows_threads() or evthread_use_pthreads() if you can.
+ */
+EVENT2_EXPORT_SYMBOL
+int evthread_set_condition_callbacks(
+ const struct evthread_condition_callbacks *);
+
+/**
+ Sets the function for determining the thread id.
+
+ @param base the event base for which to set the id function
+ @param id_fn the identify function Libevent should invoke to
+ determine the identity of a thread.
+*/
+EVENT2_EXPORT_SYMBOL
+void evthread_set_id_callback(
+ unsigned long (*id_fn)(void));
+
+#if (defined(_WIN32) && !defined(EVENT__DISABLE_THREAD_SUPPORT)) || defined(EVENT_IN_DOXYGEN_)
+/** Sets up Libevent for use with Windows builtin locking and thread ID
+ functions. Unavailable if Libevent is not built for Windows.
+
+ @return 0 on success, -1 on failure. */
+EVENT2_EXPORT_SYMBOL
+int evthread_use_windows_threads(void);
+/**
+ Defined if Libevent was built with support for evthread_use_windows_threads()
+*/
+#define EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED 1
+#endif
+
+#if defined(EVENT__HAVE_PTHREADS) || defined(EVENT_IN_DOXYGEN_)
+/** Sets up Libevent for use with Pthreads locking and thread ID functions.
+ Unavailable if Libevent is not build for use with pthreads. Requires
+ libraries to link against Libevent_pthreads as well as Libevent.
+
+ @return 0 on success, -1 on failure. */
+EVENT2_EXPORT_SYMBOL
+int evthread_use_pthreads(void);
+/** Defined if Libevent was built with support for evthread_use_pthreads() */
+#define EVTHREAD_USE_PTHREADS_IMPLEMENTED 1
+
+#endif
+
+/** Enable debugging wrappers around the current lock callbacks. If Libevent
+ * makes one of several common locking errors, exit with an assertion failure.
+ *
+ * If you're going to call this function, you must do so before any locks are
+ * allocated.
+ **/
+EVENT2_EXPORT_SYMBOL
+void evthread_enable_lock_debugging(void);
+
+/* Old (misspelled) version: This is deprecated; use
+ * evthread_enable_log_debugging instead. */
+EVENT2_EXPORT_SYMBOL
+void evthread_enable_lock_debuging(void);
+
+#endif /* EVENT__DISABLE_THREAD_SUPPORT */
+
+struct event_base;
+/** Make sure it's safe to tell an event base to wake up from another thread
+ or a signal handler.
+
+ You shouldn't need to call this by hand; configuring the base with thread
+ support should be necessary and sufficient.
+
+ @return 0 on success, -1 on failure.
+ */
+EVENT2_EXPORT_SYMBOL
+int evthread_make_base_notifiable(struct event_base *base);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT2_THREAD_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/util.h b/ipc/chromium/src/third_party/libevent/include/event2/util.h
new file mode 100644
index 0000000000..02aa7ba9da
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/util.h
@@ -0,0 +1,888 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_UTIL_H_INCLUDED_
+#define EVENT2_UTIL_H_INCLUDED_
+
+/** @file event2/util.h
+
+ Common convenience functions for cross-platform portability and
+ related socket manipulations.
+
+ */
+#include <event2/visibility.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <event2/event-config.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_STDINT_H
+#include <stdint.h>
+#elif defined(EVENT__HAVE_INTTYPES_H)
+#include <inttypes.h>
+#endif
+#ifdef EVENT__HAVE_SYS_TYPES_H
+#include <sys/types.h>
+#endif
+#ifdef EVENT__HAVE_STDDEF_H
+#include <stddef.h>
+#endif
+#ifdef _MSC_VER
+#include <BaseTsd.h>
+#endif
+#include <stdarg.h>
+#ifdef EVENT__HAVE_NETDB_H
+#include <netdb.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#ifdef EVENT__HAVE_GETADDRINFO
+/* for EAI_* definitions. */
+#include <ws2tcpip.h>
+#endif
+#else
+#ifdef EVENT__HAVE_ERRNO_H
+#include <errno.h>
+#endif
+#include <sys/socket.h>
+#endif
+
+#include <time.h>
+
+/* Some openbsd autoconf versions get the name of this macro wrong. */
+#if defined(EVENT__SIZEOF_VOID__) && !defined(EVENT__SIZEOF_VOID_P)
+#define EVENT__SIZEOF_VOID_P EVENT__SIZEOF_VOID__
+#endif
+
+/**
+ * @name Standard integer types.
+ *
+ * Integer type definitions for types that are supposed to be defined in the
+ * C99-specified stdint.h. Shamefully, some platforms do not include
+ * stdint.h, so we need to replace it. (If you are on a platform like this,
+ * your C headers are now over 10 years out of date. You should bug them to
+ * do something about this.)
+ *
+ * We define:
+ *
+ * <dl>
+ * <dt>ev_uint64_t, ev_uint32_t, ev_uint16_t, ev_uint8_t</dt>
+ * <dd>unsigned integer types of exactly 64, 32, 16, and 8 bits
+ * respectively.</dd>
+ * <dt>ev_int64_t, ev_int32_t, ev_int16_t, ev_int8_t</dt>
+ * <dd>signed integer types of exactly 64, 32, 16, and 8 bits
+ * respectively.</dd>
+ * <dt>ev_uintptr_t, ev_intptr_t</dt>
+ * <dd>unsigned/signed integers large enough
+ * to hold a pointer without loss of bits.</dd>
+ * <dt>ev_ssize_t</dt>
+ * <dd>A signed type of the same size as size_t</dd>
+ * <dt>ev_off_t</dt>
+ * <dd>A signed type typically used to represent offsets within a
+ * (potentially large) file</dd>
+ *
+ * @{
+ */
+#ifdef EVENT__HAVE_UINT64_T
+#define ev_uint64_t uint64_t
+#define ev_int64_t int64_t
+#elif defined(_WIN32)
+#define ev_uint64_t unsigned __int64
+#define ev_int64_t signed __int64
+#elif EVENT__SIZEOF_LONG_LONG == 8
+#define ev_uint64_t unsigned long long
+#define ev_int64_t long long
+#elif EVENT__SIZEOF_LONG == 8
+#define ev_uint64_t unsigned long
+#define ev_int64_t long
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_uint64_t ...
+#define ev_int64_t ...
+#else
+#error "No way to define ev_uint64_t"
+#endif
+
+#ifdef EVENT__HAVE_UINT32_T
+#define ev_uint32_t uint32_t
+#define ev_int32_t int32_t
+#elif defined(_WIN32)
+#define ev_uint32_t unsigned int
+#define ev_int32_t signed int
+#elif EVENT__SIZEOF_LONG == 4
+#define ev_uint32_t unsigned long
+#define ev_int32_t signed long
+#elif EVENT__SIZEOF_INT == 4
+#define ev_uint32_t unsigned int
+#define ev_int32_t signed int
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_uint32_t ...
+#define ev_int32_t ...
+#else
+#error "No way to define ev_uint32_t"
+#endif
+
+#ifdef EVENT__HAVE_UINT16_T
+#define ev_uint16_t uint16_t
+#define ev_int16_t int16_t
+#elif defined(_WIN32)
+#define ev_uint16_t unsigned short
+#define ev_int16_t signed short
+#elif EVENT__SIZEOF_INT == 2
+#define ev_uint16_t unsigned int
+#define ev_int16_t signed int
+#elif EVENT__SIZEOF_SHORT == 2
+#define ev_uint16_t unsigned short
+#define ev_int16_t signed short
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_uint16_t ...
+#define ev_int16_t ...
+#else
+#error "No way to define ev_uint16_t"
+#endif
+
+#ifdef EVENT__HAVE_UINT8_T
+#define ev_uint8_t uint8_t
+#define ev_int8_t int8_t
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_uint8_t ...
+#define ev_int8_t ...
+#else
+#define ev_uint8_t unsigned char
+#define ev_int8_t signed char
+#endif
+
+#ifdef EVENT__HAVE_UINTPTR_T
+#define ev_uintptr_t uintptr_t
+#define ev_intptr_t intptr_t
+#elif EVENT__SIZEOF_VOID_P <= 4
+#define ev_uintptr_t ev_uint32_t
+#define ev_intptr_t ev_int32_t
+#elif EVENT__SIZEOF_VOID_P <= 8
+#define ev_uintptr_t ev_uint64_t
+#define ev_intptr_t ev_int64_t
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_uintptr_t ...
+#define ev_intptr_t ...
+#else
+#error "No way to define ev_uintptr_t"
+#endif
+
+#ifdef EVENT__ssize_t
+#define ev_ssize_t EVENT__ssize_t
+#else
+#define ev_ssize_t ssize_t
+#endif
+
+/* Note that we define ev_off_t based on the compile-time size of off_t that
+ * we used to build Libevent, and not based on the current size of off_t.
+ * (For example, we don't define ev_off_t to off_t.). We do this because
+ * some systems let you build your software with different off_t sizes
+ * at runtime, and so putting in any dependency on off_t would risk API
+ * mismatch.
+ */
+#ifdef _WIN32
+#define ev_off_t ev_int64_t
+#elif EVENT__SIZEOF_OFF_T == 8
+#define ev_off_t ev_int64_t
+#elif EVENT__SIZEOF_OFF_T == 4
+#define ev_off_t ev_int32_t
+#elif defined(EVENT_IN_DOXYGEN_)
+#define ev_off_t ...
+#else
+#define ev_off_t off_t
+#endif
+/**@}*/
+
+/* Limits for integer types.
+
+ We're making two assumptions here:
+ - The compiler does constant folding properly.
+ - The platform does signed arithmetic in two's complement.
+*/
+
+/**
+ @name Limits for integer types
+
+ These macros hold the largest or smallest values possible for the
+ ev_[u]int*_t types.
+
+ @{
+*/
+#ifndef EVENT__HAVE_STDINT_H
+#define EV_UINT64_MAX ((((ev_uint64_t)0xffffffffUL) << 32) | 0xffffffffUL)
+#define EV_INT64_MAX ((((ev_int64_t) 0x7fffffffL) << 32) | 0xffffffffL)
+#define EV_INT64_MIN ((-EV_INT64_MAX) - 1)
+#define EV_UINT32_MAX ((ev_uint32_t)0xffffffffUL)
+#define EV_INT32_MAX ((ev_int32_t) 0x7fffffffL)
+#define EV_INT32_MIN ((-EV_INT32_MAX) - 1)
+#define EV_UINT16_MAX ((ev_uint16_t)0xffffUL)
+#define EV_INT16_MAX ((ev_int16_t) 0x7fffL)
+#define EV_INT16_MIN ((-EV_INT16_MAX) - 1)
+#define EV_UINT8_MAX 255
+#define EV_INT8_MAX 127
+#define EV_INT8_MIN ((-EV_INT8_MAX) - 1)
+#else
+#define EV_UINT64_MAX UINT64_MAX
+#define EV_INT64_MAX INT64_MAX
+#define EV_INT64_MIN INT64_MIN
+#define EV_UINT32_MAX UINT32_MAX
+#define EV_INT32_MAX INT32_MAX
+#define EV_INT32_MIN INT32_MIN
+#define EV_UINT16_MAX UINT16_MAX
+#define EV_INT16_MIN INT16_MIN
+#define EV_INT16_MAX INT16_MAX
+#define EV_UINT8_MAX UINT8_MAX
+#define EV_INT8_MAX INT8_MAX
+#define EV_INT8_MIN INT8_MIN
+/** @} */
+#endif
+
+
+/**
+ @name Limits for SIZE_T and SSIZE_T
+
+ @{
+*/
+#if EVENT__SIZEOF_SIZE_T == 8
+#define EV_SIZE_MAX EV_UINT64_MAX
+#define EV_SSIZE_MAX EV_INT64_MAX
+#elif EVENT__SIZEOF_SIZE_T == 4
+#define EV_SIZE_MAX EV_UINT32_MAX
+#define EV_SSIZE_MAX EV_INT32_MAX
+#elif defined(EVENT_IN_DOXYGEN_)
+#define EV_SIZE_MAX ...
+#define EV_SSIZE_MAX ...
+#else
+#error "No way to define SIZE_MAX"
+#endif
+
+#define EV_SSIZE_MIN ((-EV_SSIZE_MAX) - 1)
+/**@}*/
+
+#ifdef _WIN32
+#define ev_socklen_t int
+#elif defined(EVENT__socklen_t)
+#define ev_socklen_t EVENT__socklen_t
+#else
+#define ev_socklen_t socklen_t
+#endif
+
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
+#if !defined(EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY) \
+ && !defined(ss_family)
+#define ss_family __ss_family
+#endif
+#endif
+
+/**
+ * A type wide enough to hold the output of "socket()" or "accept()". On
+ * Windows, this is an intptr_t; elsewhere, it is an int. */
+#ifdef _WIN32
+#define evutil_socket_t intptr_t
+#else
+#define evutil_socket_t int
+#endif
+
+/**
+ * Structure to hold information about a monotonic timer
+ *
+ * Use this with evutil_configure_monotonic_time() and
+ * evutil_gettime_monotonic().
+ *
+ * This is an opaque structure; you can allocate one using
+ * evutil_monotonic_timer_new().
+ *
+ * @see evutil_monotonic_timer_new(), evutil_monotonic_timer_free(),
+ * evutil_configure_monotonic_time(), evutil_gettime_monotonic()
+ */
+struct evutil_monotonic_timer
+#ifdef EVENT_IN_DOXYGEN_
+{/*Empty body so that doxygen will generate documentation here.*/}
+#endif
+;
+
+#define EV_MONOT_PRECISE 1
+#define EV_MONOT_FALLBACK 2
+
+/** Format a date string using RFC 1123 format (used in HTTP).
+ * If `tm` is NULL, current system's time will be used.
+ * The number of characters written will be returned.
+ * One should check if the return value is smaller than `datelen` to check if
+ * the result is truncated or not.
+ */
+EVENT2_EXPORT_SYMBOL int
+evutil_date_rfc1123(char *date, const size_t datelen, const struct tm *tm);
+
+/** Allocate a new struct evutil_monotonic_timer for use with the
+ * evutil_configure_monotonic_time() and evutil_gettime_monotonic()
+ * functions. You must configure the timer with
+ * evutil_configure_monotonic_time() before using it.
+ */
+EVENT2_EXPORT_SYMBOL
+struct evutil_monotonic_timer * evutil_monotonic_timer_new(void);
+
+/** Free a struct evutil_monotonic_timer that was allocated using
+ * evutil_monotonic_timer_new().
+ */
+EVENT2_EXPORT_SYMBOL
+void evutil_monotonic_timer_free(struct evutil_monotonic_timer *timer);
+
+/** Set up a struct evutil_monotonic_timer; flags can include
+ * EV_MONOT_PRECISE and EV_MONOT_FALLBACK.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_configure_monotonic_time(struct evutil_monotonic_timer *timer,
+ int flags);
+
+/** Query the current monotonic time from a struct evutil_monotonic_timer
+ * previously configured with evutil_configure_monotonic_time(). Monotonic
+ * time is guaranteed never to run in reverse, but is not necessarily epoch-
+ * based, or relative to any other definite point. Use it to make reliable
+ * measurements of elapsed time between events even when the system time
+ * may be changed.
+ *
+ * It is not safe to use this funtion on the same timer from multiple
+ * threads.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_gettime_monotonic(struct evutil_monotonic_timer *timer,
+ struct timeval *tp);
+
+/** Create two new sockets that are connected to each other.
+
+ On Unix, this simply calls socketpair(). On Windows, it uses the
+ loopback network interface on 127.0.0.1, and only
+ AF_INET,SOCK_STREAM are supported.
+
+ (This may fail on some Windows hosts where firewall software has cleverly
+ decided to keep 127.0.0.1 from talking to itself.)
+
+ Parameters and return values are as for socketpair()
+*/
+EVENT2_EXPORT_SYMBOL
+int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
+/** Do platform-specific operations as needed to make a socket nonblocking.
+
+ @param sock The socket to make nonblocking
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_socket_nonblocking(evutil_socket_t sock);
+
+/** Do platform-specific operations to make a listener socket reusable.
+
+ Specifically, we want to make sure that another program will be able
+ to bind this address right after we've closed the listener.
+
+ This differs from Windows's interpretation of "reusable", which
+ allows multiple listeners to bind the same address at the same time.
+
+ @param sock The socket to make reusable
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_listen_socket_reuseable(evutil_socket_t sock);
+
+/** Do platform-specific operations to make a listener port reusable.
+
+ Specifically, we want to make sure that multiple programs which also
+ set the same socket option will be able to bind, listen at the same time.
+
+ This is a feature available only to Linux 3.9+
+
+ @param sock The socket to make reusable
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_listen_socket_reuseable_port(evutil_socket_t sock);
+
+/** Set ipv6 only bind socket option to make listener work only in ipv6 sockets.
+
+ According to RFC3493 and most Linux distributions, default value for the
+ sockets is to work in IPv4-mapped mode. In IPv4-mapped mode, it is not possible
+ to bind same port from different IPv4 and IPv6 handlers.
+
+ @param sock The socket to make in ipv6only working mode
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_listen_socket_ipv6only(evutil_socket_t sock);
+
+/** Do platform-specific operations as needed to close a socket upon a
+ successful execution of one of the exec*() functions.
+
+ @param sock The socket to be closed
+ @return 0 on success, -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_socket_closeonexec(evutil_socket_t sock);
+
+/** Do the platform-specific call needed to close a socket returned from
+ socket() or accept().
+
+ @param sock The socket to be closed
+ @return 0 on success (whether the operation is supported or not),
+ -1 on failure
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_closesocket(evutil_socket_t sock);
+#define EVUTIL_CLOSESOCKET(s) evutil_closesocket(s)
+
+/** Do platform-specific operations, if possible, to make a tcp listener
+ * socket defer accept()s until there is data to read.
+ *
+ * Not all platforms support this. You don't want to do this for every
+ * listener socket: only the ones that implement a protocol where the
+ * client transmits before the server needs to respond.
+ *
+ * @param sock The listening socket to to make deferred
+ * @return 0 on success (whether the operation is supported or not),
+ * -1 on failure
+*/
+EVENT2_EXPORT_SYMBOL
+int evutil_make_tcp_listen_socket_deferred(evutil_socket_t sock);
+
+#ifdef _WIN32
+/** Return the most recent socket error. Not idempotent on all platforms. */
+#define EVUTIL_SOCKET_ERROR() WSAGetLastError()
+/** Replace the most recent socket error with errcode */
+#define EVUTIL_SET_SOCKET_ERROR(errcode) \
+ do { WSASetLastError(errcode); } while (0)
+/** Return the most recent socket error to occur on sock. */
+EVENT2_EXPORT_SYMBOL
+int evutil_socket_geterror(evutil_socket_t sock);
+/** Convert a socket error to a string. */
+EVENT2_EXPORT_SYMBOL
+const char *evutil_socket_error_to_string(int errcode);
+#define EVUTIL_INVALID_SOCKET INVALID_SOCKET
+#elif defined(EVENT_IN_DOXYGEN_)
+/**
+ @name Socket error functions
+
+ These functions are needed for making programs compatible between
+ Windows and Unix-like platforms.
+
+ You see, Winsock handles socket errors differently from the rest of
+ the world. Elsewhere, a socket error is like any other error and is
+ stored in errno. But winsock functions require you to retrieve the
+ error with a special function, and don't let you use strerror for
+ the error codes. And handling EWOULDBLOCK is ... different.
+
+ @{
+*/
+/** Return the most recent socket error. Not idempotent on all platforms. */
+#define EVUTIL_SOCKET_ERROR() ...
+/** Replace the most recent socket error with errcode */
+#define EVUTIL_SET_SOCKET_ERROR(errcode) ...
+/** Return the most recent socket error to occur on sock. */
+#define evutil_socket_geterror(sock) ...
+/** Convert a socket error to a string. */
+#define evutil_socket_error_to_string(errcode) ...
+#define EVUTIL_INVALID_SOCKET -1
+/**@}*/
+#else /** !EVENT_IN_DOXYGEN_ && !_WIN32 */
+#define EVUTIL_SOCKET_ERROR() (errno)
+#define EVUTIL_SET_SOCKET_ERROR(errcode) \
+ do { errno = (errcode); } while (0)
+#define evutil_socket_geterror(sock) (errno)
+#define evutil_socket_error_to_string(errcode) (strerror(errcode))
+#define EVUTIL_INVALID_SOCKET -1
+#endif /** !_WIN32 */
+
+
+/**
+ * @name Manipulation macros for struct timeval.
+ *
+ * We define replacements
+ * for timeradd, timersub, timerclear, timercmp, and timerisset.
+ *
+ * @{
+ */
+#ifdef EVENT__HAVE_TIMERADD
+#define evutil_timeradd(tvp, uvp, vvp) timeradd((tvp), (uvp), (vvp))
+#define evutil_timersub(tvp, uvp, vvp) timersub((tvp), (uvp), (vvp))
+#else
+#define evutil_timeradd(tvp, uvp, vvp) \
+ do { \
+ (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec; \
+ (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec; \
+ if ((vvp)->tv_usec >= 1000000) { \
+ (vvp)->tv_sec++; \
+ (vvp)->tv_usec -= 1000000; \
+ } \
+ } while (0)
+#define evutil_timersub(tvp, uvp, vvp) \
+ do { \
+ (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec; \
+ (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec; \
+ if ((vvp)->tv_usec < 0) { \
+ (vvp)->tv_sec--; \
+ (vvp)->tv_usec += 1000000; \
+ } \
+ } while (0)
+#endif /* !EVENT__HAVE_TIMERADD */
+
+#ifdef EVENT__HAVE_TIMERCLEAR
+#define evutil_timerclear(tvp) timerclear(tvp)
+#else
+#define evutil_timerclear(tvp) (tvp)->tv_sec = (tvp)->tv_usec = 0
+#endif
+/**@}*/
+
+/** Return true iff the tvp is related to uvp according to the relational
+ * operator cmp. Recognized values for cmp are ==, <=, <, >=, and >. */
+#define evutil_timercmp(tvp, uvp, cmp) \
+ (((tvp)->tv_sec == (uvp)->tv_sec) ? \
+ ((tvp)->tv_usec cmp (uvp)->tv_usec) : \
+ ((tvp)->tv_sec cmp (uvp)->tv_sec))
+
+#ifdef EVENT__HAVE_TIMERISSET
+#define evutil_timerisset(tvp) timerisset(tvp)
+#else
+#define evutil_timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec)
+#endif
+
+/** Replacement for offsetof on platforms that don't define it. */
+#ifdef offsetof
+#define evutil_offsetof(type, field) offsetof(type, field)
+#else
+#define evutil_offsetof(type, field) ((off_t)(&((type *)0)->field))
+#endif
+
+/* big-int related functions */
+/** Parse a 64-bit value from a string. Arguments are as for strtol. */
+EVENT2_EXPORT_SYMBOL
+ev_int64_t evutil_strtoll(const char *s, char **endptr, int base);
+
+/** Replacement for gettimeofday on platforms that lack it. */
+#ifdef EVENT__HAVE_GETTIMEOFDAY
+#define evutil_gettimeofday(tv, tz) gettimeofday((tv), (tz))
+#else
+struct timezone;
+EVENT2_EXPORT_SYMBOL
+int evutil_gettimeofday(struct timeval *tv, struct timezone *tz);
+#endif
+
+/** Replacement for snprintf to get consistent behavior on platforms for
+ which the return value of snprintf does not conform to C99.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_snprintf(char *buf, size_t buflen, const char *format, ...)
+#ifdef __GNUC__
+ __attribute__((format(printf, 3, 4)))
+#endif
+;
+/** Replacement for vsnprintf to get consistent behavior on platforms for
+ which the return value of snprintf does not conform to C99.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_vsnprintf(char *buf, size_t buflen, const char *format, va_list ap)
+#ifdef __GNUC__
+ __attribute__((format(printf, 3, 0)))
+#endif
+;
+
+/** Replacement for inet_ntop for platforms which lack it. */
+EVENT2_EXPORT_SYMBOL
+const char *evutil_inet_ntop(int af, const void *src, char *dst, size_t len);
+/** Variation of inet_pton that also parses IPv6 scopes. Public for
+ unit tests. No reason to call this directly.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_inet_pton_scope(int af, const char *src, void *dst,
+ unsigned *indexp);
+/** Replacement for inet_pton for platforms which lack it. */
+EVENT2_EXPORT_SYMBOL
+int evutil_inet_pton(int af, const char *src, void *dst);
+struct sockaddr;
+
+/** Parse an IPv4 or IPv6 address, with optional port, from a string.
+
+ Recognized formats are:
+ - [IPv6Address]:port
+ - [IPv6Address]
+ - IPv6Address
+ - IPv4Address:port
+ - IPv4Address
+
+ If no port is specified, the port in the output is set to 0.
+
+ @param str The string to parse.
+ @param out A struct sockaddr to hold the result. This should probably be
+ a struct sockaddr_storage.
+ @param outlen A pointer to the number of bytes that that 'out' can safely
+ hold. Set to the number of bytes used in 'out' on success.
+ @return -1 if the address is not well-formed, if the port is out of range,
+ or if out is not large enough to hold the result. Otherwise returns
+ 0 on success.
+*/
+EVENT2_EXPORT_SYMBOL
+int evutil_parse_sockaddr_port(const char *str, struct sockaddr *out, int *outlen);
+
+/** Compare two sockaddrs; return 0 if they are equal, or less than 0 if sa1
+ * preceeds sa2, or greater than 0 if sa1 follows sa2. If include_port is
+ * true, consider the port as well as the address. Only implemented for
+ * AF_INET and AF_INET6 addresses. The ordering is not guaranteed to remain
+ * the same between Libevent versions. */
+EVENT2_EXPORT_SYMBOL
+int evutil_sockaddr_cmp(const struct sockaddr *sa1, const struct sockaddr *sa2,
+ int include_port);
+
+/** As strcasecmp, but always compares the characters in locale-independent
+ ASCII. That's useful if you're handling data in ASCII-based protocols.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_ascii_strcasecmp(const char *str1, const char *str2);
+/** As strncasecmp, but always compares the characters in locale-independent
+ ASCII. That's useful if you're handling data in ASCII-based protocols.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_ascii_strncasecmp(const char *str1, const char *str2, size_t n);
+
+/* Here we define evutil_addrinfo to the native addrinfo type, or redefine it
+ * if this system has no getaddrinfo(). */
+#ifdef EVENT__HAVE_STRUCT_ADDRINFO
+#define evutil_addrinfo addrinfo
+#else
+/** A definition of struct addrinfo for systems that lack it.
+
+ (This is just an alias for struct addrinfo if the system defines
+ struct addrinfo.)
+*/
+struct evutil_addrinfo {
+ int ai_flags; /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
+ int ai_family; /* PF_xxx */
+ int ai_socktype; /* SOCK_xxx */
+ int ai_protocol; /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
+ size_t ai_addrlen; /* length of ai_addr */
+ char *ai_canonname; /* canonical name for nodename */
+ struct sockaddr *ai_addr; /* binary address */
+ struct evutil_addrinfo *ai_next; /* next structure in linked list */
+};
+#endif
+/** @name evutil_getaddrinfo() error codes
+
+ These values are possible error codes for evutil_getaddrinfo() and
+ related functions.
+
+ @{
+*/
+#if defined(EAI_ADDRFAMILY) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_ADDRFAMILY EAI_ADDRFAMILY
+#else
+#define EVUTIL_EAI_ADDRFAMILY -901
+#endif
+#if defined(EAI_AGAIN) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_AGAIN EAI_AGAIN
+#else
+#define EVUTIL_EAI_AGAIN -902
+#endif
+#if defined(EAI_BADFLAGS) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_BADFLAGS EAI_BADFLAGS
+#else
+#define EVUTIL_EAI_BADFLAGS -903
+#endif
+#if defined(EAI_FAIL) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_FAIL EAI_FAIL
+#else
+#define EVUTIL_EAI_FAIL -904
+#endif
+#if defined(EAI_FAMILY) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_FAMILY EAI_FAMILY
+#else
+#define EVUTIL_EAI_FAMILY -905
+#endif
+#if defined(EAI_MEMORY) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_MEMORY EAI_MEMORY
+#else
+#define EVUTIL_EAI_MEMORY -906
+#endif
+/* This test is a bit complicated, since some MS SDKs decide to
+ * remove NODATA or redefine it to be the same as NONAME, in a
+ * fun interpretation of RFC 2553 and RFC 3493. */
+#if defined(EAI_NODATA) && defined(EVENT__HAVE_GETADDRINFO) && (!defined(EAI_NONAME) || EAI_NODATA != EAI_NONAME)
+#define EVUTIL_EAI_NODATA EAI_NODATA
+#else
+#define EVUTIL_EAI_NODATA -907
+#endif
+#if defined(EAI_NONAME) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_NONAME EAI_NONAME
+#else
+#define EVUTIL_EAI_NONAME -908
+#endif
+#if defined(EAI_SERVICE) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_SERVICE EAI_SERVICE
+#else
+#define EVUTIL_EAI_SERVICE -909
+#endif
+#if defined(EAI_SOCKTYPE) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_SOCKTYPE EAI_SOCKTYPE
+#else
+#define EVUTIL_EAI_SOCKTYPE -910
+#endif
+#if defined(EAI_SYSTEM) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_EAI_SYSTEM EAI_SYSTEM
+#else
+#define EVUTIL_EAI_SYSTEM -911
+#endif
+
+#define EVUTIL_EAI_CANCEL -90001
+
+#if defined(AI_PASSIVE) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_PASSIVE AI_PASSIVE
+#else
+#define EVUTIL_AI_PASSIVE 0x1000
+#endif
+#if defined(AI_CANONNAME) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_CANONNAME AI_CANONNAME
+#else
+#define EVUTIL_AI_CANONNAME 0x2000
+#endif
+#if defined(AI_NUMERICHOST) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_NUMERICHOST AI_NUMERICHOST
+#else
+#define EVUTIL_AI_NUMERICHOST 0x4000
+#endif
+#if defined(AI_NUMERICSERV) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_NUMERICSERV AI_NUMERICSERV
+#else
+#define EVUTIL_AI_NUMERICSERV 0x8000
+#endif
+#if defined(AI_V4MAPPED) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_V4MAPPED AI_V4MAPPED
+#else
+#define EVUTIL_AI_V4MAPPED 0x10000
+#endif
+#if defined(AI_ALL) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_ALL AI_ALL
+#else
+#define EVUTIL_AI_ALL 0x20000
+#endif
+#if defined(AI_ADDRCONFIG) && defined(EVENT__HAVE_GETADDRINFO)
+#define EVUTIL_AI_ADDRCONFIG AI_ADDRCONFIG
+#else
+#define EVUTIL_AI_ADDRCONFIG 0x40000
+#endif
+/**@}*/
+
+struct evutil_addrinfo;
+/**
+ * This function clones getaddrinfo for systems that don't have it. For full
+ * details, see RFC 3493, section 6.1.
+ *
+ * Limitations:
+ * - When the system has no getaddrinfo, we fall back to gethostbyname_r or
+ * gethostbyname, with their attendant issues.
+ * - The AI_V4MAPPED and AI_ALL flags are not currently implemented.
+ *
+ * For a nonblocking variant, see evdns_getaddrinfo.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_getaddrinfo(const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in, struct evutil_addrinfo **res);
+
+/** Release storage allocated by evutil_getaddrinfo or evdns_getaddrinfo. */
+EVENT2_EXPORT_SYMBOL
+void evutil_freeaddrinfo(struct evutil_addrinfo *ai);
+
+EVENT2_EXPORT_SYMBOL
+const char *evutil_gai_strerror(int err);
+
+/** Generate n bytes of secure pseudorandom data, and store them in buf.
+ *
+ * Current versions of Libevent use an ARC4-based random number generator,
+ * seeded using the platform's entropy source (/dev/urandom on Unix-like
+ * systems; CryptGenRandom on Windows). This is not actually as secure as it
+ * should be: ARC4 is a pretty lousy cipher, and the current implementation
+ * provides only rudimentary prediction- and backtracking-resistance. Don't
+ * use this for serious cryptographic applications.
+ */
+EVENT2_EXPORT_SYMBOL
+void evutil_secure_rng_get_bytes(void *buf, size_t n);
+
+/**
+ * Seed the secure random number generator if needed, and return 0 on
+ * success or -1 on failure.
+ *
+ * It is okay to call this function more than once; it will still return
+ * 0 if the RNG has been successfully seeded and -1 if it can't be
+ * seeded.
+ *
+ * Ordinarily you don't need to call this function from your own code;
+ * Libevent will seed the RNG itself the first time it needs good random
+ * numbers. You only need to call it if (a) you want to double-check
+ * that one of the seeding methods did succeed, or (b) you plan to drop
+ * the capability to seed (by chrooting, or dropping capabilities, or
+ * whatever), and you want to make sure that seeding happens before your
+ * program loses the ability to do it.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_secure_rng_init(void);
+
+/**
+ * Set a filename to use in place of /dev/urandom for seeding the secure
+ * PRNG. Return 0 on success, -1 on failure.
+ *
+ * Call this function BEFORE calling any other initialization or RNG
+ * functions.
+ *
+ * (This string will _NOT_ be copied internally. Do not free it while any
+ * user of the secure RNG might be running. Don't pass anything other than a
+ * real /dev/...random device file here, or you might lose security.)
+ *
+ * This API is unstable, and might change in a future libevent version.
+ */
+EVENT2_EXPORT_SYMBOL
+int evutil_secure_rng_set_urandom_device_file(char *fname);
+
+#if !defined(EVENT__HAVE_ARC4RANDOM) || defined(EVENT__HAVE_ARC4RANDOM_ADDRANDOM)
+/** Seed the random number generator with extra random bytes.
+
+ You should almost never need to call this function; it should be
+ sufficient to invoke evutil_secure_rng_init(), or let Libevent take
+ care of calling evutil_secure_rng_init() on its own.
+
+ If you call this function as a _replacement_ for the regular
+ entropy sources, then you need to be sure that your input
+ contains a fairly large amount of strong entropy. Doing so is
+ notoriously hard: most people who try get it wrong. Watch out!
+
+ @param dat a buffer full of a strong source of random numbers
+ @param datlen the number of bytes to read from datlen
+ */
+EVENT2_EXPORT_SYMBOL
+void evutil_secure_rng_add_bytes(const char *dat, size_t datlen);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/event2/visibility.h b/ipc/chromium/src/third_party/libevent/include/event2/visibility.h
new file mode 100644
index 0000000000..006bbf06d8
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/event2/visibility.h
@@ -0,0 +1,67 @@
+/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT2_VISIBILITY_H_INCLUDED_
+#define EVENT2_VISIBILITY_H_INCLUDED_
+
+#include <event2/event-config.h>
+
+#if defined(event_shared_EXPORTS) || \
+ defined(event_extra_shared_EXPORTS) || \
+ defined(event_core_shared_EXPORTS) || \
+ defined(event_pthreads_shared_EXPORTS) || \
+ defined(event_openssl_shared_EXPORTS)
+
+# if defined (__SUNPRO_C) && (__SUNPRO_C >= 0x550)
+# define EVENT2_EXPORT_SYMBOL __global
+# elif defined __GNUC__
+# define EVENT2_EXPORT_SYMBOL __attribute__ ((visibility("default")))
+# elif defined(_MSC_VER)
+# define EVENT2_EXPORT_SYMBOL __declspec(dllexport)
+# else
+# define EVENT2_EXPORT_SYMBOL /* unknown compiler */
+# endif
+
+#else /* event_*_EXPORTS */
+
+# define EVENT2_EXPORT_SYMBOL
+
+#endif /* event_*_EXPORTS */
+
+/** We need to dllimport event_debug_logging_mask_ into event_extra */
+#if defined(_MSC_VER)
+# if defined(event_core_shared_EXPORTS) /** from core export */
+# define EVENT2_CORE_EXPORT_SYMBOL __declspec(dllexport)
+# elif defined(event_extra_shared_EXPORTS) || /** from extra import */ \
+ defined(EVENT_VISIBILITY_WANT_DLLIMPORT)
+# define EVENT2_CORE_EXPORT_SYMBOL __declspec(dllimport)
+# endif
+#endif /* _MSC_VER */
+#if !defined(EVENT2_CORE_EXPORT_SYMBOL)
+# define EVENT2_CORE_EXPORT_SYMBOL EVENT2_EXPORT_SYMBOL
+#endif
+
+#endif /* EVENT2_VISIBILITY_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/evhttp.h b/ipc/chromium/src/third_party/libevent/include/evhttp.h
new file mode 100644
index 0000000000..549bc9b14a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/evhttp.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT1_EVHTTP_H_INCLUDED_
+#define EVENT1_EVHTTP_H_INCLUDED_
+
+/** @file evhttp.h
+
+ An http implementation subsystem for Libevent.
+
+ The <evhttp.h> header is deprecated in Libevent 2.0 and later; please
+ use <event2/http.h> instead. Depending on what functionality you
+ need, you may also want to include more of the other <event2/...>
+ headers.
+ */
+
+#include <event.h>
+#include <event2/http.h>
+#include <event2/http_struct.h>
+#include <event2/http_compat.h>
+
+#endif /* EVENT1_EVHTTP_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/evrpc.h b/ipc/chromium/src/third_party/libevent/include/evrpc.h
new file mode 100644
index 0000000000..7e986f7dab
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/evrpc.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT1_EVRPC_H_INCLUDED_
+#define EVENT1_EVRPC_H_INCLUDED_
+
+/** @file evrpc.h
+
+ An RPC system for Libevent.
+
+ The <evrpc.h> header is deprecated in Libevent 2.0 and later; please
+ use <event2/rpc.h> instead. Depending on what functionality you
+ need, you may also want to include more of the other <event2/...>
+ headers.
+ */
+
+#include <event.h>
+#include <event2/rpc.h>
+#include <event2/rpc_struct.h>
+#include <event2/rpc_compat.h>
+
+#endif /* EVENT1_EVRPC_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/evutil.h b/ipc/chromium/src/third_party/libevent/include/evutil.h
new file mode 100644
index 0000000000..12c137d745
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/evutil.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef EVENT1_EVUTIL_H_INCLUDED_
+#define EVENT1_EVUTIL_H_INCLUDED_
+
+/** @file evutil.h
+
+ Utility and compatibility functions for Libevent.
+
+ The <evutil.h> header is deprecated in Libevent 2.0 and later; please
+ use <event2/util.h> instead.
+*/
+
+#include <event2/util.h>
+
+#endif /* EVENT1_EVUTIL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/include/include.am b/ipc/chromium/src/third_party/libevent/include/include.am
new file mode 100644
index 0000000000..aaa2042af1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/include/include.am
@@ -0,0 +1,49 @@
+# include/include.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+include_event2dir = $(includedir)/event2
+
+EVENT2_EXPORT = \
+ include/event2/buffer.h \
+ include/event2/buffer_compat.h \
+ include/event2/bufferevent.h \
+ include/event2/bufferevent_compat.h \
+ include/event2/bufferevent_struct.h \
+ include/event2/dns.h \
+ include/event2/dns_compat.h \
+ include/event2/dns_struct.h \
+ include/event2/event.h \
+ include/event2/event_compat.h \
+ include/event2/event_struct.h \
+ include/event2/http.h \
+ include/event2/http_compat.h \
+ include/event2/http_struct.h \
+ include/event2/keyvalq_struct.h \
+ include/event2/listener.h \
+ include/event2/rpc.h \
+ include/event2/rpc_compat.h \
+ include/event2/rpc_struct.h \
+ include/event2/tag.h \
+ include/event2/tag_compat.h \
+ include/event2/thread.h \
+ include/event2/util.h \
+ include/event2/visibility.h
+
+if OPENSSL
+EVENT2_EXPORT += include/event2/bufferevent_ssl.h
+endif
+
+## Without the nobase_ prefixing, Automake would strip "include/event2/" from
+## the source header filename to derive the installed header filename.
+## With nobase_ the installed path is $(includedir)/include/event2/ev*.h.
+
+if INSTALL_LIBEVENT
+include_event2_HEADERS = $(EVENT2_EXPORT)
+nodist_include_event2_HEADERS = include/event2/event-config.h
+else
+noinst_HEADERS += $(EVENT2_EXPORT)
+nodist_noinst_HEADERS = include/event2/event-config.h
+endif
diff --git a/ipc/chromium/src/third_party/libevent/iocp-internal.h b/ipc/chromium/src/third_party/libevent/iocp-internal.h
new file mode 100644
index 0000000000..21e0e0af68
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/iocp-internal.h
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef IOCP_INTERNAL_H_INCLUDED_
+#define IOCP_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct event_overlapped;
+struct event_iocp_port;
+struct evbuffer;
+typedef void (*iocp_callback)(struct event_overlapped *, ev_uintptr_t, ev_ssize_t, int success);
+
+/* This whole file is actually win32 only. We wrap the structures in a win32
+ * ifdef so that we can test-compile code that uses these interfaces on
+ * non-win32 platforms. */
+#ifdef _WIN32
+
+/**
+ Internal use only. Wraps an OVERLAPPED that we're using for libevent
+ functionality. Whenever an event_iocp_port gets an event for a given
+ OVERLAPPED*, it upcasts the pointer to an event_overlapped, and calls the
+ iocp_callback function with the event_overlapped, the iocp key, and the
+ number of bytes transferred as arguments.
+ */
+struct event_overlapped {
+ OVERLAPPED overlapped;
+ iocp_callback cb;
+};
+
+/* Mingw's headers don't define LPFN_ACCEPTEX. */
+
+typedef BOOL (WINAPI *AcceptExPtr)(SOCKET, SOCKET, PVOID, DWORD, DWORD, DWORD, LPDWORD, LPOVERLAPPED);
+typedef BOOL (WINAPI *ConnectExPtr)(SOCKET, const struct sockaddr *, int, PVOID, DWORD, LPDWORD, LPOVERLAPPED);
+typedef void (WINAPI *GetAcceptExSockaddrsPtr)(PVOID, DWORD, DWORD, DWORD, LPSOCKADDR *, LPINT, LPSOCKADDR *, LPINT);
+
+/** Internal use only. Holds pointers to functions that only some versions of
+ Windows provide.
+ */
+struct win32_extension_fns {
+ AcceptExPtr AcceptEx;
+ ConnectExPtr ConnectEx;
+ GetAcceptExSockaddrsPtr GetAcceptExSockaddrs;
+};
+
+/**
+ Internal use only. Stores a Windows IO Completion port, along with
+ related data.
+ */
+struct event_iocp_port {
+ /** The port itself */
+ HANDLE port;
+ /* A lock to cover internal structures. */
+ CRITICAL_SECTION lock;
+ /** Number of threads ever open on the port. */
+ short n_threads;
+ /** True iff we're shutting down all the threads on this port */
+ short shutdown;
+ /** How often the threads on this port check for shutdown and other
+ * conditions */
+ long ms;
+ /* The threads that are waiting for events. */
+ HANDLE *threads;
+ /** Number of threads currently open on this port. */
+ short n_live_threads;
+ /** A semaphore to signal when we are done shutting down. */
+ HANDLE *shutdownSemaphore;
+};
+
+EVENT2_EXPORT_SYMBOL
+const struct win32_extension_fns *event_get_win32_extension_fns_(void);
+#else
+/* Dummy definition so we can test-compile more things on unix. */
+struct event_overlapped {
+ iocp_callback cb;
+};
+#endif
+
+/** Initialize the fields in an event_overlapped.
+
+ @param overlapped The struct event_overlapped to initialize
+ @param cb The callback that should be invoked once the IO operation has
+ finished.
+ */
+EVENT2_EXPORT_SYMBOL
+void event_overlapped_init_(struct event_overlapped *, iocp_callback cb);
+
+/** Allocate and return a new evbuffer that supports overlapped IO on a given
+ socket. The socket must be associated with an IO completion port using
+ event_iocp_port_associate_.
+*/
+EVENT2_EXPORT_SYMBOL
+struct evbuffer *evbuffer_overlapped_new_(evutil_socket_t fd);
+
+/** XXXX Document (nickm) */
+evutil_socket_t evbuffer_overlapped_get_fd_(struct evbuffer *buf);
+
+void evbuffer_overlapped_set_fd_(struct evbuffer *buf, evutil_socket_t fd);
+
+/** Start reading data onto the end of an overlapped evbuffer.
+
+ An evbuffer can only have one read pending at a time. While the read
+ is in progress, no other data may be added to the end of the buffer.
+ The buffer must be created with event_overlapped_init_().
+ evbuffer_commit_read_() must be called in the completion callback.
+
+ @param buf The buffer to read onto
+ @param n The number of bytes to try to read.
+ @param ol Overlapped object with associated completion callback.
+ @return 0 on success, -1 on error.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_launch_read_(struct evbuffer *buf, size_t n, struct event_overlapped *ol);
+
+/** Start writing data from the start of an evbuffer.
+
+ An evbuffer can only have one write pending at a time. While the write is
+ in progress, no other data may be removed from the front of the buffer.
+ The buffer must be created with event_overlapped_init_().
+ evbuffer_commit_write_() must be called in the completion callback.
+
+ @param buf The buffer to read onto
+ @param n The number of bytes to try to read.
+ @param ol Overlapped object with associated completion callback.
+ @return 0 on success, -1 on error.
+ */
+EVENT2_EXPORT_SYMBOL
+int evbuffer_launch_write_(struct evbuffer *buf, ev_ssize_t n, struct event_overlapped *ol);
+
+/** XXX document */
+EVENT2_EXPORT_SYMBOL
+void evbuffer_commit_read_(struct evbuffer *, ev_ssize_t);
+EVENT2_EXPORT_SYMBOL
+void evbuffer_commit_write_(struct evbuffer *, ev_ssize_t);
+
+/** Create an IOCP, and launch its worker threads. Internal use only.
+
+ This interface is unstable, and will change.
+ */
+EVENT2_EXPORT_SYMBOL
+struct event_iocp_port *event_iocp_port_launch_(int n_cpus);
+
+/** Associate a file descriptor with an iocp, such that overlapped IO on the
+ fd will happen on one of the iocp's worker threads.
+*/
+EVENT2_EXPORT_SYMBOL
+int event_iocp_port_associate_(struct event_iocp_port *port, evutil_socket_t fd,
+ ev_uintptr_t key);
+
+/** Tell all threads serving an iocp to stop. Wait for up to waitMsec for all
+ the threads to finish whatever they're doing. If waitMsec is -1, wait
+ as long as required. If all the threads are done, free the port and return
+ 0. Otherwise, return -1. If you get a -1 return value, it is safe to call
+ this function again.
+*/
+EVENT2_EXPORT_SYMBOL
+int event_iocp_shutdown_(struct event_iocp_port *port, long waitMsec);
+
+/* FIXME document. */
+EVENT2_EXPORT_SYMBOL
+int event_iocp_activate_overlapped_(struct event_iocp_port *port,
+ struct event_overlapped *o,
+ ev_uintptr_t key, ev_uint32_t n_bytes);
+
+struct event_base;
+/* FIXME document. */
+EVENT2_EXPORT_SYMBOL
+struct event_iocp_port *event_base_get_iocp_(struct event_base *base);
+
+/* FIXME document. */
+EVENT2_EXPORT_SYMBOL
+int event_base_start_iocp_(struct event_base *base, int n_cpus);
+void event_base_stop_iocp_(struct event_base *base);
+
+/* FIXME document. */
+EVENT2_EXPORT_SYMBOL
+struct bufferevent *bufferevent_async_new_(struct event_base *base,
+ evutil_socket_t fd, int options);
+
+/* FIXME document. */
+void bufferevent_async_set_connected_(struct bufferevent *bev);
+int bufferevent_async_can_connect_(struct bufferevent *bev);
+int bufferevent_async_connect_(struct bufferevent *bev, evutil_socket_t fd,
+ const struct sockaddr *sa, int socklen);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/ipv6-internal.h b/ipc/chromium/src/third_party/libevent/ipv6-internal.h
new file mode 100644
index 0000000000..0c207377b8
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ipv6-internal.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* Internal use only: Fake IPv6 structures and values on platforms that
+ * do not have them */
+
+#ifndef IPV6_INTERNAL_H_INCLUDED_
+#define IPV6_INTERNAL_H_INCLUDED_
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include "event2/util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** @file ipv6-internal.h
+ *
+ * Replacement types and functions for platforms that don't support ipv6
+ * properly.
+ */
+
+#ifndef EVENT__HAVE_STRUCT_IN6_ADDR
+struct in6_addr {
+ ev_uint8_t s6_addr[16];
+};
+#endif
+
+#ifndef EVENT__HAVE_SA_FAMILY_T
+typedef int sa_family_t;
+#endif
+
+#ifndef EVENT__HAVE_STRUCT_SOCKADDR_IN6
+struct sockaddr_in6 {
+ /* This will fail if we find a struct sockaddr that doesn't have
+ * sa_family as the first element. */
+ sa_family_t sin6_family;
+ ev_uint16_t sin6_port;
+ struct in6_addr sin6_addr;
+};
+#endif
+
+#ifndef AF_INET6
+#define AF_INET6 3333
+#endif
+#ifndef PF_INET6
+#define PF_INET6 AF_INET6
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/kqueue-internal.h b/ipc/chromium/src/third_party/libevent/kqueue-internal.h
new file mode 100644
index 0000000000..02c5a3606c
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/kqueue-internal.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef KQUEUE_INTERNAL_H_INCLUDED_
+#define KQUEUE_INTERNAL_H_INCLUDED_
+
+/** Notification function, used to tell an event base to wake up from another
+ * thread. Only works when event_kq_add_notify_event_() has previously been
+ * called successfully on that base. */
+int event_kq_notify_base_(struct event_base *base);
+
+/** Prepare a kqueue-using event base to receive notifications via an internal
+ * EVFILT_USER event. Return 0 on sucess, -1 on failure.
+ */
+int event_kq_add_notify_event_(struct event_base *base);
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/kqueue.c b/ipc/chromium/src/third_party/libevent/kqueue.c
new file mode 100644
index 0000000000..dfd7751d64
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/kqueue.c
@@ -0,0 +1,580 @@
+/* $OpenBSD: kqueue.c,v 1.5 2002/07/10 14:41:31 art Exp $ */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_KQUEUE
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <sys/event.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+#ifdef EVENT__HAVE_INTTYPES_H
+#include <inttypes.h>
+#endif
+
+/* Some platforms apparently define the udata field of struct kevent as
+ * intptr_t, whereas others define it as void*. There doesn't seem to be an
+ * easy way to tell them apart via autoconf, so we need to use OS macros. */
+#if defined(__NetBSD__)
+#define PTR_TO_UDATA(x) ((typeof(((struct kevent *)0)->udata))(x))
+#define INT_TO_UDATA(x) ((typeof(((struct kevent *)0)->udata))(intptr_t)(x))
+#elif defined(EVENT__HAVE_INTTYPES_H) && !defined(__OpenBSD__) && !defined(__FreeBSD__) && !defined(__darwin__) && !defined(__APPLE__) && !defined(__CloudABI__)
+#define PTR_TO_UDATA(x) ((intptr_t)(x))
+#define INT_TO_UDATA(x) ((intptr_t)(x))
+#else
+#define PTR_TO_UDATA(x) (x)
+#define INT_TO_UDATA(x) ((void*)(x))
+#endif
+
+#include "event-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "event2/util.h"
+#include "evthread-internal.h"
+#include "changelist-internal.h"
+
+#include "kqueue-internal.h"
+
+#define NEVENT 64
+
+struct kqop {
+ struct kevent *changes;
+ int changes_size;
+
+ struct kevent *events;
+ int events_size;
+ int kq;
+ int notify_event_added;
+ pid_t pid;
+};
+
+static void kqop_free(struct kqop *kqop);
+
+static void *kq_init(struct event_base *);
+static int kq_sig_add(struct event_base *, int, short, short, void *);
+static int kq_sig_del(struct event_base *, int, short, short, void *);
+static int kq_dispatch(struct event_base *, struct timeval *);
+static void kq_dealloc(struct event_base *);
+
+const struct eventop kqops = {
+ "kqueue",
+ kq_init,
+ event_changelist_add_,
+ event_changelist_del_,
+ kq_dispatch,
+ kq_dealloc,
+ 1 /* need reinit */,
+ EV_FEATURE_ET|EV_FEATURE_O1|EV_FEATURE_FDS,
+ EVENT_CHANGELIST_FDINFO_SIZE
+};
+
+static const struct eventop kqsigops = {
+ "kqueue_signal",
+ NULL,
+ kq_sig_add,
+ kq_sig_del,
+ NULL,
+ NULL,
+ 1 /* need reinit */,
+ 0,
+ 0
+};
+
+static void *
+kq_init(struct event_base *base)
+{
+ int kq = -1;
+ struct kqop *kqueueop = NULL;
+
+ if (!(kqueueop = mm_calloc(1, sizeof(struct kqop))))
+ return (NULL);
+
+/* Initialize the kernel queue */
+
+ if ((kq = kqueue()) == -1) {
+ event_warn("kqueue");
+ goto err;
+ }
+
+ kqueueop->kq = kq;
+
+ kqueueop->pid = getpid();
+
+ /* Initialize fields */
+ kqueueop->changes = mm_calloc(NEVENT, sizeof(struct kevent));
+ if (kqueueop->changes == NULL)
+ goto err;
+ kqueueop->events = mm_calloc(NEVENT, sizeof(struct kevent));
+ if (kqueueop->events == NULL)
+ goto err;
+ kqueueop->events_size = kqueueop->changes_size = NEVENT;
+
+ /* Check for Mac OS X kqueue bug. */
+ memset(&kqueueop->changes[0], 0, sizeof kqueueop->changes[0]);
+ kqueueop->changes[0].ident = -1;
+ kqueueop->changes[0].filter = EVFILT_READ;
+ kqueueop->changes[0].flags = EV_ADD;
+ /*
+ * If kqueue works, then kevent will succeed, and it will
+ * stick an error in events[0]. If kqueue is broken, then
+ * kevent will fail.
+ */
+ if (kevent(kq,
+ kqueueop->changes, 1, kqueueop->events, NEVENT, NULL) != 1 ||
+ (int)kqueueop->events[0].ident != -1 ||
+ !(kqueueop->events[0].flags & EV_ERROR)) {
+ event_warn("%s: detected broken kqueue; not using.", __func__);
+ goto err;
+ }
+
+ base->evsigsel = &kqsigops;
+
+ return (kqueueop);
+err:
+ if (kqueueop)
+ kqop_free(kqueueop);
+
+ return (NULL);
+}
+
+#define ADD_UDATA 0x30303
+
+static void
+kq_setup_kevent(struct kevent *out, evutil_socket_t fd, int filter, short change)
+{
+ memset(out, 0, sizeof(struct kevent));
+ out->ident = fd;
+ out->filter = filter;
+
+ if (change & EV_CHANGE_ADD) {
+ out->flags = EV_ADD;
+ /* We set a magic number here so that we can tell 'add'
+ * errors from 'del' errors. */
+ out->udata = INT_TO_UDATA(ADD_UDATA);
+ if (change & EV_ET)
+ out->flags |= EV_CLEAR;
+#ifdef NOTE_EOF
+ /* Make it behave like select() and poll() */
+ if (filter == EVFILT_READ)
+ out->fflags = NOTE_EOF;
+#endif
+ } else {
+ EVUTIL_ASSERT(change & EV_CHANGE_DEL);
+ out->flags = EV_DELETE;
+ }
+}
+
+static int
+kq_build_changes_list(const struct event_changelist *changelist,
+ struct kqop *kqop)
+{
+ int i;
+ int n_changes = 0;
+
+ for (i = 0; i < changelist->n_changes; ++i) {
+ struct event_change *in_ch = &changelist->changes[i];
+ struct kevent *out_ch;
+ if (n_changes >= kqop->changes_size - 1) {
+ int newsize;
+ struct kevent *newchanges;
+
+ if (kqop->changes_size > INT_MAX / 2 ||
+ (size_t)kqop->changes_size * 2 > EV_SIZE_MAX /
+ sizeof(struct kevent)) {
+ event_warnx("%s: int overflow", __func__);
+ return (-1);
+ }
+
+ newsize = kqop->changes_size * 2;
+ newchanges = mm_realloc(kqop->changes,
+ newsize * sizeof(struct kevent));
+ if (newchanges == NULL) {
+ event_warn("%s: realloc", __func__);
+ return (-1);
+ }
+ kqop->changes = newchanges;
+ kqop->changes_size = newsize;
+ }
+ if (in_ch->read_change) {
+ out_ch = &kqop->changes[n_changes++];
+ kq_setup_kevent(out_ch, in_ch->fd, EVFILT_READ,
+ in_ch->read_change);
+ }
+ if (in_ch->write_change) {
+ out_ch = &kqop->changes[n_changes++];
+ kq_setup_kevent(out_ch, in_ch->fd, EVFILT_WRITE,
+ in_ch->write_change);
+ }
+ }
+ return n_changes;
+}
+
+static int
+kq_grow_events(struct kqop *kqop, size_t new_size)
+{
+ struct kevent *newresult;
+
+ newresult = mm_realloc(kqop->events,
+ new_size * sizeof(struct kevent));
+
+ if (newresult) {
+ kqop->events = newresult;
+ kqop->events_size = new_size;
+ return 0;
+ } else {
+ return -1;
+ }
+}
+
+static int
+kq_dispatch(struct event_base *base, struct timeval *tv)
+{
+ struct kqop *kqop = base->evbase;
+ struct kevent *events = kqop->events;
+ struct kevent *changes;
+ struct timespec ts, *ts_p = NULL;
+ int i, n_changes, res;
+
+ if (tv != NULL) {
+ ts.tv_sec = tv->tv_sec;
+ ts.tv_nsec = tv->tv_usec * 1000;
+ ts_p = &ts;
+ }
+
+ /* Build "changes" from "base->changes" */
+ EVUTIL_ASSERT(kqop->changes);
+ n_changes = kq_build_changes_list(&base->changelist, kqop);
+ if (n_changes < 0)
+ return -1;
+
+ event_changelist_remove_all_(&base->changelist, base);
+
+ /* steal the changes array in case some broken code tries to call
+ * dispatch twice at once. */
+ changes = kqop->changes;
+ kqop->changes = NULL;
+
+ /* Make sure that 'events' is at least as long as the list of changes:
+ * otherwise errors in the changes can get reported as a -1 return
+ * value from kevent() rather than as EV_ERROR events in the events
+ * array.
+ *
+ * (We could instead handle -1 return values from kevent() by
+ * retrying with a smaller changes array or a larger events array,
+ * but this approach seems less risky for now.)
+ */
+ if (kqop->events_size < n_changes) {
+ int new_size = kqop->events_size;
+ do {
+ new_size *= 2;
+ } while (new_size < n_changes);
+
+ kq_grow_events(kqop, new_size);
+ events = kqop->events;
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = kevent(kqop->kq, changes, n_changes,
+ events, kqop->events_size, ts_p);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ EVUTIL_ASSERT(kqop->changes == NULL);
+ kqop->changes = changes;
+
+ if (res == -1) {
+ if (errno != EINTR) {
+ event_warn("kevent");
+ return (-1);
+ }
+
+ return (0);
+ }
+
+ event_debug(("%s: kevent reports %d", __func__, res));
+
+ for (i = 0; i < res; i++) {
+ int which = 0;
+
+ if (events[i].flags & EV_ERROR) {
+ switch (events[i].data) {
+
+ /* Can occur on delete if we are not currently
+ * watching any events on this fd. That can
+ * happen when the fd was closed and another
+ * file was opened with that fd. */
+ case ENOENT:
+ /* Can occur for reasons not fully understood
+ * on FreeBSD. */
+ case EINVAL:
+ continue;
+#if defined(__FreeBSD__)
+ /*
+ * This currently occurs if an FD is closed
+ * before the EV_DELETE makes it out via kevent().
+ * The FreeBSD capabilities code sees the blank
+ * capability set and rejects the request to
+ * modify an event.
+ *
+ * To be strictly correct - when an FD is closed,
+ * all the registered events are also removed.
+ * Queuing EV_DELETE to a closed FD is wrong.
+ * The event(s) should just be deleted from
+ * the pending changelist.
+ */
+ case ENOTCAPABLE:
+ continue;
+#endif
+
+ /* Can occur on a delete if the fd is closed. */
+ case EBADF:
+ /* XXXX On NetBSD, we can also get EBADF if we
+ * try to add the write side of a pipe, but
+ * the read side has already been closed.
+ * Other BSDs call this situation 'EPIPE'. It
+ * would be good if we had a way to report
+ * this situation. */
+ continue;
+ /* These two can occur on an add if the fd was one side
+ * of a pipe, and the other side was closed. */
+ case EPERM:
+ case EPIPE:
+ /* Report read events, if we're listening for
+ * them, so that the user can learn about any
+ * add errors. (If the operation was a
+ * delete, then udata should be cleared.) */
+ if (events[i].udata) {
+ /* The operation was an add:
+ * report the error as a read. */
+ which |= EV_READ;
+ break;
+ } else {
+ /* The operation was a del:
+ * report nothing. */
+ continue;
+ }
+
+ /* Other errors shouldn't occur. */
+ default:
+ errno = events[i].data;
+ return (-1);
+ }
+ } else if (events[i].filter == EVFILT_READ) {
+ which |= EV_READ;
+ } else if (events[i].filter == EVFILT_WRITE) {
+ which |= EV_WRITE;
+ } else if (events[i].filter == EVFILT_SIGNAL) {
+ which |= EV_SIGNAL;
+#ifdef EVFILT_USER
+ } else if (events[i].filter == EVFILT_USER) {
+ base->is_notify_pending = 0;
+#endif
+ }
+
+ if (!which)
+ continue;
+
+ if (events[i].filter == EVFILT_SIGNAL) {
+ evmap_signal_active_(base, events[i].ident, 1);
+ } else {
+ evmap_io_active_(base, events[i].ident, which | EV_ET);
+ }
+ }
+
+ if (res == kqop->events_size) {
+ /* We used all the events space that we have. Maybe we should
+ make it bigger. */
+ kq_grow_events(kqop, kqop->events_size * 2);
+ }
+
+ return (0);
+}
+
+static void
+kqop_free(struct kqop *kqop)
+{
+ if (kqop->changes)
+ mm_free(kqop->changes);
+ if (kqop->events)
+ mm_free(kqop->events);
+ if (kqop->kq >= 0 && kqop->pid == getpid())
+ close(kqop->kq);
+ memset(kqop, 0, sizeof(struct kqop));
+ mm_free(kqop);
+}
+
+static void
+kq_dealloc(struct event_base *base)
+{
+ struct kqop *kqop = base->evbase;
+ evsig_dealloc_(base);
+ kqop_free(kqop);
+}
+
+/* signal handling */
+static int
+kq_sig_add(struct event_base *base, int nsignal, short old, short events, void *p)
+{
+ struct kqop *kqop = base->evbase;
+ struct kevent kev;
+ struct timespec timeout = { 0, 0 };
+ (void)p;
+
+ EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
+
+ memset(&kev, 0, sizeof(kev));
+ kev.ident = nsignal;
+ kev.filter = EVFILT_SIGNAL;
+ kev.flags = EV_ADD;
+
+ /* Be ready for the signal if it is sent any
+ * time between now and the next call to
+ * kq_dispatch. */
+ if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
+ return (-1);
+
+ /* We can set the handler for most signals to SIG_IGN and
+ * still have them reported to us in the queue. However,
+ * if the handler for SIGCHLD is SIG_IGN, the system reaps
+ * zombie processes for us, and we don't get any notification.
+ * This appears to be the only signal with this quirk. */
+ if (evsig_set_handler_(base, nsignal,
+ nsignal == SIGCHLD ? SIG_DFL : SIG_IGN) == -1)
+ return (-1);
+
+ return (0);
+}
+
+static int
+kq_sig_del(struct event_base *base, int nsignal, short old, short events, void *p)
+{
+ struct kqop *kqop = base->evbase;
+ struct kevent kev;
+
+ struct timespec timeout = { 0, 0 };
+ (void)p;
+
+ EVUTIL_ASSERT(nsignal >= 0 && nsignal < NSIG);
+
+ memset(&kev, 0, sizeof(kev));
+ kev.ident = nsignal;
+ kev.filter = EVFILT_SIGNAL;
+ kev.flags = EV_DELETE;
+
+ /* Because we insert signal events
+ * immediately, we need to delete them
+ * immediately, too */
+ if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1)
+ return (-1);
+
+ if (evsig_restore_handler_(base, nsignal) == -1)
+ return (-1);
+
+ return (0);
+}
+
+
+/* OSX 10.6 and FreeBSD 8.1 add support for EVFILT_USER, which we can use
+ * to wake up the event loop from another thread. */
+
+/* Magic number we use for our filter ID. */
+#define NOTIFY_IDENT 42
+
+int
+event_kq_add_notify_event_(struct event_base *base)
+{
+ struct kqop *kqop = base->evbase;
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+ struct kevent kev;
+ struct timespec timeout = { 0, 0 };
+#endif
+
+ if (kqop->notify_event_added)
+ return 0;
+
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+ memset(&kev, 0, sizeof(kev));
+ kev.ident = NOTIFY_IDENT;
+ kev.filter = EVFILT_USER;
+ kev.flags = EV_ADD | EV_CLEAR;
+
+ if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
+ event_warn("kevent: adding EVFILT_USER event");
+ return -1;
+ }
+
+ kqop->notify_event_added = 1;
+
+ return 0;
+#else
+ return -1;
+#endif
+}
+
+int
+event_kq_notify_base_(struct event_base *base)
+{
+ struct kqop *kqop = base->evbase;
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+ struct kevent kev;
+ struct timespec timeout = { 0, 0 };
+#endif
+ if (! kqop->notify_event_added)
+ return -1;
+
+#if defined(EVFILT_USER) && defined(NOTE_TRIGGER)
+ memset(&kev, 0, sizeof(kev));
+ kev.ident = NOTIFY_IDENT;
+ kev.filter = EVFILT_USER;
+ kev.fflags = NOTE_TRIGGER;
+
+ if (kevent(kqop->kq, &kev, 1, NULL, 0, &timeout) == -1) {
+ event_warn("kevent: triggering EVFILT_USER event");
+ return -1;
+ }
+
+ return 0;
+#else
+ return -1;
+#endif
+}
+
+#endif /* EVENT__HAVE_KQUEUE */
diff --git a/ipc/chromium/src/third_party/libevent/libevent.pc.in b/ipc/chromium/src/third_party/libevent/libevent.pc.in
new file mode 100644
index 0000000000..7030884eeb
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/libevent.pc.in
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent
+Description: libevent is an asynchronous notification event loop library
+Version: @VERSION@
+Requires:
+Conflicts:
+Libs: -L${libdir} -levent
+Libs.private: @LIBS@
+Cflags: -I${includedir}
+
diff --git a/ipc/chromium/src/third_party/libevent/libevent_core.pc.in b/ipc/chromium/src/third_party/libevent/libevent_core.pc.in
new file mode 100644
index 0000000000..98ab1efe7f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/libevent_core.pc.in
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_core
+Description: libevent_core
+Version: @VERSION@
+Requires:
+Conflicts:
+Libs: -L${libdir} -levent_core
+Libs.private: @LIBS@
+Cflags: -I${includedir}
+
diff --git a/ipc/chromium/src/third_party/libevent/libevent_extra.pc.in b/ipc/chromium/src/third_party/libevent/libevent_extra.pc.in
new file mode 100644
index 0000000000..b9633998d0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/libevent_extra.pc.in
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_extra
+Description: libevent_extra
+Version: @VERSION@
+Requires:
+Conflicts:
+Libs: -L${libdir} -levent_extra
+Libs.private: @LIBS@
+Cflags: -I${includedir}
+
diff --git a/ipc/chromium/src/third_party/libevent/libevent_openssl.pc.in b/ipc/chromium/src/third_party/libevent/libevent_openssl.pc.in
new file mode 100644
index 0000000000..a65d1e0668
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/libevent_openssl.pc.in
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_openssl
+Description: libevent_openssl adds openssl-based TLS support to libevent
+Version: @VERSION@
+Requires: libevent
+Conflicts:
+Libs: -L${libdir} -levent_openssl
+Libs.private: @LIBS@ @OPENSSL_LIBS@
+Cflags: -I${includedir} @OPENSSL_INCS@
+
diff --git a/ipc/chromium/src/third_party/libevent/libevent_pthreads.pc.in b/ipc/chromium/src/third_party/libevent/libevent_pthreads.pc.in
new file mode 100644
index 0000000000..9bc2392b34
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/libevent_pthreads.pc.in
@@ -0,0 +1,16 @@
+#libevent pkg-config source file
+
+prefix=@prefix@
+exec_prefix=@exec_prefix@
+libdir=@libdir@
+includedir=@includedir@
+
+Name: libevent_pthreads
+Description: libevent_pthreads adds pthreads-based threading support to libevent
+Version: @VERSION@
+Requires: libevent
+Conflicts:
+Libs: -L${libdir} -levent_pthreads
+Libs.private: @LIBS@ @PTHREAD_LIBS@
+Cflags: -I${includedir} @PTHREAD_CFLAGS@
+
diff --git a/ipc/chromium/src/third_party/libevent/linux/event2/event-config.h b/ipc/chromium/src/third_party/libevent/linux/event2/event-config.h
new file mode 100644
index 0000000000..49864f7400
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/linux/event2/event-config.h
@@ -0,0 +1,610 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if libevent should build without support for a debug mode */
+/* #undef EVENT__DISABLE_DEBUG_MODE */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define to 1 if you have the `accept4' function. */
+#define EVENT__HAVE_ACCEPT4 1
+
+/* Define to 1 if you have the <afunix.h> header file. */
+/* #undef EVENT__HAVE_AFUNIX_H 1 */
+
+#ifdef HAVE_ARC4RANDOM
+/* Define to 1 if you have the `arc4random' function. */
+#define EVENT__HAVE_ARC4RANDOM 1
+#endif
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+/* #undef EVENT__HAVE_ARC4RANDOM_ADDRANDOM */
+
+#ifdef HAVE_ARC4RANDOM_BUF
+/* Define to 1 if you have the `arc4random_buf' function. */
+#define EVENT__HAVE_ARC4RANDOM_BUF 1
+#endif
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define EVENT__HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_CTL_KERN 1
+
+/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_KERN_ARND 0
+
+/* Define if /dev/poll is available */
+/* #undef EVENT__HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+#define EVENT__HAVE_EPOLL 1
+
+/* Define to 1 if you have the `epoll_create1' function. */
+#define EVENT__HAVE_EPOLL_CREATE1 1
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+#define EVENT__HAVE_EPOLL_CTL 1
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define EVENT__HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the `eventfd' function. */
+#define EVENT__HAVE_EVENTFD 1
+
+/* Define if your system supports event ports */
+/* #undef EVENT__HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+#define EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if the system has the type `fd_mask'. */
+#define EVENT__HAVE_FD_MASK 1
+
+/* Do we have getaddrinfo()? */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define EVENT__HAVE_GETEUID 1
+
+/* Define this if you have any gethostbyname_r() */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
+
+/* Define this if gethostbyname_r takes 3 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if gethostbyname_r takes 5 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if gethostbyname_r takes 6 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#define EVENT__HAVE_GETIFADDRS 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getrandom' function. */
+/* #undef EVENT__HAVE_GETRANDOM */
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define EVENT__HAVE_IFADDRS_H 1
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#define EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#define EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+/* #undef EVENT__HAVE_ISSETUGID */
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef EVENT__HAVE_KQUEUE */
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+/* #undef EVENT__HAVE_LIBWS2_32 */
+
+/* Define if the system has zlib */
+#define EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+/* #undef EVENT__HAVE_MACH_ABSOLUTE_TIME */
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_H */
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_TIME_H */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define if the system has openssl */
+/* #undef EVENT__HAVE_OPENSSL */
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+/* #undef EVENT__HAVE_OPENSSL_SSL_H */
+
+/* Define to 1 if you have the `pipe' function. */
+#define EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#define EVENT__HAVE_PIPE2 1
+
+/* Define to 1 if you have the `poll' function. */
+#define EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef EVENT__HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef EVENT__HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+#define EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#define EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#define EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `setenv' function. */
+#define EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#define EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+#define EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+#define EVENT__HAVE_SPLICE 1
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+/* #undef EVENT__HAVE_STRLCPY */
+
+/* Define to 1 if you have the `strsep' function. */
+#define EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 1
+
+/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 1
+
+/* Define to 1 if the system has the type `struct linger'. */
+#define EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if you have the `sysctl' function. */
+/* #undef EVENT__HAVE_SYSCTL */
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+#define EVENT__HAVE_SYS_EPOLL_H 1
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+#define EVENT__HAVE_SYS_EVENTFD_H 1
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#define EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+/* #undef EVENT__HAVE_SYS_RANDOM_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#define EVENT__HAVE_SYS_SENDFILE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+/* #undef EVENT__HAVE_SYS_SYSCTL_H */
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+#define EVENT__HAVE_SYS_TIMERFD_H 1
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#define EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define to 1 if you have the `timerfd_create' function. */
+/* #define EVENT__HAVE_TIMERFD_CREATE */
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#define EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `usleep' function. */
+#define EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+/* #undef EVENT__HAVE_WORKING_KQUEUE */
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define EVENT__HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+/* #undef EVENT__HAVE__GMTIME64 */
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+/* #undef EVENT__HAVE__GMTIME64_S */
+
+/* Define to 1 if compiler have __FUNCTION__ */
+#define EVENT__HAVE___FUNCTION__ 1
+
+/* Define to 1 if compiler have __func__ */
+#define EVENT__HAVE___func__ 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define EVENT__LT_OBJDIR ".libs/"
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME "libevent"
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING "libevent 2.1.12-stable"
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME "libevent"
+
+/* Define to the home page for this package. */
+#define EVENT__PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION "2.1.12-stable"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* ------------------------------------------------------------------------ */
+/* MOZILLA NOTE: the following constants are hand-modified to be suitable */
+/* for both 32-bit and 64-bit platforms. See README.mozilla for details. */
+/* ------------------------------------------------------------------------ */
+
+/* The size of `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_LONG 8
+#else
+#define EVENT__SIZEOF_LONG 4
+#endif
+
+/* The size of `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#if defined(__LP64__) || (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64)
+#define EVENT__SIZEOF_OFF_T 8
+#else
+#define EVENT__SIZEOF_OFF_T 4
+#endif
+
+/* The size of `pthread_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_PTHREAD_T 8
+#else
+#define EVENT__SIZEOF_PTHREAD_T 4
+#endif
+
+/* The size of `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_SIZE_T 8
+#else
+#define EVENT__SIZEOF_SIZE_T 4
+#endif
+
+/* The size of `time_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_TIME_T 8
+#else
+#define EVENT__SIZEOF_TIME_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_VOID_P 8
+#else
+#define EVENT__SIZEOF_VOID_P 4
+#endif
+
+/* ------------------------------------------------------------------------ */
+/* END MOZILLA NOTE */
+/* ------------------------------------------------------------------------ */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Enable large inode numbers on Mac OS X 10.5. */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+/* #undef __func__ */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to unsigned int if you dont have it */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef ssize_t */
+
+#endif /* event2/event-config.h */
diff --git a/ipc/chromium/src/third_party/libevent/listener.c b/ipc/chromium/src/third_party/libevent/listener.c
new file mode 100644
index 0000000000..f5c00c9c0e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/listener.c
@@ -0,0 +1,899 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos, Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifdef _WIN32
+#ifndef _WIN32_WINNT
+/* Minimum required for InitializeCriticalSectionAndSpinCount */
+#define _WIN32_WINNT 0x0403
+#endif
+#include <winsock2.h>
+#include <winerror.h>
+#include <ws2tcpip.h>
+#include <mswsock.h>
+#endif
+#include <errno.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#include "event2/listener.h"
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "mm-internal.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "evthread-internal.h"
+#ifdef _WIN32
+#include "iocp-internal.h"
+#include "defer-internal.h"
+#include "event-internal.h"
+#endif
+
+struct evconnlistener_ops {
+ int (*enable)(struct evconnlistener *);
+ int (*disable)(struct evconnlistener *);
+ void (*destroy)(struct evconnlistener *);
+ void (*shutdown)(struct evconnlistener *);
+ evutil_socket_t (*getfd)(struct evconnlistener *);
+ struct event_base *(*getbase)(struct evconnlistener *);
+};
+
+struct evconnlistener {
+ const struct evconnlistener_ops *ops;
+ void *lock;
+ evconnlistener_cb cb;
+ evconnlistener_errorcb errorcb;
+ void *user_data;
+ unsigned flags;
+ short refcnt;
+ int accept4_flags;
+ unsigned enabled : 1;
+};
+
+struct evconnlistener_event {
+ struct evconnlistener base;
+ struct event listener;
+};
+
+#ifdef _WIN32
+struct evconnlistener_iocp {
+ struct evconnlistener base;
+ evutil_socket_t fd;
+ struct event_base *event_base;
+ struct event_iocp_port *port;
+ short n_accepting;
+ unsigned shutting_down : 1;
+ unsigned event_added : 1;
+ struct accepting_socket **accepting;
+};
+#endif
+
+#define LOCK(listener) EVLOCK_LOCK((listener)->lock, 0)
+#define UNLOCK(listener) EVLOCK_UNLOCK((listener)->lock, 0)
+
+struct evconnlistener *
+evconnlistener_new_async(struct event_base *base,
+ evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+ evutil_socket_t fd); /* XXXX export this? */
+
+static int event_listener_enable(struct evconnlistener *);
+static int event_listener_disable(struct evconnlistener *);
+static void event_listener_destroy(struct evconnlistener *);
+static evutil_socket_t event_listener_getfd(struct evconnlistener *);
+static struct event_base *event_listener_getbase(struct evconnlistener *);
+
+#if 0
+static void
+listener_incref_and_lock(struct evconnlistener *listener)
+{
+ LOCK(listener);
+ ++listener->refcnt;
+}
+#endif
+
+static int
+listener_decref_and_unlock(struct evconnlistener *listener)
+{
+ int refcnt = --listener->refcnt;
+ if (refcnt == 0) {
+ listener->ops->destroy(listener);
+ UNLOCK(listener);
+ EVTHREAD_FREE_LOCK(listener->lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ mm_free(listener);
+ return 1;
+ } else {
+ UNLOCK(listener);
+ return 0;
+ }
+}
+
+static const struct evconnlistener_ops evconnlistener_event_ops = {
+ event_listener_enable,
+ event_listener_disable,
+ event_listener_destroy,
+ NULL, /* shutdown */
+ event_listener_getfd,
+ event_listener_getbase
+};
+
+static void listener_read_cb(evutil_socket_t, short, void *);
+
+struct evconnlistener *
+evconnlistener_new(struct event_base *base,
+ evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+ evutil_socket_t fd)
+{
+ struct evconnlistener_event *lev;
+
+#ifdef _WIN32
+ if (base && event_base_get_iocp_(base)) {
+ const struct win32_extension_fns *ext =
+ event_get_win32_extension_fns_();
+ if (ext->AcceptEx && ext->GetAcceptExSockaddrs)
+ return evconnlistener_new_async(base, cb, ptr, flags,
+ backlog, fd);
+ }
+#endif
+
+ if (backlog > 0) {
+ if (listen(fd, backlog) < 0)
+ return NULL;
+ } else if (backlog < 0) {
+ if (listen(fd, 128) < 0)
+ return NULL;
+ }
+
+ lev = mm_calloc(1, sizeof(struct evconnlistener_event));
+ if (!lev)
+ return NULL;
+
+ lev->base.ops = &evconnlistener_event_ops;
+ lev->base.cb = cb;
+ lev->base.user_data = ptr;
+ lev->base.flags = flags;
+ lev->base.refcnt = 1;
+
+ lev->base.accept4_flags = 0;
+ if (!(flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
+ lev->base.accept4_flags |= EVUTIL_SOCK_NONBLOCK;
+ if (flags & LEV_OPT_CLOSE_ON_EXEC)
+ lev->base.accept4_flags |= EVUTIL_SOCK_CLOEXEC;
+
+ if (flags & LEV_OPT_THREADSAFE) {
+ EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ }
+
+ event_assign(&lev->listener, base, fd, EV_READ|EV_PERSIST,
+ listener_read_cb, lev);
+
+ if (!(flags & LEV_OPT_DISABLED))
+ evconnlistener_enable(&lev->base);
+
+ return &lev->base;
+}
+
+struct evconnlistener *
+evconnlistener_new_bind(struct event_base *base, evconnlistener_cb cb,
+ void *ptr, unsigned flags, int backlog, const struct sockaddr *sa,
+ int socklen)
+{
+ struct evconnlistener *listener;
+ evutil_socket_t fd;
+ int on = 1;
+ int family = sa ? sa->sa_family : AF_UNSPEC;
+ int socktype = SOCK_STREAM | EVUTIL_SOCK_NONBLOCK;
+
+ if (backlog == 0)
+ return NULL;
+
+ if (flags & LEV_OPT_CLOSE_ON_EXEC)
+ socktype |= EVUTIL_SOCK_CLOEXEC;
+
+ fd = evutil_socket_(family, socktype, 0);
+ if (fd == -1)
+ return NULL;
+
+ if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&on, sizeof(on))<0)
+ goto err;
+
+ if (flags & LEV_OPT_REUSEABLE) {
+ if (evutil_make_listen_socket_reuseable(fd) < 0)
+ goto err;
+ }
+
+ if (flags & LEV_OPT_REUSEABLE_PORT) {
+ if (evutil_make_listen_socket_reuseable_port(fd) < 0)
+ goto err;
+ }
+
+ if (flags & LEV_OPT_DEFERRED_ACCEPT) {
+ if (evutil_make_tcp_listen_socket_deferred(fd) < 0)
+ goto err;
+ }
+
+ if (flags & LEV_OPT_BIND_IPV6ONLY) {
+ if (evutil_make_listen_socket_ipv6only(fd) < 0)
+ goto err;
+ }
+
+ if (sa) {
+ if (bind(fd, sa, socklen)<0)
+ goto err;
+ }
+
+ listener = evconnlistener_new(base, cb, ptr, flags, backlog, fd);
+ if (!listener)
+ goto err;
+
+ return listener;
+err:
+ evutil_closesocket(fd);
+ return NULL;
+}
+
+void
+evconnlistener_free(struct evconnlistener *lev)
+{
+ LOCK(lev);
+ lev->cb = NULL;
+ lev->errorcb = NULL;
+ if (lev->ops->shutdown)
+ lev->ops->shutdown(lev);
+ listener_decref_and_unlock(lev);
+}
+
+static void
+event_listener_destroy(struct evconnlistener *lev)
+{
+ struct evconnlistener_event *lev_e =
+ EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+
+ event_del(&lev_e->listener);
+ if (lev->flags & LEV_OPT_CLOSE_ON_FREE)
+ evutil_closesocket(event_get_fd(&lev_e->listener));
+ event_debug_unassign(&lev_e->listener);
+}
+
+int
+evconnlistener_enable(struct evconnlistener *lev)
+{
+ int r;
+ LOCK(lev);
+ lev->enabled = 1;
+ if (lev->cb)
+ r = lev->ops->enable(lev);
+ else
+ r = 0;
+ UNLOCK(lev);
+ return r;
+}
+
+int
+evconnlistener_disable(struct evconnlistener *lev)
+{
+ int r;
+ LOCK(lev);
+ lev->enabled = 0;
+ r = lev->ops->disable(lev);
+ UNLOCK(lev);
+ return r;
+}
+
+static int
+event_listener_enable(struct evconnlistener *lev)
+{
+ struct evconnlistener_event *lev_e =
+ EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+ return event_add(&lev_e->listener, NULL);
+}
+
+static int
+event_listener_disable(struct evconnlistener *lev)
+{
+ struct evconnlistener_event *lev_e =
+ EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+ return event_del(&lev_e->listener);
+}
+
+evutil_socket_t
+evconnlistener_get_fd(struct evconnlistener *lev)
+{
+ evutil_socket_t fd;
+ LOCK(lev);
+ fd = lev->ops->getfd(lev);
+ UNLOCK(lev);
+ return fd;
+}
+
+static evutil_socket_t
+event_listener_getfd(struct evconnlistener *lev)
+{
+ struct evconnlistener_event *lev_e =
+ EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+ return event_get_fd(&lev_e->listener);
+}
+
+struct event_base *
+evconnlistener_get_base(struct evconnlistener *lev)
+{
+ struct event_base *base;
+ LOCK(lev);
+ base = lev->ops->getbase(lev);
+ UNLOCK(lev);
+ return base;
+}
+
+static struct event_base *
+event_listener_getbase(struct evconnlistener *lev)
+{
+ struct evconnlistener_event *lev_e =
+ EVUTIL_UPCAST(lev, struct evconnlistener_event, base);
+ return event_get_base(&lev_e->listener);
+}
+
+void
+evconnlistener_set_cb(struct evconnlistener *lev,
+ evconnlistener_cb cb, void *arg)
+{
+ int enable = 0;
+ LOCK(lev);
+ if (lev->enabled && !lev->cb)
+ enable = 1;
+ lev->cb = cb;
+ lev->user_data = arg;
+ if (enable)
+ evconnlistener_enable(lev);
+ UNLOCK(lev);
+}
+
+void
+evconnlistener_set_error_cb(struct evconnlistener *lev,
+ evconnlistener_errorcb errorcb)
+{
+ LOCK(lev);
+ lev->errorcb = errorcb;
+ UNLOCK(lev);
+}
+
+static void
+listener_read_cb(evutil_socket_t fd, short what, void *p)
+{
+ struct evconnlistener *lev = p;
+ int err;
+ evconnlistener_cb cb;
+ evconnlistener_errorcb errorcb;
+ void *user_data;
+ LOCK(lev);
+ while (1) {
+ struct sockaddr_storage ss;
+ ev_socklen_t socklen = sizeof(ss);
+ evutil_socket_t new_fd = evutil_accept4_(fd, (struct sockaddr*)&ss, &socklen, lev->accept4_flags);
+ if (new_fd < 0)
+ break;
+ if (socklen == 0) {
+ /* This can happen with some older linux kernels in
+ * response to nmap. */
+ evutil_closesocket(new_fd);
+ continue;
+ }
+
+ if (lev->cb == NULL) {
+ evutil_closesocket(new_fd);
+ UNLOCK(lev);
+ return;
+ }
+ ++lev->refcnt;
+ cb = lev->cb;
+ user_data = lev->user_data;
+ UNLOCK(lev);
+ cb(lev, new_fd, (struct sockaddr*)&ss, (int)socklen,
+ user_data);
+ LOCK(lev);
+ if (lev->refcnt == 1) {
+ int freed = listener_decref_and_unlock(lev);
+ EVUTIL_ASSERT(freed);
+ return;
+ }
+ --lev->refcnt;
+ if (!lev->enabled) {
+ /* the callback could have disabled the listener */
+ UNLOCK(lev);
+ return;
+ }
+ }
+ err = evutil_socket_geterror(fd);
+ if (EVUTIL_ERR_ACCEPT_RETRIABLE(err)) {
+ UNLOCK(lev);
+ return;
+ }
+ if (lev->errorcb != NULL) {
+ ++lev->refcnt;
+ errorcb = lev->errorcb;
+ user_data = lev->user_data;
+ UNLOCK(lev);
+ errorcb(lev, user_data);
+ LOCK(lev);
+ listener_decref_and_unlock(lev);
+ } else {
+ event_sock_warn(fd, "Error from accept() call");
+ UNLOCK(lev);
+ }
+}
+
+#ifdef _WIN32
+struct accepting_socket {
+ CRITICAL_SECTION lock;
+ struct event_overlapped overlapped;
+ SOCKET s;
+ int error;
+ struct event_callback deferred;
+ struct evconnlistener_iocp *lev;
+ ev_uint8_t buflen;
+ ev_uint8_t family;
+ unsigned free_on_cb:1;
+ char addrbuf[1];
+};
+
+static void accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key,
+ ev_ssize_t n, int ok);
+static void accepted_socket_invoke_user_cb(struct event_callback *cb, void *arg);
+
+static void
+iocp_listener_event_add(struct evconnlistener_iocp *lev)
+{
+ if (lev->event_added)
+ return;
+
+ lev->event_added = 1;
+ event_base_add_virtual_(lev->event_base);
+}
+
+static void
+iocp_listener_event_del(struct evconnlistener_iocp *lev)
+{
+ if (!lev->event_added)
+ return;
+
+ lev->event_added = 0;
+ event_base_del_virtual_(lev->event_base);
+}
+
+static struct accepting_socket *
+new_accepting_socket(struct evconnlistener_iocp *lev, int family)
+{
+ struct accepting_socket *res;
+ int addrlen;
+ int buflen;
+
+ if (family == AF_INET)
+ addrlen = sizeof(struct sockaddr_in);
+ else if (family == AF_INET6)
+ addrlen = sizeof(struct sockaddr_in6);
+ else
+ return NULL;
+ buflen = (addrlen+16)*2;
+
+ res = mm_calloc(1,sizeof(struct accepting_socket)-1+buflen);
+ if (!res)
+ return NULL;
+
+ event_overlapped_init_(&res->overlapped, accepted_socket_cb);
+ res->s = EVUTIL_INVALID_SOCKET;
+ res->lev = lev;
+ res->buflen = buflen;
+ res->family = family;
+
+ event_deferred_cb_init_(&res->deferred,
+ event_base_get_npriorities(lev->event_base) / 2,
+ accepted_socket_invoke_user_cb, res);
+
+ InitializeCriticalSectionAndSpinCount(&res->lock, 1000);
+
+ return res;
+}
+
+static void
+free_and_unlock_accepting_socket(struct accepting_socket *as)
+{
+ /* requires lock. */
+ if (as->s != EVUTIL_INVALID_SOCKET)
+ closesocket(as->s);
+
+ LeaveCriticalSection(&as->lock);
+ DeleteCriticalSection(&as->lock);
+ mm_free(as);
+}
+
+static int
+start_accepting(struct accepting_socket *as)
+{
+ /* requires lock */
+ const struct win32_extension_fns *ext = event_get_win32_extension_fns_();
+ DWORD pending = 0;
+ SOCKET s = socket(as->family, SOCK_STREAM, 0);
+ int error = 0;
+
+ if (!as->lev->base.enabled)
+ return 0;
+
+ if (s == EVUTIL_INVALID_SOCKET) {
+ error = WSAGetLastError();
+ goto report_err;
+ }
+
+ /* XXXX It turns out we need to do this again later. Does this call
+ * have any effect? */
+ setsockopt(s, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
+ (char *)&as->lev->fd, sizeof(&as->lev->fd));
+
+ if (!(as->lev->base.flags & LEV_OPT_LEAVE_SOCKETS_BLOCKING))
+ evutil_make_socket_nonblocking(s);
+
+ if (event_iocp_port_associate_(as->lev->port, s, 1) < 0) {
+ closesocket(s);
+ return -1;
+ }
+
+ as->s = s;
+
+ if (ext->AcceptEx(as->lev->fd, s, as->addrbuf, 0,
+ as->buflen/2, as->buflen/2, &pending, &as->overlapped.overlapped))
+ {
+ /* Immediate success! */
+ accepted_socket_cb(&as->overlapped, 1, 0, 1);
+ } else {
+ error = WSAGetLastError();
+ if (error != ERROR_IO_PENDING) {
+ goto report_err;
+ }
+ }
+
+ return 0;
+
+report_err:
+ as->error = error;
+ event_deferred_cb_schedule_(
+ as->lev->event_base,
+ &as->deferred);
+ return 0;
+}
+
+static void
+stop_accepting(struct accepting_socket *as)
+{
+ /* requires lock. */
+ SOCKET s = as->s;
+ as->s = EVUTIL_INVALID_SOCKET;
+ closesocket(s);
+}
+
+static void
+accepted_socket_invoke_user_cb(struct event_callback *dcb, void *arg)
+{
+ struct accepting_socket *as = arg;
+
+ struct sockaddr *sa_local=NULL, *sa_remote=NULL;
+ int socklen_local=0, socklen_remote=0;
+ const struct win32_extension_fns *ext = event_get_win32_extension_fns_();
+ struct evconnlistener *lev = &as->lev->base;
+ evutil_socket_t sock=-1;
+ void *data;
+ evconnlistener_cb cb=NULL;
+ evconnlistener_errorcb errorcb=NULL;
+ int error;
+
+ EVUTIL_ASSERT(ext->GetAcceptExSockaddrs);
+
+ LOCK(lev);
+ EnterCriticalSection(&as->lock);
+ if (as->free_on_cb) {
+ free_and_unlock_accepting_socket(as);
+ listener_decref_and_unlock(lev);
+ return;
+ }
+
+ ++lev->refcnt;
+
+ error = as->error;
+ if (error) {
+ as->error = 0;
+ errorcb = lev->errorcb;
+ } else {
+ ext->GetAcceptExSockaddrs(
+ as->addrbuf, 0, as->buflen/2, as->buflen/2,
+ &sa_local, &socklen_local, &sa_remote,
+ &socklen_remote);
+ sock = as->s;
+ cb = lev->cb;
+ as->s = EVUTIL_INVALID_SOCKET;
+
+ /* We need to call this so getsockname, getpeername, and
+ * shutdown work correctly on the accepted socket. */
+ /* XXXX handle error? */
+ setsockopt(sock, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
+ (char *)&as->lev->fd, sizeof(&as->lev->fd));
+ }
+ data = lev->user_data;
+
+ LeaveCriticalSection(&as->lock);
+ UNLOCK(lev);
+
+ if (errorcb) {
+ WSASetLastError(error);
+ errorcb(lev, data);
+ } else if (cb) {
+ cb(lev, sock, sa_remote, socklen_remote, data);
+ }
+
+ LOCK(lev);
+ if (listener_decref_and_unlock(lev))
+ return;
+
+ EnterCriticalSection(&as->lock);
+ start_accepting(as);
+ LeaveCriticalSection(&as->lock);
+}
+
+static void
+accepted_socket_cb(struct event_overlapped *o, ev_uintptr_t key, ev_ssize_t n, int ok)
+{
+ struct accepting_socket *as =
+ EVUTIL_UPCAST(o, struct accepting_socket, overlapped);
+
+ LOCK(&as->lev->base);
+ EnterCriticalSection(&as->lock);
+ if (ok) {
+ /* XXXX Don't do this if some EV_MT flag is set. */
+ event_deferred_cb_schedule_(
+ as->lev->event_base,
+ &as->deferred);
+ LeaveCriticalSection(&as->lock);
+ } else if (as->free_on_cb) {
+ struct evconnlistener *lev = &as->lev->base;
+ free_and_unlock_accepting_socket(as);
+ listener_decref_and_unlock(lev);
+ return;
+ } else if (as->s == EVUTIL_INVALID_SOCKET) {
+ /* This is okay; we were disabled by iocp_listener_disable. */
+ LeaveCriticalSection(&as->lock);
+ } else {
+ /* Some error on accept that we couldn't actually handle. */
+ BOOL ok;
+ DWORD transfer = 0, flags=0;
+ event_sock_warn(as->s, "Unexpected error on AcceptEx");
+ ok = WSAGetOverlappedResult(as->s, &o->overlapped,
+ &transfer, FALSE, &flags);
+ if (ok) {
+ /* well, that was confusing! */
+ as->error = 1;
+ } else {
+ as->error = WSAGetLastError();
+ }
+ event_deferred_cb_schedule_(
+ as->lev->event_base,
+ &as->deferred);
+ LeaveCriticalSection(&as->lock);
+ }
+ UNLOCK(&as->lev->base);
+}
+
+static int
+iocp_listener_enable(struct evconnlistener *lev)
+{
+ int i;
+ struct evconnlistener_iocp *lev_iocp =
+ EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+ LOCK(lev);
+ iocp_listener_event_add(lev_iocp);
+ for (i = 0; i < lev_iocp->n_accepting; ++i) {
+ struct accepting_socket *as = lev_iocp->accepting[i];
+ if (!as)
+ continue;
+ EnterCriticalSection(&as->lock);
+ if (!as->free_on_cb && as->s == EVUTIL_INVALID_SOCKET)
+ start_accepting(as);
+ LeaveCriticalSection(&as->lock);
+ }
+ UNLOCK(lev);
+ return 0;
+}
+
+static int
+iocp_listener_disable_impl(struct evconnlistener *lev, int shutdown)
+{
+ int i;
+ struct evconnlistener_iocp *lev_iocp =
+ EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+ LOCK(lev);
+ iocp_listener_event_del(lev_iocp);
+ for (i = 0; i < lev_iocp->n_accepting; ++i) {
+ struct accepting_socket *as = lev_iocp->accepting[i];
+ if (!as)
+ continue;
+ EnterCriticalSection(&as->lock);
+ if (!as->free_on_cb && as->s != EVUTIL_INVALID_SOCKET) {
+ if (shutdown)
+ as->free_on_cb = 1;
+ stop_accepting(as);
+ }
+ LeaveCriticalSection(&as->lock);
+ }
+
+ if (shutdown && lev->flags & LEV_OPT_CLOSE_ON_FREE)
+ evutil_closesocket(lev_iocp->fd);
+
+ UNLOCK(lev);
+ return 0;
+}
+
+static int
+iocp_listener_disable(struct evconnlistener *lev)
+{
+ return iocp_listener_disable_impl(lev,0);
+}
+
+static void
+iocp_listener_destroy(struct evconnlistener *lev)
+{
+ struct evconnlistener_iocp *lev_iocp =
+ EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+
+ if (! lev_iocp->shutting_down) {
+ lev_iocp->shutting_down = 1;
+ iocp_listener_disable_impl(lev,1);
+ }
+
+}
+
+static evutil_socket_t
+iocp_listener_getfd(struct evconnlistener *lev)
+{
+ struct evconnlistener_iocp *lev_iocp =
+ EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+ return lev_iocp->fd;
+}
+static struct event_base *
+iocp_listener_getbase(struct evconnlistener *lev)
+{
+ struct evconnlistener_iocp *lev_iocp =
+ EVUTIL_UPCAST(lev, struct evconnlistener_iocp, base);
+ return lev_iocp->event_base;
+}
+
+static const struct evconnlistener_ops evconnlistener_iocp_ops = {
+ iocp_listener_enable,
+ iocp_listener_disable,
+ iocp_listener_destroy,
+ iocp_listener_destroy, /* shutdown */
+ iocp_listener_getfd,
+ iocp_listener_getbase
+};
+
+/* XXX define some way to override this. */
+#define N_SOCKETS_PER_LISTENER 4
+
+struct evconnlistener *
+evconnlistener_new_async(struct event_base *base,
+ evconnlistener_cb cb, void *ptr, unsigned flags, int backlog,
+ evutil_socket_t fd)
+{
+ struct sockaddr_storage ss;
+ int socklen = sizeof(ss);
+ struct evconnlistener_iocp *lev;
+ int i;
+
+ flags |= LEV_OPT_THREADSAFE;
+
+ if (!base || !event_base_get_iocp_(base))
+ goto err;
+
+ /* XXXX duplicate code */
+ if (backlog > 0) {
+ if (listen(fd, backlog) < 0)
+ goto err;
+ } else if (backlog < 0) {
+ if (listen(fd, 128) < 0)
+ goto err;
+ }
+ if (getsockname(fd, (struct sockaddr*)&ss, &socklen)) {
+ event_sock_warn(fd, "getsockname");
+ goto err;
+ }
+ lev = mm_calloc(1, sizeof(struct evconnlistener_iocp));
+ if (!lev) {
+ event_warn("calloc");
+ goto err;
+ }
+ lev->base.ops = &evconnlistener_iocp_ops;
+ lev->base.cb = cb;
+ lev->base.user_data = ptr;
+ lev->base.flags = flags;
+ lev->base.refcnt = 1;
+ lev->base.enabled = 1;
+
+ lev->port = event_base_get_iocp_(base);
+ lev->fd = fd;
+ lev->event_base = base;
+
+
+ if (event_iocp_port_associate_(lev->port, fd, 1) < 0)
+ goto err_free_lev;
+
+ EVTHREAD_ALLOC_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+ lev->n_accepting = N_SOCKETS_PER_LISTENER;
+ lev->accepting = mm_calloc(lev->n_accepting,
+ sizeof(struct accepting_socket *));
+ if (!lev->accepting) {
+ event_warn("calloc");
+ goto err_delete_lock;
+ }
+ for (i = 0; i < lev->n_accepting; ++i) {
+ lev->accepting[i] = new_accepting_socket(lev, ss.ss_family);
+ if (!lev->accepting[i]) {
+ event_warnx("Couldn't create accepting socket");
+ goto err_free_accepting;
+ }
+ if (cb && start_accepting(lev->accepting[i]) < 0) {
+ event_warnx("Couldn't start accepting on socket");
+ EnterCriticalSection(&lev->accepting[i]->lock);
+ free_and_unlock_accepting_socket(lev->accepting[i]);
+ goto err_free_accepting;
+ }
+ ++lev->base.refcnt;
+ }
+
+ iocp_listener_event_add(lev);
+
+ return &lev->base;
+
+err_free_accepting:
+ mm_free(lev->accepting);
+ /* XXXX free the other elements. */
+err_delete_lock:
+ EVTHREAD_FREE_LOCK(lev->base.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+err_free_lev:
+ mm_free(lev);
+err:
+ /* Don't close the fd, it is caller's responsibility. */
+ return NULL;
+}
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/log-internal.h b/ipc/chromium/src/third_party/libevent/log-internal.h
new file mode 100644
index 0000000000..2c31608b25
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/log-internal.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef LOG_INTERNAL_H_INCLUDED_
+#define LOG_INTERNAL_H_INCLUDED_
+
+#include "event2/util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef __GNUC__
+#define EV_CHECK_FMT(a,b) __attribute__((format(printf, a, b)))
+#define EV_NORETURN __attribute__((noreturn))
+#else
+#define EV_CHECK_FMT(a,b)
+#define EV_NORETURN
+#endif
+
+#define EVENT_ERR_ABORT_ ((int)0xdeaddead)
+
+#if !defined(EVENT__DISABLE_DEBUG_MODE) || defined(USE_DEBUG)
+#define EVENT_DEBUG_LOGGING_ENABLED
+#endif
+
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+EVENT2_CORE_EXPORT_SYMBOL extern ev_uint32_t event_debug_logging_mask_;
+#define event_debug_get_logging_mask_() (event_debug_logging_mask_)
+#else
+#define event_debug_get_logging_mask_() (0)
+#endif
+
+EVENT2_EXPORT_SYMBOL
+void event_err(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
+EVENT2_EXPORT_SYMBOL
+void event_warn(const char *fmt, ...) EV_CHECK_FMT(1,2);
+EVENT2_EXPORT_SYMBOL
+void event_sock_err(int eval, evutil_socket_t sock, const char *fmt, ...) EV_CHECK_FMT(3,4) EV_NORETURN;
+EVENT2_EXPORT_SYMBOL
+void event_sock_warn(evutil_socket_t sock, const char *fmt, ...) EV_CHECK_FMT(2,3);
+EVENT2_EXPORT_SYMBOL
+void event_errx(int eval, const char *fmt, ...) EV_CHECK_FMT(2,3) EV_NORETURN;
+EVENT2_EXPORT_SYMBOL
+void event_warnx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+EVENT2_EXPORT_SYMBOL
+void event_msgx(const char *fmt, ...) EV_CHECK_FMT(1,2);
+EVENT2_EXPORT_SYMBOL
+void event_debugx_(const char *fmt, ...) EV_CHECK_FMT(1,2);
+
+EVENT2_EXPORT_SYMBOL
+void event_logv_(int severity, const char *errstr, const char *fmt, va_list ap)
+ EV_CHECK_FMT(3,0);
+
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+#define event_debug(x) do { \
+ if (event_debug_get_logging_mask_()) { \
+ event_debugx_ x; \
+ } \
+ } while (0)
+#else
+#define event_debug(x) ((void)0)
+#endif
+
+#undef EV_CHECK_FMT
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* LOG_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/log.c b/ipc/chromium/src/third_party/libevent/log.c
new file mode 100644
index 0000000000..a9debb864e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/log.c
@@ -0,0 +1,244 @@
+/* $OpenBSD: err.c,v 1.2 2002/06/25 15:50:15 mickey Exp $ */
+
+/*
+ * log.c
+ *
+ * Based on err.c, which was adapted from OpenBSD libc *err* *warn* code.
+ *
+ * Copyright (c) 2005-2012 Niels Provos and Nick Mathewson
+ *
+ * Copyright (c) 2000 Dug Song <dugsong@monkey.org>
+ *
+ * Copyright (c) 1993
+ * The Regents of the University of California. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the University nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <errno.h>
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "log-internal.h"
+
+static void event_log(int severity, const char *msg);
+static void event_exit(int errcode) EV_NORETURN;
+
+static event_fatal_cb fatal_fn = NULL;
+
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+#ifdef USE_DEBUG
+#define DEFAULT_MASK EVENT_DBG_ALL
+#else
+#define DEFAULT_MASK 0
+#endif
+
+EVENT2_EXPORT_SYMBOL ev_uint32_t event_debug_logging_mask_ = DEFAULT_MASK;
+#endif /* EVENT_DEBUG_LOGGING_ENABLED */
+
+void
+event_enable_debug_logging(ev_uint32_t which)
+{
+#ifdef EVENT_DEBUG_LOGGING_ENABLED
+ event_debug_logging_mask_ = which;
+#endif
+}
+
+void
+event_set_fatal_callback(event_fatal_cb cb)
+{
+ fatal_fn = cb;
+}
+
+static void
+event_exit(int errcode)
+{
+ if (fatal_fn) {
+ fatal_fn(errcode);
+ exit(errcode); /* should never be reached */
+ } else if (errcode == EVENT_ERR_ABORT_)
+ abort();
+ else
+ exit(errcode);
+}
+
+void
+event_err(int eval, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_ERR, strerror(errno), fmt, ap);
+ va_end(ap);
+ event_exit(eval);
+}
+
+void
+event_warn(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_WARN, strerror(errno), fmt, ap);
+ va_end(ap);
+}
+
+void
+event_sock_err(int eval, evutil_socket_t sock, const char *fmt, ...)
+{
+ va_list ap;
+ int err = evutil_socket_geterror(sock);
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_ERR, evutil_socket_error_to_string(err), fmt, ap);
+ va_end(ap);
+ event_exit(eval);
+}
+
+void
+event_sock_warn(evutil_socket_t sock, const char *fmt, ...)
+{
+ va_list ap;
+ int err = evutil_socket_geterror(sock);
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_WARN, evutil_socket_error_to_string(err), fmt, ap);
+ va_end(ap);
+}
+
+void
+event_errx(int eval, const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_ERR, NULL, fmt, ap);
+ va_end(ap);
+ event_exit(eval);
+}
+
+void
+event_warnx(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_WARN, NULL, fmt, ap);
+ va_end(ap);
+}
+
+void
+event_msgx(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_MSG, NULL, fmt, ap);
+ va_end(ap);
+}
+
+void
+event_debugx_(const char *fmt, ...)
+{
+ va_list ap;
+
+ va_start(ap, fmt);
+ event_logv_(EVENT_LOG_DEBUG, NULL, fmt, ap);
+ va_end(ap);
+}
+
+void
+event_logv_(int severity, const char *errstr, const char *fmt, va_list ap)
+{
+ char buf[1024];
+ size_t len;
+
+ if (severity == EVENT_LOG_DEBUG && !event_debug_get_logging_mask_())
+ return;
+
+ if (fmt != NULL)
+ evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
+ else
+ buf[0] = '\0';
+
+ if (errstr) {
+ len = strlen(buf);
+ if (len < sizeof(buf) - 3) {
+ evutil_snprintf(buf + len, sizeof(buf) - len, ": %s", errstr);
+ }
+ }
+
+ event_log(severity, buf);
+}
+
+static event_log_cb log_fn = NULL;
+
+void
+event_set_log_callback(event_log_cb cb)
+{
+ log_fn = cb;
+}
+
+static void
+event_log(int severity, const char *msg)
+{
+ if (log_fn)
+ log_fn(severity, msg);
+ else {
+ const char *severity_str;
+ switch (severity) {
+ case EVENT_LOG_DEBUG:
+ severity_str = "debug";
+ break;
+ case EVENT_LOG_MSG:
+ severity_str = "msg";
+ break;
+ case EVENT_LOG_WARN:
+ severity_str = "warn";
+ break;
+ case EVENT_LOG_ERR:
+ severity_str = "err";
+ break;
+ default:
+ severity_str = "???";
+ break;
+ }
+ (void)fprintf(stderr, "[%s] %s\n", severity_str, msg);
+ }
+}
diff --git a/ipc/chromium/src/third_party/libevent/m4/ac_backport_259_ssizet.m4 b/ipc/chromium/src/third_party/libevent/m4/ac_backport_259_ssizet.m4
new file mode 100644
index 0000000000..75fde386cb
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/ac_backport_259_ssizet.m4
@@ -0,0 +1,3 @@
+AN_IDENTIFIER([ssize_t], [AC_TYPE_SSIZE_T])
+AC_DEFUN([AC_TYPE_SSIZE_T], [AC_CHECK_TYPE(ssize_t, int)])
+
diff --git a/ipc/chromium/src/third_party/libevent/m4/acx_pthread.m4 b/ipc/chromium/src/third_party/libevent/m4/acx_pthread.m4
new file mode 100644
index 0000000000..d2b116945f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/acx_pthread.m4
@@ -0,0 +1,279 @@
+##### http://autoconf-archive.cryp.to/acx_pthread.html
+#
+# SYNOPSIS
+#
+# ACX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
+#
+# DESCRIPTION
+#
+# This macro figures out how to build C programs using POSIX threads.
+# It sets the PTHREAD_LIBS output variable to the threads library and
+# linker flags, and the PTHREAD_CFLAGS output variable to any special
+# C compiler flags that are needed. (The user can also force certain
+# compiler flags/libs to be tested by setting these environment
+# variables.)
+#
+# Also sets PTHREAD_CC to any special C compiler that is needed for
+# multi-threaded programs (defaults to the value of CC otherwise).
+# (This is necessary on AIX to use the special cc_r compiler alias.)
+#
+# NOTE: You are assumed to not only compile your program with these
+# flags, but also link it with them as well. e.g. you should link
+# with $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS
+# $LIBS
+#
+# If you are only building threads programs, you may wish to use
+# these variables in your default LIBS, CFLAGS, and CC:
+#
+# LIBS="$PTHREAD_LIBS $LIBS"
+# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+# CC="$PTHREAD_CC"
+#
+# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute
+# constant has a nonstandard name, defines PTHREAD_CREATE_JOINABLE to
+# that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
+#
+# ACTION-IF-FOUND is a list of shell commands to run if a threads
+# library is found, and ACTION-IF-NOT-FOUND is a list of commands to
+# run it if it is not found. If ACTION-IF-FOUND is not specified, the
+# default action will define HAVE_PTHREAD.
+#
+# Please let the authors know if this macro fails on any platform, or
+# if you have any other suggestions or comments. This macro was based
+# on work by SGJ on autoconf scripts for FFTW (http://www.fftw.org/)
+# (with help from M. Frigo), as well as ac_pthread and hb_pthread
+# macros posted by Alejandro Forero Cuervo to the autoconf macro
+# repository. We are also grateful for the helpful feedback of
+# numerous users.
+#
+# LAST MODIFICATION
+#
+# 2007-07-29
+#
+# COPYLEFT
+#
+# Copyright (c) 2007 Steven G. Johnson <stevenj@alum.mit.edu>
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see
+# <http://www.gnu.org/licenses/>.
+#
+# As a special exception, the respective Autoconf Macro's copyright
+# owner gives unlimited permission to copy, distribute and modify the
+# configure scripts that are the output of Autoconf when processing
+# the Macro. You need not follow the terms of the GNU General Public
+# License when using or distributing such scripts, even though
+# portions of the text of the Macro appear in them. The GNU General
+# Public License (GPL) does govern all other use of the material that
+# constitutes the Autoconf Macro.
+#
+# This special exception to the GPL applies to versions of the
+# Autoconf Macro released by the Autoconf Macro Archive. When you
+# make and distribute a modified version of the Autoconf Macro, you
+# may extend this special exception to the GPL to apply to your
+# modified version as well.
+
+AC_DEFUN([ACX_PTHREAD], [
+AC_REQUIRE([AC_CANONICAL_HOST])
+AC_LANG_SAVE
+AC_LANG_C
+acx_pthread_ok=no
+
+# We used to check for pthread.h first, but this fails if pthread.h
+# requires special compiler flags (e.g. on True64 or Sequent).
+# It gets checked for in the link test anyway.
+
+# First of all, check if the user has set any of the PTHREAD_LIBS,
+# etcetera environment variables, and if threads linking works using
+# them:
+if test x"$PTHREAD_LIBS$PTHREAD_CFLAGS" != x; then
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+ save_LIBS="$LIBS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+ AC_MSG_CHECKING([for pthread_join in LIBS=$PTHREAD_LIBS with CFLAGS=$PTHREAD_CFLAGS])
+ AC_TRY_LINK_FUNC(pthread_join, acx_pthread_ok=yes)
+ AC_MSG_RESULT($acx_pthread_ok)
+ if test x"$acx_pthread_ok" = xno; then
+ PTHREAD_LIBS=""
+ PTHREAD_CFLAGS=""
+ fi
+ LIBS="$save_LIBS"
+ CFLAGS="$save_CFLAGS"
+fi
+
+# We must check for the threads library under a number of different
+# names; the ordering is very important because some systems
+# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
+# libraries is broken (non-POSIX).
+
+# Create a list of thread flags to try. Items starting with a "-" are
+# C compiler flags, and other items are library names, except for "none"
+# which indicates that we try without any flags at all, and "pthread-config"
+# which is a program returning the flags for the Pth emulation library.
+
+acx_pthread_flags="pthreads none -Kthread -kthread lthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
+
+# The ordering *is* (sometimes) important. Some notes on the
+# individual items follow:
+
+# pthreads: AIX (must check this before -lpthread)
+# none: in case threads are in libc; should be tried before -Kthread and
+# other compiler flags to prevent continual compiler warnings
+# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
+# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
+# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
+# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads)
+# -pthreads: Solaris/gcc
+# -mthreads: Mingw32/gcc, Lynx/gcc
+# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
+# doesn't hurt to check since this sometimes defines pthreads too;
+# also defines -D_REENTRANT)
+# ... -mt is also the pthreads flag for HP/aCC
+# pthread: Linux, etcetera
+# --thread-safe: KAI C++
+# pthread-config: use pthread-config program (for GNU Pth library)
+
+case "${host_cpu}-${host_os}" in
+ *solaris*)
+
+ # On Solaris (at least, for some versions), libc contains stubbed
+ # (non-functional) versions of the pthreads routines, so link-based
+ # tests will erroneously succeed. (We need to link with -pthreads/-mt/
+ # -lpthread.) (The stubs are missing pthread_cleanup_push, or rather
+ # a function called by this macro, so we could check for that, but
+ # who knows whether they'll stub that too in a future libc.) So,
+ # we'll just look for -pthreads and -lpthread first:
+
+ acx_pthread_flags="-pthreads pthread -mt -pthread $acx_pthread_flags"
+ ;;
+esac
+
+if test x"$acx_pthread_ok" = xno; then
+for flag in $acx_pthread_flags; do
+
+ case $flag in
+ none)
+ AC_MSG_CHECKING([whether pthreads work without any flags])
+ ;;
+
+ -*)
+ AC_MSG_CHECKING([whether pthreads work with $flag])
+ PTHREAD_CFLAGS="$flag"
+ ;;
+
+ pthread-config)
+ AC_CHECK_PROG(acx_pthread_config, pthread-config, yes, no)
+ if test x"$acx_pthread_config" = xno; then continue; fi
+ PTHREAD_CFLAGS="`pthread-config --cflags`"
+ PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
+ ;;
+
+ *)
+ AC_MSG_CHECKING([for the pthreads library -l$flag])
+ PTHREAD_LIBS="-l$flag"
+ ;;
+ esac
+
+ save_LIBS="$LIBS"
+ save_CFLAGS="$CFLAGS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+ # Check for various functions. We must include pthread.h,
+ # since some functions may be macros. (On the Sequent, we
+ # need a special flag -Kthread to make this header compile.)
+ # We check for pthread_join because it is in -lpthread on IRIX
+ # while pthread_create is in libc. We check for pthread_attr_init
+ # due to DEC craziness with -lpthreads. We check for
+ # pthread_cleanup_push because it is one of the few pthread
+ # functions on Solaris that doesn't have a non-functional libc stub.
+ # We try pthread_create on general principles.
+ AC_TRY_LINK([#include <pthread.h>],
+ [pthread_t th; pthread_join(th, 0);
+ pthread_attr_init(0); pthread_cleanup_push(0, 0);
+ pthread_create(0,0,0,0); pthread_cleanup_pop(0); ],
+ [acx_pthread_ok=yes])
+
+ LIBS="$save_LIBS"
+ CFLAGS="$save_CFLAGS"
+
+ AC_MSG_RESULT($acx_pthread_ok)
+ if test "x$acx_pthread_ok" = xyes; then
+ break;
+ fi
+
+ PTHREAD_LIBS=""
+ PTHREAD_CFLAGS=""
+done
+fi
+
+# Various other checks:
+if test "x$acx_pthread_ok" = xyes; then
+ save_LIBS="$LIBS"
+ LIBS="$PTHREAD_LIBS $LIBS"
+ save_CFLAGS="$CFLAGS"
+ CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
+
+ # Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
+ AC_MSG_CHECKING([for joinable pthread attribute])
+ attr_name=unknown
+ for attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
+ AC_TRY_LINK([#include <pthread.h>], [int attr=$attr; return attr;],
+ [attr_name=$attr; break])
+ done
+ AC_MSG_RESULT($attr_name)
+ if test "$attr_name" != PTHREAD_CREATE_JOINABLE; then
+ AC_DEFINE_UNQUOTED(PTHREAD_CREATE_JOINABLE, $attr_name,
+ [Define to necessary symbol if this constant
+ uses a non-standard name on your system.])
+ fi
+
+ AC_MSG_CHECKING([if more special flags are required for pthreads])
+ flag=no
+ case "${host_cpu}-${host_os}" in
+ *-aix* | *-freebsd* | *-darwin*) flag="-D_THREAD_SAFE";;
+ *solaris* | *-osf* | *-hpux*) flag="-D_REENTRANT";;
+ esac
+ AC_MSG_RESULT(${flag})
+ if test "x$flag" != xno; then
+ PTHREAD_CFLAGS="$flag $PTHREAD_CFLAGS"
+ fi
+
+ LIBS="$save_LIBS"
+ CFLAGS="$save_CFLAGS"
+
+ # More AIX lossage: must compile with xlc_r or cc_r
+ if test x"$GCC" != xyes; then
+ AC_CHECK_PROGS(PTHREAD_CC, xlc_r cc_r, ${CC})
+ else
+ PTHREAD_CC=$CC
+ fi
+else
+ PTHREAD_CC="$CC"
+fi
+
+AC_SUBST(PTHREAD_LIBS)
+AC_SUBST(PTHREAD_CFLAGS)
+AC_SUBST(PTHREAD_CC)
+
+# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
+if test x"$acx_pthread_ok" = xyes; then
+ ifelse([$1],,AC_DEFINE(HAVE_PTHREAD,1,[Define if you have POSIX threads libraries and header files.]),[$1])
+ :
+else
+ acx_pthread_ok=no
+ $2
+fi
+AC_LANG_RESTORE
+])dnl ACX_PTHREAD
diff --git a/ipc/chromium/src/third_party/libevent/m4/ax_check_funcs_ex.m4 b/ipc/chromium/src/third_party/libevent/m4/ax_check_funcs_ex.m4
new file mode 100644
index 0000000000..7aaa58b054
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/ax_check_funcs_ex.m4
@@ -0,0 +1,22 @@
+# Check if the function is available.
+# HAVE_XXX will be defined if yes.
+
+# $1: the name of function
+# $2: the headers in where the function declared
+AC_DEFUN([AX_CHECK_DECL_EX], [dnl
+ AS_IF([test "x$2" = "x"], [AC_MSG_ERROR([header not privided])])
+ AS_VAR_PUSHDEF([have_func_var], [HAVE_[]m4_toupper($1)])
+ AC_CHECK_DECL([$1],dnl
+ [AC_DEFINE([have_func_var], [1], [Define to 1 if you have the `$1' function.])],,dnl
+ [$2]dnl
+ )
+ AS_VAR_POPDEF([have_func_var])dnl
+])
+
+AC_DEFUN([AX_CHECK_DECLS_EX], [dnl
+ AS_IF([test "x$2" = "x"], [AC_MSG_ERROR([header not privided])])
+ m4_foreach([decl],dnl
+ m4_split(m4_normalize($1)),dnl
+ [AX_CHECK_DECL_EX([decl], [$2])]dnl
+ )
+])
diff --git a/ipc/chromium/src/third_party/libevent/m4/ax_prog_doxygen.m4 b/ipc/chromium/src/third_party/libevent/m4/ax_prog_doxygen.m4
new file mode 100644
index 0000000000..e5bdeb5992
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/ax_prog_doxygen.m4
@@ -0,0 +1,600 @@
+# ===========================================================================
+# https://www.gnu.org/software/autoconf-archive/ax_prog_doxygen.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+# DX_INIT_DOXYGEN(PROJECT-NAME, [DOXYFILE-PATH], [OUTPUT-DIR], ...)
+# DX_DOXYGEN_FEATURE(ON|OFF)
+# DX_DOT_FEATURE(ON|OFF)
+# DX_HTML_FEATURE(ON|OFF)
+# DX_CHM_FEATURE(ON|OFF)
+# DX_CHI_FEATURE(ON|OFF)
+# DX_MAN_FEATURE(ON|OFF)
+# DX_RTF_FEATURE(ON|OFF)
+# DX_XML_FEATURE(ON|OFF)
+# DX_PDF_FEATURE(ON|OFF)
+# DX_PS_FEATURE(ON|OFF)
+#
+# DESCRIPTION
+#
+# The DX_*_FEATURE macros control the default setting for the given
+# Doxygen feature. Supported features are 'DOXYGEN' itself, 'DOT' for
+# generating graphics, 'HTML' for plain HTML, 'CHM' for compressed HTML
+# help (for MS users), 'CHI' for generating a separate .chi file by the
+# .chm file, and 'MAN', 'RTF', 'XML', 'PDF' and 'PS' for the appropriate
+# output formats. The environment variable DOXYGEN_PAPER_SIZE may be
+# specified to override the default 'a4wide' paper size.
+#
+# By default, HTML, PDF and PS documentation is generated as this seems to
+# be the most popular and portable combination. MAN pages created by
+# Doxygen are usually problematic, though by picking an appropriate subset
+# and doing some massaging they might be better than nothing. CHM and RTF
+# are specific for MS (note that you can't generate both HTML and CHM at
+# the same time). The XML is rather useless unless you apply specialized
+# post-processing to it.
+#
+# The macros mainly control the default state of the feature. The use can
+# override the default by specifying --enable or --disable. The macros
+# ensure that contradictory flags are not given (e.g.,
+# --enable-doxygen-html and --enable-doxygen-chm,
+# --enable-doxygen-anything with --disable-doxygen, etc.) Finally, each
+# feature will be automatically disabled (with a warning) if the required
+# programs are missing.
+#
+# Once all the feature defaults have been specified, call DX_INIT_DOXYGEN
+# with the following parameters: a one-word name for the project for use
+# as a filename base etc., an optional configuration file name (the
+# default is '$(srcdir)/Doxyfile', the same as Doxygen's default), and an
+# optional output directory name (the default is 'doxygen-doc'). To run
+# doxygen multiple times for different configuration files and output
+# directories provide more parameters: the second, forth, sixth, etc
+# parameter are configuration file names and the third, fifth, seventh,
+# etc parameter are output directories. No checking is done to catch
+# duplicates.
+#
+# Automake Support
+#
+# The DX_RULES substitution can be used to add all needed rules to the
+# Makefile. Note that this is a substitution without being a variable:
+# only the @DX_RULES@ syntax will work.
+#
+# The provided targets are:
+#
+# doxygen-doc: Generate all doxygen documentation.
+#
+# doxygen-run: Run doxygen, which will generate some of the
+# documentation (HTML, CHM, CHI, MAN, RTF, XML)
+# but will not do the post processing required
+# for the rest of it (PS, PDF).
+#
+# doxygen-ps: Generate doxygen PostScript documentation.
+#
+# doxygen-pdf: Generate doxygen PDF documentation.
+#
+# Note that by default these are not integrated into the automake targets.
+# If doxygen is used to generate man pages, you can achieve this
+# integration by setting man3_MANS to the list of man pages generated and
+# then adding the dependency:
+#
+# $(man3_MANS): doxygen-doc
+#
+# This will cause make to run doxygen and generate all the documentation.
+#
+# The following variable is intended for use in Makefile.am:
+#
+# DX_CLEANFILES = everything to clean.
+#
+# Then add this variable to MOSTLYCLEANFILES.
+#
+# LICENSE
+#
+# Copyright (c) 2009 Oren Ben-Kiki <oren@ben-kiki.org>
+# Copyright (c) 2015 Olaf Mandel <olaf@mandel.name>
+#
+# Copying and distribution of this file, with or without modification, are
+# permitted in any medium without royalty provided the copyright notice
+# and this notice are preserved. This file is offered as-is, without any
+# warranty.
+
+#serial 24
+
+## ----------##
+## Defaults. ##
+## ----------##
+
+DX_ENV=""
+AC_DEFUN([DX_FEATURE_doc], OFF)
+AC_DEFUN([DX_FEATURE_dot], OFF)
+AC_DEFUN([DX_FEATURE_man], OFF)
+AC_DEFUN([DX_FEATURE_html], ON)
+AC_DEFUN([DX_FEATURE_chm], OFF)
+AC_DEFUN([DX_FEATURE_chi], OFF)
+AC_DEFUN([DX_FEATURE_rtf], OFF)
+AC_DEFUN([DX_FEATURE_xml], OFF)
+AC_DEFUN([DX_FEATURE_pdf], ON)
+AC_DEFUN([DX_FEATURE_ps], ON)
+
+## --------------- ##
+## Private macros. ##
+## --------------- ##
+
+# DX_ENV_APPEND(VARIABLE, VALUE)
+# ------------------------------
+# Append VARIABLE="VALUE" to DX_ENV for invoking doxygen and add it
+# as a substitution (but not a Makefile variable). The substitution
+# is skipped if the variable name is VERSION.
+AC_DEFUN([DX_ENV_APPEND],
+[AC_SUBST([DX_ENV], ["$DX_ENV $1='$2'"])dnl
+m4_if([$1], [VERSION], [], [AC_SUBST([$1], [$2])dnl
+AM_SUBST_NOTMAKE([$1])])dnl
+])
+
+# DX_DIRNAME_EXPR
+# ---------------
+# Expand into a shell expression prints the directory part of a path.
+AC_DEFUN([DX_DIRNAME_EXPR],
+ [[expr ".$1" : '\(\.\)[^/]*$' \| "x$1" : 'x\(.*\)/[^/]*$']])
+
+# DX_IF_FEATURE(FEATURE, IF-ON, IF-OFF)
+# -------------------------------------
+# Expands according to the M4 (static) status of the feature.
+AC_DEFUN([DX_IF_FEATURE], [ifelse(DX_FEATURE_$1, ON, [$2], [$3])])
+
+# DX_REQUIRE_PROG(VARIABLE, PROGRAM)
+# ----------------------------------
+# Require the specified program to be found for the DX_CURRENT_FEATURE to work.
+AC_DEFUN([DX_REQUIRE_PROG], [
+AC_PATH_TOOL([$1], [$2])
+if test "$DX_FLAG_[]DX_CURRENT_FEATURE$$1" = 1; then
+ if test "x$2" = "xdoxygen"; then
+ AC_MSG_ERROR([$2 not found - will not DX_CURRENT_DESCRIPTION])
+ else
+ AC_MSG_WARN([$2 not found - will not DX_CURRENT_DESCRIPTION])
+ fi
+ AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0)
+fi
+])
+
+# DX_TEST_FEATURE(FEATURE)
+# ------------------------
+# Expand to a shell expression testing whether the feature is active.
+AC_DEFUN([DX_TEST_FEATURE], [test "$DX_FLAG_$1" = 1])
+
+# DX_CHECK_DEPEND(REQUIRED_FEATURE, REQUIRED_STATE)
+# -------------------------------------------------
+# Verify that a required features has the right state before trying to turn on
+# the DX_CURRENT_FEATURE.
+AC_DEFUN([DX_CHECK_DEPEND], [
+test "$DX_FLAG_$1" = "$2" \
+|| AC_MSG_ERROR([doxygen-DX_CURRENT_FEATURE ifelse([$2], 1,
+ requires, contradicts) doxygen-$1])
+])
+
+# DX_CLEAR_DEPEND(FEATURE, REQUIRED_FEATURE, REQUIRED_STATE)
+# ----------------------------------------------------------
+# Turn off the DX_CURRENT_FEATURE if the required feature is off.
+AC_DEFUN([DX_CLEAR_DEPEND], [
+test "$DX_FLAG_$1" = "$2" || AC_SUBST(DX_FLAG_[]DX_CURRENT_FEATURE, 0)
+])
+
+# DX_FEATURE_ARG(FEATURE, DESCRIPTION,
+# CHECK_DEPEND, CLEAR_DEPEND,
+# REQUIRE, DO-IF-ON, DO-IF-OFF)
+# --------------------------------------------
+# Parse the command-line option controlling a feature. CHECK_DEPEND is called
+# if the user explicitly turns the feature on (and invokes DX_CHECK_DEPEND),
+# otherwise CLEAR_DEPEND is called to turn off the default state if a required
+# feature is disabled (using DX_CLEAR_DEPEND). REQUIRE performs additional
+# requirement tests (DX_REQUIRE_PROG). Finally, an automake flag is set and
+# DO-IF-ON or DO-IF-OFF are called according to the final state of the feature.
+AC_DEFUN([DX_ARG_ABLE], [
+ AC_DEFUN([DX_CURRENT_FEATURE], [$1])
+ AC_DEFUN([DX_CURRENT_DESCRIPTION], [$2])
+ AC_ARG_ENABLE(doxygen-$1,
+ [AS_HELP_STRING(DX_IF_FEATURE([$1], [--disable-doxygen-$1],
+ [--enable-doxygen-$1]),
+ DX_IF_FEATURE([$1], [don't $2], [$2]))],
+ [
+case "$enableval" in
+#(
+y|Y|yes|Yes|YES)
+ AC_SUBST([DX_FLAG_$1], 1)
+ $3
+;; #(
+n|N|no|No|NO)
+ AC_SUBST([DX_FLAG_$1], 0)
+;; #(
+*)
+ AC_MSG_ERROR([invalid value '$enableval' given to doxygen-$1])
+;;
+esac
+], [
+AC_SUBST([DX_FLAG_$1], [DX_IF_FEATURE([$1], 1, 0)])
+$4
+])
+if DX_TEST_FEATURE([$1]); then
+ $5
+ :
+fi
+if DX_TEST_FEATURE([$1]); then
+ $6
+ :
+else
+ $7
+ :
+fi
+])
+
+## -------------- ##
+## Public macros. ##
+## -------------- ##
+
+# DX_XXX_FEATURE(DEFAULT_STATE)
+# -----------------------------
+AC_DEFUN([DX_DOXYGEN_FEATURE], [AC_DEFUN([DX_FEATURE_doc], [$1])])
+AC_DEFUN([DX_DOT_FEATURE], [AC_DEFUN([DX_FEATURE_dot], [$1])])
+AC_DEFUN([DX_MAN_FEATURE], [AC_DEFUN([DX_FEATURE_man], [$1])])
+AC_DEFUN([DX_HTML_FEATURE], [AC_DEFUN([DX_FEATURE_html], [$1])])
+AC_DEFUN([DX_CHM_FEATURE], [AC_DEFUN([DX_FEATURE_chm], [$1])])
+AC_DEFUN([DX_CHI_FEATURE], [AC_DEFUN([DX_FEATURE_chi], [$1])])
+AC_DEFUN([DX_RTF_FEATURE], [AC_DEFUN([DX_FEATURE_rtf], [$1])])
+AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])])
+AC_DEFUN([DX_XML_FEATURE], [AC_DEFUN([DX_FEATURE_xml], [$1])])
+AC_DEFUN([DX_PDF_FEATURE], [AC_DEFUN([DX_FEATURE_pdf], [$1])])
+AC_DEFUN([DX_PS_FEATURE], [AC_DEFUN([DX_FEATURE_ps], [$1])])
+
+# DX_INIT_DOXYGEN(PROJECT, [CONFIG-FILE], [OUTPUT-DOC-DIR], ...)
+# --------------------------------------------------------------
+# PROJECT also serves as the base name for the documentation files.
+# The default CONFIG-FILE is "$(srcdir)/Doxyfile" and OUTPUT-DOC-DIR is
+# "doxygen-doc".
+# More arguments are interpreted as interleaved CONFIG-FILE and
+# OUTPUT-DOC-DIR values.
+AC_DEFUN([DX_INIT_DOXYGEN], [
+
+# Files:
+AC_SUBST([DX_PROJECT], [$1])
+AC_SUBST([DX_CONFIG], ['ifelse([$2], [], [$(srcdir)/Doxyfile], [$2])'])
+AC_SUBST([DX_DOCDIR], ['ifelse([$3], [], [doxygen-doc], [$3])'])
+m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 4, m4_count($@), 2,
+ [AC_SUBST([DX_CONFIG]m4_eval(DX_i[/2]),
+ 'm4_default_nblank_quoted(m4_argn(DX_i, $@),
+ [$(srcdir)/Doxyfile])')])])dnl
+m4_if(m4_eval(3 < m4_count($@)), 1, [m4_for([DX_i], 5, m4_count($@,), 2,
+ [AC_SUBST([DX_DOCDIR]m4_eval([(]DX_i[-1)/2]),
+ 'm4_default_nblank_quoted(m4_argn(DX_i, $@),
+ [doxygen-doc])')])])dnl
+m4_define([DX_loop], m4_dquote(m4_if(m4_eval(3 < m4_count($@)), 1,
+ [m4_for([DX_i], 4, m4_count($@), 2, [, m4_eval(DX_i[/2])])],
+ [])))dnl
+
+# Environment variables used inside doxygen.cfg:
+DX_ENV_APPEND(SRCDIR, $srcdir)
+DX_ENV_APPEND(PROJECT, $DX_PROJECT)
+DX_ENV_APPEND(VERSION, $PACKAGE_VERSION)
+
+# Doxygen itself:
+DX_ARG_ABLE(doc, [generate any doxygen documentation],
+ [],
+ [],
+ [DX_REQUIRE_PROG([DX_DOXYGEN], doxygen)
+ DX_REQUIRE_PROG([DX_PERL], perl)],
+ [DX_ENV_APPEND(PERL_PATH, $DX_PERL)])
+
+# Dot for graphics:
+DX_ARG_ABLE(dot, [generate graphics for doxygen documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [DX_REQUIRE_PROG([DX_DOT], dot)],
+ [DX_ENV_APPEND(HAVE_DOT, YES)
+ DX_ENV_APPEND(DOT_PATH, [`DX_DIRNAME_EXPR($DX_DOT)`])],
+ [DX_ENV_APPEND(HAVE_DOT, NO)])
+
+# Man pages generation:
+DX_ARG_ABLE(man, [generate doxygen manual pages],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [],
+ [DX_ENV_APPEND(GENERATE_MAN, YES)],
+ [DX_ENV_APPEND(GENERATE_MAN, NO)])
+
+# RTF file generation:
+DX_ARG_ABLE(rtf, [generate doxygen RTF documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [],
+ [DX_ENV_APPEND(GENERATE_RTF, YES)],
+ [DX_ENV_APPEND(GENERATE_RTF, NO)])
+
+# XML file generation:
+DX_ARG_ABLE(xml, [generate doxygen XML documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [],
+ [DX_ENV_APPEND(GENERATE_XML, YES)],
+ [DX_ENV_APPEND(GENERATE_XML, NO)])
+
+# (Compressed) HTML help generation:
+DX_ARG_ABLE(chm, [generate doxygen compressed HTML help documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [DX_REQUIRE_PROG([DX_HHC], hhc)],
+ [DX_ENV_APPEND(HHC_PATH, $DX_HHC)
+ DX_ENV_APPEND(GENERATE_HTML, YES)
+ DX_ENV_APPEND(GENERATE_HTMLHELP, YES)],
+ [DX_ENV_APPEND(GENERATE_HTMLHELP, NO)])
+
+# Separate CHI file generation.
+DX_ARG_ABLE(chi, [generate doxygen separate compressed HTML help index file],
+ [DX_CHECK_DEPEND(chm, 1)],
+ [DX_CLEAR_DEPEND(chm, 1)],
+ [],
+ [DX_ENV_APPEND(GENERATE_CHI, YES)],
+ [DX_ENV_APPEND(GENERATE_CHI, NO)])
+
+# Plain HTML pages generation:
+DX_ARG_ABLE(html, [generate doxygen plain HTML documentation],
+ [DX_CHECK_DEPEND(doc, 1) DX_CHECK_DEPEND(chm, 0)],
+ [DX_CLEAR_DEPEND(doc, 1) DX_CLEAR_DEPEND(chm, 0)],
+ [],
+ [DX_ENV_APPEND(GENERATE_HTML, YES)],
+ [DX_TEST_FEATURE(chm) || DX_ENV_APPEND(GENERATE_HTML, NO)])
+
+# PostScript file generation:
+DX_ARG_ABLE(ps, [generate doxygen PostScript documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [DX_REQUIRE_PROG([DX_LATEX], latex)
+ DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex)
+ DX_REQUIRE_PROG([DX_DVIPS], dvips)
+ DX_REQUIRE_PROG([DX_EGREP], egrep)])
+
+# PDF file generation:
+DX_ARG_ABLE(pdf, [generate doxygen PDF documentation],
+ [DX_CHECK_DEPEND(doc, 1)],
+ [DX_CLEAR_DEPEND(doc, 1)],
+ [DX_REQUIRE_PROG([DX_PDFLATEX], pdflatex)
+ DX_REQUIRE_PROG([DX_MAKEINDEX], makeindex)
+ DX_REQUIRE_PROG([DX_EGREP], egrep)])
+
+# LaTeX generation for PS and/or PDF:
+if DX_TEST_FEATURE(ps) || DX_TEST_FEATURE(pdf); then
+ DX_ENV_APPEND(GENERATE_LATEX, YES)
+else
+ DX_ENV_APPEND(GENERATE_LATEX, NO)
+fi
+
+# Paper size for PS and/or PDF:
+AC_ARG_VAR(DOXYGEN_PAPER_SIZE,
+ [a4wide (default), a4, letter, legal or executive])
+case "$DOXYGEN_PAPER_SIZE" in
+#(
+"")
+ AC_SUBST(DOXYGEN_PAPER_SIZE, "")
+;; #(
+a4wide|a4|letter|legal|executive)
+ DX_ENV_APPEND(PAPER_SIZE, $DOXYGEN_PAPER_SIZE)
+;; #(
+*)
+ AC_MSG_ERROR([unknown DOXYGEN_PAPER_SIZE='$DOXYGEN_PAPER_SIZE'])
+;;
+esac
+
+# Rules:
+AS_IF([[test $DX_FLAG_html -eq 1]],
+[[DX_SNIPPET_html="## ------------------------------- ##
+## Rules specific for HTML output. ##
+## ------------------------------- ##
+
+DX_CLEAN_HTML = \$(DX_DOCDIR)/html]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/html]])[
+
+"]],
+[[DX_SNIPPET_html=""]])
+AS_IF([[test $DX_FLAG_chi -eq 1]],
+[[DX_SNIPPET_chi="
+DX_CLEAN_CHI = \$(DX_DOCDIR)/\$(PACKAGE).chi]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).chi]])["]],
+[[DX_SNIPPET_chi=""]])
+AS_IF([[test $DX_FLAG_chm -eq 1]],
+[[DX_SNIPPET_chm="## ------------------------------ ##
+## Rules specific for CHM output. ##
+## ------------------------------ ##
+
+DX_CLEAN_CHM = \$(DX_DOCDIR)/chm]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/chm]])[\
+${DX_SNIPPET_chi}
+
+"]],
+[[DX_SNIPPET_chm=""]])
+AS_IF([[test $DX_FLAG_man -eq 1]],
+[[DX_SNIPPET_man="## ------------------------------ ##
+## Rules specific for MAN output. ##
+## ------------------------------ ##
+
+DX_CLEAN_MAN = \$(DX_DOCDIR)/man]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/man]])[
+
+"]],
+[[DX_SNIPPET_man=""]])
+AS_IF([[test $DX_FLAG_rtf -eq 1]],
+[[DX_SNIPPET_rtf="## ------------------------------ ##
+## Rules specific for RTF output. ##
+## ------------------------------ ##
+
+DX_CLEAN_RTF = \$(DX_DOCDIR)/rtf]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/rtf]])[
+
+"]],
+[[DX_SNIPPET_rtf=""]])
+AS_IF([[test $DX_FLAG_xml -eq 1]],
+[[DX_SNIPPET_xml="## ------------------------------ ##
+## Rules specific for XML output. ##
+## ------------------------------ ##
+
+DX_CLEAN_XML = \$(DX_DOCDIR)/xml]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/xml]])[
+
+"]],
+[[DX_SNIPPET_xml=""]])
+AS_IF([[test $DX_FLAG_ps -eq 1]],
+[[DX_SNIPPET_ps="## ----------------------------- ##
+## Rules specific for PS output. ##
+## ----------------------------- ##
+
+DX_CLEAN_PS = \$(DX_DOCDIR)/\$(PACKAGE).ps]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps]])[
+
+DX_PS_GOAL = doxygen-ps
+
+doxygen-ps: \$(DX_CLEAN_PS)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).ps: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag
+ \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\
+ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\
+ \$(DX_LATEX) refman.tex; \\
+ \$(DX_MAKEINDEX) refman.idx; \\
+ \$(DX_LATEX) refman.tex; \\
+ countdown=5; \\
+ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\
+ refman.log > /dev/null 2>&1 \\
+ && test \$\$countdown -gt 0; do \\
+ \$(DX_LATEX) refman.tex; \\
+ countdown=\`expr \$\$countdown - 1\`; \\
+ done; \\
+ \$(DX_DVIPS) -o ../\$(PACKAGE).ps refman.dvi
+
+]])["]],
+[[DX_SNIPPET_ps=""]])
+AS_IF([[test $DX_FLAG_pdf -eq 1]],
+[[DX_SNIPPET_pdf="## ------------------------------ ##
+## Rules specific for PDF output. ##
+## ------------------------------ ##
+
+DX_CLEAN_PDF = \$(DX_DOCDIR)/\$(PACKAGE).pdf]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf]])[
+
+DX_PDF_GOAL = doxygen-pdf
+
+doxygen-pdf: \$(DX_CLEAN_PDF)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).pdf: \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag
+ \$(DX_V_LATEX)cd \$(DX_DOCDIR]DX_i[)/latex; \\
+ rm -f *.aux *.toc *.idx *.ind *.ilg *.log *.out; \\
+ \$(DX_PDFLATEX) refman.tex; \\
+ \$(DX_MAKEINDEX) refman.idx; \\
+ \$(DX_PDFLATEX) refman.tex; \\
+ countdown=5; \\
+ while \$(DX_EGREP) 'Rerun (LaTeX|to get cross-references right)' \\
+ refman.log > /dev/null 2>&1 \\
+ && test \$\$countdown -gt 0; do \\
+ \$(DX_PDFLATEX) refman.tex; \\
+ countdown=\`expr \$\$countdown - 1\`; \\
+ done; \\
+ mv refman.pdf ../\$(PACKAGE).pdf
+
+]])["]],
+[[DX_SNIPPET_pdf=""]])
+AS_IF([[test $DX_FLAG_ps -eq 1 -o $DX_FLAG_pdf -eq 1]],
+[[DX_SNIPPET_latex="## ------------------------------------------------- ##
+## Rules specific for LaTeX (shared for PS and PDF). ##
+## ------------------------------------------------- ##
+
+DX_V_LATEX = \$(_DX_v_LATEX_\$(V))
+_DX_v_LATEX_ = \$(_DX_v_LATEX_\$(AM_DEFAULT_VERBOSITY))
+_DX_v_LATEX_0 = @echo \" LATEX \" \$][@;
+
+DX_CLEAN_LATEX = \$(DX_DOCDIR)/latex]dnl
+m4_foreach([DX_i], [m4_shift(DX_loop)], [[\\
+ \$(DX_DOCDIR]DX_i[)/latex]])[
+
+"]],
+[[DX_SNIPPET_latex=""]])
+
+AS_IF([[test $DX_FLAG_doc -eq 1]],
+[[DX_SNIPPET_doc="## --------------------------------- ##
+## Format-independent Doxygen rules. ##
+## --------------------------------- ##
+
+${DX_SNIPPET_html}\
+${DX_SNIPPET_chm}\
+${DX_SNIPPET_man}\
+${DX_SNIPPET_rtf}\
+${DX_SNIPPET_xml}\
+${DX_SNIPPET_ps}\
+${DX_SNIPPET_pdf}\
+${DX_SNIPPET_latex}\
+DX_V_DXGEN = \$(_DX_v_DXGEN_\$(V))
+_DX_v_DXGEN_ = \$(_DX_v_DXGEN_\$(AM_DEFAULT_VERBOSITY))
+_DX_v_DXGEN_0 = @echo \" DXGEN \" \$<;
+
+.PHONY: doxygen-run doxygen-doc \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+.INTERMEDIATE: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+doxygen-run:]m4_foreach([DX_i], [DX_loop],
+ [[ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag]])[
+
+doxygen-doc: doxygen-run \$(DX_PS_GOAL) \$(DX_PDF_GOAL)
+
+]m4_foreach([DX_i], [DX_loop],
+[[\$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag: \$(DX_CONFIG]DX_i[) \$(pkginclude_HEADERS)
+ \$(A""M_V_at)rm -rf \$(DX_DOCDIR]DX_i[)
+ \$(DX_V_DXGEN)\$(DX_ENV) DOCDIR=\$(DX_DOCDIR]DX_i[) \$(DX_DOXYGEN) \$(DX_CONFIG]DX_i[)
+ \$(A""M_V_at)echo Timestamp >\$][@
+
+]])dnl
+[DX_CLEANFILES = \\]
+m4_foreach([DX_i], [DX_loop],
+[[ \$(DX_DOCDIR]DX_i[)/doxygen_sqlite3.db \\
+ \$(DX_DOCDIR]DX_i[)/\$(PACKAGE).tag \\
+]])dnl
+[ -r \\
+ \$(DX_CLEAN_HTML) \\
+ \$(DX_CLEAN_CHM) \\
+ \$(DX_CLEAN_CHI) \\
+ \$(DX_CLEAN_MAN) \\
+ \$(DX_CLEAN_RTF) \\
+ \$(DX_CLEAN_XML) \\
+ \$(DX_CLEAN_PS) \\
+ \$(DX_CLEAN_PDF) \\
+ \$(DX_CLEAN_LATEX)
+DX_INSTALL_DOCS = \\
+ \$(DX_CLEAN_HTML) \\
+ \$(DX_CLEAN_CHM) \\
+ \$(DX_CLEAN_CHI) \\
+ \$(DX_CLEAN_RTF) \\
+ \$(DX_CLEAN_XML) \\
+ \$(DX_CLEAN_PS) \\
+ \$(DX_CLEAN_PDF) \\
+ \$(DX_CLEAN_LATEX)
+ "]],
+[[DX_SNIPPET_doc=""]])
+AC_SUBST([DX_RULES],
+["${DX_SNIPPET_doc}"])dnl
+AM_SUBST_NOTMAKE([DX_RULES])
+
+#For debugging:
+#echo DX_FLAG_doc=$DX_FLAG_doc
+#echo DX_FLAG_dot=$DX_FLAG_dot
+#echo DX_FLAG_man=$DX_FLAG_man
+#echo DX_FLAG_html=$DX_FLAG_html
+#echo DX_FLAG_chm=$DX_FLAG_chm
+#echo DX_FLAG_chi=$DX_FLAG_chi
+#echo DX_FLAG_rtf=$DX_FLAG_rtf
+#echo DX_FLAG_xml=$DX_FLAG_xml
+#echo DX_FLAG_pdf=$DX_FLAG_pdf
+#echo DX_FLAG_ps=$DX_FLAG_ps
+#echo DX_ENV=$DX_ENV
+])
diff --git a/ipc/chromium/src/third_party/libevent/m4/libevent_openssl.m4 b/ipc/chromium/src/third_party/libevent/m4/libevent_openssl.m4
new file mode 100644
index 0000000000..a5ea676200
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/libevent_openssl.m4
@@ -0,0 +1,61 @@
+dnl ######################################################################
+dnl OpenSSL support
+AC_DEFUN([LIBEVENT_OPENSSL], [
+AC_REQUIRE([NTP_PKG_CONFIG])dnl
+
+case "$enable_openssl" in
+ yes)
+ have_openssl=no
+ case "$PKG_CONFIG" in
+ '')
+ ;;
+ *)
+ OPENSSL_LIBS=`$PKG_CONFIG --libs openssl 2>/dev/null`
+ case "$OPENSSL_LIBS" in
+ '') ;;
+ *) OPENSSL_LIBS="$OPENSSL_LIBS $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD"
+ have_openssl=yes
+ ;;
+ esac
+ OPENSSL_INCS=`$PKG_CONFIG --cflags openssl 2>/dev/null`
+ ;;
+ esac
+ case "$have_openssl" in
+ yes) ;;
+ *)
+ save_LIBS="$LIBS"
+ LIBS=""
+ OPENSSL_LIBS=""
+ for lib in crypto eay32; do
+ # clear cache
+ unset ac_cv_search_SSL_new
+ AC_SEARCH_LIBS([SSL_new], [ssl ssl32],
+ [have_openssl=yes
+ OPENSSL_LIBS="$LIBS -l$lib $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD"],
+ [have_openssl=no],
+ [-l$lib $EV_LIB_GDI $EV_LIB_WS32 $OPENSSL_LIBADD])
+ LIBS="$save_LIBS"
+ test "$have_openssl" = "yes" && break
+ done
+ ;;
+ esac
+ CPPFLAGS_SAVE=$CPPFLAGS
+ CPPFLAGS="$CPPFLAGS $OPENSSL_INCS"
+ AC_CHECK_HEADERS([openssl/ssl.h], [], [have_openssl=no])
+ CPPFLAGS=$CPPFLAGS_SAVE
+ AC_SUBST(OPENSSL_INCS)
+ AC_SUBST(OPENSSL_LIBS)
+ case "$have_openssl" in
+ yes) AC_DEFINE(HAVE_OPENSSL, 1, [Define if the system has openssl]) ;;
+ *) AC_MSG_ERROR([openssl is a must but can not be found. You should add the \
+directory containing `openssl.pc' to the `PKG_CONFIG_PATH' environment variable, \
+or set `CFLAGS' and `LDFLAGS' directly for openssl, or use `--disable-openssl' \
+to disable support for openssl encryption])
+ ;;
+ esac
+ ;;
+esac
+
+# check if we have and should use openssl
+AM_CONDITIONAL(OPENSSL, [test "$enable_openssl" != "no" && test "$have_openssl" = "yes"])
+])
diff --git a/ipc/chromium/src/third_party/libevent/m4/ntp_pkg_config.m4 b/ipc/chromium/src/third_party/libevent/m4/ntp_pkg_config.m4
new file mode 100644
index 0000000000..1bce8a6e4d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/m4/ntp_pkg_config.m4
@@ -0,0 +1,27 @@
+dnl NTP_PKG_CONFIG -*- Autoconf -*-
+dnl
+dnl Look for pkg-config, which must be at least
+dnl $ntp_pkgconfig_min_version.
+dnl
+AC_DEFUN([NTP_PKG_CONFIG], [
+
+dnl lower the minimum version if you find an earlier one works
+ntp_pkgconfig_min_version='0.15.0'
+AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
+AS_UNSET([ac_cv_path_PKG_CONFIG])
+AS_UNSET([ac_cv_path_ac_pt_PKG_CONFIG])
+
+case "$PKG_CONFIG" in
+ /*)
+ AC_MSG_CHECKING([if pkg-config is at least version $ntp_pkgconfig_min_version])
+ if $PKG_CONFIG --atleast-pkgconfig-version $ntp_pkgconfig_min_version; then
+ AC_MSG_RESULT([yes])
+ else
+ AC_MSG_RESULT([no])
+ PKG_CONFIG=""
+ fi
+ ;;
+esac
+
+]) dnl NTP_PKG_CONFIG
+
diff --git a/ipc/chromium/src/third_party/libevent/mac/event2/event-config.h b/ipc/chromium/src/third_party/libevent/mac/event2/event-config.h
new file mode 100644
index 0000000000..e9a71e4767
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/mac/event2/event-config.h
@@ -0,0 +1,573 @@
+/* event2/event-config.h
+*
+* This file was generated by autoconf when libevent was built, and post-
+* processed by Libevent so that its macros would have a uniform prefix.
+*
+* DO NOT EDIT THIS FILE.
+*
+* Do not rely on macros in this file existing in later versions.
+*/
+
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if libevent should build without support for a debug mode */
+/* #undef EVENT__DISABLE_DEBUG_MODE */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define to 1 if you have the `accept4' function. */
+/* #undef EVENT__HAVE_ACCEPT4 */
+
+/* Define to 1 if you have the <afunix.h> header file. */
+/* #undef EVENT__HAVE_AFUNIX_H */
+
+/* Define to 1 if you have the `arc4random' function. */
+#define EVENT__HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+#define EVENT__HAVE_ARC4RANDOM_ADDRANDOM 1
+
+/* Define to 1 if you have the `arc4random_buf' function. */
+#define EVENT__HAVE_ARC4RANDOM_BUF 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+/* #undef EVENT__HAVE_CLOCK_GETTIME */
+
+/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_CTL_KERN 1
+
+/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
+ don't. */
+#define EVENT__HAVE_DECL_KERN_ARND 0
+
+/* Define if /dev/poll is available */
+/* #undef EVENT__HAVE_DEVPOLL */
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+/* #undef EVENT__HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_create1' function. */
+/* #undef EVENT__HAVE_EPOLL_CREATE1 */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef EVENT__HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define EVENT__HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the `eventfd' function. */
+/* #undef EVENT__HAVE_EVENTFD */
+
+/* Define if your system supports event ports */
+/* #undef EVENT__HAVE_EVENT_PORTS */
+
+/* Define to 1 if you have the `fcntl' function. */
+#define EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if the system has the type `fd_mask'. */
+#define EVENT__HAVE_FD_MASK 1
+
+/* Do we have getaddrinfo()? */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define EVENT__HAVE_GETEUID 1
+
+/* Define this if you have any gethostbyname_r() */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
+
+/* Define this if gethostbyname_r takes 3 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if gethostbyname_r takes 5 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if gethostbyname_r takes 6 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#define EVENT__HAVE_GETIFADDRS 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getrandom' function. */
+/* #undef EVENT__HAVE_GETRANDOM */
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define EVENT__HAVE_IFADDRS_H 1
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#define EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#define EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+#define EVENT__HAVE_ISSETUGID 1
+
+/* Define to 1 if you have the `kqueue' function. */
+#define EVENT__HAVE_KQUEUE 1
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+/* #undef EVENT__HAVE_LIBWS2_32 */
+
+/* Define if the system has zlib */
+#define EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+#define EVENT__HAVE_MACH_MACH_H 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+#define EVENT__HAVE_MACH_ABSOLUTE_TIME 1
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+#define EVENT__HAVE_MACH_MACH_TIME_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define if the system has openssl */
+/* #undef EVENT__HAVE_OPENSSL */
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+/* #undef EVENT__HAVE_OPENSSL_SSL_H */
+
+/* Define to 1 if you have the `pipe' function. */
+#define EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+/* #undef EVENT__HAVE_PIPE2 */
+
+/* Define to 1 if you have the `poll' function. */
+#define EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+/* #undef EVENT__HAVE_PORT_CREATE */
+
+/* Define to 1 if you have the <port.h> header file. */
+/* #undef EVENT__HAVE_PORT_H */
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+#define EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#define EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#define EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `setenv' function. */
+#define EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#define EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+#define EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef EVENT__HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+#define EVENT__HAVE_STRLCPY 1
+
+/* Define to 1 if you have the `strsep' function. */
+#define EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 */
+
+/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 */
+
+/* Define to 1 if the system has the type `struct linger'. */
+#define EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN 1
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN 1
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if you have the `sysctl' function. */
+#define EVENT__HAVE_SYSCTL 1
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_DEVPOLL_H */
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENTFD_H */
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+#define EVENT__HAVE_SYS_EVENT_H 1
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#define EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+/* #undef EVENT__HAVE_SYS_RANDOM_H */
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+/* #undef EVENT__HAVE_SYS_SENDFILE_H */
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+#define EVENT__HAVE_SYS_SYSCTL_H 1
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_TIMERFD_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#define EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define to 1 if you have the `timerfd_create' function. */
+/* #undef EVENT__HAVE_TIMERFD_CREATE */
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#define EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `usleep' function. */
+#define EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+#define EVENT__HAVE_WORKING_KQUEUE 1
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define EVENT__HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+/* #undef EVENT__HAVE__GMTIME64 */
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+/* #undef EVENT__HAVE__GMTIME64_S */
+
+/* Define to 1 if compiler have __FUNCTION__ */
+#define EVENT__HAVE___FUNCTION__ 1
+
+/* Define to 1 if compiler have __func__ */
+#define EVENT__HAVE___func__ 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define EVENT__LT_OBJDIR ".libs/"
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME "libevent"
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING "libevent 2.1.12-stable"
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME "libevent"
+
+/* Define to the home page for this package. */
+#define EVENT__PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION "2.1.12-stable"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* The size of `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG 8
+
+/* The size of `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#define EVENT__SIZEOF_OFF_T 8
+
+/* The size of `pthread_t', as computed by sizeof. */
+#define EVENT__SIZEOF_PTHREAD_T 8
+
+/* The size of `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#define EVENT__SIZEOF_SIZE_T 8
+
+/* The size of `time_t', as computed by sizeof. */
+#define EVENT__SIZEOF_TIME_T 8
+
+/* The size of `void *', as computed by sizeof. */
+#define EVENT__SIZEOF_VOID_P 8
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Enable large inode numbers on Mac OS X 10.5. */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+/* #undef _FILE_OFFSET_BITS */
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+/* #undef __func__ */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to unsigned int if you dont have it */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef ssize_t */
+
+#endif /* event2/event-config.h */
diff --git a/ipc/chromium/src/third_party/libevent/make-event-config.sed b/ipc/chromium/src/third_party/libevent/make-event-config.sed
new file mode 100644
index 0000000000..3dc404b5cc
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/make-event-config.sed
@@ -0,0 +1,27 @@
+# Sed script to postprocess config.h into event-config.h.
+
+1i\
+/* event2/event-config.h\
+ *\
+ * This file was generated by autoconf when libevent was built, and post-\
+ * processed by Libevent so that its macros would have a uniform prefix.\
+ *\
+ * DO NOT EDIT THIS FILE.\
+ *\
+ * Do not rely on macros in this file existing in later versions.\
+ */\
+\
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_\
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_\
+
+$a\
+\
+#endif /* event2/event-config.h */
+
+/#\( *\)undef STDC_HEADERS\>/b
+/#\( *\)define STDC_HEADERS\>/b
+
+# Only rewrite symbols starting with capitals
+s/#\( *\)define \([A-Z]\)/#\1define EVENT__\2/
+s/#\( *\)undef \([A-Z]\)/#\1undef EVENT__\2/
+s/#\( *\)if\(n*\)def \([A-Z]\)/#\1if\2def EVENT__\2/
diff --git a/ipc/chromium/src/third_party/libevent/make_epoll_table.py b/ipc/chromium/src/third_party/libevent/make_epoll_table.py
new file mode 100755
index 0000000000..1b15a91a67
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/make_epoll_table.py
@@ -0,0 +1,63 @@
+#!/usr/bin/python2
+
+def get(old,wc,rc,cc):
+ if ('xxx' in (rc, wc, cc)):
+ return "0",255
+
+ if ('add' in (rc, wc, cc)):
+ events = []
+ if rc == 'add' or (rc != 'del' and 'r' in old):
+ events.append("EPOLLIN")
+ if wc == 'add' or (wc != 'del' and 'w' in old):
+ events.append("EPOLLOUT")
+ if cc == 'add' or (cc != 'del' and 'c' in old):
+ events.append("EPOLLRDHUP")
+
+ if old == "0":
+ op = "EPOLL_CTL_ADD"
+ else:
+ op = "EPOLL_CTL_MOD"
+ return "|".join(events), op
+
+ if ('del' in (rc, wc, cc)):
+ delevents = []
+ modevents = []
+ op = "EPOLL_CTL_DEL"
+
+ if 'r' in old:
+ modevents.append("EPOLLIN")
+ if 'w' in old:
+ modevents.append("EPOLLOUT")
+ if 'c' in old:
+ modevents.append("EPOLLRDHUP")
+
+ for item, event in [(rc,"EPOLLIN"),
+ (wc,"EPOLLOUT"),
+ (cc,"EPOLLRDHUP")]:
+ if item == 'del':
+ delevents.append(event)
+ if event in modevents:
+ modevents.remove(event)
+
+ if modevents:
+ return "|".join(modevents), "EPOLL_CTL_MOD"
+ else:
+ return "|".join(delevents), "EPOLL_CTL_DEL"
+
+ return 0, 0
+
+
+def fmt(op, ev, old, wc, rc, cc):
+ entry = "{ %s, %s },"%(op, ev)
+ print "\t/* old=%3s, write:%3s, read:%3s, close:%3s */\n\t%s" % (
+ old, wc, rc, cc, entry)
+ return len(entry)
+
+for old in ('0','r','w','rw','c','cr','cw','crw'):
+ for wc in ('0', 'add', 'del', 'xxx'):
+ for rc in ('0', 'add', 'del', 'xxx'):
+ for cc in ('0', 'add', 'del', 'xxx'):
+
+ op,ev = get(old,wc,rc,cc)
+
+ fmt(op, ev, old, wc, rc, cc)
diff --git a/ipc/chromium/src/third_party/libevent/minheap-internal.h b/ipc/chromium/src/third_party/libevent/minheap-internal.h
new file mode 100644
index 0000000000..b3a0eb1fb5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/minheap-internal.h
@@ -0,0 +1,192 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Copyright (c) 2006 Maxim Yegorushkin <maxim.yegorushkin@gmail.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef MINHEAP_INTERNAL_H_INCLUDED_
+#define MINHEAP_INTERNAL_H_INCLUDED_
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "util-internal.h"
+#include "mm-internal.h"
+
+typedef struct min_heap
+{
+ struct event** p;
+ unsigned n, a;
+} min_heap_t;
+
+static inline void min_heap_ctor_(min_heap_t* s);
+static inline void min_heap_dtor_(min_heap_t* s);
+static inline void min_heap_elem_init_(struct event* e);
+static inline int min_heap_elt_is_top_(const struct event *e);
+static inline int min_heap_empty_(min_heap_t* s);
+static inline unsigned min_heap_size_(min_heap_t* s);
+static inline struct event* min_heap_top_(min_heap_t* s);
+static inline int min_heap_reserve_(min_heap_t* s, unsigned n);
+static inline int min_heap_push_(min_heap_t* s, struct event* e);
+static inline struct event* min_heap_pop_(min_heap_t* s);
+static inline int min_heap_adjust_(min_heap_t *s, struct event* e);
+static inline int min_heap_erase_(min_heap_t* s, struct event* e);
+static inline void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e);
+static inline void min_heap_shift_up_unconditional_(min_heap_t* s, unsigned hole_index, struct event* e);
+static inline void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e);
+
+#define min_heap_elem_greater(a, b) \
+ (evutil_timercmp(&(a)->ev_timeout, &(b)->ev_timeout, >))
+
+void min_heap_ctor_(min_heap_t* s) { s->p = 0; s->n = 0; s->a = 0; }
+void min_heap_dtor_(min_heap_t* s) { if (s->p) mm_free(s->p); }
+void min_heap_elem_init_(struct event* e) { e->ev_timeout_pos.min_heap_idx = -1; }
+int min_heap_empty_(min_heap_t* s) { return 0u == s->n; }
+unsigned min_heap_size_(min_heap_t* s) { return s->n; }
+struct event* min_heap_top_(min_heap_t* s) { return s->n ? *s->p : 0; }
+
+int min_heap_push_(min_heap_t* s, struct event* e)
+{
+ if (s->n == UINT32_MAX || min_heap_reserve_(s, s->n + 1))
+ return -1;
+ min_heap_shift_up_(s, s->n++, e);
+ return 0;
+}
+
+struct event* min_heap_pop_(min_heap_t* s)
+{
+ if (s->n)
+ {
+ struct event* e = *s->p;
+ min_heap_shift_down_(s, 0u, s->p[--s->n]);
+ e->ev_timeout_pos.min_heap_idx = -1;
+ return e;
+ }
+ return 0;
+}
+
+int min_heap_elt_is_top_(const struct event *e)
+{
+ return e->ev_timeout_pos.min_heap_idx == 0;
+}
+
+int min_heap_erase_(min_heap_t* s, struct event* e)
+{
+ if (-1 != e->ev_timeout_pos.min_heap_idx)
+ {
+ struct event *last = s->p[--s->n];
+ unsigned parent = (e->ev_timeout_pos.min_heap_idx - 1) / 2;
+ /* we replace e with the last element in the heap. We might need to
+ shift it upward if it is less than its parent, or downward if it is
+ greater than one or both its children. Since the children are known
+ to be less than the parent, it can't need to shift both up and
+ down. */
+ if (e->ev_timeout_pos.min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], last))
+ min_heap_shift_up_unconditional_(s, e->ev_timeout_pos.min_heap_idx, last);
+ else
+ min_heap_shift_down_(s, e->ev_timeout_pos.min_heap_idx, last);
+ e->ev_timeout_pos.min_heap_idx = -1;
+ return 0;
+ }
+ return -1;
+}
+
+int min_heap_adjust_(min_heap_t *s, struct event *e)
+{
+ if (-1 == e->ev_timeout_pos.min_heap_idx) {
+ return min_heap_push_(s, e);
+ } else {
+ unsigned parent = (e->ev_timeout_pos.min_heap_idx - 1) / 2;
+ /* The position of e has changed; we shift it up or down
+ * as needed. We can't need to do both. */
+ if (e->ev_timeout_pos.min_heap_idx > 0 && min_heap_elem_greater(s->p[parent], e))
+ min_heap_shift_up_unconditional_(s, e->ev_timeout_pos.min_heap_idx, e);
+ else
+ min_heap_shift_down_(s, e->ev_timeout_pos.min_heap_idx, e);
+ return 0;
+ }
+}
+
+int min_heap_reserve_(min_heap_t* s, unsigned n)
+{
+ if (s->a < n)
+ {
+ struct event** p;
+ unsigned a = s->a ? s->a * 2 : 8;
+ if (a < n)
+ a = n;
+#if (SIZE_MAX == UINT32_MAX)
+ if (a > SIZE_MAX / sizeof *p)
+ return -1;
+#endif
+ if (!(p = (struct event**)mm_realloc(s->p, a * sizeof *p)))
+ return -1;
+ s->p = p;
+ s->a = a;
+ }
+ return 0;
+}
+
+void min_heap_shift_up_unconditional_(min_heap_t* s, unsigned hole_index, struct event* e)
+{
+ unsigned parent = (hole_index - 1) / 2;
+ do
+ {
+ (s->p[hole_index] = s->p[parent])->ev_timeout_pos.min_heap_idx = hole_index;
+ hole_index = parent;
+ parent = (hole_index - 1) / 2;
+ } while (hole_index && min_heap_elem_greater(s->p[parent], e));
+ (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
+}
+
+void min_heap_shift_up_(min_heap_t* s, unsigned hole_index, struct event* e)
+{
+ unsigned parent = (hole_index - 1) / 2;
+ while (hole_index && min_heap_elem_greater(s->p[parent], e))
+ {
+ (s->p[hole_index] = s->p[parent])->ev_timeout_pos.min_heap_idx = hole_index;
+ hole_index = parent;
+ parent = (hole_index - 1) / 2;
+ }
+ (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
+}
+
+void min_heap_shift_down_(min_heap_t* s, unsigned hole_index, struct event* e)
+{
+ unsigned min_child = 2 * (hole_index + 1);
+ while (min_child <= s->n)
+ {
+ min_child -= min_child == s->n || min_heap_elem_greater(s->p[min_child], s->p[min_child - 1]);
+ if (!(min_heap_elem_greater(e, s->p[min_child])))
+ break;
+ (s->p[hole_index] = s->p[min_child])->ev_timeout_pos.min_heap_idx = hole_index;
+ hole_index = min_child;
+ min_child = 2 * (hole_index + 1);
+ }
+ (s->p[hole_index] = e)->ev_timeout_pos.min_heap_idx = hole_index;
+}
+
+#endif /* MINHEAP_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/mm-internal.h b/ipc/chromium/src/third_party/libevent/mm-internal.h
new file mode 100644
index 0000000000..7a95c99561
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/mm-internal.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef MM_INTERNAL_H_INCLUDED_
+#define MM_INTERNAL_H_INCLUDED_
+
+#include <sys/types.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+/* Internal use only: Memory allocation functions. We give them nice short
+ * mm_names for our own use, but make sure that the symbols have longer names
+ * so they don't conflict with other libraries (like, say, libmm). */
+
+/** Allocate uninitialized memory.
+ *
+ * @return On success, return a pointer to sz newly allocated bytes.
+ * On failure, set errno to ENOMEM and return NULL.
+ * If the argument sz is 0, simply return NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+void *event_mm_malloc_(size_t sz);
+
+/** Allocate memory initialized to zero.
+ *
+ * @return On success, return a pointer to (count * size) newly allocated
+ * bytes, initialized to zero.
+ * On failure, or if the product would result in an integer overflow,
+ * set errno to ENOMEM and return NULL.
+ * If either arguments are 0, simply return NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+void *event_mm_calloc_(size_t count, size_t size);
+
+/** Duplicate a string.
+ *
+ * @return On success, return a pointer to a newly allocated duplicate
+ * of a string.
+ * Set errno to ENOMEM and return NULL if a memory allocation error
+ * occurs (or would occur) in the process.
+ * If the argument str is NULL, set errno to EINVAL and return NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+char *event_mm_strdup_(const char *str);
+
+EVENT2_EXPORT_SYMBOL
+void *event_mm_realloc_(void *p, size_t sz);
+EVENT2_EXPORT_SYMBOL
+void event_mm_free_(void *p);
+#define mm_malloc(sz) event_mm_malloc_(sz)
+#define mm_calloc(count, size) event_mm_calloc_((count), (size))
+#define mm_strdup(s) event_mm_strdup_(s)
+#define mm_realloc(p, sz) event_mm_realloc_((p), (sz))
+#define mm_free(p) event_mm_free_(p)
+#else
+#define mm_malloc(sz) malloc(sz)
+#define mm_calloc(n, sz) calloc((n), (sz))
+#define mm_strdup(s) strdup(s)
+#define mm_realloc(p, sz) realloc((p), (sz))
+#define mm_free(p) free(p)
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/openssl-compat.h b/ipc/chromium/src/third_party/libevent/openssl-compat.h
new file mode 100644
index 0000000000..a23e34251b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/openssl-compat.h
@@ -0,0 +1,47 @@
+#ifndef OPENSSL_COMPAT_H
+#define OPENSSL_COMPAT_H
+
+#include <openssl/bio.h>
+#include "util-internal.h"
+
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+
+static inline BIO_METHOD *BIO_meth_new(int type, const char *name)
+{
+ BIO_METHOD *biom = calloc(1, sizeof(BIO_METHOD));
+
+ if (biom != NULL) {
+ biom->type = type;
+ biom->name = name;
+ }
+ return biom;
+}
+
+#define BIO_meth_set_write(b, f) (b)->bwrite = (f)
+#define BIO_meth_set_read(b, f) (b)->bread = (f)
+#define BIO_meth_set_puts(b, f) (b)->bputs = (f)
+#define BIO_meth_set_ctrl(b, f) (b)->ctrl = (f)
+#define BIO_meth_set_create(b, f) (b)->create = (f)
+#define BIO_meth_set_destroy(b, f) (b)->destroy = (f)
+
+#define BIO_set_init(b, val) (b)->init = (val)
+#define BIO_set_data(b, val) (b)->ptr = (val)
+#define BIO_set_shutdown(b, val) (b)->shutdown = (val)
+#define BIO_get_init(b) (b)->init
+#define BIO_get_data(b) (b)->ptr
+#define BIO_get_shutdown(b) (b)->shutdown
+
+#define TLS_method SSLv23_method
+
+#define X509_getm_notBefore X509_get_notBefore
+#define X509_getm_notAfter X509_get_notAfter
+
+#endif /* (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) */
+
+#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x20700000L
+#define BIO_get_init(b) (b)->init
+#endif
+
+#endif /* OPENSSL_COMPAT_H */
diff --git a/ipc/chromium/src/third_party/libevent/poll.c b/ipc/chromium/src/third_party/libevent/poll.c
new file mode 100644
index 0000000000..c3c9aac52a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/poll.c
@@ -0,0 +1,358 @@
+/* $OpenBSD: poll.c,v 1.2 2002/06/25 15:50:15 mickey Exp $ */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_POLL
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <poll.h>
+#include <signal.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "time-internal.h"
+
+/* Since Linux 2.6.17, poll is able to report about peer half-closed connection
+ using special POLLRDHUP flag on a read event.
+*/
+#if !defined(POLLRDHUP)
+#define POLLRDHUP 0
+#define EARLY_CLOSE_IF_HAVE_RDHUP 0
+#else
+#define EARLY_CLOSE_IF_HAVE_RDHUP EV_FEATURE_EARLY_CLOSE
+#endif
+
+
+struct pollidx {
+ int idxplus1;
+};
+
+struct pollop {
+ int event_count; /* Highest number alloc */
+ int nfds; /* Highest number used */
+ int realloc_copy; /* True iff we must realloc
+ * event_set_copy */
+ struct pollfd *event_set;
+ struct pollfd *event_set_copy;
+};
+
+static void *poll_init(struct event_base *);
+static int poll_add(struct event_base *, int, short old, short events, void *idx);
+static int poll_del(struct event_base *, int, short old, short events, void *idx);
+static int poll_dispatch(struct event_base *, struct timeval *);
+static void poll_dealloc(struct event_base *);
+
+const struct eventop pollops = {
+ "poll",
+ poll_init,
+ poll_add,
+ poll_del,
+ poll_dispatch,
+ poll_dealloc,
+ 1, /* need_reinit */
+ EV_FEATURE_FDS|EARLY_CLOSE_IF_HAVE_RDHUP,
+ sizeof(struct pollidx),
+};
+
+static void *
+poll_init(struct event_base *base)
+{
+ struct pollop *pollop;
+
+ if (!(pollop = mm_calloc(1, sizeof(struct pollop))))
+ return (NULL);
+
+ evsig_init_(base);
+
+ evutil_weakrand_seed_(&base->weakrand_seed, 0);
+
+ return (pollop);
+}
+
+#ifdef CHECK_INVARIANTS
+static void
+poll_check_ok(struct pollop *pop)
+{
+ int i, idx;
+ struct event *ev;
+
+ for (i = 0; i < pop->fd_count; ++i) {
+ idx = pop->idxplus1_by_fd[i]-1;
+ if (idx < 0)
+ continue;
+ EVUTIL_ASSERT(pop->event_set[idx].fd == i);
+ }
+ for (i = 0; i < pop->nfds; ++i) {
+ struct pollfd *pfd = &pop->event_set[i];
+ EVUTIL_ASSERT(pop->idxplus1_by_fd[pfd->fd] == i+1);
+ }
+}
+#else
+#define poll_check_ok(pop)
+#endif
+
+static int
+poll_dispatch(struct event_base *base, struct timeval *tv)
+{
+ int res, i, j, nfds;
+ long msec = -1;
+ struct pollop *pop = base->evbase;
+ struct pollfd *event_set;
+
+ poll_check_ok(pop);
+
+ nfds = pop->nfds;
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (base->th_base_lock) {
+ /* If we're using this backend in a multithreaded setting,
+ * then we need to work on a copy of event_set, so that we can
+ * let other threads modify the main event_set while we're
+ * polling. If we're not multithreaded, then we'll skip the
+ * copy step here to save memory and time. */
+ if (pop->realloc_copy) {
+ struct pollfd *tmp = mm_realloc(pop->event_set_copy,
+ pop->event_count * sizeof(struct pollfd));
+ if (tmp == NULL) {
+ event_warn("realloc");
+ return -1;
+ }
+ pop->event_set_copy = tmp;
+ pop->realloc_copy = 0;
+ }
+ memcpy(pop->event_set_copy, pop->event_set,
+ sizeof(struct pollfd)*nfds);
+ event_set = pop->event_set_copy;
+ } else {
+ event_set = pop->event_set;
+ }
+#else
+ event_set = pop->event_set;
+#endif
+
+ if (tv != NULL) {
+ msec = evutil_tv_to_msec_(tv);
+ if (msec < 0 || msec > INT_MAX)
+ msec = INT_MAX;
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = poll(event_set, nfds, msec);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ if (res == -1) {
+ if (errno != EINTR) {
+ event_warn("poll");
+ return (-1);
+ }
+
+ return (0);
+ }
+
+ event_debug(("%s: poll reports %d", __func__, res));
+
+ if (res == 0 || nfds == 0)
+ return (0);
+
+ i = evutil_weakrand_range_(&base->weakrand_seed, nfds);
+ for (j = 0; j < nfds; j++) {
+ int what;
+ if (++i == nfds)
+ i = 0;
+ what = event_set[i].revents;
+ if (!what)
+ continue;
+
+ res = 0;
+
+ /* If the file gets closed notify */
+ if (what & (POLLHUP|POLLERR|POLLNVAL))
+ what |= POLLIN|POLLOUT;
+ if (what & POLLIN)
+ res |= EV_READ;
+ if (what & POLLOUT)
+ res |= EV_WRITE;
+ if (what & POLLRDHUP)
+ res |= EV_CLOSED;
+ if (res == 0)
+ continue;
+
+ evmap_io_active_(base, event_set[i].fd, res);
+ }
+
+ return (0);
+}
+
+static int
+poll_add(struct event_base *base, int fd, short old, short events, void *idx_)
+{
+ struct pollop *pop = base->evbase;
+ struct pollfd *pfd = NULL;
+ struct pollidx *idx = idx_;
+ int i;
+
+ EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+ if (!(events & (EV_READ|EV_WRITE|EV_CLOSED)))
+ return (0);
+
+ poll_check_ok(pop);
+ if (pop->nfds + 1 >= pop->event_count) {
+ struct pollfd *tmp_event_set;
+ int tmp_event_count;
+
+ if (pop->event_count < 32)
+ tmp_event_count = 32;
+ else
+ tmp_event_count = pop->event_count * 2;
+
+ /* We need more file descriptors */
+ tmp_event_set = mm_realloc(pop->event_set,
+ tmp_event_count * sizeof(struct pollfd));
+ if (tmp_event_set == NULL) {
+ event_warn("realloc");
+ return (-1);
+ }
+ pop->event_set = tmp_event_set;
+
+ pop->event_count = tmp_event_count;
+ pop->realloc_copy = 1;
+ }
+
+ i = idx->idxplus1 - 1;
+
+ if (i >= 0) {
+ pfd = &pop->event_set[i];
+ } else {
+ i = pop->nfds++;
+ pfd = &pop->event_set[i];
+ pfd->events = 0;
+ pfd->fd = fd;
+ idx->idxplus1 = i + 1;
+ }
+
+ pfd->revents = 0;
+ if (events & EV_WRITE)
+ pfd->events |= POLLOUT;
+ if (events & EV_READ)
+ pfd->events |= POLLIN;
+ if (events & EV_CLOSED)
+ pfd->events |= POLLRDHUP;
+ poll_check_ok(pop);
+
+ return (0);
+}
+
+/*
+ * Nothing to be done here.
+ */
+
+static int
+poll_del(struct event_base *base, int fd, short old, short events, void *idx_)
+{
+ struct pollop *pop = base->evbase;
+ struct pollfd *pfd = NULL;
+ struct pollidx *idx = idx_;
+ int i;
+
+ EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+ if (!(events & (EV_READ|EV_WRITE|EV_CLOSED)))
+ return (0);
+
+ poll_check_ok(pop);
+ i = idx->idxplus1 - 1;
+ if (i < 0)
+ return (-1);
+
+ /* Do we still want to read or write? */
+ pfd = &pop->event_set[i];
+ if (events & EV_READ)
+ pfd->events &= ~POLLIN;
+ if (events & EV_WRITE)
+ pfd->events &= ~POLLOUT;
+ if (events & EV_CLOSED)
+ pfd->events &= ~POLLRDHUP;
+ poll_check_ok(pop);
+ if (pfd->events)
+ /* Another event cares about that fd. */
+ return (0);
+
+ /* Okay, so we aren't interested in that fd anymore. */
+ idx->idxplus1 = 0;
+
+ --pop->nfds;
+ if (i != pop->nfds) {
+ /*
+ * Shift the last pollfd down into the now-unoccupied
+ * position.
+ */
+ memcpy(&pop->event_set[i], &pop->event_set[pop->nfds],
+ sizeof(struct pollfd));
+ idx = evmap_io_get_fdinfo_(&base->io, pop->event_set[i].fd);
+ EVUTIL_ASSERT(idx);
+ EVUTIL_ASSERT(idx->idxplus1 == pop->nfds + 1);
+ idx->idxplus1 = i + 1;
+ }
+
+ poll_check_ok(pop);
+ return (0);
+}
+
+static void
+poll_dealloc(struct event_base *base)
+{
+ struct pollop *pop = base->evbase;
+
+ evsig_dealloc_(base);
+ if (pop->event_set)
+ mm_free(pop->event_set);
+ if (pop->event_set_copy)
+ mm_free(pop->event_set_copy);
+
+ memset(pop, 0, sizeof(struct pollop));
+ mm_free(pop);
+}
+
+#endif /* EVENT__HAVE_POLL */
diff --git a/ipc/chromium/src/third_party/libevent/ratelim-internal.h b/ipc/chromium/src/third_party/libevent/ratelim-internal.h
new file mode 100644
index 0000000000..6cc1cdde2c
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/ratelim-internal.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef RATELIM_INTERNAL_H_INCLUDED_
+#define RATELIM_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/util.h"
+
+/** A token bucket is an internal structure that tracks how many bytes we are
+ * currently willing to read or write on a given bufferevent or group of
+ * bufferevents */
+struct ev_token_bucket {
+ /** How many bytes are we willing to read or write right now? These
+ * values are signed so that we can do "defecit spending" */
+ ev_ssize_t read_limit, write_limit;
+ /** When was this bucket last updated? Measured in abstract 'ticks'
+ * relative to the token bucket configuration. */
+ ev_uint32_t last_updated;
+};
+
+/** Configuration info for a token bucket or set of token buckets. */
+struct ev_token_bucket_cfg {
+ /** How many bytes are we willing to read on average per tick? */
+ size_t read_rate;
+ /** How many bytes are we willing to read at most in any one tick? */
+ size_t read_maximum;
+ /** How many bytes are we willing to write on average per tick? */
+ size_t write_rate;
+ /** How many bytes are we willing to write at most in any one tick? */
+ size_t write_maximum;
+
+ /* How long is a tick? Note that fractions of a millisecond are
+ * ignored. */
+ struct timeval tick_timeout;
+
+ /* How long is a tick, in milliseconds? Derived from tick_timeout. */
+ unsigned msec_per_tick;
+};
+
+/** The current tick is 'current_tick': add bytes to 'bucket' as specified in
+ * 'cfg'. */
+int ev_token_bucket_update_(struct ev_token_bucket *bucket,
+ const struct ev_token_bucket_cfg *cfg,
+ ev_uint32_t current_tick);
+
+/** In which tick does 'tv' fall according to 'cfg'? Note that ticks can
+ * overflow easily; your code needs to handle this. */
+ev_uint32_t ev_token_bucket_get_tick_(const struct timeval *tv,
+ const struct ev_token_bucket_cfg *cfg);
+
+/** Adjust 'bucket' to respect 'cfg', and note that it was last updated in
+ * 'current_tick'. If 'reinitialize' is true, we are changing the
+ * configuration of 'bucket'; otherwise, we are setting it up for the first
+ * time.
+ */
+int ev_token_bucket_init_(struct ev_token_bucket *bucket,
+ const struct ev_token_bucket_cfg *cfg,
+ ev_uint32_t current_tick,
+ int reinitialize);
+
+int bufferevent_remove_from_rate_limit_group_internal_(struct bufferevent *bev,
+ int unsuspend);
+
+/** Decrease the read limit of 'b' by 'n' bytes */
+#define ev_token_bucket_decrement_read(b,n) \
+ do { \
+ (b)->read_limit -= (n); \
+ } while (0)
+/** Decrease the write limit of 'b' by 'n' bytes */
+#define ev_token_bucket_decrement_write(b,n) \
+ do { \
+ (b)->write_limit -= (n); \
+ } while (0)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/sample/dns-example.c b/ipc/chromium/src/third_party/libevent/sample/dns-example.c
new file mode 100644
index 0000000000..2d07c3874b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/dns-example.c
@@ -0,0 +1,264 @@
+/*
+ This example code shows how to use the high-level, low-level, and
+ server-level interfaces of evdns.
+
+ XXX It's pretty ugly and should probably be cleaned up.
+ */
+
+#include <event2/event-config.h>
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../ipv6-internal.h"
+
+#include <sys/types.h>
+
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <getopt.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/dns.h>
+#include <event2/dns_struct.h>
+#include <event2/util.h>
+
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define u32 ev_uint32_t
+#define u8 ev_uint8_t
+
+static const char *
+debug_ntoa(u32 address)
+{
+ static char buf[32];
+ u32 a = ntohl(address);
+ evutil_snprintf(buf, sizeof(buf), "%d.%d.%d.%d",
+ (int)(u8)((a>>24)&0xff),
+ (int)(u8)((a>>16)&0xff),
+ (int)(u8)((a>>8 )&0xff),
+ (int)(u8)((a )&0xff));
+ return buf;
+}
+
+static void
+main_callback(int result, char type, int count, int ttl,
+ void *addrs, void *orig) {
+ char *n = (char*)orig;
+ int i;
+ for (i = 0; i < count; ++i) {
+ if (type == DNS_IPv4_A) {
+ printf("%s: %s\n", n, debug_ntoa(((u32*)addrs)[i]));
+ } else if (type == DNS_PTR) {
+ printf("%s: %s\n", n, ((char**)addrs)[i]);
+ }
+ }
+ if (!count) {
+ printf("%s: No answer (%d)\n", n, result);
+ }
+ fflush(stdout);
+}
+
+static void
+gai_callback(int err, struct evutil_addrinfo *ai, void *arg)
+{
+ const char *name = arg;
+ int i;
+ struct evutil_addrinfo *first_ai = ai;
+
+ if (err) {
+ printf("%s: %s\n", name, evutil_gai_strerror(err));
+ }
+ if (ai && ai->ai_canonname)
+ printf(" %s ==> %s\n", name, ai->ai_canonname);
+ for (i=0; ai; ai = ai->ai_next, ++i) {
+ char buf[128];
+ if (ai->ai_family == PF_INET) {
+ struct sockaddr_in *sin =
+ (struct sockaddr_in*)ai->ai_addr;
+ evutil_inet_ntop(AF_INET, &sin->sin_addr, buf,
+ sizeof(buf));
+ printf("[%d] %s: %s\n",i,name,buf);
+ } else {
+ struct sockaddr_in6 *sin6 =
+ (struct sockaddr_in6*)ai->ai_addr;
+ evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
+ sizeof(buf));
+ printf("[%d] %s: %s\n",i,name,buf);
+ }
+ }
+
+ if (first_ai)
+ evutil_freeaddrinfo(first_ai);
+}
+
+static void
+evdns_server_callback(struct evdns_server_request *req, void *data)
+{
+ int i, r;
+ (void)data;
+ /* dummy; give 192.168.11.11 as an answer for all A questions,
+ * give foo.bar.example.com as an answer for all PTR questions. */
+ for (i = 0; i < req->nquestions; ++i) {
+ u32 ans = htonl(0xc0a80b0bUL);
+ if (req->questions[i]->type == EVDNS_TYPE_A &&
+ req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+ printf(" -- replying for %s (A)\n", req->questions[i]->name);
+ r = evdns_server_request_add_a_reply(req, req->questions[i]->name,
+ 1, &ans, 10);
+ if (r<0)
+ printf("eeep, didn't work.\n");
+ } else if (req->questions[i]->type == EVDNS_TYPE_PTR &&
+ req->questions[i]->dns_question_class == EVDNS_CLASS_INET) {
+ printf(" -- replying for %s (PTR)\n", req->questions[i]->name);
+ r = evdns_server_request_add_ptr_reply(req, NULL, req->questions[i]->name,
+ "foo.bar.example.com", 10);
+ if (r<0)
+ printf("ugh, no luck");
+ } else {
+ printf(" -- skipping %s [%d %d]\n", req->questions[i]->name,
+ req->questions[i]->type, req->questions[i]->dns_question_class);
+ }
+ }
+
+ r = evdns_server_request_respond(req, 0);
+ if (r<0)
+ printf("eeek, couldn't send reply.\n");
+}
+
+static int verbose = 0;
+
+static void
+logfn(int is_warn, const char *msg) {
+ if (!is_warn && !verbose)
+ return;
+ fprintf(stderr, "%s: %s\n", is_warn?"WARN":"INFO", msg);
+}
+
+int
+main(int c, char **v) {
+ struct options {
+ int reverse;
+ int use_getaddrinfo;
+ int servertest;
+ const char *resolv_conf;
+ const char *ns;
+ };
+ struct options o;
+ int opt;
+ struct event_base *event_base = NULL;
+ struct evdns_base *evdns_base = NULL;
+
+ memset(&o, 0, sizeof(o));
+
+ if (c < 2) {
+ fprintf(stderr, "syntax: %s [-x] [-v] [-c resolv.conf] [-s ns] hostname\n", v[0]);
+ fprintf(stderr, "syntax: %s [-T]\n", v[0]);
+ return 1;
+ }
+
+ while ((opt = getopt(c, v, "xvc:Ts:g")) != -1) {
+ switch (opt) {
+ case 'x': o.reverse = 1; break;
+ case 'v': ++verbose; break;
+ case 'g': o.use_getaddrinfo = 1; break;
+ case 'T': o.servertest = 1; break;
+ case 'c': o.resolv_conf = optarg; break;
+ case 's': o.ns = optarg; break;
+ default : fprintf(stderr, "Unknown option %c\n", opt); break;
+ }
+ }
+
+#ifdef _WIN32
+ {
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+ }
+#endif
+
+ event_base = event_base_new();
+ evdns_base = evdns_base_new(event_base, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+ evdns_set_log_fn(logfn);
+
+ if (o.servertest) {
+ evutil_socket_t sock;
+ struct sockaddr_in my_addr;
+ sock = socket(PF_INET, SOCK_DGRAM, 0);
+ if (sock == -1) {
+ perror("socket");
+ exit(1);
+ }
+ evutil_make_socket_nonblocking(sock);
+ my_addr.sin_family = AF_INET;
+ my_addr.sin_port = htons(10053);
+ my_addr.sin_addr.s_addr = INADDR_ANY;
+ if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr))<0) {
+ perror("bind");
+ exit(1);
+ }
+ evdns_add_server_port_with_base(event_base, sock, 0, evdns_server_callback, NULL);
+ }
+ if (optind < c) {
+ int res;
+#ifdef _WIN32
+ if (o.resolv_conf == NULL && !o.ns)
+ res = evdns_base_config_windows_nameservers(evdns_base);
+ else
+#endif
+ if (o.ns)
+ res = evdns_base_nameserver_ip_add(evdns_base, o.ns);
+ else
+ res = evdns_base_resolv_conf_parse(evdns_base,
+ DNS_OPTION_NAMESERVERS, o.resolv_conf);
+
+ if (res) {
+ fprintf(stderr, "Couldn't configure nameservers\n");
+ return 1;
+ }
+ }
+
+ printf("EVUTIL_AI_CANONNAME in example = %d\n", EVUTIL_AI_CANONNAME);
+ for (; optind < c; ++optind) {
+ if (o.reverse) {
+ struct in_addr addr;
+ if (evutil_inet_pton(AF_INET, v[optind], &addr)!=1) {
+ fprintf(stderr, "Skipping non-IP %s\n", v[optind]);
+ continue;
+ }
+ fprintf(stderr, "resolving %s...\n",v[optind]);
+ evdns_base_resolve_reverse(evdns_base, &addr, 0, main_callback, v[optind]);
+ } else if (o.use_getaddrinfo) {
+ struct evutil_addrinfo hints;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_protocol = IPPROTO_TCP;
+ hints.ai_flags = EVUTIL_AI_CANONNAME;
+ fprintf(stderr, "resolving (fwd) %s...\n",v[optind]);
+ evdns_getaddrinfo(evdns_base, v[optind], NULL, &hints,
+ gai_callback, v[optind]);
+ } else {
+ fprintf(stderr, "resolving (fwd) %s...\n",v[optind]);
+ evdns_base_resolve_ipv4(evdns_base, v[optind], 0, main_callback, v[optind]);
+ }
+ }
+ fflush(stdout);
+ event_base_dispatch(event_base);
+ evdns_base_free(evdns_base, 1);
+ event_base_free(event_base);
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/sample/event-read-fifo.c b/ipc/chromium/src/third_party/libevent/sample/event-read-fifo.c
new file mode 100644
index 0000000000..a17b9bd9ae
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/event-read-fifo.c
@@ -0,0 +1,162 @@
+/*
+ * This sample code shows how to use Libevent to read from a named pipe.
+ * XXX This code could make better use of the Libevent interfaces.
+ *
+ * XXX This does not work on Windows; ignore everything inside the _WIN32 block.
+ *
+ * On UNIX, compile with:
+ * cc -I/usr/local/include -o event-read-fifo event-read-fifo.c \
+ * -L/usr/local/lib -levent
+ */
+
+#include <event2/event-config.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifndef _WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <signal.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event2/event.h>
+
+static void
+fifo_read(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[255];
+ int len;
+ struct event *ev = arg;
+#ifdef _WIN32
+ DWORD dwBytesRead;
+#endif
+
+ fprintf(stderr, "fifo_read called with fd: %d, event: %d, arg: %p\n",
+ (int)fd, event, arg);
+#ifdef _WIN32
+ len = ReadFile((HANDLE)fd, buf, sizeof(buf) - 1, &dwBytesRead, NULL);
+
+ /* Check for end of file. */
+ if (len && dwBytesRead == 0) {
+ fprintf(stderr, "End Of File");
+ event_del(ev);
+ return;
+ }
+
+ buf[dwBytesRead] = '\0';
+#else
+ len = read(fd, buf, sizeof(buf) - 1);
+
+ if (len <= 0) {
+ if (len == -1)
+ perror("read");
+ else if (len == 0)
+ fprintf(stderr, "Connection closed\n");
+ event_del(ev);
+ event_base_loopbreak(event_get_base(ev));
+ return;
+ }
+
+ buf[len] = '\0';
+#endif
+ fprintf(stdout, "Read: %s\n", buf);
+}
+
+/* On Unix, cleanup event.fifo if SIGINT is received. */
+#ifndef _WIN32
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event_base *base = arg;
+ event_base_loopbreak(base);
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+ struct event *evfifo;
+ struct event_base* base;
+#ifdef _WIN32
+ HANDLE socket;
+ /* Open a file. */
+ socket = CreateFileA("test.txt", /* open File */
+ GENERIC_READ, /* open for reading */
+ 0, /* do not share */
+ NULL, /* no security */
+ OPEN_EXISTING, /* existing file only */
+ FILE_ATTRIBUTE_NORMAL, /* normal file */
+ NULL); /* no attr. template */
+
+ if (socket == INVALID_HANDLE_VALUE)
+ return 1;
+
+#else
+ struct event *signal_int;
+ struct stat st;
+ const char *fifo = "event.fifo";
+ int socket;
+
+ if (lstat(fifo, &st) == 0) {
+ if ((st.st_mode & S_IFMT) == S_IFREG) {
+ errno = EEXIST;
+ perror("lstat");
+ exit(1);
+ }
+ }
+
+ unlink(fifo);
+ if (mkfifo(fifo, 0600) == -1) {
+ perror("mkfifo");
+ exit(1);
+ }
+
+ socket = open(fifo, O_RDONLY | O_NONBLOCK, 0);
+
+ if (socket == -1) {
+ perror("open");
+ exit(1);
+ }
+
+ fprintf(stderr, "Write data to %s\n", fifo);
+#endif
+ /* Initialize the event library */
+ base = event_base_new();
+
+ /* Initialize one event */
+#ifdef _WIN32
+ evfifo = event_new(base, (evutil_socket_t)socket, EV_READ|EV_PERSIST, fifo_read,
+ event_self_cbarg());
+#else
+ /* catch SIGINT so that event.fifo can be cleaned up */
+ signal_int = evsignal_new(base, SIGINT, signal_cb, base);
+ event_add(signal_int, NULL);
+
+ evfifo = event_new(base, socket, EV_READ|EV_PERSIST, fifo_read,
+ event_self_cbarg());
+#endif
+
+ /* Add it to the active events, without a timeout */
+ event_add(evfifo, NULL);
+
+ event_base_dispatch(base);
+ event_base_free(base);
+#ifdef _WIN32
+ CloseHandle(socket);
+#else
+ close(socket);
+ unlink(fifo);
+#endif
+ libevent_global_shutdown();
+ return (0);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/sample/hello-world.c b/ipc/chromium/src/third_party/libevent/sample/hello-world.c
new file mode 100644
index 0000000000..a13e06af61
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/hello-world.c
@@ -0,0 +1,140 @@
+/*
+ This example program provides a trivial server program that listens for TCP
+ connections on port 9995. When they arrive, it writes a short message to
+ each client connection, and closes each connection once it is flushed.
+
+ Where possible, it exits cleanly in response to a SIGINT (ctrl-c).
+*/
+
+
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+#include <signal.h>
+#ifndef _WIN32
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+# include <arpa/inet.h>
+# endif
+#include <sys/socket.h>
+#endif
+
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+#include <event2/event.h>
+
+static const char MESSAGE[] = "Hello, World!\n";
+
+static const int PORT = 9995;
+
+static void listener_cb(struct evconnlistener *, evutil_socket_t,
+ struct sockaddr *, int socklen, void *);
+static void conn_writecb(struct bufferevent *, void *);
+static void conn_eventcb(struct bufferevent *, short, void *);
+static void signal_cb(evutil_socket_t, short, void *);
+
+int
+main(int argc, char **argv)
+{
+ struct event_base *base;
+ struct evconnlistener *listener;
+ struct event *signal_event;
+
+ struct sockaddr_in sin = {0};
+#ifdef _WIN32
+ WSADATA wsa_data;
+ WSAStartup(0x0201, &wsa_data);
+#endif
+
+ base = event_base_new();
+ if (!base) {
+ fprintf(stderr, "Could not initialize libevent!\n");
+ return 1;
+ }
+
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(PORT);
+
+ listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
+ LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_FREE, -1,
+ (struct sockaddr*)&sin,
+ sizeof(sin));
+
+ if (!listener) {
+ fprintf(stderr, "Could not create a listener!\n");
+ return 1;
+ }
+
+ signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
+
+ if (!signal_event || event_add(signal_event, NULL)<0) {
+ fprintf(stderr, "Could not create/add a signal event!\n");
+ return 1;
+ }
+
+ event_base_dispatch(base);
+
+ evconnlistener_free(listener);
+ event_free(signal_event);
+ event_base_free(base);
+
+ printf("done\n");
+ return 0;
+}
+
+static void
+listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *sa, int socklen, void *user_data)
+{
+ struct event_base *base = user_data;
+ struct bufferevent *bev;
+
+ bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
+ if (!bev) {
+ fprintf(stderr, "Error constructing bufferevent!");
+ event_base_loopbreak(base);
+ return;
+ }
+ bufferevent_setcb(bev, NULL, conn_writecb, conn_eventcb, NULL);
+ bufferevent_enable(bev, EV_WRITE);
+ bufferevent_disable(bev, EV_READ);
+
+ bufferevent_write(bev, MESSAGE, strlen(MESSAGE));
+}
+
+static void
+conn_writecb(struct bufferevent *bev, void *user_data)
+{
+ struct evbuffer *output = bufferevent_get_output(bev);
+ if (evbuffer_get_length(output) == 0) {
+ printf("flushed answer\n");
+ bufferevent_free(bev);
+ }
+}
+
+static void
+conn_eventcb(struct bufferevent *bev, short events, void *user_data)
+{
+ if (events & BEV_EVENT_EOF) {
+ printf("Connection closed.\n");
+ } else if (events & BEV_EVENT_ERROR) {
+ printf("Got an error on the connection: %s\n",
+ strerror(errno));/*XXX win32*/
+ }
+ /* None of the other events can happen here, since we haven't enabled
+ * timeouts */
+ bufferevent_free(bev);
+}
+
+static void
+signal_cb(evutil_socket_t sig, short events, void *user_data)
+{
+ struct event_base *base = user_data;
+ struct timeval delay = { 2, 0 };
+
+ printf("Caught an interrupt signal; exiting cleanly in two seconds.\n");
+
+ event_base_loopexit(base, &delay);
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/hostcheck.c b/ipc/chromium/src/third_party/libevent/sample/hostcheck.c
new file mode 100644
index 0000000000..50709369c0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/hostcheck.c
@@ -0,0 +1,217 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* This file is an amalgamation of hostcheck.c and most of rawstr.c
+ from cURL. The contents of the COPYING file mentioned above are:
+
+COPYRIGHT AND PERMISSION NOTICE
+
+Copyright (c) 1996 - 2013, Daniel Stenberg, <daniel@haxx.se>.
+
+All rights reserved.
+
+Permission to use, copy, modify, and distribute this software for any purpose
+with or without fee is hereby granted, provided that the above copyright
+notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
+OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of a copyright holder shall not
+be used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization of the copyright holder.
+*/
+
+#include "hostcheck.h"
+#include <string.h>
+
+/* Portable, consistent toupper (remember EBCDIC). Do not use toupper() because
+ its behavior is altered by the current locale. */
+static char Curl_raw_toupper(char in)
+{
+ switch (in) {
+ case 'a':
+ return 'A';
+ case 'b':
+ return 'B';
+ case 'c':
+ return 'C';
+ case 'd':
+ return 'D';
+ case 'e':
+ return 'E';
+ case 'f':
+ return 'F';
+ case 'g':
+ return 'G';
+ case 'h':
+ return 'H';
+ case 'i':
+ return 'I';
+ case 'j':
+ return 'J';
+ case 'k':
+ return 'K';
+ case 'l':
+ return 'L';
+ case 'm':
+ return 'M';
+ case 'n':
+ return 'N';
+ case 'o':
+ return 'O';
+ case 'p':
+ return 'P';
+ case 'q':
+ return 'Q';
+ case 'r':
+ return 'R';
+ case 's':
+ return 'S';
+ case 't':
+ return 'T';
+ case 'u':
+ return 'U';
+ case 'v':
+ return 'V';
+ case 'w':
+ return 'W';
+ case 'x':
+ return 'X';
+ case 'y':
+ return 'Y';
+ case 'z':
+ return 'Z';
+ }
+ return in;
+}
+
+/*
+ * Curl_raw_equal() is for doing "raw" case insensitive strings. This is meant
+ * to be locale independent and only compare strings we know are safe for
+ * this. See http://daniel.haxx.se/blog/2008/10/15/strcasecmp-in-turkish/ for
+ * some further explanation to why this function is necessary.
+ *
+ * The function is capable of comparing a-z case insensitively even for
+ * non-ascii.
+ */
+
+static int Curl_raw_equal(const char *first, const char *second)
+{
+ while(*first && *second) {
+ if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second))
+ /* get out of the loop as soon as they don't match */
+ break;
+ first++;
+ second++;
+ }
+ /* we do the comparison here (possibly again), just to make sure that if the
+ loop above is skipped because one of the strings reached zero, we must not
+ return this as a successful match */
+ return (Curl_raw_toupper(*first) == Curl_raw_toupper(*second));
+}
+
+static int Curl_raw_nequal(const char *first, const char *second, size_t max)
+{
+ while(*first && *second && max) {
+ if(Curl_raw_toupper(*first) != Curl_raw_toupper(*second)) {
+ break;
+ }
+ max--;
+ first++;
+ second++;
+ }
+ if(0 == max)
+ return 1; /* they are equal this far */
+
+ return Curl_raw_toupper(*first) == Curl_raw_toupper(*second);
+}
+
+/*
+ * Match a hostname against a wildcard pattern.
+ * E.g.
+ * "foo.host.com" matches "*.host.com".
+ *
+ * We use the matching rule described in RFC6125, section 6.4.3.
+ * http://tools.ietf.org/html/rfc6125#section-6.4.3
+ */
+
+static int hostmatch(const char *hostname, const char *pattern)
+{
+ const char *pattern_label_end, *pattern_wildcard, *hostname_label_end;
+ int wildcard_enabled;
+ size_t prefixlen, suffixlen;
+ pattern_wildcard = strchr(pattern, '*');
+ if(pattern_wildcard == NULL)
+ return Curl_raw_equal(pattern, hostname) ?
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+
+ /* We require at least 2 dots in pattern to avoid too wide wildcard
+ match. */
+ wildcard_enabled = 1;
+ pattern_label_end = strchr(pattern, '.');
+ if(pattern_label_end == NULL || strchr(pattern_label_end+1, '.') == NULL ||
+ pattern_wildcard > pattern_label_end ||
+ Curl_raw_nequal(pattern, "xn--", 4)) {
+ wildcard_enabled = 0;
+ }
+ if(!wildcard_enabled)
+ return Curl_raw_equal(pattern, hostname) ?
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+
+ hostname_label_end = strchr(hostname, '.');
+ if(hostname_label_end == NULL ||
+ !Curl_raw_equal(pattern_label_end, hostname_label_end))
+ return CURL_HOST_NOMATCH;
+
+ /* The wildcard must match at least one character, so the left-most
+ label of the hostname is at least as large as the left-most label
+ of the pattern. */
+ if(hostname_label_end - hostname < pattern_label_end - pattern)
+ return CURL_HOST_NOMATCH;
+
+ prefixlen = pattern_wildcard - pattern;
+ suffixlen = pattern_label_end - (pattern_wildcard+1);
+ return Curl_raw_nequal(pattern, hostname, prefixlen) &&
+ Curl_raw_nequal(pattern_wildcard+1, hostname_label_end - suffixlen,
+ suffixlen) ?
+ CURL_HOST_MATCH : CURL_HOST_NOMATCH;
+}
+
+int Curl_cert_hostcheck(const char *match_pattern, const char *hostname)
+{
+ if(!match_pattern || !*match_pattern ||
+ !hostname || !*hostname) /* sanity check */
+ return 0;
+
+ if(Curl_raw_equal(hostname, match_pattern)) /* trivial case */
+ return 1;
+
+ if(hostmatch(hostname,match_pattern) == CURL_HOST_MATCH)
+ return 1;
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/hostcheck.h b/ipc/chromium/src/third_party/libevent/sample/hostcheck.h
new file mode 100644
index 0000000000..f40bc43435
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/hostcheck.h
@@ -0,0 +1,30 @@
+#ifndef HEADER_CURL_HOSTCHECK_H
+#define HEADER_CURL_HOSTCHECK_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at http://curl.haxx.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#define CURL_HOST_NOMATCH 0
+#define CURL_HOST_MATCH 1
+int Curl_cert_hostcheck(const char *match_pattern, const char *hostname);
+
+#endif /* HEADER_CURL_HOSTCHECK_H */
+
diff --git a/ipc/chromium/src/third_party/libevent/sample/http-connect.c b/ipc/chromium/src/third_party/libevent/sample/http-connect.c
new file mode 100644
index 0000000000..53f816d3ae
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/http-connect.c
@@ -0,0 +1,131 @@
+#include "event2/event-config.h"
+
+#include <event2/event.h>
+#include <event2/http.h>
+#include <event2/http_struct.h>
+#include <event2/buffer.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <limits.h>
+
+#define VERIFY(cond) do { \
+ if (!(cond)) { \
+ fprintf(stderr, "[error] %s\n", #cond); \
+ exit(EXIT_FAILURE); \
+ } \
+} while (0); \
+
+#define URL_MAX 4096
+
+struct connect_base
+{
+ struct evhttp_connection *evcon;
+ struct evhttp_uri *location;
+};
+
+static struct evhttp_uri* uri_parse(const char *str)
+{
+ struct evhttp_uri *uri;
+ VERIFY(uri = evhttp_uri_parse(str));
+ VERIFY(evhttp_uri_get_host(uri));
+ VERIFY(evhttp_uri_get_port(uri) > 0);
+ return uri;
+}
+static char* uri_path(struct evhttp_uri *uri, char buffer[URL_MAX])
+{
+ struct evhttp_uri *path;
+
+ VERIFY(evhttp_uri_join(uri, buffer, URL_MAX));
+
+ path = evhttp_uri_parse(buffer);
+ evhttp_uri_set_scheme(path, NULL);
+ evhttp_uri_set_userinfo(path, 0);
+ evhttp_uri_set_host(path, NULL);
+ evhttp_uri_set_port(path, -1);
+ VERIFY(evhttp_uri_join(path, buffer, URL_MAX));
+ return buffer;
+}
+static char* uri_hostport(struct evhttp_uri *uri, char buffer[URL_MAX])
+{
+ VERIFY(evhttp_uri_join(uri, buffer, URL_MAX));
+ VERIFY(evhttp_uri_get_host(uri));
+ VERIFY(evhttp_uri_get_port(uri) > 0);
+ evutil_snprintf(buffer, URL_MAX, "%s:%d",
+ evhttp_uri_get_host(uri), evhttp_uri_get_port(uri));
+ return buffer;
+}
+
+static void get_cb(struct evhttp_request *req, void *arg)
+{
+ ev_ssize_t len;
+ struct evbuffer *evbuf;
+
+ VERIFY(req);
+
+ evbuf = evhttp_request_get_input_buffer(req);
+ len = evbuffer_get_length(evbuf);
+ fwrite(evbuffer_pullup(evbuf, len), len, 1, stdout);
+ evbuffer_drain(evbuf, len);
+}
+
+static void connect_cb(struct evhttp_request *proxy_req, void *arg)
+{
+ struct connect_base *base = arg;
+ struct evhttp_connection *evcon = base->evcon;
+ struct evhttp_uri *location = base->location;
+ struct evhttp_request *req;
+ char buffer[URL_MAX];
+
+ VERIFY(proxy_req);
+ VERIFY(evcon);
+
+ req = evhttp_request_new(get_cb, NULL);
+ evhttp_add_header(req->output_headers, "Connection", "close");
+ evhttp_add_header(req->output_headers, "Host", evhttp_uri_get_host(location));
+ VERIFY(!evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ uri_path(location, buffer)));
+}
+
+int main(int argc, const char **argv)
+{
+ char hostport[URL_MAX];
+
+ struct evhttp_uri *location;
+ struct evhttp_uri *proxy;
+
+ struct event_base *base;
+ struct evhttp_connection *evcon;
+ struct evhttp_request *req;
+
+ struct connect_base connect_base;
+
+ if (argc != 3) {
+ printf("Usage: %s proxy url\n", argv[0]);
+ return 1;
+ }
+
+ proxy = uri_parse(argv[1]);
+ location = uri_parse(argv[2]);
+
+ VERIFY(base = event_base_new());
+ VERIFY(evcon = evhttp_connection_base_new(base, NULL,
+ evhttp_uri_get_host(proxy), evhttp_uri_get_port(proxy)));
+ connect_base.evcon = evcon;
+ connect_base.location = location;
+ VERIFY(req = evhttp_request_new(connect_cb, &connect_base));
+
+ uri_hostport(location, hostport);
+ evhttp_add_header(req->output_headers, "Connection", "keep-alive");
+ evhttp_add_header(req->output_headers, "Proxy-Connection", "keep-alive");
+ evhttp_add_header(req->output_headers, "Host", hostport);
+ evhttp_make_request(evcon, req, EVHTTP_REQ_CONNECT, hostport);
+
+ event_base_dispatch(base);
+
+ evhttp_connection_free(evcon);
+ event_base_free(base);
+ evhttp_uri_free(proxy);
+ evhttp_uri_free(location);
+
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/http-server.c b/ipc/chromium/src/third_party/libevent/sample/http-server.c
new file mode 100644
index 0000000000..049aabc441
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/http-server.c
@@ -0,0 +1,582 @@
+/*
+ A trivial static http webserver using Libevent's evhttp.
+
+ This is not the best code in the world, and it does some fairly stupid stuff
+ that you would never want to do in a production webserver. Caveat hackor!
+
+ */
+
+/* Compatibility for possible missing IPv6 declarations */
+#include "../util-internal.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#include <getopt.h>
+#include <io.h>
+#include <fcntl.h>
+#ifndef S_ISDIR
+#define S_ISDIR(x) (((x) & S_IFMT) == S_IFDIR)
+#endif
+#else /* !_WIN32 */
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <dirent.h>
+#endif /* _WIN32 */
+#include <signal.h>
+
+#ifdef EVENT__HAVE_SYS_UN_H
+#include <sys/un.h>
+#endif
+#ifdef EVENT__HAVE_AFUNIX_H
+#include <afunix.h>
+#endif
+
+#include <event2/event.h>
+#include <event2/http.h>
+#include <event2/listener.h>
+#include <event2/buffer.h>
+#include <event2/util.h>
+#include <event2/keyvalq_struct.h>
+
+#ifdef _WIN32
+#include <event2/thread.h>
+#endif /* _WIN32 */
+
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+# include <arpa/inet.h>
+# endif
+#endif
+
+#ifdef _WIN32
+#ifndef stat
+#define stat _stat
+#endif
+#ifndef fstat
+#define fstat _fstat
+#endif
+#ifndef open
+#define open _open
+#endif
+#ifndef close
+#define close _close
+#endif
+#ifndef O_RDONLY
+#define O_RDONLY _O_RDONLY
+#endif
+#endif /* _WIN32 */
+
+char uri_root[512];
+
+static const struct table_entry {
+ const char *extension;
+ const char *content_type;
+} content_type_table[] = {
+ { "txt", "text/plain" },
+ { "c", "text/plain" },
+ { "h", "text/plain" },
+ { "html", "text/html" },
+ { "htm", "text/htm" },
+ { "css", "text/css" },
+ { "gif", "image/gif" },
+ { "jpg", "image/jpeg" },
+ { "jpeg", "image/jpeg" },
+ { "png", "image/png" },
+ { "pdf", "application/pdf" },
+ { "ps", "application/postscript" },
+ { NULL, NULL },
+};
+
+struct options {
+ int port;
+ int iocp;
+ int verbose;
+
+ int unlink;
+ const char *unixsock;
+ const char *docroot;
+};
+
+/* Try to guess a good content-type for 'path' */
+static const char *
+guess_content_type(const char *path)
+{
+ const char *last_period, *extension;
+ const struct table_entry *ent;
+ last_period = strrchr(path, '.');
+ if (!last_period || strchr(last_period, '/'))
+ goto not_found; /* no exension */
+ extension = last_period + 1;
+ for (ent = &content_type_table[0]; ent->extension; ++ent) {
+ if (!evutil_ascii_strcasecmp(ent->extension, extension))
+ return ent->content_type;
+ }
+
+not_found:
+ return "application/misc";
+}
+
+/* Callback used for the /dump URI, and for every non-GET request:
+ * dumps all information to stdout and gives back a trivial 200 ok */
+static void
+dump_request_cb(struct evhttp_request *req, void *arg)
+{
+ const char *cmdtype;
+ struct evkeyvalq *headers;
+ struct evkeyval *header;
+ struct evbuffer *buf;
+
+ switch (evhttp_request_get_command(req)) {
+ case EVHTTP_REQ_GET: cmdtype = "GET"; break;
+ case EVHTTP_REQ_POST: cmdtype = "POST"; break;
+ case EVHTTP_REQ_HEAD: cmdtype = "HEAD"; break;
+ case EVHTTP_REQ_PUT: cmdtype = "PUT"; break;
+ case EVHTTP_REQ_DELETE: cmdtype = "DELETE"; break;
+ case EVHTTP_REQ_OPTIONS: cmdtype = "OPTIONS"; break;
+ case EVHTTP_REQ_TRACE: cmdtype = "TRACE"; break;
+ case EVHTTP_REQ_CONNECT: cmdtype = "CONNECT"; break;
+ case EVHTTP_REQ_PATCH: cmdtype = "PATCH"; break;
+ default: cmdtype = "unknown"; break;
+ }
+
+ printf("Received a %s request for %s\nHeaders:\n",
+ cmdtype, evhttp_request_get_uri(req));
+
+ headers = evhttp_request_get_input_headers(req);
+ for (header = headers->tqh_first; header;
+ header = header->next.tqe_next) {
+ printf(" %s: %s\n", header->key, header->value);
+ }
+
+ buf = evhttp_request_get_input_buffer(req);
+ puts("Input data: <<<");
+ while (evbuffer_get_length(buf)) {
+ int n;
+ char cbuf[128];
+ n = evbuffer_remove(buf, cbuf, sizeof(cbuf));
+ if (n > 0)
+ (void) fwrite(cbuf, 1, n, stdout);
+ }
+ puts(">>>");
+
+ evhttp_send_reply(req, 200, "OK", NULL);
+}
+
+/* This callback gets invoked when we get any http request that doesn't match
+ * any other callback. Like any evhttp server callback, it has a simple job:
+ * it must eventually call evhttp_send_error() or evhttp_send_reply().
+ */
+static void
+send_document_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = NULL;
+ struct options *o = arg;
+ const char *uri = evhttp_request_get_uri(req);
+ struct evhttp_uri *decoded = NULL;
+ const char *path;
+ char *decoded_path;
+ char *whole_path = NULL;
+ size_t len;
+ int fd = -1;
+ struct stat st;
+
+ if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) {
+ dump_request_cb(req, arg);
+ return;
+ }
+
+ printf("Got a GET request for <%s>\n", uri);
+
+ /* Decode the URI */
+ decoded = evhttp_uri_parse(uri);
+ if (!decoded) {
+ printf("It's not a good URI. Sending BADREQUEST\n");
+ evhttp_send_error(req, HTTP_BADREQUEST, 0);
+ return;
+ }
+
+ /* Let's see what path the user asked for. */
+ path = evhttp_uri_get_path(decoded);
+ if (!path) path = "/";
+
+ /* We need to decode it, to see what path the user really wanted. */
+ decoded_path = evhttp_uridecode(path, 0, NULL);
+ if (decoded_path == NULL)
+ goto err;
+ /* Don't allow any ".."s in the path, to avoid exposing stuff outside
+ * of the docroot. This test is both overzealous and underzealous:
+ * it forbids aceptable paths like "/this/one..here", but it doesn't
+ * do anything to prevent symlink following." */
+ if (strstr(decoded_path, ".."))
+ goto err;
+
+ len = strlen(decoded_path)+strlen(o->docroot)+2;
+ if (!(whole_path = malloc(len))) {
+ perror("malloc");
+ goto err;
+ }
+ evutil_snprintf(whole_path, len, "%s/%s", o->docroot, decoded_path);
+
+ if (stat(whole_path, &st)<0) {
+ goto err;
+ }
+
+ /* This holds the content we're sending. */
+ evb = evbuffer_new();
+
+ if (S_ISDIR(st.st_mode)) {
+ /* If it's a directory, read the comments and make a little
+ * index page */
+#ifdef _WIN32
+ HANDLE d;
+ WIN32_FIND_DATAA ent;
+ char *pattern;
+ size_t dirlen;
+#else
+ DIR *d;
+ struct dirent *ent;
+#endif
+ const char *trailing_slash = "";
+
+ if (!strlen(path) || path[strlen(path)-1] != '/')
+ trailing_slash = "/";
+
+#ifdef _WIN32
+ dirlen = strlen(whole_path);
+ pattern = malloc(dirlen+3);
+ memcpy(pattern, whole_path, dirlen);
+ pattern[dirlen] = '\\';
+ pattern[dirlen+1] = '*';
+ pattern[dirlen+2] = '\0';
+ d = FindFirstFileA(pattern, &ent);
+ free(pattern);
+ if (d == INVALID_HANDLE_VALUE)
+ goto err;
+#else
+ if (!(d = opendir(whole_path)))
+ goto err;
+#endif
+
+ evbuffer_add_printf(evb,
+ "<!DOCTYPE html>\n"
+ "<html>\n <head>\n"
+ " <meta charset='utf-8'>\n"
+ " <title>%s</title>\n"
+ " <base href='%s%s'>\n"
+ " </head>\n"
+ " <body>\n"
+ " <h1>%s</h1>\n"
+ " <ul>\n",
+ decoded_path, /* XXX html-escape this. */
+ path, /* XXX html-escape this? */
+ trailing_slash,
+ decoded_path /* XXX html-escape this */);
+#ifdef _WIN32
+ do {
+ const char *name = ent.cFileName;
+#else
+ while ((ent = readdir(d))) {
+ const char *name = ent->d_name;
+#endif
+ evbuffer_add_printf(evb,
+ " <li><a href=\"%s\">%s</a>\n",
+ name, name);/* XXX escape this */
+#ifdef _WIN32
+ } while (FindNextFileA(d, &ent));
+#else
+ }
+#endif
+ evbuffer_add_printf(evb, "</ul></body></html>\n");
+#ifdef _WIN32
+ FindClose(d);
+#else
+ closedir(d);
+#endif
+ evhttp_add_header(evhttp_request_get_output_headers(req),
+ "Content-Type", "text/html");
+ } else {
+ /* Otherwise it's a file; add it to the buffer to get
+ * sent via sendfile */
+ const char *type = guess_content_type(decoded_path);
+ if ((fd = open(whole_path, O_RDONLY)) < 0) {
+ perror("open");
+ goto err;
+ }
+
+ if (fstat(fd, &st)<0) {
+ /* Make sure the length still matches, now that we
+ * opened the file :/ */
+ perror("fstat");
+ goto err;
+ }
+ evhttp_add_header(evhttp_request_get_output_headers(req),
+ "Content-Type", type);
+ evbuffer_add_file(evb, fd, 0, st.st_size);
+ }
+
+ evhttp_send_reply(req, 200, "OK", evb);
+ goto done;
+err:
+ evhttp_send_error(req, 404, "Document was not found");
+ if (fd>=0)
+ close(fd);
+done:
+ if (decoded)
+ evhttp_uri_free(decoded);
+ if (decoded_path)
+ free(decoded_path);
+ if (whole_path)
+ free(whole_path);
+ if (evb)
+ evbuffer_free(evb);
+}
+
+static void
+print_usage(FILE *out, const char *prog, int exit_code)
+{
+ fprintf(out,
+ "Syntax: %s [ OPTS ] <docroot>\n"
+ " -p - port\n"
+ " -U - bind to unix socket\n"
+ " -u - unlink unix socket before bind\n"
+ " -I - IOCP\n"
+ " -v - verbosity, enables libevent debug logging too\n", prog);
+ exit(exit_code);
+}
+static struct options
+parse_opts(int argc, char **argv)
+{
+ struct options o;
+ int opt;
+
+ memset(&o, 0, sizeof(o));
+
+ while ((opt = getopt(argc, argv, "hp:U:uIv")) != -1) {
+ switch (opt) {
+ case 'p': o.port = atoi(optarg); break;
+ case 'U': o.unixsock = optarg; break;
+ case 'u': o.unlink = 1; break;
+ case 'I': o.iocp = 1; break;
+ case 'v': ++o.verbose; break;
+ case 'h': print_usage(stdout, argv[0], 0); break;
+ default : fprintf(stderr, "Unknown option %c\n", opt); break;
+ }
+ }
+
+ if (optind >= argc || (argc - optind) > 1) {
+ print_usage(stdout, argv[0], 1);
+ }
+ o.docroot = argv[optind];
+
+ return o;
+}
+
+static void
+do_term(int sig, short events, void *arg)
+{
+ struct event_base *base = arg;
+ event_base_loopbreak(base);
+ fprintf(stderr, "Got %i, Terminating\n", sig);
+}
+
+static int
+display_listen_sock(struct evhttp_bound_socket *handle)
+{
+ struct sockaddr_storage ss;
+ evutil_socket_t fd;
+ ev_socklen_t socklen = sizeof(ss);
+ char addrbuf[128];
+ void *inaddr;
+ const char *addr;
+ int got_port = -1;
+
+ fd = evhttp_bound_socket_get_fd(handle);
+ memset(&ss, 0, sizeof(ss));
+ if (getsockname(fd, (struct sockaddr *)&ss, &socklen)) {
+ perror("getsockname() failed");
+ return 1;
+ }
+
+ if (ss.ss_family == AF_INET) {
+ got_port = ntohs(((struct sockaddr_in*)&ss)->sin_port);
+ inaddr = &((struct sockaddr_in*)&ss)->sin_addr;
+ } else if (ss.ss_family == AF_INET6) {
+ got_port = ntohs(((struct sockaddr_in6*)&ss)->sin6_port);
+ inaddr = &((struct sockaddr_in6*)&ss)->sin6_addr;
+ }
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
+ else if (ss.ss_family == AF_UNIX) {
+ printf("Listening on <%s>\n", ((struct sockaddr_un*)&ss)->sun_path);
+ return 0;
+ }
+#endif
+ else {
+ fprintf(stderr, "Weird address family %d\n",
+ ss.ss_family);
+ return 1;
+ }
+
+ addr = evutil_inet_ntop(ss.ss_family, inaddr, addrbuf,
+ sizeof(addrbuf));
+ if (addr) {
+ printf("Listening on %s:%d\n", addr, got_port);
+ evutil_snprintf(uri_root, sizeof(uri_root),
+ "http://%s:%d",addr,got_port);
+ } else {
+ fprintf(stderr, "evutil_inet_ntop failed\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event_config *cfg = NULL;
+ struct event_base *base = NULL;
+ struct evhttp *http = NULL;
+ struct evhttp_bound_socket *handle = NULL;
+ struct evconnlistener *lev = NULL;
+ struct event *term = NULL;
+ struct options o = parse_opts(argc, argv);
+ int ret = 0;
+
+#ifdef _WIN32
+ {
+ WORD wVersionRequested;
+ WSADATA wsaData;
+ wVersionRequested = MAKEWORD(2, 2);
+ WSAStartup(wVersionRequested, &wsaData);
+ }
+#else
+ if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
+ ret = 1;
+ goto err;
+ }
+#endif
+
+ setbuf(stdout, NULL);
+ setbuf(stderr, NULL);
+
+ /** Read env like in regress */
+ if (o.verbose || getenv("EVENT_DEBUG_LOGGING_ALL"))
+ event_enable_debug_logging(EVENT_DBG_ALL);
+
+ cfg = event_config_new();
+#ifdef _WIN32
+ if (o.iocp) {
+#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
+ evthread_use_windows_threads();
+ event_config_set_num_cpus_hint(cfg, 8);
+#endif
+ event_config_set_flag(cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
+ }
+#endif
+
+ base = event_base_new_with_config(cfg);
+ if (!base) {
+ fprintf(stderr, "Couldn't create an event_base: exiting\n");
+ ret = 1;
+ }
+ event_config_free(cfg);
+ cfg = NULL;
+
+ /* Create a new evhttp object to handle requests. */
+ http = evhttp_new(base);
+ if (!http) {
+ fprintf(stderr, "couldn't create evhttp. Exiting.\n");
+ ret = 1;
+ }
+
+ /* The /dump URI will dump all requests to stdout and say 200 ok. */
+ evhttp_set_cb(http, "/dump", dump_request_cb, NULL);
+
+ /* We want to accept arbitrary requests, so we need to set a "generic"
+ * cb. We can also add callbacks for specific paths. */
+ evhttp_set_gencb(http, send_document_cb, &o);
+
+ if (o.unixsock) {
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_UN
+ struct sockaddr_un addr;
+
+ if (o.unlink && (unlink(o.unixsock) && errno != ENOENT)) {
+ perror(o.unixsock);
+ ret = 1;
+ goto err;
+ }
+
+ addr.sun_family = AF_UNIX;
+ strcpy(addr.sun_path, o.unixsock);
+
+ lev = evconnlistener_new_bind(base, NULL, NULL,
+ LEV_OPT_CLOSE_ON_FREE, -1,
+ (struct sockaddr *)&addr, sizeof(addr));
+ if (!lev) {
+ perror("Cannot create listener");
+ ret = 1;
+ goto err;
+ }
+
+ handle = evhttp_bind_listener(http, lev);
+ if (!handle) {
+ fprintf(stderr, "couldn't bind to %s. Exiting.\n", o.unixsock);
+ ret = 1;
+ goto err;
+ }
+#else /* !EVENT__HAVE_STRUCT_SOCKADDR_UN */
+ fprintf(stderr, "-U is not supported on this platform. Exiting.\n");
+ ret = 1;
+ goto err;
+#endif /* EVENT__HAVE_STRUCT_SOCKADDR_UN */
+ }
+ else {
+ handle = evhttp_bind_socket_with_handle(http, "0.0.0.0", o.port);
+ if (!handle) {
+ fprintf(stderr, "couldn't bind to port %d. Exiting.\n", o.port);
+ ret = 1;
+ goto err;
+ }
+ }
+
+ if (display_listen_sock(handle)) {
+ ret = 1;
+ goto err;
+ }
+
+ term = evsignal_new(base, SIGINT, do_term, base);
+ if (!term)
+ goto err;
+ if (event_add(term, NULL))
+ goto err;
+
+ event_base_dispatch(base);
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+err:
+ if (cfg)
+ event_config_free(cfg);
+ if (http)
+ evhttp_free(http);
+ if (term)
+ event_free(term);
+ if (base)
+ event_base_free(base);
+
+ return ret;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/https-client.c b/ipc/chromium/src/third_party/libevent/sample/https-client.c
new file mode 100644
index 0000000000..5136acebd7
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/https-client.c
@@ -0,0 +1,544 @@
+/*
+ This is an example of how to hook up evhttp with bufferevent_ssl
+
+ It just GETs an https URL given on the command-line and prints the response
+ body to stdout.
+
+ Actually, it also accepts plain http URLs to make it easy to compare http vs
+ https code paths.
+
+ Loosely based on le-proxy.c.
+ */
+
+// Get rid of OSX 10.7 and greater deprecation warnings.
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+#define snprintf _snprintf
+#define strcasecmp _stricmp
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include <event2/bufferevent_ssl.h>
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+#include <event2/http.h>
+
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+
+#include "openssl_hostname_validation.h"
+
+static int ignore_cert = 0;
+
+static void
+http_request_done(struct evhttp_request *req, void *ctx)
+{
+ char buffer[256];
+ int nread;
+
+ if (!req || !evhttp_request_get_response_code(req)) {
+ /* If req is NULL, it means an error occurred, but
+ * sadly we are mostly left guessing what the error
+ * might have been. We'll do our best... */
+ struct bufferevent *bev = (struct bufferevent *) ctx;
+ unsigned long oslerr;
+ int printed_err = 0;
+ int errcode = EVUTIL_SOCKET_ERROR();
+ fprintf(stderr, "some request failed - no idea which one though!\n");
+ /* Print out the OpenSSL error queue that libevent
+ * squirreled away for us, if any. */
+ while ((oslerr = bufferevent_get_openssl_error(bev))) {
+ ERR_error_string_n(oslerr, buffer, sizeof(buffer));
+ fprintf(stderr, "%s\n", buffer);
+ printed_err = 1;
+ }
+ /* If the OpenSSL error queue was empty, maybe it was a
+ * socket error; let's try printing that. */
+ if (! printed_err)
+ fprintf(stderr, "socket error = %s (%d)\n",
+ evutil_socket_error_to_string(errcode),
+ errcode);
+ return;
+ }
+
+ fprintf(stderr, "Response line: %d %s\n",
+ evhttp_request_get_response_code(req),
+ evhttp_request_get_response_code_line(req));
+
+ while ((nread = evbuffer_remove(evhttp_request_get_input_buffer(req),
+ buffer, sizeof(buffer)))
+ > 0) {
+ /* These are just arbitrary chunks of 256 bytes.
+ * They are not lines, so we can't treat them as such. */
+ fwrite(buffer, nread, 1, stdout);
+ }
+}
+
+static void
+syntax(void)
+{
+ fputs("Syntax:\n", stderr);
+ fputs(" https-client -url <https-url> [-data data-file.bin] [-ignore-cert] [-retries num] [-timeout sec] [-crt crt]\n", stderr);
+ fputs("Example:\n", stderr);
+ fputs(" https-client -url https://ip.appspot.com/\n", stderr);
+}
+
+static void
+err(const char *msg)
+{
+ fputs(msg, stderr);
+}
+
+static void
+err_openssl(const char *func)
+{
+ fprintf (stderr, "%s failed:\n", func);
+
+ /* This is the OpenSSL function that prints the contents of the
+ * error stack to the specified file handle. */
+ ERR_print_errors_fp (stderr);
+
+ exit(1);
+}
+
+/* See http://archives.seul.org/libevent/users/Jan-2013/msg00039.html */
+static int cert_verify_callback(X509_STORE_CTX *x509_ctx, void *arg)
+{
+ char cert_str[256];
+ const char *host = (const char *) arg;
+ const char *res_str = "X509_verify_cert failed";
+ HostnameValidationResult res = Error;
+
+ /* This is the function that OpenSSL would call if we hadn't called
+ * SSL_CTX_set_cert_verify_callback(). Therefore, we are "wrapping"
+ * the default functionality, rather than replacing it. */
+ int ok_so_far = 0;
+
+ X509 *server_cert = NULL;
+
+ if (ignore_cert) {
+ return 1;
+ }
+
+ ok_so_far = X509_verify_cert(x509_ctx);
+
+ server_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
+
+ if (ok_so_far) {
+ res = validate_hostname(host, server_cert);
+
+ switch (res) {
+ case MatchFound:
+ res_str = "MatchFound";
+ break;
+ case MatchNotFound:
+ res_str = "MatchNotFound";
+ break;
+ case NoSANPresent:
+ res_str = "NoSANPresent";
+ break;
+ case MalformedCertificate:
+ res_str = "MalformedCertificate";
+ break;
+ case Error:
+ res_str = "Error";
+ break;
+ default:
+ res_str = "WTF!";
+ break;
+ }
+ }
+
+ X509_NAME_oneline(X509_get_subject_name (server_cert),
+ cert_str, sizeof (cert_str));
+
+ if (res == MatchFound) {
+ printf("https server '%s' has this certificate, "
+ "which looks good to me:\n%s\n",
+ host, cert_str);
+ return 1;
+ } else {
+ printf("Got '%s' for hostname '%s' and certificate:\n%s\n",
+ res_str, host, cert_str);
+ return 0;
+ }
+}
+
+#ifdef _WIN32
+static int
+add_cert_for_store(X509_STORE *store, const char *name)
+{
+ HCERTSTORE sys_store = NULL;
+ PCCERT_CONTEXT ctx = NULL;
+ int r = 0;
+
+ sys_store = CertOpenSystemStore(0, name);
+ if (!sys_store) {
+ err("failed to open system certificate store");
+ return -1;
+ }
+ while ((ctx = CertEnumCertificatesInStore(sys_store, ctx))) {
+ X509 *x509 = d2i_X509(NULL, (unsigned char const **)&ctx->pbCertEncoded,
+ ctx->cbCertEncoded);
+ if (x509) {
+ X509_STORE_add_cert(store, x509);
+ X509_free(x509);
+ } else {
+ r = -1;
+ err_openssl("d2i_X509");
+ break;
+ }
+ }
+ CertCloseStore(sys_store, 0);
+ return r;
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+ int r;
+ struct event_base *base = NULL;
+ struct evhttp_uri *http_uri = NULL;
+ const char *url = NULL, *data_file = NULL;
+ const char *crt = NULL;
+ const char *scheme, *host, *path, *query;
+ char uri[256];
+ int port;
+ int retries = 0;
+ int timeout = -1;
+
+ SSL_CTX *ssl_ctx = NULL;
+ SSL *ssl = NULL;
+ struct bufferevent *bev;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req;
+ struct evkeyvalq *output_headers;
+ struct evbuffer *output_buffer;
+
+ int i;
+ int ret = 0;
+ enum { HTTP, HTTPS } type = HTTP;
+
+ for (i = 1; i < argc; i++) {
+ if (!strcmp("-url", argv[i])) {
+ if (i < argc - 1) {
+ url = argv[i + 1];
+ } else {
+ syntax();
+ goto error;
+ }
+ } else if (!strcmp("-crt", argv[i])) {
+ if (i < argc - 1) {
+ crt = argv[i + 1];
+ } else {
+ syntax();
+ goto error;
+ }
+ } else if (!strcmp("-ignore-cert", argv[i])) {
+ ignore_cert = 1;
+ } else if (!strcmp("-data", argv[i])) {
+ if (i < argc - 1) {
+ data_file = argv[i + 1];
+ } else {
+ syntax();
+ goto error;
+ }
+ } else if (!strcmp("-retries", argv[i])) {
+ if (i < argc - 1) {
+ retries = atoi(argv[i + 1]);
+ } else {
+ syntax();
+ goto error;
+ }
+ } else if (!strcmp("-timeout", argv[i])) {
+ if (i < argc - 1) {
+ timeout = atoi(argv[i + 1]);
+ } else {
+ syntax();
+ goto error;
+ }
+ } else if (!strcmp("-help", argv[i])) {
+ syntax();
+ goto error;
+ }
+ }
+
+ if (!url) {
+ syntax();
+ goto error;
+ }
+
+#ifdef _WIN32
+ {
+ WORD wVersionRequested;
+ WSADATA wsaData;
+ int err;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ err = WSAStartup(wVersionRequested, &wsaData);
+ if (err != 0) {
+ printf("WSAStartup failed with error: %d\n", err);
+ goto error;
+ }
+ }
+#endif // _WIN32
+
+ http_uri = evhttp_uri_parse(url);
+ if (http_uri == NULL) {
+ err("malformed url");
+ goto error;
+ }
+
+ scheme = evhttp_uri_get_scheme(http_uri);
+ if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
+ strcasecmp(scheme, "http") != 0)) {
+ err("url must be http or https");
+ goto error;
+ }
+
+ host = evhttp_uri_get_host(http_uri);
+ if (host == NULL) {
+ err("url must have a host");
+ goto error;
+ }
+
+ port = evhttp_uri_get_port(http_uri);
+ if (port == -1) {
+ port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
+ }
+
+ path = evhttp_uri_get_path(http_uri);
+ if (strlen(path) == 0) {
+ path = "/";
+ }
+
+ query = evhttp_uri_get_query(http_uri);
+ if (query == NULL) {
+ snprintf(uri, sizeof(uri) - 1, "%s", path);
+ } else {
+ snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
+ }
+ uri[sizeof(uri) - 1] = '\0';
+
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+ // Initialize OpenSSL
+ SSL_library_init();
+ ERR_load_crypto_strings();
+ SSL_load_error_strings();
+ OpenSSL_add_all_algorithms();
+#endif
+
+ /* This isn't strictly necessary... OpenSSL performs RAND_poll
+ * automatically on first use of random number generator. */
+ r = RAND_poll();
+ if (r == 0) {
+ err_openssl("RAND_poll");
+ goto error;
+ }
+
+ /* Create a new OpenSSL context */
+ ssl_ctx = SSL_CTX_new(SSLv23_method());
+ if (!ssl_ctx) {
+ err_openssl("SSL_CTX_new");
+ goto error;
+ }
+
+ if (crt == NULL) {
+ X509_STORE *store;
+ /* Attempt to use the system's trusted root certificates. */
+ store = SSL_CTX_get_cert_store(ssl_ctx);
+#ifdef _WIN32
+ if (add_cert_for_store(store, "CA") < 0 ||
+ add_cert_for_store(store, "AuthRoot") < 0 ||
+ add_cert_for_store(store, "ROOT") < 0) {
+ goto error;
+ }
+#else // _WIN32
+ if (X509_STORE_set_default_paths(store) != 1) {
+ err_openssl("X509_STORE_set_default_paths");
+ goto error;
+ }
+#endif // _WIN32
+ } else {
+ if (SSL_CTX_load_verify_locations(ssl_ctx, crt, NULL) != 1) {
+ err_openssl("SSL_CTX_load_verify_locations");
+ goto error;
+ }
+ }
+ /* Ask OpenSSL to verify the server certificate. Note that this
+ * does NOT include verifying that the hostname is correct.
+ * So, by itself, this means anyone with any legitimate
+ * CA-issued certificate for any website, can impersonate any
+ * other website in the world. This is not good. See "The
+ * Most Dangerous Code in the World" article at
+ * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
+ */
+ SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
+ /* This is how we solve the problem mentioned in the previous
+ * comment. We "wrap" OpenSSL's validation routine in our
+ * own routine, which also validates the hostname by calling
+ * the code provided by iSECPartners. Note that even though
+ * the "Everything You've Always Wanted to Know About
+ * Certificate Validation With OpenSSL (But Were Afraid to
+ * Ask)" paper from iSECPartners says very explicitly not to
+ * call SSL_CTX_set_cert_verify_callback (at the bottom of
+ * page 2), what we're doing here is safe because our
+ * cert_verify_callback() calls X509_verify_cert(), which is
+ * OpenSSL's built-in routine which would have been called if
+ * we hadn't set the callback. Therefore, we're just
+ * "wrapping" OpenSSL's routine, not replacing it. */
+ SSL_CTX_set_cert_verify_callback(ssl_ctx, cert_verify_callback,
+ (void *) host);
+
+ // Create event base
+ base = event_base_new();
+ if (!base) {
+ perror("event_base_new()");
+ goto error;
+ }
+
+ // Create OpenSSL bufferevent and stack evhttp on top of it
+ ssl = SSL_new(ssl_ctx);
+ if (ssl == NULL) {
+ err_openssl("SSL_new()");
+ goto error;
+ }
+
+ #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
+ // Set hostname for SNI extension
+ SSL_set_tlsext_host_name(ssl, host);
+ #endif
+
+ if (strcasecmp(scheme, "http") == 0) {
+ bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
+ } else {
+ type = HTTPS;
+ bev = bufferevent_openssl_socket_new(base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ }
+
+ if (bev == NULL) {
+ fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
+ goto error;
+ }
+
+ bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
+
+ // For simplicity, we let DNS resolution block. Everything else should be
+ // asynchronous though.
+ evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
+ host, port);
+ if (evcon == NULL) {
+ fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
+ goto error;
+ }
+
+ if (retries > 0) {
+ evhttp_connection_set_retries(evcon, retries);
+ }
+ if (timeout >= 0) {
+ evhttp_connection_set_timeout(evcon, timeout);
+ }
+
+ // Fire off the request
+ req = evhttp_request_new(http_request_done, bev);
+ if (req == NULL) {
+ fprintf(stderr, "evhttp_request_new() failed\n");
+ goto error;
+ }
+
+ output_headers = evhttp_request_get_output_headers(req);
+ evhttp_add_header(output_headers, "Host", host);
+ evhttp_add_header(output_headers, "Connection", "close");
+
+ if (data_file) {
+ /* NOTE: In production code, you'd probably want to use
+ * evbuffer_add_file() or evbuffer_add_file_segment(), to
+ * avoid needless copying. */
+ FILE * f = fopen(data_file, "rb");
+ char buf[1024];
+ size_t s;
+ size_t bytes = 0;
+
+ if (!f) {
+ syntax();
+ goto error;
+ }
+
+ output_buffer = evhttp_request_get_output_buffer(req);
+ while ((s = fread(buf, 1, sizeof(buf), f)) > 0) {
+ evbuffer_add(output_buffer, buf, s);
+ bytes += s;
+ }
+ evutil_snprintf(buf, sizeof(buf)-1, "%lu", (unsigned long)bytes);
+ evhttp_add_header(output_headers, "Content-Length", buf);
+ fclose(f);
+ }
+
+ r = evhttp_make_request(evcon, req, data_file ? EVHTTP_REQ_POST : EVHTTP_REQ_GET, uri);
+ if (r != 0) {
+ fprintf(stderr, "evhttp_make_request() failed\n");
+ goto error;
+ }
+
+ event_base_dispatch(base);
+ goto cleanup;
+
+error:
+ ret = 1;
+cleanup:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http_uri)
+ evhttp_uri_free(http_uri);
+ if (base)
+ event_base_free(base);
+
+ if (ssl_ctx)
+ SSL_CTX_free(ssl_ctx);
+ if (type == HTTP && ssl)
+ SSL_free(ssl);
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+ EVP_cleanup();
+ ERR_free_strings();
+
+#if OPENSSL_VERSION_NUMBER < 0x10000000L
+ ERR_remove_state(0);
+#else
+ ERR_remove_thread_state(NULL);
+#endif
+
+ CRYPTO_cleanup_all_ex_data();
+
+ sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
+#endif /* (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L) */
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+ return ret;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/include.am b/ipc/chromium/src/third_party/libevent/sample/include.am
new file mode 100644
index 0000000000..b6894d46e5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/include.am
@@ -0,0 +1,56 @@
+# sample/include.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+SAMPLES = \
+ sample/dns-example \
+ sample/event-read-fifo \
+ sample/hello-world \
+ sample/http-server \
+ sample/http-connect \
+ sample/signal-test \
+ sample/time-test
+
+if OPENSSL
+SAMPLES += sample/le-proxy
+sample_le_proxy_SOURCES = sample/le-proxy.c
+sample_le_proxy_LDADD = libevent.la libevent_openssl.la $(OPENSSL_LIBS) $(OPENSSL_LIBADD)
+sample_le_proxy_CPPFLAGS = $(AM_CPPFLAGS) $(OPENSSL_INCS)
+
+SAMPLES += sample/https-client
+sample_https_client_SOURCES = \
+ sample/https-client.c \
+ sample/hostcheck.c \
+ sample/openssl_hostname_validation.c
+sample_https_client_LDADD = libevent.la libevent_openssl.la $(OPENSSL_LIBS) $(OPENSSL_LIBADD)
+if BUILD_WIN32
+sample_https_client_LDADD += -lcrypt32
+endif
+sample_https_client_CPPFLAGS = $(AM_CPPFLAGS) $(OPENSSL_INCS)
+noinst_HEADERS += \
+ sample/hostcheck.h \
+ sample/openssl_hostname_validation.h
+endif
+
+if BUILD_SAMPLES
+noinst_PROGRAMS += $(SAMPLES)
+endif
+
+$(SAMPLES) : libevent.la
+
+sample_event_read_fifo_SOURCES = sample/event-read-fifo.c
+sample_event_read_fifo_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_time_test_SOURCES = sample/time-test.c
+sample_time_test_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_signal_test_SOURCES = sample/signal-test.c
+sample_signal_test_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_dns_example_SOURCES = sample/dns-example.c
+sample_dns_example_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_hello_world_SOURCES = sample/hello-world.c
+sample_hello_world_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_http_server_SOURCES = sample/http-server.c
+sample_http_server_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+sample_http_connect_SOURCES = sample/http-connect.c
+sample_http_connect_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
diff --git a/ipc/chromium/src/third_party/libevent/sample/le-proxy.c b/ipc/chromium/src/third_party/libevent/sample/le-proxy.c
new file mode 100644
index 0000000000..13e0e2aea9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/le-proxy.c
@@ -0,0 +1,305 @@
+/*
+ This example code shows how to write an (optionally encrypting) SSL proxy
+ with Libevent's bufferevent layer.
+
+ XXX It's a little ugly and should probably be cleaned up.
+ */
+
+// Get rid of OSX 10.7 and greater deprecation warnings.
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+#include <stdio.h>
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include <event2/bufferevent_ssl.h>
+#include <event2/bufferevent.h>
+#include <event2/buffer.h>
+#include <event2/listener.h>
+#include <event2/util.h>
+
+#include "util-internal.h"
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <openssl/rand.h>
+#include "openssl-compat.h"
+
+static struct event_base *base;
+static struct sockaddr_storage listen_on_addr;
+static struct sockaddr_storage connect_to_addr;
+static int connect_to_addrlen;
+static int use_wrapper = 1;
+
+static SSL_CTX *ssl_ctx = NULL;
+
+#define MAX_OUTPUT (512*1024)
+
+static void drained_writecb(struct bufferevent *bev, void *ctx);
+static void eventcb(struct bufferevent *bev, short what, void *ctx);
+
+static void
+readcb(struct bufferevent *bev, void *ctx)
+{
+ struct bufferevent *partner = ctx;
+ struct evbuffer *src, *dst;
+ size_t len;
+ src = bufferevent_get_input(bev);
+ len = evbuffer_get_length(src);
+ if (!partner) {
+ evbuffer_drain(src, len);
+ return;
+ }
+ dst = bufferevent_get_output(partner);
+ evbuffer_add_buffer(dst, src);
+
+ if (evbuffer_get_length(dst) >= MAX_OUTPUT) {
+ /* We're giving the other side data faster than it can
+ * pass it on. Stop reading here until we have drained the
+ * other side to MAX_OUTPUT/2 bytes. */
+ bufferevent_setcb(partner, readcb, drained_writecb,
+ eventcb, bev);
+ bufferevent_setwatermark(partner, EV_WRITE, MAX_OUTPUT/2,
+ MAX_OUTPUT);
+ bufferevent_disable(bev, EV_READ);
+ }
+}
+
+static void
+drained_writecb(struct bufferevent *bev, void *ctx)
+{
+ struct bufferevent *partner = ctx;
+
+ /* We were choking the other side until we drained our outbuf a bit.
+ * Now it seems drained. */
+ bufferevent_setcb(bev, readcb, NULL, eventcb, partner);
+ bufferevent_setwatermark(bev, EV_WRITE, 0, 0);
+ if (partner)
+ bufferevent_enable(partner, EV_READ);
+}
+
+static void
+close_on_finished_writecb(struct bufferevent *bev, void *ctx)
+{
+ struct evbuffer *b = bufferevent_get_output(bev);
+
+ if (evbuffer_get_length(b) == 0) {
+ bufferevent_free(bev);
+ }
+}
+
+static void
+eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ struct bufferevent *partner = ctx;
+
+ if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+ if (what & BEV_EVENT_ERROR) {
+ unsigned long err;
+ while ((err = (bufferevent_get_openssl_error(bev)))) {
+ const char *msg = (const char*)
+ ERR_reason_error_string(err);
+ const char *lib = (const char*)
+ ERR_lib_error_string(err);
+ const char *func = (const char*)
+ ERR_func_error_string(err);
+ fprintf(stderr,
+ "%s in %s %s\n", msg, lib, func);
+ }
+ if (errno)
+ perror("connection error");
+ }
+
+ if (partner) {
+ /* Flush all pending data */
+ readcb(bev, ctx);
+
+ if (evbuffer_get_length(
+ bufferevent_get_output(partner))) {
+ /* We still have to flush data from the other
+ * side, but when that's done, close the other
+ * side. */
+ bufferevent_setcb(partner,
+ NULL, close_on_finished_writecb,
+ eventcb, NULL);
+ bufferevent_disable(partner, EV_READ);
+ } else {
+ /* We have nothing left to say to the other
+ * side; close it. */
+ bufferevent_free(partner);
+ }
+ }
+ bufferevent_free(bev);
+ }
+}
+
+static void
+syntax(void)
+{
+ fputs("Syntax:\n", stderr);
+ fputs(" le-proxy [-s] [-W] <listen-on-addr> <connect-to-addr>\n", stderr);
+ fputs("Example:\n", stderr);
+ fputs(" le-proxy 127.0.0.1:8888 1.2.3.4:80\n", stderr);
+
+ exit(1);
+}
+
+static void
+accept_cb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *a, int slen, void *p)
+{
+ struct bufferevent *b_out, *b_in;
+ /* Create two linked bufferevent objects: one to connect, one for the
+ * new connection */
+ b_in = bufferevent_socket_new(base, fd,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+
+ if (!ssl_ctx || use_wrapper)
+ b_out = bufferevent_socket_new(base, -1,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ else {
+ SSL *ssl = SSL_new(ssl_ctx);
+ b_out = bufferevent_openssl_socket_new(base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ }
+
+ assert(b_in && b_out);
+
+ if (bufferevent_socket_connect(b_out,
+ (struct sockaddr*)&connect_to_addr, connect_to_addrlen)<0) {
+ perror("bufferevent_socket_connect");
+ bufferevent_free(b_out);
+ bufferevent_free(b_in);
+ return;
+ }
+
+ if (ssl_ctx && use_wrapper) {
+ struct bufferevent *b_ssl;
+ SSL *ssl = SSL_new(ssl_ctx);
+ b_ssl = bufferevent_openssl_filter_new(base,
+ b_out, ssl, BUFFEREVENT_SSL_CONNECTING,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ if (!b_ssl) {
+ perror("Bufferevent_openssl_new");
+ bufferevent_free(b_out);
+ bufferevent_free(b_in);
+ return;
+ }
+ b_out = b_ssl;
+ }
+
+ bufferevent_setcb(b_in, readcb, NULL, eventcb, b_out);
+ bufferevent_setcb(b_out, readcb, NULL, eventcb, b_in);
+
+ bufferevent_enable(b_in, EV_READ|EV_WRITE);
+ bufferevent_enable(b_out, EV_READ|EV_WRITE);
+}
+
+int
+main(int argc, char **argv)
+{
+ int i;
+ int socklen;
+
+ int use_ssl = 0;
+ struct evconnlistener *listener;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+ wVersionRequested = MAKEWORD(2, 2);
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ if (argc < 3)
+ syntax();
+
+ for (i=1; i < argc; ++i) {
+ if (!strcmp(argv[i], "-s")) {
+ use_ssl = 1;
+ } else if (!strcmp(argv[i], "-W")) {
+ use_wrapper = 0;
+ } else if (argv[i][0] == '-') {
+ syntax();
+ } else
+ break;
+ }
+
+ if (i+2 != argc)
+ syntax();
+
+ memset(&listen_on_addr, 0, sizeof(listen_on_addr));
+ socklen = sizeof(listen_on_addr);
+ if (evutil_parse_sockaddr_port(argv[i],
+ (struct sockaddr*)&listen_on_addr, &socklen)<0) {
+ int p = atoi(argv[i]);
+ struct sockaddr_in *sin = (struct sockaddr_in*)&listen_on_addr;
+ if (p < 1 || p > 65535)
+ syntax();
+ sin->sin_port = htons(p);
+ sin->sin_addr.s_addr = htonl(0x7f000001);
+ sin->sin_family = AF_INET;
+ socklen = sizeof(struct sockaddr_in);
+ }
+
+ memset(&connect_to_addr, 0, sizeof(connect_to_addr));
+ connect_to_addrlen = sizeof(connect_to_addr);
+ if (evutil_parse_sockaddr_port(argv[i+1],
+ (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0)
+ syntax();
+
+ base = event_base_new();
+ if (!base) {
+ perror("event_base_new()");
+ return 1;
+ }
+
+ if (use_ssl) {
+ int r;
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+ SSL_library_init();
+ ERR_load_crypto_strings();
+ SSL_load_error_strings();
+ OpenSSL_add_all_algorithms();
+#endif
+ r = RAND_poll();
+ if (r == 0) {
+ fprintf(stderr, "RAND_poll() failed.\n");
+ return 1;
+ }
+ ssl_ctx = SSL_CTX_new(TLS_method());
+ }
+
+ listener = evconnlistener_new_bind(base, accept_cb, NULL,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_CLOSE_ON_EXEC|LEV_OPT_REUSEABLE,
+ -1, (struct sockaddr*)&listen_on_addr, socklen);
+
+ if (! listener) {
+ fprintf(stderr, "Couldn't open listener.\n");
+ event_base_free(base);
+ return 1;
+ }
+ event_base_dispatch(base);
+
+ evconnlistener_free(listener);
+ event_base_free(base);
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.c b/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.c
new file mode 100644
index 0000000000..4036ccbaab
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.c
@@ -0,0 +1,178 @@
+/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
+
+/*
+Copyright (C) 2012, iSEC Partners.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+ */
+
+/*
+ * Helper functions to perform basic hostname validation using OpenSSL.
+ *
+ * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
+ * attempting to use this code. This whitepaper describes how the code works,
+ * how it should be used, and what its limitations are.
+ *
+ * Author: Alban Diquet
+ * License: See LICENSE
+ *
+ */
+
+// Get rid of OSX 10.7 and greater deprecation warnings.
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+#include <openssl/x509v3.h>
+#include <openssl/ssl.h>
+#include <string.h>
+
+#include "openssl_hostname_validation.h"
+#include "hostcheck.h"
+
+#define HOSTNAME_MAX_SIZE 255
+
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+#define ASN1_STRING_get0_data ASN1_STRING_data
+#endif
+
+/**
+* Tries to find a match for hostname in the certificate's Common Name field.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if the Common Name had a NUL character embedded in it.
+* Returns Error if the Common Name could not be extracted.
+*/
+static HostnameValidationResult matches_common_name(const char *hostname, const X509 *server_cert) {
+ int common_name_loc = -1;
+ X509_NAME_ENTRY *common_name_entry = NULL;
+ ASN1_STRING *common_name_asn1 = NULL;
+ const char *common_name_str = NULL;
+
+ // Find the position of the CN field in the Subject field of the certificate
+ common_name_loc = X509_NAME_get_index_by_NID(X509_get_subject_name((X509 *) server_cert), NID_commonName, -1);
+ if (common_name_loc < 0) {
+ return Error;
+ }
+
+ // Extract the CN field
+ common_name_entry = X509_NAME_get_entry(X509_get_subject_name((X509 *) server_cert), common_name_loc);
+ if (common_name_entry == NULL) {
+ return Error;
+ }
+
+ // Convert the CN field to a C string
+ common_name_asn1 = X509_NAME_ENTRY_get_data(common_name_entry);
+ if (common_name_asn1 == NULL) {
+ return Error;
+ }
+ common_name_str = (char *) ASN1_STRING_get0_data(common_name_asn1);
+
+ // Make sure there isn't an embedded NUL character in the CN
+ if ((size_t)ASN1_STRING_length(common_name_asn1) != strlen(common_name_str)) {
+ return MalformedCertificate;
+ }
+
+ // Compare expected hostname with the CN
+ if (Curl_cert_hostcheck(common_name_str, hostname) == CURL_HOST_MATCH) {
+ return MatchFound;
+ }
+ else {
+ return MatchNotFound;
+ }
+}
+
+
+/**
+* Tries to find a match for hostname in the certificate's Subject Alternative Name extension.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
+* Returns NoSANPresent if the SAN extension was not present in the certificate.
+*/
+static HostnameValidationResult matches_subject_alternative_name(const char *hostname, const X509 *server_cert) {
+ HostnameValidationResult result = MatchNotFound;
+ int i;
+ int san_names_nb = -1;
+ STACK_OF(GENERAL_NAME) *san_names = NULL;
+
+ // Try to extract the names within the SAN extension from the certificate
+ san_names = X509_get_ext_d2i((X509 *) server_cert, NID_subject_alt_name, NULL, NULL);
+ if (san_names == NULL) {
+ return NoSANPresent;
+ }
+ san_names_nb = sk_GENERAL_NAME_num(san_names);
+
+ // Check each name within the extension
+ for (i=0; i<san_names_nb; i++) {
+ const GENERAL_NAME *current_name = sk_GENERAL_NAME_value(san_names, i);
+
+ if (current_name->type == GEN_DNS) {
+ // Current name is a DNS name, let's check it
+ const char *dns_name = (char *) ASN1_STRING_get0_data(current_name->d.dNSName);
+
+ // Make sure there isn't an embedded NUL character in the DNS name
+ if ((size_t)ASN1_STRING_length(current_name->d.dNSName) != strlen(dns_name)) {
+ result = MalformedCertificate;
+ break;
+ }
+ else { // Compare expected hostname with the DNS name
+ if (Curl_cert_hostcheck(dns_name, hostname)
+ == CURL_HOST_MATCH) {
+ result = MatchFound;
+ break;
+ }
+ }
+ }
+ }
+ sk_GENERAL_NAME_pop_free(san_names, GENERAL_NAME_free);
+
+ return result;
+}
+
+
+/**
+* Validates the server's identity by looking for the expected hostname in the
+* server's certificate. As described in RFC 6125, it first tries to find a match
+* in the Subject Alternative Name extension. If the extension is not present in
+* the certificate, it checks the Common Name instead.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
+* Returns Error if there was an error.
+*/
+HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert) {
+ HostnameValidationResult result;
+
+ if((hostname == NULL) || (server_cert == NULL))
+ return Error;
+
+ // First try the Subject Alternative Names extension
+ result = matches_subject_alternative_name(hostname, server_cert);
+ if (result == NoSANPresent) {
+ // Extension was not found: try the Common Name
+ result = matches_common_name(hostname, server_cert);
+ }
+
+ return result;
+}
diff --git a/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.h b/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.h
new file mode 100644
index 0000000000..54aa1c436d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/openssl_hostname_validation.h
@@ -0,0 +1,56 @@
+/* Obtained from: https://github.com/iSECPartners/ssl-conservatory */
+
+/*
+Copyright (C) 2012, iSEC Partners.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+ */
+
+/*
+ * Helper functions to perform basic hostname validation using OpenSSL.
+ *
+ * Please read "everything-you-wanted-to-know-about-openssl.pdf" before
+ * attempting to use this code. This whitepaper describes how the code works,
+ * how it should be used, and what its limitations are.
+ *
+ * Author: Alban Diquet
+ * License: See LICENSE
+ *
+ */
+
+typedef enum {
+ MatchFound,
+ MatchNotFound,
+ NoSANPresent,
+ MalformedCertificate,
+ Error
+} HostnameValidationResult;
+
+/**
+* Validates the server's identity by looking for the expected hostname in the
+* server's certificate. As described in RFC 6125, it first tries to find a match
+* in the Subject Alternative Name extension. If the extension is not present in
+* the certificate, it checks the Common Name instead.
+*
+* Returns MatchFound if a match was found.
+* Returns MatchNotFound if no matches were found.
+* Returns MalformedCertificate if any of the hostnames had a NUL character embedded in it.
+* Returns Error if there was an error.
+*/
+HostnameValidationResult validate_hostname(const char *hostname, const X509 *server_cert);
diff --git a/ipc/chromium/src/third_party/libevent/sample/signal-test.c b/ipc/chromium/src/third_party/libevent/sample/signal-test.c
new file mode 100644
index 0000000000..4aef420515
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/signal-test.c
@@ -0,0 +1,83 @@
+/*
+ * Compile with:
+ * cc -I/usr/local/include -o signal-test \
+ * signal-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef _WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#include <sys/time.h>
+#else
+#include <winsock2.h>
+#include <windows.h>
+#endif
+#include <signal.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event2/event.h>
+
+int called = 0;
+
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *signal = arg;
+
+ printf("signal_cb: got signal %d\n", event_get_signal(signal));
+
+ if (called >= 2)
+ event_del(signal);
+
+ called++;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event *signal_int = NULL;
+ struct event_base* base;
+ int ret = 0;
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ /* Initialize the event library */
+ base = event_base_new();
+ if (!base) {
+ ret = 1;
+ goto out;
+ }
+
+ /* Initialize one event */
+ signal_int = evsignal_new(base, SIGINT, signal_cb, event_self_cbarg());
+ if (!signal_int) {
+ ret = 2;
+ goto out;
+ }
+ event_add(signal_int, NULL);
+
+ event_base_dispatch(base);
+
+out:
+ if (signal_int)
+ event_free(signal_int);
+ if (base)
+ event_base_free(base);
+ return ret;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/sample/time-test.c b/ipc/chromium/src/third_party/libevent/sample/time-test.c
new file mode 100644
index 0000000000..671a1d2108
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/sample/time-test.c
@@ -0,0 +1,110 @@
+/*
+ * XXX This sample code was once meant to show how to use the basic Libevent
+ * interfaces, but it never worked on non-Unix platforms, and some of the
+ * interfaces have changed since it was first written. It should probably
+ * be removed or replaced with something better.
+ *
+ * Compile with:
+ * cc -I/usr/local/include -o time-test time-test.c -L/usr/local/lib -levent
+ */
+
+#include <sys/types.h>
+
+#include <event2/event-config.h>
+
+#include <sys/stat.h>
+#ifndef _WIN32
+#include <sys/queue.h>
+#include <unistd.h>
+#endif
+#include <time.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event2/event.h>
+#include <event2/event_struct.h>
+#include <event2/util.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+struct timeval lasttime;
+
+int event_is_persistent;
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct timeval newtime, difference;
+ struct event *timeout = arg;
+ double elapsed;
+
+ evutil_gettimeofday(&newtime, NULL);
+ evutil_timersub(&newtime, &lasttime, &difference);
+ elapsed = difference.tv_sec +
+ (difference.tv_usec / 1.0e6);
+
+ printf("timeout_cb called at %d: %.3f seconds elapsed.\n",
+ (int)newtime.tv_sec, elapsed);
+ lasttime = newtime;
+
+ if (! event_is_persistent) {
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_sec = 2;
+ event_add(timeout, &tv);
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event timeout;
+ struct timeval tv;
+ struct event_base *base;
+ int flags;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void)WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ if (argc == 2 && !strcmp(argv[1], "-p")) {
+ event_is_persistent = 1;
+ flags = EV_PERSIST;
+ } else {
+ event_is_persistent = 0;
+ flags = 0;
+ }
+
+ /* Initialize the event library */
+ base = event_base_new();
+
+ /* Initialize one event */
+ event_assign(&timeout, base, -1, flags, timeout_cb, (void*) &timeout);
+
+ evutil_timerclear(&tv);
+ tv.tv_sec = 2;
+ event_add(&timeout, &tv);
+
+ evutil_gettimeofday(&lasttime, NULL);
+
+ setbuf(stdout, NULL);
+ setbuf(stderr, NULL);
+
+ event_base_dispatch(base);
+
+ return (0);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/select.c b/ipc/chromium/src/third_party/libevent/select.c
new file mode 100644
index 0000000000..b1db0e44b6
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/select.c
@@ -0,0 +1,346 @@
+/* $OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $ */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_SELECT
+
+#ifdef __APPLE__
+/* Apple wants us to define this if we might ever pass more than
+ * FD_SETSIZE bits to select(). */
+#define _DARWIN_UNLIMITED_SELECT
+#endif
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_SELECT_H
+#include <sys/select.h>
+#endif
+#include <sys/queue.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+#include "event-internal.h"
+#include "evsignal-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+
+#ifndef EVENT__HAVE_FD_MASK
+/* This type is mandatory, but Android doesn't define it. */
+typedef unsigned long fd_mask;
+#endif
+
+#ifndef NFDBITS
+#define NFDBITS (sizeof(fd_mask)*8)
+#endif
+
+/* Divide positive x by y, rounding up. */
+#define DIV_ROUNDUP(x, y) (((x)+((y)-1))/(y))
+
+/* How many bytes to allocate for N fds? */
+#define SELECT_ALLOC_SIZE(n) \
+ (DIV_ROUNDUP(n, NFDBITS) * sizeof(fd_mask))
+
+struct selectop {
+ int event_fds; /* Highest fd in fd set */
+ int event_fdsz;
+ int resize_out_sets;
+ fd_set *event_readset_in;
+ fd_set *event_writeset_in;
+ fd_set *event_readset_out;
+ fd_set *event_writeset_out;
+};
+
+static void *select_init(struct event_base *);
+static int select_add(struct event_base *, int, short old, short events, void*);
+static int select_del(struct event_base *, int, short old, short events, void*);
+static int select_dispatch(struct event_base *, struct timeval *);
+static void select_dealloc(struct event_base *);
+
+const struct eventop selectops = {
+ "select",
+ select_init,
+ select_add,
+ select_del,
+ select_dispatch,
+ select_dealloc,
+ 1, /* need_reinit. */
+ EV_FEATURE_FDS,
+ 0,
+};
+
+static int select_resize(struct selectop *sop, int fdsz);
+static void select_free_selectop(struct selectop *sop);
+
+static void *
+select_init(struct event_base *base)
+{
+ struct selectop *sop;
+
+ if (!(sop = mm_calloc(1, sizeof(struct selectop))))
+ return (NULL);
+
+ if (select_resize(sop, SELECT_ALLOC_SIZE(32 + 1))) {
+ select_free_selectop(sop);
+ return (NULL);
+ }
+
+ evsig_init_(base);
+
+ evutil_weakrand_seed_(&base->weakrand_seed, 0);
+
+ return (sop);
+}
+
+#ifdef CHECK_INVARIANTS
+static void
+check_selectop(struct selectop *sop)
+{
+ /* nothing to be done here */
+}
+#else
+#define check_selectop(sop) do { (void) sop; } while (0)
+#endif
+
+static int
+select_dispatch(struct event_base *base, struct timeval *tv)
+{
+ int res=0, i, j, nfds;
+ struct selectop *sop = base->evbase;
+
+ check_selectop(sop);
+ if (sop->resize_out_sets) {
+ fd_set *readset_out=NULL, *writeset_out=NULL;
+ size_t sz = sop->event_fdsz;
+ if (!(readset_out = mm_realloc(sop->event_readset_out, sz)))
+ return (-1);
+ sop->event_readset_out = readset_out;
+ if (!(writeset_out = mm_realloc(sop->event_writeset_out, sz))) {
+ /* We don't free readset_out here, since it was
+ * already successfully reallocated. The next time
+ * we call select_dispatch, the realloc will be a
+ * no-op. */
+ return (-1);
+ }
+ sop->event_writeset_out = writeset_out;
+ sop->resize_out_sets = 0;
+ }
+
+ memcpy(sop->event_readset_out, sop->event_readset_in,
+ sop->event_fdsz);
+ memcpy(sop->event_writeset_out, sop->event_writeset_in,
+ sop->event_fdsz);
+
+ nfds = sop->event_fds+1;
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = select(nfds, sop->event_readset_out,
+ sop->event_writeset_out, NULL, tv);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ check_selectop(sop);
+
+ if (res == -1) {
+ if (errno != EINTR) {
+ event_warn("select");
+ return (-1);
+ }
+
+ return (0);
+ }
+
+ event_debug(("%s: select reports %d", __func__, res));
+
+ check_selectop(sop);
+ i = evutil_weakrand_range_(&base->weakrand_seed, nfds);
+ for (j = 0; j < nfds; ++j) {
+ if (++i >= nfds)
+ i = 0;
+ res = 0;
+ if (FD_ISSET(i, sop->event_readset_out))
+ res |= EV_READ;
+ if (FD_ISSET(i, sop->event_writeset_out))
+ res |= EV_WRITE;
+
+ if (res == 0)
+ continue;
+
+ evmap_io_active_(base, i, res);
+ }
+ check_selectop(sop);
+
+ return (0);
+}
+
+static int
+select_resize(struct selectop *sop, int fdsz)
+{
+ fd_set *readset_in = NULL;
+ fd_set *writeset_in = NULL;
+
+ if (sop->event_readset_in)
+ check_selectop(sop);
+
+ if ((readset_in = mm_realloc(sop->event_readset_in, fdsz)) == NULL)
+ goto error;
+ sop->event_readset_in = readset_in;
+ if ((writeset_in = mm_realloc(sop->event_writeset_in, fdsz)) == NULL) {
+ /* Note that this will leave event_readset_in expanded.
+ * That's okay; we wouldn't want to free it, since that would
+ * change the semantics of select_resize from "expand the
+ * readset_in and writeset_in, or return -1" to "expand the
+ * *set_in members, or trash them and return -1."
+ */
+ goto error;
+ }
+ sop->event_writeset_in = writeset_in;
+ sop->resize_out_sets = 1;
+
+ memset((char *)sop->event_readset_in + sop->event_fdsz, 0,
+ fdsz - sop->event_fdsz);
+ memset((char *)sop->event_writeset_in + sop->event_fdsz, 0,
+ fdsz - sop->event_fdsz);
+
+ sop->event_fdsz = fdsz;
+ check_selectop(sop);
+
+ return (0);
+
+ error:
+ event_warn("malloc");
+ return (-1);
+}
+
+
+static int
+select_add(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct selectop *sop = base->evbase;
+ (void) p;
+
+ EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+ check_selectop(sop);
+ /*
+ * Keep track of the highest fd, so that we can calculate the size
+ * of the fd_sets for select(2)
+ */
+ if (sop->event_fds < fd) {
+ int fdsz = sop->event_fdsz;
+
+ if (fdsz < (int)sizeof(fd_mask))
+ fdsz = (int)sizeof(fd_mask);
+
+ /* In theory we should worry about overflow here. In
+ * reality, though, the highest fd on a unixy system will
+ * not overflow here. XXXX */
+ while (fdsz < (int) SELECT_ALLOC_SIZE(fd + 1))
+ fdsz *= 2;
+
+ if (fdsz != sop->event_fdsz) {
+ if (select_resize(sop, fdsz)) {
+ check_selectop(sop);
+ return (-1);
+ }
+ }
+
+ sop->event_fds = fd;
+ }
+
+ if (events & EV_READ)
+ FD_SET(fd, sop->event_readset_in);
+ if (events & EV_WRITE)
+ FD_SET(fd, sop->event_writeset_in);
+ check_selectop(sop);
+
+ return (0);
+}
+
+/*
+ * Nothing to be done here.
+ */
+
+static int
+select_del(struct event_base *base, int fd, short old, short events, void *p)
+{
+ struct selectop *sop = base->evbase;
+ (void)p;
+
+ EVUTIL_ASSERT((events & EV_SIGNAL) == 0);
+ check_selectop(sop);
+
+ if (sop->event_fds < fd) {
+ check_selectop(sop);
+ return (0);
+ }
+
+ if (events & EV_READ)
+ FD_CLR(fd, sop->event_readset_in);
+
+ if (events & EV_WRITE)
+ FD_CLR(fd, sop->event_writeset_in);
+
+ check_selectop(sop);
+ return (0);
+}
+
+static void
+select_free_selectop(struct selectop *sop)
+{
+ if (sop->event_readset_in)
+ mm_free(sop->event_readset_in);
+ if (sop->event_writeset_in)
+ mm_free(sop->event_writeset_in);
+ if (sop->event_readset_out)
+ mm_free(sop->event_readset_out);
+ if (sop->event_writeset_out)
+ mm_free(sop->event_writeset_out);
+
+ memset(sop, 0, sizeof(struct selectop));
+ mm_free(sop);
+}
+
+static void
+select_dealloc(struct event_base *base)
+{
+ evsig_dealloc_(base);
+
+ select_free_selectop(base->evbase);
+}
+
+#endif /* EVENT__HAVE_SELECT */
diff --git a/ipc/chromium/src/third_party/libevent/signal.c b/ipc/chromium/src/third_party/libevent/signal.c
new file mode 100644
index 0000000000..89f5fc1717
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/signal.c
@@ -0,0 +1,481 @@
+/* $OpenBSD: select.c,v 1.2 2002/06/25 15:50:15 mickey Exp $ */
+
+/*
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <winsock2.h>
+#include <windows.h>
+#undef WIN32_LEAN_AND_MEAN
+#endif
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+#ifdef EVENT__HAVE_FCNTL_H
+#include <fcntl.h>
+#endif
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event-internal.h"
+#include "event2/util.h"
+#include "evsignal-internal.h"
+#include "log-internal.h"
+#include "evmap-internal.h"
+#include "evthread-internal.h"
+
+/*
+ signal.c
+
+ This is the signal-handling implementation we use for backends that don't
+ have a better way to do signal handling. It uses sigaction() or signal()
+ to set a signal handler, and a socket pair to tell the event base when
+
+ Note that I said "the event base" : only one event base can be set up to use
+ this at a time. For historical reasons and backward compatibility, if you
+ add an event for a signal to event_base A, then add an event for a signal
+ (any signal!) to event_base B, event_base B will get informed about the
+ signal, but event_base A won't.
+
+ It would be neat to change this behavior in some future version of Libevent.
+ kqueue already does something far more sensible. We can make all backends
+ on Linux do a reasonable thing using signalfd.
+*/
+
+#ifndef _WIN32
+/* Windows wants us to call our signal handlers as __cdecl. Nobody else
+ * expects you to do anything crazy like this. */
+#ifndef __cdecl
+#define __cdecl
+#endif
+#endif
+
+static int evsig_add(struct event_base *, evutil_socket_t, short, short, void *);
+static int evsig_del(struct event_base *, evutil_socket_t, short, short, void *);
+
+static const struct eventop evsigops = {
+ "signal",
+ NULL,
+ evsig_add,
+ evsig_del,
+ NULL,
+ NULL,
+ 0, 0, 0
+};
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+/* Lock for evsig_base and evsig_base_n_signals_added fields. */
+static void *evsig_base_lock = NULL;
+#endif
+/* The event base that's currently getting informed about signals. */
+static struct event_base *evsig_base = NULL;
+/* A copy of evsig_base->sigev_n_signals_added. */
+static int evsig_base_n_signals_added = 0;
+static evutil_socket_t evsig_base_fd = -1;
+
+static void __cdecl evsig_handler(int sig);
+
+#define EVSIGBASE_LOCK() EVLOCK_LOCK(evsig_base_lock, 0)
+#define EVSIGBASE_UNLOCK() EVLOCK_UNLOCK(evsig_base_lock, 0)
+
+void
+evsig_set_base_(struct event_base *base)
+{
+ EVSIGBASE_LOCK();
+ evsig_base = base;
+ evsig_base_n_signals_added = base->sig.ev_n_signals_added;
+ evsig_base_fd = base->sig.ev_signal_pair[1];
+ EVSIGBASE_UNLOCK();
+}
+
+/* Callback for when the signal handler write a byte to our signaling socket */
+static void
+evsig_cb(evutil_socket_t fd, short what, void *arg)
+{
+ static char signals[1024];
+ ev_ssize_t n;
+ int i;
+ int ncaught[NSIG];
+ struct event_base *base;
+
+ base = arg;
+
+ memset(&ncaught, 0, sizeof(ncaught));
+
+ while (1) {
+#ifdef _WIN32
+ n = recv(fd, signals, sizeof(signals), 0);
+#else
+ n = read(fd, signals, sizeof(signals));
+#endif
+ if (n == -1) {
+ int err = evutil_socket_geterror(fd);
+ if (! EVUTIL_ERR_RW_RETRIABLE(err))
+ event_sock_err(1, fd, "%s: recv", __func__);
+ break;
+ } else if (n == 0) {
+ /* XXX warn? */
+ break;
+ }
+ for (i = 0; i < n; ++i) {
+ ev_uint8_t sig = signals[i];
+ if (sig < NSIG)
+ ncaught[sig]++;
+ }
+ }
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+ for (i = 0; i < NSIG; ++i) {
+ if (ncaught[i])
+ evmap_signal_active_(base, i, ncaught[i]);
+ }
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+}
+
+int
+evsig_init_(struct event_base *base)
+{
+ /*
+ * Our signal handler is going to write to one end of the socket
+ * pair to wake up our event loop. The event loop then scans for
+ * signals that got delivered.
+ */
+ if (evutil_make_internal_pipe_(base->sig.ev_signal_pair) == -1) {
+#ifdef _WIN32
+ /* Make this nonfatal on win32, where sometimes people
+ have localhost firewalled. */
+ event_sock_warn(-1, "%s: socketpair", __func__);
+#else
+ event_sock_err(1, -1, "%s: socketpair", __func__);
+#endif
+ return -1;
+ }
+
+ if (base->sig.sh_old) {
+ mm_free(base->sig.sh_old);
+ }
+ base->sig.sh_old = NULL;
+ base->sig.sh_old_max = 0;
+
+ event_assign(&base->sig.ev_signal, base, base->sig.ev_signal_pair[0],
+ EV_READ | EV_PERSIST, evsig_cb, base);
+
+ base->sig.ev_signal.ev_flags |= EVLIST_INTERNAL;
+ event_priority_set(&base->sig.ev_signal, 0);
+
+ base->evsigsel = &evsigops;
+
+ return 0;
+}
+
+/* Helper: set the signal handler for evsignal to handler in base, so that
+ * we can restore the original handler when we clear the current one. */
+int
+evsig_set_handler_(struct event_base *base,
+ int evsignal, void (__cdecl *handler)(int))
+{
+#ifdef EVENT__HAVE_SIGACTION
+ struct sigaction sa;
+#else
+ ev_sighandler_t sh;
+#endif
+ struct evsig_info *sig = &base->sig;
+ void *p;
+
+ /*
+ * resize saved signal handler array up to the highest signal number.
+ * a dynamic array is used to keep footprint on the low side.
+ */
+ if (evsignal >= sig->sh_old_max) {
+ int new_max = evsignal + 1;
+ event_debug(("%s: evsignal (%d) >= sh_old_max (%d), resizing",
+ __func__, evsignal, sig->sh_old_max));
+ p = mm_realloc(sig->sh_old, new_max * sizeof(*sig->sh_old));
+ if (p == NULL) {
+ event_warn("realloc");
+ return (-1);
+ }
+
+ memset((char *)p + sig->sh_old_max * sizeof(*sig->sh_old),
+ 0, (new_max - sig->sh_old_max) * sizeof(*sig->sh_old));
+
+ sig->sh_old_max = new_max;
+ sig->sh_old = p;
+ }
+
+ /* allocate space for previous handler out of dynamic array */
+ sig->sh_old[evsignal] = mm_malloc(sizeof *sig->sh_old[evsignal]);
+ if (sig->sh_old[evsignal] == NULL) {
+ event_warn("malloc");
+ return (-1);
+ }
+
+ /* save previous handler and setup new handler */
+#ifdef EVENT__HAVE_SIGACTION
+ memset(&sa, 0, sizeof(sa));
+ sa.sa_handler = handler;
+ sa.sa_flags |= SA_RESTART;
+ sigfillset(&sa.sa_mask);
+
+ if (sigaction(evsignal, &sa, sig->sh_old[evsignal]) == -1) {
+ event_warn("sigaction");
+ mm_free(sig->sh_old[evsignal]);
+ sig->sh_old[evsignal] = NULL;
+ return (-1);
+ }
+#else
+ if ((sh = signal(evsignal, handler)) == SIG_ERR) {
+ event_warn("signal");
+ mm_free(sig->sh_old[evsignal]);
+ sig->sh_old[evsignal] = NULL;
+ return (-1);
+ }
+ *sig->sh_old[evsignal] = sh;
+#endif
+
+ return (0);
+}
+
+static int
+evsig_add(struct event_base *base, evutil_socket_t evsignal, short old, short events, void *p)
+{
+ struct evsig_info *sig = &base->sig;
+ (void)p;
+
+ EVUTIL_ASSERT(evsignal >= 0 && evsignal < NSIG);
+
+ /* catch signals if they happen quickly */
+ EVSIGBASE_LOCK();
+ if (evsig_base != base && evsig_base_n_signals_added) {
+ event_warnx("Added a signal to event base %p with signals "
+ "already added to event_base %p. Only one can have "
+ "signals at a time with the %s backend. The base with "
+ "the most recently added signal or the most recent "
+ "event_base_loop() call gets preference; do "
+ "not rely on this behavior in future Libevent versions.",
+ base, evsig_base, base->evsel->name);
+ }
+ evsig_base = base;
+ evsig_base_n_signals_added = ++sig->ev_n_signals_added;
+ evsig_base_fd = base->sig.ev_signal_pair[1];
+ EVSIGBASE_UNLOCK();
+
+ event_debug(("%s: %d: changing signal handler", __func__, (int)evsignal));
+ if (evsig_set_handler_(base, (int)evsignal, evsig_handler) == -1) {
+ goto err;
+ }
+
+
+ if (!sig->ev_signal_added) {
+ if (event_add_nolock_(&sig->ev_signal, NULL, 0))
+ goto err;
+ sig->ev_signal_added = 1;
+ }
+
+ return (0);
+
+err:
+ EVSIGBASE_LOCK();
+ --evsig_base_n_signals_added;
+ --sig->ev_n_signals_added;
+ EVSIGBASE_UNLOCK();
+ return (-1);
+}
+
+int
+evsig_restore_handler_(struct event_base *base, int evsignal)
+{
+ int ret = 0;
+ struct evsig_info *sig = &base->sig;
+#ifdef EVENT__HAVE_SIGACTION
+ struct sigaction *sh;
+#else
+ ev_sighandler_t *sh;
+#endif
+
+ if (evsignal >= sig->sh_old_max) {
+ /* Can't actually restore. */
+ /* XXXX.*/
+ return 0;
+ }
+
+ /* restore previous handler */
+ sh = sig->sh_old[evsignal];
+ sig->sh_old[evsignal] = NULL;
+#ifdef EVENT__HAVE_SIGACTION
+ if (sigaction(evsignal, sh, NULL) == -1) {
+ event_warn("sigaction");
+ ret = -1;
+ }
+#else
+ if (signal(evsignal, *sh) == SIG_ERR) {
+ event_warn("signal");
+ ret = -1;
+ }
+#endif
+
+ mm_free(sh);
+
+ return ret;
+}
+
+static int
+evsig_del(struct event_base *base, evutil_socket_t evsignal, short old, short events, void *p)
+{
+ EVUTIL_ASSERT(evsignal >= 0 && evsignal < NSIG);
+
+ event_debug(("%s: "EV_SOCK_FMT": restoring signal handler",
+ __func__, EV_SOCK_ARG(evsignal)));
+
+ EVSIGBASE_LOCK();
+ --evsig_base_n_signals_added;
+ --base->sig.ev_n_signals_added;
+ EVSIGBASE_UNLOCK();
+
+ return (evsig_restore_handler_(base, (int)evsignal));
+}
+
+static void __cdecl
+evsig_handler(int sig)
+{
+ int save_errno = errno;
+#ifdef _WIN32
+ int socket_errno = EVUTIL_SOCKET_ERROR();
+#endif
+ ev_uint8_t msg;
+
+ if (evsig_base == NULL) {
+ event_warnx(
+ "%s: received signal %d, but have no base configured",
+ __func__, sig);
+ return;
+ }
+
+#ifndef EVENT__HAVE_SIGACTION
+ signal(sig, evsig_handler);
+#endif
+
+ /* Wake up our notification mechanism */
+ msg = sig;
+#ifdef _WIN32
+ send(evsig_base_fd, (char*)&msg, 1, 0);
+#else
+ {
+ int r = write(evsig_base_fd, (char*)&msg, 1);
+ (void)r; /* Suppress 'unused return value' and 'unused var' */
+ }
+#endif
+ errno = save_errno;
+#ifdef _WIN32
+ EVUTIL_SET_SOCKET_ERROR(socket_errno);
+#endif
+}
+
+void
+evsig_dealloc_(struct event_base *base)
+{
+ int i = 0;
+ if (base->sig.ev_signal_added) {
+ event_del(&base->sig.ev_signal);
+ base->sig.ev_signal_added = 0;
+ }
+ /* debug event is created in evsig_init_/event_assign even when
+ * ev_signal_added == 0, so unassign is required */
+ event_debug_unassign(&base->sig.ev_signal);
+
+ for (i = 0; i < NSIG; ++i) {
+ if (i < base->sig.sh_old_max && base->sig.sh_old[i] != NULL)
+ evsig_restore_handler_(base, i);
+ }
+ EVSIGBASE_LOCK();
+ if (base == evsig_base) {
+ evsig_base = NULL;
+ evsig_base_n_signals_added = 0;
+ evsig_base_fd = -1;
+ }
+ EVSIGBASE_UNLOCK();
+
+ if (base->sig.ev_signal_pair[0] != -1) {
+ evutil_closesocket(base->sig.ev_signal_pair[0]);
+ base->sig.ev_signal_pair[0] = -1;
+ }
+ if (base->sig.ev_signal_pair[1] != -1) {
+ evutil_closesocket(base->sig.ev_signal_pair[1]);
+ base->sig.ev_signal_pair[1] = -1;
+ }
+ base->sig.sh_old_max = 0;
+
+ /* per index frees are handled in evsig_del() */
+ if (base->sig.sh_old) {
+ mm_free(base->sig.sh_old);
+ base->sig.sh_old = NULL;
+ }
+}
+
+static void
+evsig_free_globals_locks(void)
+{
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (evsig_base_lock != NULL) {
+ EVTHREAD_FREE_LOCK(evsig_base_lock, 0);
+ evsig_base_lock = NULL;
+ }
+#endif
+ return;
+}
+
+void
+evsig_free_globals_(void)
+{
+ evsig_free_globals_locks();
+}
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+int
+evsig_global_setup_locks_(const int enable_locks)
+{
+ EVTHREAD_SETUP_GLOBAL_LOCK(evsig_base_lock, 0);
+ return 0;
+}
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h b/ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h
new file mode 100644
index 0000000000..308abc5512
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/solaris/event2/event-config.h
@@ -0,0 +1,602 @@
+/* event2/event-config.h
+ *
+ * This file was generated by autoconf when libevent was built, and post-
+ * processed by Libevent so that its macros would have a uniform prefix.
+ *
+ * DO NOT EDIT THIS FILE.
+ *
+ * Do not rely on macros in this file existing in later versions.
+ */
+
+#ifndef EVENT2_EVENT_CONFIG_H_INCLUDED_
+#define EVENT2_EVENT_CONFIG_H_INCLUDED_
+
+/* config.h. Generated from config.h.in by configure. */
+/* config.h.in. Generated from configure.ac by autoheader. */
+
+/* Define if libevent should build without support for a debug mode */
+/* #undef EVENT__DISABLE_DEBUG_MODE */
+
+/* Define if libevent should not allow replacing the mm functions */
+/* #undef EVENT__DISABLE_MM_REPLACEMENT */
+
+/* Define if libevent should not be compiled with thread support */
+/* #undef EVENT__DISABLE_THREAD_SUPPORT */
+
+/* Define to 1 if you have the `accept4' function. */
+#define EVENT__HAVE_ACCEPT4 1
+
+/* Define to 1 if you have the <afunix.h> header file. */
+/* #undef EVENT__HAVE_AFUNIX_H */
+
+/* Define to 1 if you have the `arc4random' function. */
+#define EVENT__HAVE_ARC4RANDOM 1
+
+/* Define to 1 if you have the `arc4random_addrandom' function. */
+#define EVENT__HAVE_ARC4RANDOM_ADDRANDOM 1
+
+/* Define to 1 if you have the `arc4random_buf' function. */
+#define EVENT__HAVE_ARC4RANDOM_BUF 1
+
+/* Define to 1 if you have the <arpa/inet.h> header file. */
+#define EVENT__HAVE_ARPA_INET_H 1
+
+/* Define to 1 if you have the `clock_gettime' function. */
+#define EVENT__HAVE_CLOCK_GETTIME 1
+
+/* Define to 1 if you have the declaration of `CTL_KERN', and to 0 if you
+ don't. */
+/* #undef EVENT__HAVE_DECL_CTL_KERN */
+
+/* Define to 1 if you have the declaration of `KERN_ARND', and to 0 if you
+ don't. */
+/* #undef EVENT__HAVE_DECL_KERN_ARND */
+
+/* Define if /dev/poll is available */
+#define EVENT__HAVE_DEVPOLL 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define EVENT__HAVE_DLFCN_H 1
+
+/* Define if your system supports the epoll system calls */
+/* #undef EVENT__HAVE_EPOLL */
+
+/* Define to 1 if you have the `epoll_create1' function. */
+/* #undef EVENT__HAVE_EPOLL_CREATE1 */
+
+/* Define to 1 if you have the `epoll_ctl' function. */
+/* #undef EVENT__HAVE_EPOLL_CTL */
+
+/* Define to 1 if you have the <errno.h> header file. */
+#define EVENT__HAVE_ERRNO_H 1
+
+/* Define to 1 if you have the `eventfd' function. */
+/* #undef EVENT__HAVE_EVENTFD */
+
+/* Define if your system supports event ports */
+#define EVENT__HAVE_EVENT_PORTS 1
+
+/* Define to 1 if you have the `fcntl' function. */
+#define EVENT__HAVE_FCNTL 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define EVENT__HAVE_FCNTL_H 1
+
+/* Define to 1 if the system has the type `fd_mask'. */
+#define EVENT__HAVE_FD_MASK 1
+
+/* Do we have getaddrinfo()? */
+#define EVENT__HAVE_GETADDRINFO 1
+
+/* Define to 1 if you have the `getegid' function. */
+#define EVENT__HAVE_GETEGID 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define EVENT__HAVE_GETEUID 1
+
+/* Define this if you have any gethostbyname_r() */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R */
+
+/* Define this if gethostbyname_r takes 3 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_3_ARG */
+
+/* Define this if gethostbyname_r takes 5 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_5_ARG */
+
+/* Define this if gethostbyname_r takes 6 arguments */
+/* #undef EVENT__HAVE_GETHOSTBYNAME_R_6_ARG */
+
+/* Define to 1 if you have the `getifaddrs' function. */
+#define EVENT__HAVE_GETIFADDRS 1
+
+/* Define to 1 if you have the `getnameinfo' function. */
+#define EVENT__HAVE_GETNAMEINFO 1
+
+/* Define to 1 if you have the `getprotobynumber' function. */
+#define EVENT__HAVE_GETPROTOBYNUMBER 1
+
+/* Define to 1 if you have the `getrandom' function. */
+#define EVENT__HAVE_GETRANDOM 1
+
+/* Define to 1 if you have the `getservbyname' function. */
+#define EVENT__HAVE_GETSERVBYNAME 1
+
+/* Define to 1 if you have the `gettimeofday' function. */
+#define EVENT__HAVE_GETTIMEOFDAY 1
+
+/* Define to 1 if you have the <ifaddrs.h> header file. */
+#define EVENT__HAVE_IFADDRS_H 1
+
+/* Define to 1 if you have the `inet_ntop' function. */
+#define EVENT__HAVE_INET_NTOP 1
+
+/* Define to 1 if you have the `inet_pton' function. */
+#define EVENT__HAVE_INET_PTON 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define EVENT__HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the `issetugid' function. */
+#define EVENT__HAVE_ISSETUGID 1
+
+/* Define to 1 if you have the `kqueue' function. */
+/* #undef EVENT__HAVE_KQUEUE */
+
+/* Define to 1 if you have the `ws2_32' library (-lws2_32). */
+/* #undef EVENT__HAVE_LIBWS2_32 */
+
+/* Define if the system has zlib */
+#define EVENT__HAVE_LIBZ 1
+
+/* Define to 1 if you have the `mach_absolute_time' function. */
+/* #undef EVENT__HAVE_MACH_ABSOLUTE_TIME */
+
+/* Define to 1 if you have the <mach/mach.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_H */
+
+/* Define to 1 if you have the <mach/mach_time.h> header file. */
+/* #undef EVENT__HAVE_MACH_MACH_TIME_H */
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define EVENT__HAVE_MEMORY_H 1
+
+/* Define to 1 if you have the `mmap' function. */
+#define EVENT__HAVE_MMAP 1
+
+/* Define to 1 if you have the `nanosleep' function. */
+#define EVENT__HAVE_NANOSLEEP 1
+
+/* Define to 1 if you have the <netdb.h> header file. */
+#define EVENT__HAVE_NETDB_H 1
+
+/* Define to 1 if you have the <netinet/in6.h> header file. */
+/* #undef EVENT__HAVE_NETINET_IN6_H */
+
+/* Define to 1 if you have the <netinet/in.h> header file. */
+#define EVENT__HAVE_NETINET_IN_H 1
+
+/* Define to 1 if you have the <netinet/tcp.h> header file. */
+#define EVENT__HAVE_NETINET_TCP_H 1
+
+/* Define if the system has openssl */
+#define EVENT__HAVE_OPENSSL 1
+
+/* Define to 1 if you have the <openssl/ssl.h> header file. */
+#define EVENT__HAVE_OPENSSL_SSL_H 1
+
+/* Define to 1 if you have the `pipe' function. */
+#define EVENT__HAVE_PIPE 1
+
+/* Define to 1 if you have the `pipe2' function. */
+#define EVENT__HAVE_PIPE2 1
+
+/* Define to 1 if you have the `poll' function. */
+#define EVENT__HAVE_POLL 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define EVENT__HAVE_POLL_H 1
+
+/* Define to 1 if you have the `port_create' function. */
+#define EVENT__HAVE_PORT_CREATE 1
+
+/* Define to 1 if you have the <port.h> header file. */
+#define EVENT__HAVE_PORT_H 1
+
+/* Define if you have POSIX threads libraries and header files. */
+/* #undef EVENT__HAVE_PTHREAD */
+
+/* Define if we have pthreads on this system */
+#define EVENT__HAVE_PTHREADS 1
+
+/* Define to 1 if you have the `putenv' function. */
+#define EVENT__HAVE_PUTENV 1
+
+/* Define to 1 if the system has the type `sa_family_t'. */
+#define EVENT__HAVE_SA_FAMILY_T 1
+
+/* Define to 1 if you have the `select' function. */
+#define EVENT__HAVE_SELECT 1
+
+/* Define to 1 if you have the `sendfile' function. */
+#define EVENT__HAVE_SENDFILE 1
+
+/* Define to 1 if you have the `setenv' function. */
+#define EVENT__HAVE_SETENV 1
+
+/* Define if F_SETFD is defined in <fcntl.h> */
+#define EVENT__HAVE_SETFD 1
+
+/* Define to 1 if you have the `setrlimit' function. */
+#define EVENT__HAVE_SETRLIMIT 1
+
+/* Define to 1 if you have the `sigaction' function. */
+#define EVENT__HAVE_SIGACTION 1
+
+/* Define to 1 if you have the `signal' function. */
+#define EVENT__HAVE_SIGNAL 1
+
+/* Define to 1 if you have the `splice' function. */
+/* #undef EVENT__HAVE_SPLICE */
+
+/* Define to 1 if you have the <stdarg.h> header file. */
+#define EVENT__HAVE_STDARG_H 1
+
+/* Define to 1 if you have the <stddef.h> header file. */
+#define EVENT__HAVE_STDDEF_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define EVENT__HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define EVENT__HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define EVENT__HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define EVENT__HAVE_STRING_H 1
+
+/* Define to 1 if you have the `strlcpy' function. */
+#define EVENT__HAVE_STRLCPY 1
+
+/* Define to 1 if you have the `strsep' function. */
+#define EVENT__HAVE_STRSEP 1
+
+/* Define to 1 if you have the `strtok_r' function. */
+#define EVENT__HAVE_STRTOK_R 1
+
+/* Define to 1 if you have the `strtoll' function. */
+#define EVENT__HAVE_STRTOLL 1
+
+/* Define to 1 if the system has the type `struct addrinfo'. */
+#define EVENT__HAVE_STRUCT_ADDRINFO 1
+
+/* Define to 1 if the system has the type `struct in6_addr'. */
+#define EVENT__HAVE_STRUCT_IN6_ADDR 1
+
+/* Define to 1 if `s6_addr16' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR16 */
+
+/* Define to 1 if `s6_addr32' is a member of `struct in6_addr'. */
+/* #undef EVENT__HAVE_STRUCT_IN6_ADDR_S6_ADDR32 */
+
+/* Define to 1 if the system has the type `struct linger'. */
+#define EVENT__HAVE_STRUCT_LINGER 1
+
+/* Define to 1 if the system has the type `struct sockaddr_in6'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_IN6 1
+
+/* Define to 1 if `sin6_len' is a member of `struct sockaddr_in6'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN */
+
+/* Define to 1 if `sin_len' is a member of `struct sockaddr_in'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
+
+/* Define to 1 if the system has the type `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE 1
+
+/* Define to 1 if `ss_family' is a member of `struct sockaddr_storage'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY 1
+
+/* Define to 1 if `__ss_family' is a member of `struct sockaddr_storage'. */
+/* #undef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY */
+
+/* Define to 1 if the system has the type `struct sockaddr_un'. */
+#define EVENT__HAVE_STRUCT_SOCKADDR_UN 1
+
+/* Define to 1 if you have the `sysctl' function. */
+/* #undef EVENT__HAVE_SYSCTL */
+
+/* Define to 1 if you have the <sys/devpoll.h> header file. */
+#define EVENT__HAVE_SYS_DEVPOLL_H 1
+
+/* Define to 1 if you have the <sys/epoll.h> header file. */
+/* #undef EVENT__HAVE_SYS_EPOLL_H */
+
+/* Define to 1 if you have the <sys/eventfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENTFD_H */
+
+/* Define to 1 if you have the <sys/event.h> header file. */
+/* #undef EVENT__HAVE_SYS_EVENT_H */
+
+/* Define to 1 if you have the <sys/ioctl.h> header file. */
+#define EVENT__HAVE_SYS_IOCTL_H 1
+
+/* Define to 1 if you have the <sys/mman.h> header file. */
+#define EVENT__HAVE_SYS_MMAN_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define EVENT__HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/queue.h> header file. */
+#define EVENT__HAVE_SYS_QUEUE_H 1
+
+/* Define to 1 if you have the <sys/random.h> header file. */
+#define EVENT__HAVE_SYS_RANDOM_H 1
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define EVENT__HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/select.h> header file. */
+#define EVENT__HAVE_SYS_SELECT_H 1
+
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#define EVENT__HAVE_SYS_SENDFILE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define EVENT__HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define EVENT__HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/sysctl.h> header file. */
+/* #undef EVENT__HAVE_SYS_SYSCTL_H */
+
+/* Define to 1 if you have the <sys/timerfd.h> header file. */
+/* #undef EVENT__HAVE_SYS_TIMERFD_H */
+
+/* Define to 1 if you have the <sys/time.h> header file. */
+#define EVENT__HAVE_SYS_TIME_H 1
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define EVENT__HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/uio.h> header file. */
+#define EVENT__HAVE_SYS_UIO_H 1
+
+/* Define to 1 if you have the <sys/un.h> header file. */
+#define EVENT__HAVE_SYS_UN_H 1
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define EVENT__HAVE_SYS_WAIT_H 1
+
+/* Define if TAILQ_FOREACH is defined in <sys/queue.h> */
+#define EVENT__HAVE_TAILQFOREACH 1
+
+/* Define if timeradd is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERADD 1
+
+/* Define if timerclear is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCLEAR 1
+
+/* Define if timercmp is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERCMP 1
+
+/* Define to 1 if you have the `timerfd_create' function. */
+/* #undef EVENT__HAVE_TIMERFD_CREATE */
+
+/* Define if timerisset is defined in <sys/time.h> */
+#define EVENT__HAVE_TIMERISSET 1
+
+/* Define to 1 if the system has the type `uint16_t'. */
+#define EVENT__HAVE_UINT16_T 1
+
+/* Define to 1 if the system has the type `uint32_t'. */
+#define EVENT__HAVE_UINT32_T 1
+
+/* Define to 1 if the system has the type `uint64_t'. */
+#define EVENT__HAVE_UINT64_T 1
+
+/* Define to 1 if the system has the type `uint8_t'. */
+#define EVENT__HAVE_UINT8_T 1
+
+/* Define to 1 if the system has the type `uintptr_t'. */
+#define EVENT__HAVE_UINTPTR_T 1
+
+/* Define to 1 if you have the `umask' function. */
+#define EVENT__HAVE_UMASK 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define EVENT__HAVE_UNISTD_H 1
+
+/* Define to 1 if you have the `unsetenv' function. */
+#define EVENT__HAVE_UNSETENV 1
+
+/* Define to 1 if you have the `usleep' function. */
+#define EVENT__HAVE_USLEEP 1
+
+/* Define to 1 if you have the `vasprintf' function. */
+#define EVENT__HAVE_VASPRINTF 1
+
+/* Define if kqueue works correctly with pipes */
+/* #undef EVENT__HAVE_WORKING_KQUEUE */
+
+/* Define to 1 if you have the <zlib.h> header file. */
+#define EVENT__HAVE_ZLIB_H 1
+
+/* Define to 1 if you have the `_gmtime64' function. */
+/* #undef EVENT__HAVE__GMTIME64 */
+
+/* Define to 1 if you have the `_gmtime64_s' function. */
+/* #undef EVENT__HAVE__GMTIME64_S */
+
+/* Define to 1 if compiler have __FUNCTION__ */
+#define EVENT__HAVE___FUNCTION__ 1
+
+/* Define to 1 if compiler have __func__ */
+#define EVENT__HAVE___func__ 1
+
+/* Define to the sub-directory where libtool stores uninstalled libraries. */
+#define EVENT__LT_OBJDIR ".libs/"
+
+/* Numeric representation of the version */
+#define EVENT__NUMERIC_VERSION 0x02010c00
+
+/* Name of package */
+#define EVENT__PACKAGE "libevent"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define EVENT__PACKAGE_BUGREPORT ""
+
+/* Define to the full name of this package. */
+#define EVENT__PACKAGE_NAME "libevent"
+
+/* Define to the full name and version of this package. */
+#define EVENT__PACKAGE_STRING "libevent 2.1.12-stable"
+
+/* Define to the one symbol short name of this package. */
+#define EVENT__PACKAGE_TARNAME "libevent"
+
+/* Define to the home page for this package. */
+#define EVENT__PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define EVENT__PACKAGE_VERSION "2.1.12-stable"
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef EVENT__PTHREAD_CREATE_JOINABLE */
+
+/* ------------------------------------------------------------------------ */
+/* MOZILLA NOTE: the following constants are hand-modified to be suitable */
+/* for both 32-bit and 64-bit platforms. See README.mozilla for details. */
+/* ------------------------------------------------------------------------ */
+
+/* The size of `int', as computed by sizeof. */
+#define EVENT__SIZEOF_INT 4
+
+/* The size of `long', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_LONG 8
+#else
+#define EVENT__SIZEOF_LONG 4
+#endif
+
+/* The size of `long long', as computed by sizeof. */
+#define EVENT__SIZEOF_LONG_LONG 8
+
+/* The size of `off_t', as computed by sizeof. */
+#define EVENT__SIZEOF_OFF_T 8
+
+/* The size of `pthread_t', as computed by sizeof. */
+#define EVENT__SIZEOF_PTHREAD_T 4
+
+/* The size of `short', as computed by sizeof. */
+#define EVENT__SIZEOF_SHORT 2
+
+/* The size of `size_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_SIZE_T 8
+#else
+#define EVENT__SIZEOF_SIZE_T 4
+#endif
+
+/* The size of `time_t', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_TIME_T 8
+#else
+#define EVENT__SIZEOF_TIME_T 4
+#endif
+
+/* The size of `void *', as computed by sizeof. */
+#ifdef __LP64__
+#define EVENT__SIZEOF_VOID_P 8
+#else
+#define EVENT__SIZEOF_VOID_P 4
+#endif
+
+/* ------------------------------------------------------------------------ */
+/* END MOZILLA NOTE */
+/* ------------------------------------------------------------------------ */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* Define to 1 if you can safely include both <sys/time.h> and <time.h>. */
+#define EVENT__TIME_WITH_SYS_TIME 1
+
+/* Enable extensions on AIX 3, Interix. */
+#ifndef _ALL_SOURCE
+# define _ALL_SOURCE 1
+#endif
+/* Enable GNU extensions on systems that have them. */
+#ifndef _GNU_SOURCE
+# define _GNU_SOURCE 1
+#endif
+/* Enable threading extensions on Solaris. */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# define _POSIX_PTHREAD_SEMANTICS 1
+#endif
+/* Enable extensions on HP NonStop. */
+#ifndef _TANDEM_SOURCE
+# define _TANDEM_SOURCE 1
+#endif
+/* Enable general extensions on Solaris. */
+#ifndef __EXTENSIONS__
+# define __EXTENSIONS__ 1
+#endif
+
+
+/* Version number of package */
+#define EVENT__VERSION "2.1.12-stable"
+
+/* Enable large inode numbers on Mac OS X 10.5. */
+#ifndef _DARWIN_USE_64_BIT_INODE
+# define _DARWIN_USE_64_BIT_INODE 1
+#endif
+
+/* Number of bits in a file offset, on hosts where this is settable. */
+#ifdef __LP64__
+/* #undef _FILE_OFFSET_BITS */
+#else
+#define _FILE_OFFSET_BITS 64
+#endif
+
+/* Define for large files, on AIX-style hosts. */
+/* #undef _LARGE_FILES */
+
+/* Define to 1 if on MINIX. */
+/* #undef _MINIX */
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+ this defined. */
+/* #undef _POSIX_1_SOURCE */
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+/* #undef _POSIX_SOURCE */
+
+/* Define to appropriate substitue if compiler doesnt have __func__ */
+/* #undef __func__ */
+
+/* Define to empty if `const' does not conform to ANSI C. */
+/* #undef const */
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef pid_t */
+
+/* Define to `unsigned int' if <sys/types.h> does not define. */
+/* #undef size_t */
+
+/* Define to unsigned int if you dont have it */
+/* #undef socklen_t */
+
+/* Define to `int' if <sys/types.h> does not define. */
+/* #undef ssize_t */
+
+#endif /* event2/event-config.h */
diff --git a/ipc/chromium/src/third_party/libevent/strlcpy-internal.h b/ipc/chromium/src/third_party/libevent/strlcpy-internal.h
new file mode 100644
index 0000000000..4151d601d0
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/strlcpy-internal.h
@@ -0,0 +1,24 @@
+#ifndef STRLCPY_INTERNAL_H_INCLUDED_
+#define STRLCPY_INTERNAL_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "event2/event-config.h"
+#include "event2/visibility.h"
+#include "evconfig-private.h"
+
+#ifndef EVENT__HAVE_STRLCPY
+#include <string.h>
+EVENT2_EXPORT_SYMBOL
+size_t event_strlcpy_(char *dst, const char *src, size_t siz);
+#define strlcpy event_strlcpy_
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/ipc/chromium/src/third_party/libevent/strlcpy.c b/ipc/chromium/src/third_party/libevent/strlcpy.c
new file mode 100644
index 0000000000..3876475f5a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/strlcpy.c
@@ -0,0 +1,75 @@
+/* $OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $ */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+ * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
+ * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#if defined(LIBC_SCCS) && !defined(lint)
+static char *rcsid = "$OpenBSD: strlcpy.c,v 1.5 2001/05/13 15:40:16 deraadt Exp $";
+#endif /* LIBC_SCCS and not lint */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <sys/types.h>
+
+#ifndef EVENT__HAVE_STRLCPY
+#include "strlcpy-internal.h"
+
+/*
+ * Copy src to string dst of size siz. At most siz-1 characters
+ * will be copied. Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+size_t
+event_strlcpy_(dst, src, siz)
+ char *dst;
+ const char *src;
+ size_t siz;
+{
+ register char *d = dst;
+ register const char *s = src;
+ register size_t n = siz;
+
+ /* Copy as many bytes as will fit */
+ if (n != 0 && --n != 0) {
+ do {
+ if ((*d++ = *s++) == 0)
+ break;
+ } while (--n != 0);
+ }
+
+ /* Not enough room in dst, add NUL and traverse rest of src */
+ if (n == 0) {
+ if (siz != 0)
+ *d = '\0'; /* NUL-terminate dst */
+ while (*s++)
+ ;
+ }
+
+ return (s - src - 1); /* count does not include NUL */
+}
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/test-export/CMakeLists.txt b/ipc/chromium/src/third_party/libevent/test-export/CMakeLists.txt
new file mode 100644
index 0000000000..53a1cf527b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test-export/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.1.2)
+if (POLICY CMP0074)
+ cmake_policy(SET CMP0074 NEW)
+endif()
+project(verify)
+# set(CMAKE_VERBOSE_MAKEFILE 1)
+if(NOT ${EVENT__CODE_COMPONENT} STREQUAL "")
+ string(TOUPPER ${EVENT__CODE_COMPONENT} _UPPER_COMPONENT)
+endif()
+find_package(Libevent 2.1.0 REQUIRED COMPONENTS ${EVENT__LINK_COMPONENT})
+add_definitions(-DEVENT_EXPORT_TEST_COMPONENT_${_UPPER_COMPONENT})
+add_executable(test-export test-export.c)
+target_link_libraries(test-export ${LIBEVENT_LIBRARIES})
+enable_testing()
+add_test(test-export test-export)
diff --git a/ipc/chromium/src/third_party/libevent/test-export/test-export.c b/ipc/chromium/src/third_party/libevent/test-export/test-export.c
new file mode 100644
index 0000000000..9091777554
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test-export/test-export.c
@@ -0,0 +1,122 @@
+#include <event2/event.h>
+#if defined(EVENT_EXPORT_TEST_COMPONENT_EXTRA)
+#include "event2/http.h"
+#include "event2/rpc.h"
+#include <event2/dns.h>
+#elif defined(EVENT_EXPORT_TEST_COMPONENT_PTHREADS)
+#include <event2/thread.h>
+#elif defined(EVENT_EXPORT_TEST_COMPONENT_OPENSSL)
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#include <event2/bufferevent_ssl.h>
+#endif
+
+#if defined(EVENT_EXPORT_TEST_COMPONENT_EXTRA)
+static int
+test()
+{
+ struct event_base *base = NULL;
+ struct evhttp *http = NULL;
+ struct evdns_base *dns_base = NULL;
+ struct evrpc_base *rpc_base = NULL;
+
+ base = event_base_new();
+ if (base) {
+ http = evhttp_new(base);
+ dns_base = evdns_base_new(base,
+ EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+ }
+ if (http)
+ rpc_base = evrpc_init(http);
+
+ if (base)
+ event_base_free(base);
+ if (http)
+ evhttp_free(http);
+ if (rpc_base)
+ evrpc_free(rpc_base);
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+
+ return 0;
+}
+#elif defined(EVENT_EXPORT_TEST_COMPONENT_PTHREADS)
+static int
+test()
+{
+ return evthread_use_pthreads();
+}
+#elif defined(EVENT_EXPORT_TEST_COMPONENT_OPENSSL)
+static int
+test()
+{
+ struct event_base *base = NULL;
+ SSL_CTX *ssl_ctx = NULL;
+ SSL *ssl = NULL;
+ struct bufferevent *bev;
+ int r = 1;
+
+ SSL_library_init();
+ ERR_load_crypto_strings();
+ SSL_load_error_strings();
+ OpenSSL_add_all_algorithms();
+
+ base = event_base_new();
+ if (!base) {
+ goto error;
+ }
+
+ ssl_ctx = SSL_CTX_new(SSLv23_method());
+ if (!ssl_ctx) {
+ goto error;
+ }
+ ssl = SSL_new(ssl_ctx);
+ if (ssl == NULL) {
+ goto error;
+ }
+ bev = bufferevent_openssl_socket_new(base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING,
+ BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
+ if (bev == NULL) {
+ goto error;
+ }
+ r = 0;
+error:
+ if (base)
+ event_base_free(base);
+ if (ssl_ctx)
+ SSL_CTX_free(ssl_ctx);
+ if (ssl)
+ SSL_free(ssl);
+ return r;
+}
+#else
+static int
+test()
+{
+ struct event_base *base = NULL;
+
+ base = event_base_new();
+ if (base)
+ event_base_free(base);
+
+ return 0;
+}
+#endif
+
+int
+main(int argc, char const *argv[])
+{
+ int r = 0;
+#ifdef _WIN32
+ {
+ WSADATA wsaData;
+ WSAStartup(MAKEWORD(2, 2), &wsaData);
+ }
+#endif
+ r = test();
+#ifdef _WIN32
+ WSACleanup();
+#endif
+ return r;
+}
diff --git a/ipc/chromium/src/third_party/libevent/test-export/test-export.py b/ipc/chromium/src/third_party/libevent/test-export/test-export.py
new file mode 100644
index 0000000000..d71e5dbaa1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test-export/test-export.py
@@ -0,0 +1,199 @@
+#!/usr/bin/env python3
+#
+# Check if find_package(Libevent COMPONENTS xxx) can get the correct library.
+# Note: this script has only been tested on python3.
+# Usage:
+# cd cmake-build-dir
+# cmake <options> .. && cmake --build .
+# python /path/to/test-export.py [static|shared]
+
+import sys
+import os
+import shutil
+import platform
+import subprocess
+import tempfile
+
+results = ("success", "failure")
+FNULL = open(os.devnull, 'wb')
+script_dir = os.path.split(os.path.realpath(sys.argv[0]))[0]
+# working_dir is cmake build dir
+working_dir = os.getcwd()
+if len(sys.argv) > 1 and sys.argv[1] == "static":
+ link_type = sys.argv[1]
+else:
+ link_type = "shared"
+
+
+def exec_cmd(cmd, silent):
+ if silent:
+ p = subprocess.Popen(cmd, stdout=FNULL, stderr=FNULL, shell=True)
+ else:
+ p = subprocess.Popen(cmd, shell=True)
+ p.communicate()
+ return p.poll()
+
+
+def link_and_run(link, code):
+ """Check if the source code matches the library component.
+
+ Compile source code relative to one component and link to another component.
+ Then run the generated executor.
+
+ Args:
+ link: The name of component that the source code will link with.
+ code: The source code related component name.
+
+ Returns:
+ Returns 0 if links and runs successfully, otherwise 1.
+ """
+ exec_cmd("cmake --build . --target clean", True)
+ arch = ''
+ if platform.system() == "Windows":
+ arch = '-A x64'
+ cmd = 'cmake .. %s -DEVENT__LINK_COMPONENT=%s -DEVENT__CODE_COMPONENT=%s' % (
+ arch, link, code)
+ if link_type == "static":
+ cmd = "".join([cmd, " -DLIBEVENT_STATIC_LINK=1"])
+ r = exec_cmd(cmd, True)
+ if r == 0:
+ r = exec_cmd('cmake --build .', True)
+ if r == 0:
+ r = exec_cmd('ctest', True)
+ if r != 0:
+ r = 1
+ return r
+
+# expect 0:success 1:failure
+def testcase(link, code, expect):
+ r = link_and_run(link, code)
+ if link == "":
+ link = "all"
+ if code == "":
+ code = "all"
+ if r != expect:
+ print('[test-export] fail: link %s and run %s expects %s but gets %s.' %
+ (link, code, results[expect], results[r]))
+ sys.exit(1)
+ else:
+ print('[test-export] success: link %s and run %s expects and gets %s.' %
+ (link, code, results[r]))
+
+# Dependency relationships between libevent libraries:
+# core: none
+# extra: core
+# pthreads: core,pthread
+# openssl: core,openssl
+def test_group():
+ testcase("core", "core", 0)
+ testcase("extra", "extra", 0)
+ testcase("openssl", "openssl", 0)
+ testcase("", "", 0)
+ testcase("extra", "core", 0)
+ testcase("openssl", "core", 0)
+ testcase("core", "extra", 1)
+ testcase("core", "openssl", 1)
+ testcase("extra", "openssl", 1)
+ testcase("openssl", "extra", 1)
+ if platform.system() != "Windows":
+ testcase("pthreads", "pthreads", 0)
+ testcase("pthreads", "core", 0)
+ testcase("core", "pthreads", 1)
+ testcase("extra", "pthreads", 1)
+ testcase("pthreads", "extra", 1)
+ testcase("pthreads", "openssl", 1)
+ testcase("openssl", "pthreads", 1)
+
+
+def config_restore():
+ if os.path.isfile("tempconfig") and not os.path.isfile("LibeventConfig.cmake"):
+ os.rename("tempconfig", "LibeventConfig.cmake")
+
+
+def config_backup():
+ if os.path.isfile("tempconfig"):
+ os.remove("tempconfig")
+ if os.path.isfile("LibeventConfig.cmake"):
+ os.rename("LibeventConfig.cmake", "tempconfig")
+
+
+shutil.rmtree(os.path.join(script_dir, "build"), ignore_errors=True)
+
+
+def run_test_group():
+ os.chdir(script_dir)
+ if not os.path.isdir("build"):
+ os.mkdir("build")
+ os.chdir("build")
+ test_group()
+ os.chdir(working_dir)
+
+
+need_exportdll = False
+if link_type == "shared" and platform.system() == "Windows":
+ need_exportdll = True
+
+# On Windows, we need to add the directory containing the dll to the
+# 'PATH' environment variable so that the program can call it.
+def export_dll(dir):
+ if need_exportdll:
+ os.environ["PATH"] += os.pathsep + dir
+
+
+def unexport_dll(dir):
+ if need_exportdll:
+ paths = os.environ["PATH"].split(os.pathsep)
+ paths = list(set(paths))
+ if dir in paths:
+ paths.remove(dir)
+ os.environ["PATH"] = os.pathsep.join(paths)
+
+
+print("[test-export] use %s library" % link_type)
+
+# Test for build tree.
+print("[test-export] test for build tree")
+dllpath = os.path.join(working_dir, "bin", "Debug")
+config_restore()
+os.environ["CMAKE_PREFIX_PATH"] = working_dir
+export_dll(dllpath)
+run_test_group()
+del os.environ["CMAKE_PREFIX_PATH"]
+unexport_dll(dllpath)
+
+# Install libevent libraries to system path. Remove LibeventConfig.cmake
+# from build directory to avoid confusion when using find_package().
+print("[test-export] test for install tree(in system-wide path)")
+if platform.system() == "Windows":
+ prefix = "C:\\Program Files\\libevent"
+ dllpath = os.path.join(prefix, "lib")
+else:
+ prefix = "/usr/local"
+exec_cmd('cmake -DCMAKE_INSTALL_PREFIX="%s" ..' % prefix, True)
+exec_cmd('cmake --build . --target install', True)
+config_backup()
+os.environ["CMAKE_PREFIX_PATH"] = os.path.join(prefix, "lib/cmake/libevent")
+export_dll(dllpath)
+run_test_group()
+unexport_dll(dllpath)
+del os.environ["CMAKE_PREFIX_PATH"]
+
+# Uninstall the libraries installed in the above steps. Install the libraries
+# into a temporary directory. Same as above, remove LibeventConfig.cmake from
+# build directory to avoid confusion when using find_package().
+print("[test-export] test for install tree(in non-system-wide path)")
+exec_cmd("cmake --build . --target uninstall", True)
+tempdir = tempfile.TemporaryDirectory()
+cmd = 'cmake -DCMAKE_INSTALL_PREFIX="%s" ..' % tempdir.name
+exec_cmd(cmd, True)
+exec_cmd("cmake --build . --target install", True)
+config_backup()
+os.environ["CMAKE_PREFIX_PATH"] = os.path.join(tempdir.name, "lib/cmake/libevent")
+dllpath = os.path.join(tempdir.name, "lib")
+export_dll(dllpath)
+run_test_group()
+unexport_dll(dllpath)
+del os.environ["CMAKE_PREFIX_PATH"]
+config_restore()
+
+print("[test-export] all testcases have run successfully")
diff --git a/ipc/chromium/src/third_party/libevent/test/Makefile.nmake b/ipc/chromium/src/third_party/libevent/test/Makefile.nmake
new file mode 100644
index 0000000000..30c3eb792b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/Makefile.nmake
@@ -0,0 +1,79 @@
+# WATCH OUT! This makefile is a work in progress. -*- makefile -*-
+
+!IFDEF OPENSSL_DIR
+SSL_CFLAGS=/I$(OPENSSL_DIR)\include /DEVENT__HAVE_OPENSSL
+SSL_OBJS=regress_ssl.obj
+SSL_LIBS=..\libevent_openssl.lib $(OPENSSL_DIR)\lib\libeay32.lib $(OPENSSL_DIR)\lib\ssleay32.lib gdi32.lib User32.lib
+!ELSE
+SSL_CFLAGS=
+SSL_OBJS=
+SSL_LIBS=
+!ENDIF
+
+CFLAGS=/I.. /I../WIN32-Code /I../WIN32-Code/nmake /I../include /I../compat /DHAVE_CONFIG_H /DTINYTEST_LOCAL $(SSL_CFLAGS)
+
+CFLAGS=$(CFLAGS) /Ox /W3 /wd4996 /nologo
+
+REGRESS_OBJS=regress.obj regress_buffer.obj regress_http.obj regress_dns.obj \
+ regress_testutils.obj \
+ regress_rpc.obj regress.gen.obj \
+ regress_et.obj regress_bufferevent.obj \
+ regress_listener.obj regress_util.obj tinytest.obj \
+ regress_main.obj regress_minheap.obj regress_iocp.obj \
+ regress_thread.obj regress_finalize.obj $(SSL_OBJS)
+
+OTHER_OBJS=test-init.obj test-eof.obj test-closed.obj test-weof.obj test-time.obj \
+ bench.obj bench_cascade.obj bench_http.obj bench_httpclient.obj \
+ test-changelist.obj \
+ print-winsock-errors.obj
+
+PROGRAMS=regress.exe \
+ test-init.exe test-eof.exe test-closed.exe test-weof.exe test-time.exe \
+ test-changelist.exe \
+ print-winsock-errors.exe
+
+# Disabled for now:
+# bench.exe bench_cascade.exe bench_http.exe bench_httpclient.exe
+
+
+LIBS=..\libevent.lib ws2_32.lib shell32.lib advapi32.lib
+
+all: $(PROGRAMS)
+
+regress.exe: $(REGRESS_OBJS)
+ $(CC) $(CFLAGS) $(LIBS) $(SSL_LIBS) $(REGRESS_OBJS)
+
+test-init.exe: test-init.obj
+ $(CC) $(CFLAGS) $(LIBS) test-init.obj
+test-eof.exe: test-eof.obj
+ $(CC) $(CFLAGS) $(LIBS) test-eof.obj
+test-closed.exe: test-closed.obj
+ $(CC) $(CFLAGS) $(LIBS) test-closed.obj
+test-changelist.exe: test-changelist.obj
+ $(CC) $(CFLAGS) $(LIBS) test-changelist.obj
+test-weof.exe: test-weof.obj
+ $(CC) $(CFLAGS) $(LIBS) test-weof.obj
+test-time.exe: test-time.obj
+ $(CC) $(CFLAGS) $(LIBS) test-time.obj
+
+print-winsock-errors.exe: print-winsock-errors.obj
+ $(CC) $(CFLAGS) $(LIBS) print-winsock-errors.obj
+
+bench.exe: bench.obj
+ $(CC) $(CFLAGS) $(LIBS) bench.obj
+bench_cascade.exe: bench_cascade.obj
+ $(CC) $(CFLAGS) $(LIBS) bench_cascade.obj
+bench_http.exe: bench_http.obj
+ $(CC) $(CFLAGS) $(LIBS) bench_http.obj
+bench_httpclient.exe: bench_httpclient.obj
+ $(CC) $(CFLAGS) $(LIBS) bench_httpclient.obj
+
+regress.gen.c regress.gen.h: regress.rpc ../event_rpcgen.py
+ echo // > regress.gen.c
+ echo #define NO_PYTHON_EXISTS > regress.gen.h
+ -python ..\event_rpcgen.py regress.rpc
+
+clean:
+ -del $(REGRESS_OBJS)
+ -del $(OTHER_OBJS)
+ -del $(PROGRAMS)
diff --git a/ipc/chromium/src/third_party/libevent/test/bench.c b/ipc/chromium/src/third_party/libevent/test/bench.c
new file mode 100644
index 0000000000..f2af4d3f30
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/bench.c
@@ -0,0 +1,235 @@
+/*
+ * Copyright 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ *
+ * Mon 03/10/2003 - Modified by Davide Libenzi <davidel@xmailserver.org>
+ *
+ * Added chain event propagation to improve the sensitivity of
+ * the measure respect to the event loop efficency.
+ *
+ *
+ */
+
+#include "event2/event-config.h"
+#include "../util-internal.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#else
+#include <sys/socket.h>
+#include <signal.h>
+#include <sys/resource.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#ifdef _WIN32
+#include <getopt.h>
+#endif
+
+#include <event.h>
+#include <evutil.h>
+
+static ev_ssize_t count, fired;
+static int writes, failures;
+static evutil_socket_t *pipes;
+static int num_pipes, num_active, num_writes;
+static struct event *events;
+static struct event_base *base;
+
+
+static void
+read_cb(evutil_socket_t fd, short which, void *arg)
+{
+ ev_intptr_t idx = (ev_intptr_t) arg, widx = idx + 1;
+ unsigned char ch;
+ ev_ssize_t n;
+
+ n = recv(fd, (char*)&ch, sizeof(ch), 0);
+ if (n >= 0)
+ count += n;
+ else
+ failures++;
+ if (writes) {
+ if (widx >= num_pipes)
+ widx -= num_pipes;
+ n = send(pipes[2 * widx + 1], "e", 1, 0);
+ if (n != 1)
+ failures++;
+ writes--;
+ fired++;
+ }
+}
+
+static struct timeval *
+run_once(void)
+{
+ evutil_socket_t *cp, space;
+ long i;
+ static struct timeval ts, te;
+
+ for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+ if (event_initialized(&events[i]))
+ event_del(&events[i]);
+ event_assign(&events[i], base, cp[0], EV_READ | EV_PERSIST, read_cb, (void *)(ev_intptr_t) i);
+ event_add(&events[i], NULL);
+ }
+
+ event_base_loop(base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
+
+ fired = 0;
+ space = num_pipes / num_active;
+ space = space * 2;
+ for (i = 0; i < num_active; i++, fired++)
+ (void) send(pipes[i * space + 1], "e", 1, 0);
+
+ count = 0;
+ writes = num_writes;
+ {
+ int xcount = 0;
+ evutil_gettimeofday(&ts, NULL);
+ do {
+ event_base_loop(base, EVLOOP_ONCE | EVLOOP_NONBLOCK);
+ xcount++;
+ } while (count != fired);
+ evutil_gettimeofday(&te, NULL);
+
+ if (xcount != count)
+ fprintf(stderr, "Xcount: %d, Rcount: " EV_SSIZE_FMT "\n",
+ xcount, count);
+ }
+
+ evutil_timersub(&te, &ts, &te);
+
+ return (&te);
+}
+
+int
+main(int argc, char **argv)
+{
+#ifdef EVENT__HAVE_SETRLIMIT
+ struct rlimit rl;
+#endif
+ int i, c;
+ struct timeval *tv;
+ evutil_socket_t *cp;
+ const char **methods;
+ const char *method = NULL;
+ struct event_config *cfg = NULL;
+
+#ifdef _WIN32
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+#endif
+ num_pipes = 100;
+ num_active = 1;
+ num_writes = num_pipes;
+ while ((c = getopt(argc, argv, "n:a:w:m:l")) != -1) {
+ switch (c) {
+ case 'n':
+ num_pipes = atoi(optarg);
+ break;
+ case 'a':
+ num_active = atoi(optarg);
+ break;
+ case 'w':
+ num_writes = atoi(optarg);
+ break;
+ case 'm':
+ method = optarg;
+ break;
+ case 'l':
+ methods = event_get_supported_methods();
+ fprintf(stdout, "Using Libevent %s. Available methods are:\n",
+ event_get_version());
+ for (i = 0; methods[i] != NULL; ++i)
+ printf(" %s\n", methods[i]);
+ exit(0);
+ default:
+ fprintf(stderr, "Illegal argument \"%c\"\n", c);
+ exit(1);
+ }
+ }
+
+#ifdef EVENT__HAVE_SETRLIMIT
+ rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
+ if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+ perror("setrlimit");
+ exit(1);
+ }
+#endif
+
+ events = calloc(num_pipes, sizeof(struct event));
+ pipes = calloc(num_pipes * 2, sizeof(evutil_socket_t));
+ if (events == NULL || pipes == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+
+ if (method != NULL) {
+ cfg = event_config_new();
+ methods = event_get_supported_methods();
+ for (i = 0; methods[i] != NULL; ++i)
+ if (strcmp(methods[i], method))
+ event_config_avoid_method(cfg, methods[i]);
+ base = event_base_new_with_config(cfg);
+ event_config_free(cfg);
+ } else
+ base = event_base_new();
+
+ for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+#ifdef USE_PIPES
+ if (pipe(cp) == -1) {
+#else
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
+#endif
+ perror("pipe");
+ exit(1);
+ }
+ }
+
+ for (i = 0; i < 25; i++) {
+ tv = run_once();
+ if (tv == NULL)
+ exit(1);
+ fprintf(stdout, "%ld\n",
+ tv->tv_sec * 1000000L + tv->tv_usec);
+ }
+
+ exit(0);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/bench_cascade.c b/ipc/chromium/src/third_party/libevent/test/bench_cascade.c
new file mode 100644
index 0000000000..29a3203ecd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/bench_cascade.c
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <getopt.h>
+#else /* _WIN32 */
+#include <sys/socket.h>
+#include <sys/resource.h>
+#endif
+#include <signal.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <errno.h>
+#include <event.h>
+#include <evutil.h>
+
+/*
+ * This benchmark tests how quickly we can propagate a write down a chain
+ * of socket pairs. We start by writing to the first socket pair and all
+ * events will fire subsequently until the last socket pair has been reached
+ * and the benchmark terminates.
+ */
+
+static int fired;
+static evutil_socket_t *pipes;
+static struct event *events;
+
+static void
+read_cb(evutil_socket_t fd, short which, void *arg)
+{
+ char ch;
+ evutil_socket_t sock = (evutil_socket_t)(ev_intptr_t)arg;
+
+ (void) recv(fd, &ch, sizeof(ch), 0);
+ if (sock >= 0) {
+ if (send(sock, "e", 1, 0) < 0)
+ perror("send");
+ }
+ fired++;
+}
+
+static struct timeval *
+run_once(int num_pipes)
+{
+ int i;
+ evutil_socket_t *cp;
+ static struct timeval ts, te, tv_timeout;
+
+ events = (struct event *)calloc(num_pipes, sizeof(struct event));
+ pipes = (evutil_socket_t *)calloc(num_pipes * 2, sizeof(evutil_socket_t));
+
+ if (events == NULL || pipes == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+
+ for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, cp) == -1) {
+ perror("socketpair");
+ exit(1);
+ }
+ }
+
+ /* measurements includes event setup */
+ evutil_gettimeofday(&ts, NULL);
+
+ /* provide a default timeout for events */
+ evutil_timerclear(&tv_timeout);
+ tv_timeout.tv_sec = 60;
+
+ for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+ evutil_socket_t fd = i < num_pipes - 1 ? cp[3] : -1;
+ event_set(&events[i], cp[0], EV_READ, read_cb,
+ (void *)(ev_intptr_t)fd);
+ event_add(&events[i], &tv_timeout);
+ }
+
+ fired = 0;
+
+ /* kick everything off with a single write */
+ if (send(pipes[1], "e", 1, 0) < 0)
+ perror("send");
+
+ event_dispatch();
+
+ evutil_gettimeofday(&te, NULL);
+ evutil_timersub(&te, &ts, &te);
+
+ for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
+ event_del(&events[i]);
+ evutil_closesocket(cp[0]);
+ evutil_closesocket(cp[1]);
+ }
+
+ free(pipes);
+ free(events);
+
+ return (&te);
+}
+
+int
+main(int argc, char **argv)
+{
+#ifdef EVENT__HAVE_SETRLIMIT
+ struct rlimit rl;
+#endif
+ int i, c;
+ struct timeval *tv;
+
+ int num_pipes = 100;
+#ifdef _WIN32
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+#endif
+
+ while ((c = getopt(argc, argv, "n:")) != -1) {
+ switch (c) {
+ case 'n':
+ num_pipes = atoi(optarg);
+ break;
+ default:
+ fprintf(stderr, "Illegal argument \"%c\"\n", c);
+ exit(1);
+ }
+ }
+
+#ifdef EVENT__HAVE_SETRLIMIT
+ rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
+ if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+ perror("setrlimit");
+ exit(1);
+ }
+#endif
+
+ event_init();
+
+ for (i = 0; i < 25; i++) {
+ tv = run_once(num_pipes);
+ if (tv == NULL)
+ exit(1);
+ fprintf(stdout, "%ld\n",
+ tv->tv_sec * 1000000L + tv->tv_usec);
+ }
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+ exit(0);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/bench_http.c b/ipc/chromium/src/third_party/libevent/test/bench_http.c
new file mode 100644
index 0000000000..80377ee605
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/bench_http.c
@@ -0,0 +1,200 @@
+/*
+ * Copyright 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <sys/socket.h>
+#include <sys/resource.h>
+#include <sys/time.h>
+#include <unistd.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/util.h"
+#include "event2/http.h"
+#include "event2/thread.h"
+
+static void http_basic_cb(struct evhttp_request *req, void *arg);
+
+static char *content;
+static size_t content_len = 0;
+
+static void
+http_basic_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+
+ evbuffer_add(evb, content, content_len);
+
+ /* allow sending of an empty reply */
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+ evbuffer_free(evb);
+}
+
+#if LIBEVENT_VERSION_NUMBER >= 0x02000200
+static void
+http_ref_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+
+ evbuffer_add_reference(evb, content, content_len, NULL, NULL);
+
+ /* allow sending of an empty reply */
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+ evbuffer_free(evb);
+}
+#endif
+
+int
+main(int argc, char **argv)
+{
+ struct event_config *cfg = event_config_new();
+ struct event_base *base;
+ struct evhttp *http;
+ int i;
+ int c;
+ int use_iocp = 0;
+ ev_uint16_t port = 8080;
+ char *endptr = NULL;
+
+#ifdef _WIN32
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+#else
+ if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+ return (1);
+#endif
+
+ setbuf(stdout, NULL);
+ setbuf(stderr, NULL);
+
+ for (i = 1; i < argc; ++i) {
+ if (*argv[i] != '-')
+ continue;
+
+ c = argv[i][1];
+
+ if ((c == 'p' || c == 'l') && i + 1 >= argc) {
+ fprintf(stderr, "-%c requires argument.\n", c);
+ exit(1);
+ }
+
+ switch (c) {
+ case 'p':
+ if (i+1 >= argc || !argv[i+1]) {
+ fprintf(stderr, "Missing port\n");
+ exit(1);
+ }
+ port = (int)strtol(argv[i+1], &endptr, 10);
+ if (*endptr != '\0') {
+ fprintf(stderr, "Bad port\n");
+ exit(1);
+ }
+ break;
+ case 'l':
+ if (i+1 >= argc || !argv[i+1]) {
+ fprintf(stderr, "Missing content length\n");
+ exit(1);
+ }
+ content_len = (size_t)strtol(argv[i+1], &endptr, 10);
+ if (*endptr != '\0' || content_len == 0) {
+ fprintf(stderr, "Bad content length\n");
+ exit(1);
+ }
+ break;
+#ifdef _WIN32
+ case 'i':
+ use_iocp = 1;
+#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
+ evthread_use_windows_threads();
+#endif
+ event_config_set_flag(cfg,EVENT_BASE_FLAG_STARTUP_IOCP);
+ break;
+#endif
+ default:
+ fprintf(stderr, "Illegal argument \"%c\"\n", c);
+ exit(1);
+ }
+ }
+
+ base = event_base_new_with_config(cfg);
+ if (!base) {
+ fprintf(stderr, "creating event_base failed. Exiting.\n");
+ return 1;
+ }
+
+ http = evhttp_new(base);
+
+ content = malloc(content_len);
+ if (content == NULL) {
+ fprintf(stderr, "Cannot allocate content\n");
+ exit(1);
+ } else {
+ int i = 0;
+ for (i = 0; i < (int)content_len; ++i)
+ content[i] = (i & 255);
+ }
+
+ evhttp_set_cb(http, "/ind", http_basic_cb, NULL);
+ fprintf(stderr, "/ind - basic content (memory copy)\n");
+
+ evhttp_set_cb(http, "/ref", http_ref_cb, NULL);
+ fprintf(stderr, "/ref - basic content (reference)\n");
+
+ fprintf(stderr, "Serving %d bytes on port %d using %s\n",
+ (int)content_len, port,
+ use_iocp? "IOCP" : event_base_get_method(base));
+
+ evhttp_bind_socket(http, "0.0.0.0", port);
+
+#ifdef _WIN32
+ if (use_iocp) {
+ struct timeval tv={99999999,0};
+ event_base_loopexit(base, &tv);
+ }
+#endif
+ event_base_dispatch(base);
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+ /* NOTREACHED */
+ return (0);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/bench_httpclient.c b/ipc/chromium/src/third_party/libevent/test/bench_httpclient.c
new file mode 100644
index 0000000000..7c7ee470a3
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/bench_httpclient.c
@@ -0,0 +1,240 @@
+/*
+ * Copyright 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 4. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+/* for EVUTIL_ERR_CONNECT_RETRIABLE macro */
+#include "util-internal.h"
+
+#include <sys/types.h>
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+# include <arpa/inet.h>
+# endif
+#endif
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/util.h"
+
+const char *resource = NULL;
+struct event_base *base = NULL;
+
+int total_n_handled = 0;
+int total_n_errors = 0;
+int total_n_launched = 0;
+size_t total_n_bytes = 0;
+struct timeval total_time = {0,0};
+int n_errors = 0;
+
+const int PARALLELISM = 200;
+const int N_REQUESTS = 20000;
+
+struct request_info {
+ size_t n_read;
+ struct timeval started;
+};
+
+static int launch_request(void);
+static void readcb(struct bufferevent *b, void *arg);
+static void errorcb(struct bufferevent *b, short what, void *arg);
+
+static void
+readcb(struct bufferevent *b, void *arg)
+{
+ struct request_info *ri = arg;
+ struct evbuffer *input = bufferevent_get_input(b);
+ size_t n = evbuffer_get_length(input);
+
+ ri->n_read += n;
+ evbuffer_drain(input, n);
+}
+
+static void
+errorcb(struct bufferevent *b, short what, void *arg)
+{
+ struct request_info *ri = arg;
+ struct timeval now, diff;
+ if (what & BEV_EVENT_EOF) {
+ ++total_n_handled;
+ total_n_bytes += ri->n_read;
+ evutil_gettimeofday(&now, NULL);
+ evutil_timersub(&now, &ri->started, &diff);
+ evutil_timeradd(&diff, &total_time, &total_time);
+
+ if (total_n_handled && (total_n_handled%1000)==0)
+ printf("%d requests done\n",total_n_handled);
+
+ if (total_n_launched < N_REQUESTS) {
+ if (launch_request() < 0)
+ perror("Can't launch");
+ }
+ } else {
+ ++total_n_errors;
+ perror("Unexpected error");
+ }
+
+ bufferevent_setcb(b, NULL, NULL, NULL, NULL);
+ free(ri);
+ bufferevent_disable(b, EV_READ|EV_WRITE);
+ bufferevent_free(b);
+}
+
+static void
+frob_socket(evutil_socket_t sock)
+{
+#ifdef EVENT__HAVE_STRUCT_LINGER
+ struct linger l;
+#endif
+ int one = 1;
+ if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&one, sizeof(one))<0)
+ perror("setsockopt(SO_REUSEADDR)");
+#ifdef EVENT__HAVE_STRUCT_LINGER
+ l.l_onoff = 1;
+ l.l_linger = 0;
+ if (setsockopt(sock, SOL_SOCKET, SO_LINGER, (void*)&l, sizeof(l))<0)
+ perror("setsockopt(SO_LINGER)");
+#endif
+}
+
+static int
+launch_request(void)
+{
+ evutil_socket_t sock;
+ struct sockaddr_in sin;
+ struct bufferevent *b;
+
+ struct request_info *ri;
+
+ memset(&sin, 0, sizeof(sin));
+
+ ++total_n_launched;
+
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001);
+ sin.sin_port = htons(8080);
+ if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
+ return -1;
+ if (evutil_make_socket_nonblocking(sock) < 0) {
+ evutil_closesocket(sock);
+ return -1;
+ }
+ frob_socket(sock);
+ if (connect(sock, (struct sockaddr*)&sin, sizeof(sin)) < 0) {
+ int e = evutil_socket_geterror(sock);
+ if (! EVUTIL_ERR_CONNECT_RETRIABLE(e)) {
+ evutil_closesocket(sock);
+ return -1;
+ }
+ }
+
+ ri = malloc(sizeof(*ri));
+ ri->n_read = 0;
+ evutil_gettimeofday(&ri->started, NULL);
+
+ b = bufferevent_socket_new(base, sock, BEV_OPT_CLOSE_ON_FREE);
+
+ bufferevent_setcb(b, readcb, NULL, errorcb, ri);
+ bufferevent_enable(b, EV_READ|EV_WRITE);
+
+ evbuffer_add_printf(bufferevent_get_output(b),
+ "GET %s HTTP/1.0\r\n\r\n", resource);
+
+ return 0;
+}
+
+
+int
+main(int argc, char **argv)
+{
+ int i;
+ struct timeval start, end, total;
+ long long usec;
+ double throughput;
+
+#ifdef _WIN32
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+#endif
+
+ resource = "/ref";
+
+ setvbuf(stdout, NULL, _IONBF, 0);
+
+ base = event_base_new();
+
+ for (i=0; i < PARALLELISM; ++i) {
+ if (launch_request() < 0)
+ perror("launch");
+ }
+
+ evutil_gettimeofday(&start, NULL);
+
+ event_base_dispatch(base);
+
+ evutil_gettimeofday(&end, NULL);
+ evutil_timersub(&end, &start, &total);
+ usec = total_time.tv_sec * (long long)1000000 + total_time.tv_usec;
+
+ if (!total_n_handled) {
+ puts("Nothing worked. You probably did something dumb.");
+ return 0;
+ }
+
+
+ throughput = total_n_handled /
+ (total.tv_sec+ ((double)total.tv_usec)/1000000.0);
+
+#ifdef _WIN32
+#define I64_FMT "%I64d"
+#define I64_TYP __int64
+#else
+#define I64_FMT "%lld"
+#define I64_TYP long long int
+#endif
+
+ printf("\n%d requests in %d.%06d sec. (%.2f throughput)\n"
+ "Each took about %.02f msec latency\n"
+ I64_FMT "bytes read. %d errors.\n",
+ total_n_handled,
+ (int)total.tv_sec, (int)total.tv_usec,
+ throughput,
+ (double)(usec/1000) / total_n_handled,
+ (I64_TYP)total_n_bytes, n_errors);
+
+#ifdef _WIN32
+ WSACleanup();
+#endif
+
+ return 0;
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/check-dumpevents.py b/ipc/chromium/src/third_party/libevent/test/check-dumpevents.py
new file mode 100755
index 0000000000..3e1df30c4f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/check-dumpevents.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+#
+# Post-process the output of test-dumpevents and check it for correctness.
+#
+
+import math
+import re
+import sys
+
+text = sys.stdin.readlines()
+
+try:
+ expect_inserted_pos = text.index("Inserted:\n")
+ expect_active_pos = text.index("Active:\n")
+ got_inserted_pos = text.index("Inserted events:\n")
+ got_active_pos = text.index("Active events:\n")
+except ValueError:
+ sys.stderr.write("Missing expected dividing line in dumpevents output")
+ sys.exit(1)
+
+if not (expect_inserted_pos < expect_active_pos <
+ got_inserted_pos < got_active_pos):
+ sys.stderr.write("Sections out of order in dumpevents output")
+ sys.exit(1)
+
+now,T= text[1].split()
+T = float(T)
+
+want_inserted = set(text[expect_inserted_pos+1:expect_active_pos])
+want_active = set(text[expect_active_pos+1:got_inserted_pos-1])
+got_inserted = set(text[got_inserted_pos+1:got_active_pos])
+got_active = set(text[got_active_pos+1:])
+
+pat = re.compile(r'Timeout=([0-9\.]+)')
+def replace_time(m):
+ t = float(m.group(1))
+ if .9 < abs(t-T) < 1.1:
+ return "Timeout=T+1"
+ elif 2.4 < abs(t-T) < 2.6:
+ return "Timeout=T+2.5"
+ else:
+ return m.group(0)
+
+cleaned_inserted = set( pat.sub(replace_time, s) for s in got_inserted
+ if "Internal" not in s)
+
+if cleaned_inserted != want_inserted:
+ sys.stderr.write("Inserted event lists were not as expected!")
+ sys.exit(1)
+
+if set(got_active) != set(want_active):
+ sys.stderr.write("Active event lists were not as expected!")
+ sys.exit(1)
+
diff --git a/ipc/chromium/src/third_party/libevent/test/include.am b/ipc/chromium/src/third_party/libevent/test/include.am
new file mode 100644
index 0000000000..043752471a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/include.am
@@ -0,0 +1,176 @@
+# test/Makefile.am for libevent
+# Copyright 2000-2007 Niels Provos
+# Copyright 2007-2012 Niels Provos and Nick Mathewson
+#
+# See LICENSE for copying information.
+
+regress_CPPFLAGS = -DTINYTEST_LOCAL
+
+EXTRA_DIST+= \
+ test/check-dumpevents.py \
+ test/regress.gen.c \
+ test/regress.gen.h \
+ test/regress.rpc \
+ test/rpcgen_wrapper.sh \
+ test/print-winsock-errors.c \
+ test/test.sh
+
+TESTPROGRAMS = \
+ test/bench \
+ test/bench_cascade \
+ test/bench_http \
+ test/bench_httpclient \
+ test/test-changelist \
+ test/test-dumpevents \
+ test/test-eof \
+ test/test-closed \
+ test/test-fdleak \
+ test/test-init \
+ test/test-ratelim \
+ test/test-time \
+ test/test-weof \
+ test/regress
+
+if BUILD_REGRESS
+noinst_PROGRAMS += $(TESTPROGRAMS)
+EXTRA_PROGRAMS+= test/regress
+endif
+
+noinst_HEADERS+= \
+ test/regress.h \
+ test/regress_thread.h \
+ test/tinytest.h \
+ test/tinytest_local.h \
+ test/tinytest_macros.h
+
+TESTS = \
+ test_runner_epoll \
+ test_runner_select \
+ test_runner_kqueue \
+ test_runner_evport \
+ test_runner_devpoll \
+ test_runner_poll \
+ test_runner_win32 \
+ test_runner_timerfd \
+ test_runner_changelist \
+ test_runner_timerfd_changelist
+LOG_COMPILER = true
+TESTS_COMPILER = true
+
+test_runner_epoll: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b EPOLL
+test_runner_select: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b SELECT
+test_runner_kqueue: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b KQUEUE
+test_runner_evport: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b EVPORT
+test_runner_devpoll: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b DEVPOLL
+test_runner_poll: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b POLL
+test_runner_win32: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b WIN32
+test_runner_timerfd: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b "" -t
+test_runner_changelist: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b "" -c
+test_runner_timerfd_changelist: $(top_srcdir)/test/test.sh
+ $(top_srcdir)/test/test.sh -b "" -T
+
+DISTCLEANFILES += test/regress.gen.c test/regress.gen.h
+
+if BUILD_REGRESS
+BUILT_SOURCES += test/regress.gen.c test/regress.gen.h
+endif
+
+test_test_init_SOURCES = test/test-init.c
+test_test_init_LDADD = libevent_core.la
+test_test_dumpevents_SOURCES = test/test-dumpevents.c
+test_test_dumpevents_LDADD = libevent_core.la
+test_test_eof_SOURCES = test/test-eof.c
+test_test_eof_LDADD = libevent_core.la
+test_test_closed_SOURCES = test/test-closed.c
+test_test_closed_LDADD = libevent_core.la
+test_test_changelist_SOURCES = test/test-changelist.c
+test_test_changelist_LDADD = libevent_core.la
+test_test_weof_SOURCES = test/test-weof.c
+test_test_weof_LDADD = libevent_core.la
+test_test_time_SOURCES = test/test-time.c
+test_test_time_LDADD = libevent_core.la
+test_test_ratelim_SOURCES = test/test-ratelim.c
+test_test_ratelim_LDADD = libevent_core.la -lm
+test_test_fdleak_SOURCES = test/test-fdleak.c
+test_test_fdleak_LDADD = libevent_core.la
+
+test_regress_SOURCES = \
+ test/regress.c \
+ test/regress.gen.c \
+ test/regress.gen.h \
+ test/regress_buffer.c \
+ test/regress_bufferevent.c \
+ test/regress_dns.c \
+ test/regress_et.c \
+ test/regress_finalize.c \
+ test/regress_http.c \
+ test/regress_listener.c \
+ test/regress_main.c \
+ test/regress_minheap.c \
+ test/regress_rpc.c \
+ test/regress_testutils.c \
+ test/regress_testutils.h \
+ test/regress_util.c \
+ test/tinytest.c \
+ $(regress_thread_SOURCES) \
+ $(regress_zlib_SOURCES)
+
+if PTHREADS
+regress_thread_SOURCES = test/regress_thread.c
+PTHREAD_LIBS += libevent_pthreads.la
+endif
+if BUILD_WIN32
+if THREADS
+regress_thread_SOURCES = test/regress_thread.c
+endif
+endif
+if ZLIB_REGRESS
+regress_zlib_SOURCES = test/regress_zlib.c
+endif
+if BUILD_WIN32
+test_regress_SOURCES += test/regress_iocp.c
+endif
+
+test_regress_LDADD = $(LIBEVENT_GC_SECTIONS) libevent_core.la libevent_extra.la $(PTHREAD_LIBS) $(ZLIB_LIBS)
+test_regress_CPPFLAGS = $(AM_CPPFLAGS) $(PTHREAD_CFLAGS) $(ZLIB_CFLAGS) -Itest
+test_regress_LDFLAGS = $(PTHREAD_CFLAGS)
+
+if OPENSSL
+test_regress_SOURCES += test/regress_ssl.c
+test_regress_CPPFLAGS += $(OPENSSL_INCS)
+test_regress_LDADD += libevent_openssl.la $(OPENSSL_LIBS) ${OPENSSL_LIBADD}
+endif
+
+test_bench_SOURCES = test/bench.c
+test_bench_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+test_bench_cascade_SOURCES = test/bench_cascade.c
+test_bench_cascade_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+test_bench_http_SOURCES = test/bench_http.c
+test_bench_http_LDADD = $(LIBEVENT_GC_SECTIONS) libevent.la
+test_bench_httpclient_SOURCES = test/bench_httpclient.c
+test_bench_httpclient_LDADD = $(LIBEVENT_GC_SECTIONS) libevent_core.la
+
+test/regress.gen.c test/regress.gen.h: test/rpcgen-attempted
+
+test/rpcgen-attempted: test/regress.rpc event_rpcgen.py test/rpcgen_wrapper.sh
+ $(AM_V_GEN)date -u > $@
+ $(AM_V_at)if $(srcdir)/test/rpcgen_wrapper.sh $(srcdir)/test; then \
+ true; \
+ else \
+ echo "No Python installed; stubbing out RPC test." >&2; \
+ echo " "> test/regress.gen.c; \
+ echo "#define NO_PYTHON_EXISTS" > test/regress.gen.h; \
+ fi
+
+CLEANFILES += test/rpcgen-attempted
+
+$(TESTPROGRAMS) : libevent.la
diff --git a/ipc/chromium/src/third_party/libevent/test/print-winsock-errors.c b/ipc/chromium/src/third_party/libevent/test/print-winsock-errors.c
new file mode 100644
index 0000000000..64d6b0e70e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/print-winsock-errors.c
@@ -0,0 +1,86 @@
+#include <winsock2.h>
+#include <windows.h>
+
+#include <stdlib.h>
+#include <stdio.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event2/thread.h"
+
+#define E(x) printf (#x " -> \"%s\"\n", evutil_socket_error_to_string (x));
+
+int main (int argc, char **argv)
+{
+ int i, j;
+ const char *s1, *s2;
+
+#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
+ evthread_use_windows_threads ();
+#endif
+
+ s1 = evutil_socket_error_to_string (WSAEINTR);
+
+ for (i = 0; i < 3; i++) {
+ printf ("\niteration %d:\n\n", i);
+ E(WSAEINTR);
+ E(WSAEACCES);
+ E(WSAEFAULT);
+ E(WSAEINVAL);
+ E(WSAEMFILE);
+ E(WSAEWOULDBLOCK);
+ E(WSAEINPROGRESS);
+ E(WSAEALREADY);
+ E(WSAENOTSOCK);
+ E(WSAEDESTADDRREQ);
+ E(WSAEMSGSIZE);
+ E(WSAEPROTOTYPE);
+ E(WSAENOPROTOOPT);
+ E(WSAEPROTONOSUPPORT);
+ E(WSAESOCKTNOSUPPORT);
+ E(WSAEOPNOTSUPP);
+ E(WSAEPFNOSUPPORT);
+ E(WSAEAFNOSUPPORT);
+ E(WSAEADDRINUSE);
+ E(WSAEADDRNOTAVAIL);
+ E(WSAENETDOWN);
+ E(WSAENETUNREACH);
+ E(WSAENETRESET);
+ E(WSAECONNABORTED);
+ E(WSAECONNRESET);
+ E(WSAENOBUFS);
+ E(WSAEISCONN);
+ E(WSAENOTCONN);
+ E(WSAESHUTDOWN);
+ E(WSAETIMEDOUT);
+ E(WSAECONNREFUSED);
+ E(WSAEHOSTDOWN);
+ E(WSAEHOSTUNREACH);
+ E(WSAEPROCLIM);
+ E(WSASYSNOTREADY);
+ E(WSAVERNOTSUPPORTED);
+ E(WSANOTINITIALISED);
+ E(WSAEDISCON);
+ E(WSATYPE_NOT_FOUND);
+ E(WSAHOST_NOT_FOUND);
+ E(WSATRY_AGAIN);
+ E(WSANO_RECOVERY);
+ E(WSANO_DATA);
+ E(0xdeadbeef); /* test the case where no message is available */
+
+ /* fill up the hash table a bit to make sure it grows properly */
+ for (j = 0; j < 50; j++) {
+ int err;
+ evutil_secure_rng_get_bytes(&err, sizeof(err));
+ evutil_socket_error_to_string(err);
+ }
+ }
+
+ s2 = evutil_socket_error_to_string (WSAEINTR);
+ if (s1 != s2)
+ printf ("caching failed!\n");
+
+ libevent_global_shutdown ();
+
+ return EXIT_SUCCESS;
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/regress.c b/ipc/chromium/src/third_party/libevent/test/regress.c
new file mode 100644
index 0000000000..08c30fab9b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress.c
@@ -0,0 +1,3615 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <limits.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+#include <ctype.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+#include "event-internal.h"
+#include "evthread-internal.h"
+#include "log-internal.h"
+#include "time-internal.h"
+
+#include "regress.h"
+#include "regress_thread.h"
+
+#ifndef _WIN32
+#include "regress.gen.h"
+#endif
+
+evutil_socket_t pair[2];
+int test_ok;
+int called;
+struct event_base *global_base;
+
+static char wbuf[4096];
+static char rbuf[4096];
+static int woff;
+static int roff;
+static int usepersist;
+static struct timeval tset;
+static struct timeval tcalled;
+
+
+#define TEST1 "this is a test"
+
+#ifdef _WIN32
+#define write(fd,buf,len) send((fd),(buf),(int)(len),0)
+#define read(fd,buf,len) recv((fd),(buf),(int)(len),0)
+#endif
+
+struct basic_cb_args
+{
+ struct event_base *eb;
+ struct event *ev;
+ unsigned int callcount;
+};
+
+static void
+simple_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[256];
+ int len;
+
+ len = read(fd, buf, sizeof(buf));
+
+ if (len) {
+ if (!called) {
+ if (event_add(arg, NULL) == -1)
+ exit(1);
+ }
+ } else if (called == 1)
+ test_ok = 1;
+
+ called++;
+}
+
+static void
+basic_read_cb(evutil_socket_t fd, short event, void *data)
+{
+ char buf[256];
+ int len;
+ struct basic_cb_args *arg = data;
+
+ len = read(fd, buf, sizeof(buf));
+
+ if (len < 0) {
+ tt_fail_perror("read (callback)");
+ } else {
+ switch (arg->callcount++) {
+ case 0: /* first call: expect to read data; cycle */
+ if (len > 0)
+ return;
+
+ tt_fail_msg("EOF before data read");
+ break;
+
+ case 1: /* second call: expect EOF; stop */
+ if (len > 0)
+ tt_fail_msg("not all data read on first cycle");
+ break;
+
+ default: /* third call: should not happen */
+ tt_fail_msg("too many cycles");
+ }
+ }
+
+ event_del(arg->ev);
+ event_base_loopexit(arg->eb, NULL);
+}
+
+static void
+dummy_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+}
+
+static void
+simple_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+ int len;
+
+ len = write(fd, TEST1, strlen(TEST1) + 1);
+ if (len == -1)
+ test_ok = 0;
+ else
+ test_ok = 1;
+}
+
+static void
+multiple_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *ev = arg;
+ int len;
+
+ len = 128;
+ if (woff + len >= (int)sizeof(wbuf))
+ len = sizeof(wbuf) - woff;
+
+ len = write(fd, wbuf + woff, len);
+ if (len == -1) {
+ fprintf(stderr, "%s: write\n", __func__);
+ if (usepersist)
+ event_del(ev);
+ return;
+ }
+
+ woff += len;
+
+ if (woff >= (int)sizeof(wbuf)) {
+ shutdown(fd, EVUTIL_SHUT_WR);
+ if (usepersist)
+ event_del(ev);
+ return;
+ }
+
+ if (!usepersist) {
+ if (event_add(ev, NULL) == -1)
+ exit(1);
+ }
+}
+
+static void
+multiple_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *ev = arg;
+ int len;
+
+ len = read(fd, rbuf + roff, sizeof(rbuf) - roff);
+ if (len == -1)
+ fprintf(stderr, "%s: read\n", __func__);
+ if (len <= 0) {
+ if (usepersist)
+ event_del(ev);
+ return;
+ }
+
+ roff += len;
+ if (!usepersist) {
+ if (event_add(ev, NULL) == -1)
+ exit(1);
+ }
+}
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ evutil_gettimeofday(&tcalled, NULL);
+}
+
+struct both {
+ struct event ev;
+ int nread;
+};
+
+static void
+combined_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct both *both = arg;
+ char buf[128];
+ int len;
+
+ len = read(fd, buf, sizeof(buf));
+ if (len == -1)
+ fprintf(stderr, "%s: read\n", __func__);
+ if (len <= 0)
+ return;
+
+ both->nread += len;
+ if (event_add(&both->ev, NULL) == -1)
+ exit(1);
+}
+
+static void
+combined_write_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct both *both = arg;
+ char buf[128];
+ int len;
+
+ len = sizeof(buf);
+ if (len > both->nread)
+ len = both->nread;
+
+ memset(buf, 'q', len);
+
+ len = write(fd, buf, len);
+ if (len == -1)
+ fprintf(stderr, "%s: write\n", __func__);
+ if (len <= 0) {
+ shutdown(fd, EVUTIL_SHUT_WR);
+ return;
+ }
+
+ both->nread -= len;
+ if (event_add(&both->ev, NULL) == -1)
+ exit(1);
+}
+
+/* These macros used to replicate the work of the legacy test wrapper code */
+#define setup_test(x) do { \
+ if (!in_legacy_test_wrapper) { \
+ TT_FAIL(("Legacy test %s not wrapped properly", x)); \
+ return; \
+ } \
+ } while (0)
+#define cleanup_test() setup_test("cleanup")
+
+static void
+test_simpleread(void)
+{
+ struct event ev;
+
+ /* Very simple read test */
+ setup_test("Simple read: ");
+
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ shutdown(pair[0], EVUTIL_SHUT_WR);
+
+ event_set(&ev, pair[1], EV_READ, simple_read_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ cleanup_test();
+}
+
+static void
+test_simplewrite(void)
+{
+ struct event ev;
+
+ /* Very simple write test */
+ setup_test("Simple write: ");
+
+ event_set(&ev, pair[0], EV_WRITE, simple_write_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ cleanup_test();
+}
+
+static void
+simpleread_multiple_cb(evutil_socket_t fd, short event, void *arg)
+{
+ if (++called == 2)
+ test_ok = 1;
+}
+
+static void
+test_simpleread_multiple(void)
+{
+ struct event one, two;
+
+ /* Very simple read test */
+ setup_test("Simple read to multiple evens: ");
+
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ shutdown(pair[0], EVUTIL_SHUT_WR);
+
+ event_set(&one, pair[1], EV_READ, simpleread_multiple_cb, NULL);
+ if (event_add(&one, NULL) == -1)
+ exit(1);
+ event_set(&two, pair[1], EV_READ, simpleread_multiple_cb, NULL);
+ if (event_add(&two, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ cleanup_test();
+}
+
+static int have_closed = 0;
+static int premature_event = 0;
+static void
+simpleclose_close_fd_cb(evutil_socket_t s, short what, void *ptr)
+{
+ evutil_socket_t **fds = ptr;
+ TT_BLATHER(("Closing"));
+ evutil_closesocket(*fds[0]);
+ evutil_closesocket(*fds[1]);
+ *fds[0] = -1;
+ *fds[1] = -1;
+ have_closed = 1;
+}
+
+static void
+record_event_cb(evutil_socket_t s, short what, void *ptr)
+{
+ short *whatp = ptr;
+ if (!have_closed)
+ premature_event = 1;
+ *whatp = what;
+ TT_BLATHER(("Recorded %d on socket %d", (int)what, (int)s));
+}
+
+static void
+test_simpleclose_rw(void *ptr)
+{
+ /* Test that a close of FD is detected as a read and as a write. */
+ struct event_base *base = event_base_new();
+ evutil_socket_t pair1[2]={-1,-1}, pair2[2] = {-1, -1};
+ evutil_socket_t *to_close[2];
+ struct event *rev=NULL, *wev=NULL, *closeev=NULL;
+ struct timeval tv;
+ short got_read_on_close = 0, got_write_on_close = 0;
+ char buf[1024];
+ memset(buf, 99, sizeof(buf));
+#ifdef _WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+ if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair1)<0)
+ TT_DIE(("socketpair: %s", strerror(errno)));
+ if (evutil_socketpair(LOCAL_SOCKETPAIR_AF, SOCK_STREAM, 0, pair2)<0)
+ TT_DIE(("socketpair: %s", strerror(errno)));
+ if (evutil_make_socket_nonblocking(pair1[1]) < 0)
+ TT_DIE(("make_socket_nonblocking"));
+ if (evutil_make_socket_nonblocking(pair2[1]) < 0)
+ TT_DIE(("make_socket_nonblocking"));
+
+ /** Stuff pair2[1] full of data, until write fails */
+ while (1) {
+ int r = write(pair2[1], buf, sizeof(buf));
+ if (r<0) {
+ int err = evutil_socket_geterror(pair2[1]);
+ if (! EVUTIL_ERR_RW_RETRIABLE(err))
+ TT_DIE(("write failed strangely: %s",
+ evutil_socket_error_to_string(err)));
+ break;
+ }
+ }
+ to_close[0] = &pair1[0];
+ to_close[1] = &pair2[0];
+
+ closeev = event_new(base, -1, EV_TIMEOUT, simpleclose_close_fd_cb,
+ to_close);
+ rev = event_new(base, pair1[1], EV_READ, record_event_cb,
+ &got_read_on_close);
+ TT_BLATHER(("Waiting for read on %d", (int)pair1[1]));
+ wev = event_new(base, pair2[1], EV_WRITE, record_event_cb,
+ &got_write_on_close);
+ TT_BLATHER(("Waiting for write on %d", (int)pair2[1]));
+ tv.tv_sec = 0;
+ tv.tv_usec = 100*1000; /* Close pair1[0] after a little while, and make
+ * sure we get a read event. */
+ event_add(closeev, &tv);
+ event_add(rev, NULL);
+ event_add(wev, NULL);
+ /* Don't let the test go on too long. */
+ tv.tv_sec = 0;
+ tv.tv_usec = 200*1000;
+ event_base_loopexit(base, &tv);
+ event_base_loop(base, 0);
+
+ tt_int_op(got_read_on_close, ==, EV_READ);
+ tt_int_op(got_write_on_close, ==, EV_WRITE);
+ tt_int_op(premature_event, ==, 0);
+
+end:
+ if (pair1[0] >= 0)
+ evutil_closesocket(pair1[0]);
+ if (pair1[1] >= 0)
+ evutil_closesocket(pair1[1]);
+ if (pair2[0] >= 0)
+ evutil_closesocket(pair2[0]);
+ if (pair2[1] >= 0)
+ evutil_closesocket(pair2[1]);
+ if (rev)
+ event_free(rev);
+ if (wev)
+ event_free(wev);
+ if (closeev)
+ event_free(closeev);
+ if (base)
+ event_base_free(base);
+}
+
+static void
+test_simpleclose(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ evutil_socket_t *pair = data->pair;
+ const char *flags = (const char *)data->setup_data;
+ int et = !!strstr(flags, "ET");
+ int persist = !!strstr(flags, "persist");
+ short events = EV_CLOSED | (et ? EV_ET : 0) | (persist ? EV_PERSIST : 0);
+ struct event *ev = NULL;
+ short got_event;
+
+ if (!(event_base_get_features(data->base) & EV_FEATURE_EARLY_CLOSE))
+ tt_skip();
+
+ /* XXX: should this code moved to regress_et.c ? */
+ if (et && !(event_base_get_features(data->base) & EV_FEATURE_ET))
+ tt_skip();
+
+ ev = event_new(base, pair[0], events, record_event_cb, &got_event);
+ tt_assert(ev);
+ tt_assert(!event_add(ev, NULL));
+
+ got_event = 0;
+ if (strstr(flags, "close")) {
+ tt_assert(!evutil_closesocket(pair[1]));
+ /* avoid closing in setup routines */
+ pair[1] = -1;
+ } else if (strstr(flags, "shutdown")) {
+ tt_assert(!shutdown(pair[1], EVUTIL_SHUT_WR));
+ } else {
+ tt_abort_msg("unknown flags");
+ }
+
+ /* w/o edge-triggerd but w/ persist it will not stop */
+ if (!et && persist) {
+ struct timeval tv;
+ tv.tv_sec = 0;
+ tv.tv_usec = 10000;
+ tt_assert(!event_base_loopexit(base, &tv));
+ }
+
+ tt_int_op(event_base_loop(base, EVLOOP_NONBLOCK), ==, !persist);
+ tt_int_op(got_event, ==, (events & ~EV_PERSIST));
+
+end:
+ if (ev)
+ event_free(ev);
+}
+
+static void
+test_multiple(void)
+{
+ struct event ev, ev2;
+ int i;
+
+ /* Multiple read and write test */
+ setup_test("Multiple read/write: ");
+ memset(rbuf, 0, sizeof(rbuf));
+ for (i = 0; i < (int)sizeof(wbuf); i++)
+ wbuf[i] = i;
+
+ roff = woff = 0;
+ usepersist = 0;
+
+ event_set(&ev, pair[0], EV_WRITE, multiple_write_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+ event_set(&ev2, pair[1], EV_READ, multiple_read_cb, &ev2);
+ if (event_add(&ev2, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ if (roff == woff)
+ test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
+
+ cleanup_test();
+}
+
+static void
+test_persistent(void)
+{
+ struct event ev, ev2;
+ int i;
+
+ /* Multiple read and write test with persist */
+ setup_test("Persist read/write: ");
+ memset(rbuf, 0, sizeof(rbuf));
+ for (i = 0; i < (int)sizeof(wbuf); i++)
+ wbuf[i] = i;
+
+ roff = woff = 0;
+ usepersist = 1;
+
+ event_set(&ev, pair[0], EV_WRITE|EV_PERSIST, multiple_write_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+ event_set(&ev2, pair[1], EV_READ|EV_PERSIST, multiple_read_cb, &ev2);
+ if (event_add(&ev2, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ if (roff == woff)
+ test_ok = memcmp(rbuf, wbuf, sizeof(wbuf)) == 0;
+
+ cleanup_test();
+}
+
+static void
+test_combined(void)
+{
+ struct both r1, r2, w1, w2;
+
+ setup_test("Combined read/write: ");
+ memset(&r1, 0, sizeof(r1));
+ memset(&r2, 0, sizeof(r2));
+ memset(&w1, 0, sizeof(w1));
+ memset(&w2, 0, sizeof(w2));
+
+ w1.nread = 4096;
+ w2.nread = 8192;
+
+ event_set(&r1.ev, pair[0], EV_READ, combined_read_cb, &r1);
+ event_set(&w1.ev, pair[0], EV_WRITE, combined_write_cb, &w1);
+ event_set(&r2.ev, pair[1], EV_READ, combined_read_cb, &r2);
+ event_set(&w2.ev, pair[1], EV_WRITE, combined_write_cb, &w2);
+ tt_assert(event_add(&r1.ev, NULL) != -1);
+ tt_assert(!event_add(&w1.ev, NULL));
+ tt_assert(!event_add(&r2.ev, NULL));
+ tt_assert(!event_add(&w2.ev, NULL));
+ event_dispatch();
+
+ if (r1.nread == 8192 && r2.nread == 4096)
+ test_ok = 1;
+
+end:
+ cleanup_test();
+}
+
+static void
+test_simpletimeout(void)
+{
+ struct timeval tv;
+ struct event ev;
+
+ setup_test("Simple timeout: ");
+
+ tv.tv_usec = 200*1000;
+ tv.tv_sec = 0;
+ evutil_timerclear(&tcalled);
+ evtimer_set(&ev, timeout_cb, NULL);
+ evtimer_add(&ev, &tv);
+
+ evutil_gettimeofday(&tset, NULL);
+ event_dispatch();
+ test_timeval_diff_eq(&tset, &tcalled, 200);
+
+ test_ok = 1;
+end:
+ cleanup_test();
+}
+
+static void
+periodic_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ int *count = arg;
+
+ (*count)++;
+ if (*count == 6) {
+ /* call loopexit only once - on slow machines(?), it is
+ * apparently possible for this to get called twice. */
+ test_ok = 1;
+ event_base_loopexit(global_base, NULL);
+ }
+}
+
+static void
+test_persistent_timeout(void)
+{
+ struct timeval tv;
+ struct event ev;
+ int count = 0;
+
+ evutil_timerclear(&tv);
+ tv.tv_usec = 10000;
+
+ event_assign(&ev, global_base, -1, EV_TIMEOUT|EV_PERSIST,
+ periodic_timeout_cb, &count);
+ event_add(&ev, &tv);
+
+ event_dispatch();
+
+ event_del(&ev);
+}
+
+static void
+test_persistent_timeout_jump(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event ev;
+ int count = 0;
+ struct timeval msec100 = { 0, 100 * 1000 };
+ struct timeval msec50 = { 0, 50 * 1000 };
+ struct timeval msec300 = { 0, 300 * 1000 };
+
+ event_assign(&ev, data->base, -1, EV_PERSIST, periodic_timeout_cb, &count);
+ event_add(&ev, &msec100);
+ /* Wait for a bit */
+ evutil_usleep_(&msec300);
+ event_base_loopexit(data->base, &msec50);
+ event_base_dispatch(data->base);
+ tt_int_op(count, ==, 1);
+
+end:
+ event_del(&ev);
+}
+
+struct persist_active_timeout_called {
+ int n;
+ short events[16];
+ struct timeval tvs[16];
+};
+
+static void
+activate_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *ev = arg;
+ event_active(ev, EV_READ, 1);
+}
+
+static void
+persist_active_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct persist_active_timeout_called *c = arg;
+ if (c->n < 15) {
+ c->events[c->n] = event;
+ evutil_gettimeofday(&c->tvs[c->n], NULL);
+ ++c->n;
+ }
+}
+
+static void
+test_persistent_active_timeout(void *ptr)
+{
+ struct timeval tv, tv2, tv_exit, start;
+ struct event ev;
+ struct persist_active_timeout_called res;
+
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+
+ memset(&res, 0, sizeof(res));
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 200 * 1000;
+ event_assign(&ev, base, -1, EV_TIMEOUT|EV_PERSIST,
+ persist_active_timeout_cb, &res);
+ event_add(&ev, &tv);
+
+ tv2.tv_sec = 0;
+ tv2.tv_usec = 100 * 1000;
+ event_base_once(base, -1, EV_TIMEOUT, activate_cb, &ev, &tv2);
+
+ tv_exit.tv_sec = 0;
+ tv_exit.tv_usec = 600 * 1000;
+ event_base_loopexit(base, &tv_exit);
+
+ event_base_assert_ok_(base);
+ evutil_gettimeofday(&start, NULL);
+
+ event_base_dispatch(base);
+ event_base_assert_ok_(base);
+
+ tt_int_op(res.n, ==, 3);
+ tt_int_op(res.events[0], ==, EV_READ);
+ tt_int_op(res.events[1], ==, EV_TIMEOUT);
+ tt_int_op(res.events[2], ==, EV_TIMEOUT);
+ test_timeval_diff_eq(&start, &res.tvs[0], 100);
+ test_timeval_diff_eq(&start, &res.tvs[1], 300);
+ test_timeval_diff_eq(&start, &res.tvs[2], 500);
+end:
+ event_del(&ev);
+}
+
+struct common_timeout_info {
+ struct event ev;
+ struct timeval called_at;
+ int which;
+ int count;
+};
+
+static void
+common_timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct common_timeout_info *ti = arg;
+ ++ti->count;
+ evutil_gettimeofday(&ti->called_at, NULL);
+ if (ti->count >= 4)
+ event_del(&ti->ev);
+}
+
+static void
+test_common_timeout(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+
+ struct event_base *base = data->base;
+ int i;
+ struct common_timeout_info info[100];
+
+ struct timeval start;
+ struct timeval tmp_100_ms = { 0, 100*1000 };
+ struct timeval tmp_200_ms = { 0, 200*1000 };
+ struct timeval tmp_5_sec = { 5, 0 };
+ struct timeval tmp_5M_usec = { 0, 5*1000*1000 };
+
+ const struct timeval *ms_100, *ms_200, *sec_5;
+
+ ms_100 = event_base_init_common_timeout(base, &tmp_100_ms);
+ ms_200 = event_base_init_common_timeout(base, &tmp_200_ms);
+ sec_5 = event_base_init_common_timeout(base, &tmp_5_sec);
+ tt_assert(ms_100);
+ tt_assert(ms_200);
+ tt_assert(sec_5);
+ tt_ptr_op(event_base_init_common_timeout(base, &tmp_200_ms),
+ ==, ms_200);
+ tt_ptr_op(event_base_init_common_timeout(base, ms_200), ==, ms_200);
+ tt_ptr_op(event_base_init_common_timeout(base, &tmp_5M_usec), ==, sec_5);
+ tt_int_op(ms_100->tv_sec, ==, 0);
+ tt_int_op(ms_200->tv_sec, ==, 0);
+ tt_int_op(sec_5->tv_sec, ==, 5);
+ tt_int_op(ms_100->tv_usec, ==, 100000|0x50000000);
+ tt_int_op(ms_200->tv_usec, ==, 200000|0x50100000);
+ tt_int_op(sec_5->tv_usec, ==, 0|0x50200000);
+
+ memset(info, 0, sizeof(info));
+
+ for (i=0; i<100; ++i) {
+ info[i].which = i;
+ event_assign(&info[i].ev, base, -1, EV_TIMEOUT|EV_PERSIST,
+ common_timeout_cb, &info[i]);
+ if (i % 2) {
+ if ((i%20)==1) {
+ /* Glass-box test: Make sure we survive the
+ * transition to non-common timeouts. It's
+ * a little tricky. */
+ event_add(&info[i].ev, ms_200);
+ event_add(&info[i].ev, &tmp_100_ms);
+ } else if ((i%20)==3) {
+ /* Check heap-to-common too. */
+ event_add(&info[i].ev, &tmp_200_ms);
+ event_add(&info[i].ev, ms_100);
+ } else if ((i%20)==5) {
+ /* Also check common-to-common. */
+ event_add(&info[i].ev, ms_200);
+ event_add(&info[i].ev, ms_100);
+ } else {
+ event_add(&info[i].ev, ms_100);
+ }
+ } else {
+ event_add(&info[i].ev, ms_200);
+ }
+ }
+
+ event_base_assert_ok_(base);
+ evutil_gettimeofday(&start, NULL);
+ event_base_dispatch(base);
+
+ event_base_assert_ok_(base);
+
+ for (i=0; i<10; ++i) {
+ tt_int_op(info[i].count, ==, 4);
+ if (i % 2) {
+ test_timeval_diff_eq(&start, &info[i].called_at, 400);
+ } else {
+ test_timeval_diff_eq(&start, &info[i].called_at, 800);
+ }
+ }
+
+ /* Make sure we can free the base with some events in. */
+ for (i=0; i<100; ++i) {
+ if (i % 2) {
+ event_add(&info[i].ev, ms_100);
+ } else {
+ event_add(&info[i].ev, ms_200);
+ }
+ }
+
+end:
+ event_base_free(data->base); /* need to do this here before info is
+ * out-of-scope */
+ data->base = NULL;
+}
+
+#ifndef _WIN32
+
+#define current_base event_global_current_base_
+extern struct event_base *current_base;
+
+static void
+fork_signal_cb(evutil_socket_t fd, short events, void *arg)
+{
+ event_del(arg);
+}
+
+int child_pair[2] = { -1, -1 };
+static void
+simple_child_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[256];
+ int len;
+
+ len = read(fd, buf, sizeof(buf));
+ if (write(child_pair[0], "", 1) < 0)
+ tt_fail_perror("write");
+
+ if (len) {
+ if (!called) {
+ if (event_add(arg, NULL) == -1)
+ exit(1);
+ }
+ } else if (called == 1)
+ test_ok = 1;
+
+ called++;
+}
+
+#define TEST_FORK_EXIT_SUCCESS 76
+static void fork_wait_check(int pid)
+{
+ int status;
+
+ TT_BLATHER(("Before waitpid"));
+
+#ifdef WNOWAIT
+ if ((waitpid(pid, &status, WNOWAIT) == -1 && errno == EINVAL) &&
+#else
+ if (
+#endif
+ waitpid(pid, &status, 0) == -1) {
+ perror("waitpid");
+ exit(1);
+ }
+ TT_BLATHER(("After waitpid"));
+
+ if (WEXITSTATUS(status) != TEST_FORK_EXIT_SUCCESS) {
+ fprintf(stdout, "FAILED (exit): %d\n", WEXITSTATUS(status));
+ exit(1);
+ }
+}
+static void
+test_fork(void)
+{
+ char c;
+ struct event ev, sig_ev, usr_ev, existing_ev;
+ pid_t pid;
+
+ setup_test("After fork: ");
+
+ {
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, child_pair) == -1) {
+ fprintf(stderr, "%s: socketpair\n", __func__);
+ exit(1);
+ }
+
+ if (evutil_make_socket_nonblocking(child_pair[0]) == -1) {
+ fprintf(stderr, "fcntl(O_NONBLOCK)");
+ exit(1);
+ }
+ }
+
+ tt_assert(current_base);
+ evthread_make_base_notifiable(current_base);
+
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ event_set(&ev, pair[1], EV_READ, simple_child_read_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+
+ evsignal_set(&sig_ev, SIGCHLD, fork_signal_cb, &sig_ev);
+ evsignal_add(&sig_ev, NULL);
+
+ evsignal_set(&existing_ev, SIGUSR2, fork_signal_cb, &existing_ev);
+ evsignal_add(&existing_ev, NULL);
+
+ event_base_assert_ok_(current_base);
+ TT_BLATHER(("Before fork"));
+ if ((pid = regress_fork()) == 0) {
+ /* in the child */
+ TT_BLATHER(("In child, before reinit"));
+ event_base_assert_ok_(current_base);
+ if (event_reinit(current_base) == -1) {
+ fprintf(stdout, "FAILED (reinit)\n");
+ exit(1);
+ }
+ TT_BLATHER(("After reinit"));
+ event_base_assert_ok_(current_base);
+ TT_BLATHER(("After assert-ok"));
+
+ evsignal_del(&sig_ev);
+
+ evsignal_set(&usr_ev, SIGUSR1, fork_signal_cb, &usr_ev);
+ evsignal_add(&usr_ev, NULL);
+ kill(getpid(), SIGUSR1);
+ kill(getpid(), SIGUSR2);
+
+ called = 0;
+
+ event_dispatch();
+
+ event_base_free(current_base);
+
+ /* we do not send an EOF; simple_read_cb requires an EOF
+ * to set test_ok. we just verify that the callback was
+ * called. */
+ exit(test_ok != 0 || called != 2 ? -2 : TEST_FORK_EXIT_SUCCESS);
+ }
+
+ /** wait until client read first message */
+ if (read(child_pair[1], &c, 1) < 0) {
+ tt_fail_perror("read");
+ }
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ fork_wait_check(pid);
+
+ /* test that the current event loop still works */
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ fprintf(stderr, "%s: write\n", __func__);
+ }
+
+ shutdown(pair[0], EVUTIL_SHUT_WR);
+
+ evsignal_set(&usr_ev, SIGUSR1, fork_signal_cb, &usr_ev);
+ evsignal_add(&usr_ev, NULL);
+ kill(getpid(), SIGUSR1);
+ kill(getpid(), SIGUSR2);
+
+ event_dispatch();
+
+ evsignal_del(&sig_ev);
+ tt_int_op(test_ok, ==, 1);
+
+ end:
+ cleanup_test();
+ if (child_pair[0] != -1)
+ evutil_closesocket(child_pair[0]);
+ if (child_pair[1] != -1)
+ evutil_closesocket(child_pair[1]);
+}
+
+#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
+static void* del_wait_thread(void *arg)
+{
+ struct timeval tv_start, tv_end;
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_dispatch();
+ evutil_gettimeofday(&tv_end, NULL);
+
+ test_timeval_diff_eq(&tv_start, &tv_end, 300);
+
+ end:
+ return NULL;
+}
+
+static void
+del_wait_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct timeval delay = { 0, 300*1000 };
+ TT_BLATHER(("Sleeping: %i", test_ok));
+ evutil_usleep_(&delay);
+ ++test_ok;
+}
+
+static void
+test_del_wait(void)
+{
+ struct event ev;
+ THREAD_T thread;
+
+ setup_test("event_del will wait: ");
+
+ event_set(&ev, pair[1], EV_READ|EV_PERSIST, del_wait_cb, &ev);
+ event_add(&ev, NULL);
+
+ THREAD_START(thread, del_wait_thread, NULL);
+
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ {
+ struct timeval delay = { 0, 30*1000 };
+ evutil_usleep_(&delay);
+ }
+
+ {
+ struct timeval tv_start, tv_end;
+ evutil_gettimeofday(&tv_start, NULL);
+ event_del(&ev);
+ evutil_gettimeofday(&tv_end, NULL);
+ test_timeval_diff_eq(&tv_start, &tv_end, 270);
+ }
+
+ THREAD_JOIN(thread);
+
+ tt_int_op(test_ok, ==, 1);
+
+ end:
+ ;
+}
+
+static void null_cb(evutil_socket_t fd, short what, void *arg) {}
+static void* test_del_notify_thread(void *arg)
+{
+ event_dispatch();
+ return NULL;
+}
+static void
+test_del_notify(void)
+{
+ struct event ev;
+ THREAD_T thread;
+
+ test_ok = 1;
+
+ event_set(&ev, -1, EV_READ, null_cb, &ev);
+ event_add(&ev, NULL);
+
+ THREAD_START(thread, test_del_notify_thread, NULL);
+
+ {
+ struct timeval delay = { 0, 1000 };
+ evutil_usleep_(&delay);
+ }
+
+ event_del(&ev);
+ THREAD_JOIN(thread);
+}
+#endif
+
+static void
+signal_cb_sa(int sig)
+{
+ test_ok = 2;
+}
+
+static void
+signal_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *ev = arg;
+
+ evsignal_del(ev);
+ test_ok = 1;
+}
+
+static void
+test_simplesignal_impl(int find_reorder)
+{
+ struct event ev;
+ struct itimerval itv;
+
+ evsignal_set(&ev, SIGALRM, signal_cb, &ev);
+ evsignal_add(&ev, NULL);
+ /* find bugs in which operations are re-ordered */
+ if (find_reorder) {
+ evsignal_del(&ev);
+ evsignal_add(&ev, NULL);
+ }
+
+ memset(&itv, 0, sizeof(itv));
+ itv.it_value.tv_sec = 0;
+ itv.it_value.tv_usec = 100000;
+ if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
+ goto skip_simplesignal;
+
+ event_dispatch();
+ skip_simplesignal:
+ if (evsignal_del(&ev) == -1)
+ test_ok = 0;
+
+ cleanup_test();
+}
+
+static void
+test_simplestsignal(void)
+{
+ setup_test("Simplest one signal: ");
+ test_simplesignal_impl(0);
+}
+
+static void
+test_simplesignal(void)
+{
+ setup_test("Simple signal: ");
+ test_simplesignal_impl(1);
+}
+
+static void
+test_multiplesignal(void)
+{
+ struct event ev_one, ev_two;
+ struct itimerval itv;
+
+ setup_test("Multiple signal: ");
+
+ evsignal_set(&ev_one, SIGALRM, signal_cb, &ev_one);
+ evsignal_add(&ev_one, NULL);
+
+ evsignal_set(&ev_two, SIGALRM, signal_cb, &ev_two);
+ evsignal_add(&ev_two, NULL);
+
+ memset(&itv, 0, sizeof(itv));
+ itv.it_value.tv_sec = 0;
+ itv.it_value.tv_usec = 100000;
+ if (setitimer(ITIMER_REAL, &itv, NULL) == -1)
+ goto skip_simplesignal;
+
+ event_dispatch();
+
+ skip_simplesignal:
+ if (evsignal_del(&ev_one) == -1)
+ test_ok = 0;
+ if (evsignal_del(&ev_two) == -1)
+ test_ok = 0;
+
+ cleanup_test();
+}
+
+static void
+test_immediatesignal(void)
+{
+ struct event ev;
+
+ test_ok = 0;
+ evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+ evsignal_add(&ev, NULL);
+ kill(getpid(), SIGUSR1);
+ event_loop(EVLOOP_NONBLOCK);
+ evsignal_del(&ev);
+ cleanup_test();
+}
+
+static void
+test_signal_dealloc(void)
+{
+ /* make sure that evsignal_event is event_del'ed and pipe closed */
+ struct event ev;
+ struct event_base *base = event_init();
+ evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+ evsignal_add(&ev, NULL);
+ evsignal_del(&ev);
+ event_base_free(base);
+ /* If we got here without asserting, we're fine. */
+ test_ok = 1;
+ cleanup_test();
+}
+
+static void
+test_signal_pipeloss(void)
+{
+ /* make sure that the base1 pipe is closed correctly. */
+ struct event_base *base1, *base2;
+ int pipe1;
+ test_ok = 0;
+ base1 = event_init();
+ pipe1 = base1->sig.ev_signal_pair[0];
+ base2 = event_init();
+ event_base_free(base2);
+ event_base_free(base1);
+ if (close(pipe1) != -1 || errno!=EBADF) {
+ /* fd must be closed, so second close gives -1, EBADF */
+ printf("signal pipe not closed. ");
+ test_ok = 0;
+ } else {
+ test_ok = 1;
+ }
+ cleanup_test();
+}
+
+/*
+ * make two bases to catch signals, use both of them. this only works
+ * for event mechanisms that use our signal pipe trick. kqueue handles
+ * signals internally, and all interested kqueues get all the signals.
+ */
+static void
+test_signal_switchbase(void)
+{
+ struct event ev1, ev2;
+ struct event_base *base1, *base2;
+ int is_kqueue;
+ test_ok = 0;
+ base1 = event_init();
+ base2 = event_init();
+ is_kqueue = !strcmp(event_get_method(),"kqueue");
+ evsignal_set(&ev1, SIGUSR1, signal_cb, &ev1);
+ evsignal_set(&ev2, SIGUSR1, signal_cb, &ev2);
+ if (event_base_set(base1, &ev1) ||
+ event_base_set(base2, &ev2) ||
+ event_add(&ev1, NULL) ||
+ event_add(&ev2, NULL)) {
+ fprintf(stderr, "%s: cannot set base, add\n", __func__);
+ exit(1);
+ }
+
+ tt_ptr_op(event_get_base(&ev1), ==, base1);
+ tt_ptr_op(event_get_base(&ev2), ==, base2);
+
+ test_ok = 0;
+ /* can handle signal before loop is called */
+ kill(getpid(), SIGUSR1);
+ event_base_loop(base2, EVLOOP_NONBLOCK);
+ if (is_kqueue) {
+ if (!test_ok)
+ goto end;
+ test_ok = 0;
+ }
+ event_base_loop(base1, EVLOOP_NONBLOCK);
+ if (test_ok && !is_kqueue) {
+ test_ok = 0;
+
+ /* set base1 to handle signals */
+ event_base_loop(base1, EVLOOP_NONBLOCK);
+ kill(getpid(), SIGUSR1);
+ event_base_loop(base1, EVLOOP_NONBLOCK);
+ event_base_loop(base2, EVLOOP_NONBLOCK);
+ }
+end:
+ event_base_free(base1);
+ event_base_free(base2);
+ cleanup_test();
+}
+
+/*
+ * assert that a signal event removed from the event queue really is
+ * removed - with no possibility of it's parent handler being fired.
+ */
+static void
+test_signal_assert(void)
+{
+ struct event ev;
+ struct event_base *base = event_init();
+ test_ok = 0;
+ /* use SIGCONT so we don't kill ourselves when we signal to nowhere */
+ evsignal_set(&ev, SIGCONT, signal_cb, &ev);
+ evsignal_add(&ev, NULL);
+ /*
+ * if evsignal_del() fails to reset the handler, it's current handler
+ * will still point to evsig_handler().
+ */
+ evsignal_del(&ev);
+
+ kill(getpid(), SIGCONT);
+#if 0
+ /* only way to verify we were in evsig_handler() */
+ /* XXXX Now there's no longer a good way. */
+ if (base->sig.evsig_caught)
+ test_ok = 0;
+ else
+ test_ok = 1;
+#else
+ test_ok = 1;
+#endif
+
+ event_base_free(base);
+ cleanup_test();
+ return;
+}
+
+/*
+ * assert that we restore our previous signal handler properly.
+ */
+static void
+test_signal_restore(void)
+{
+ struct event ev;
+ struct event_base *base = event_init();
+#ifdef EVENT__HAVE_SIGACTION
+ struct sigaction sa;
+#endif
+
+ test_ok = 0;
+#ifdef EVENT__HAVE_SIGACTION
+ sa.sa_handler = signal_cb_sa;
+ sa.sa_flags = 0x0;
+ sigemptyset(&sa.sa_mask);
+ if (sigaction(SIGUSR1, &sa, NULL) == -1)
+ goto out;
+#else
+ if (signal(SIGUSR1, signal_cb_sa) == SIG_ERR)
+ goto out;
+#endif
+ evsignal_set(&ev, SIGUSR1, signal_cb, &ev);
+ evsignal_add(&ev, NULL);
+ evsignal_del(&ev);
+
+ kill(getpid(), SIGUSR1);
+ /* 1 == signal_cb, 2 == signal_cb_sa, we want our previous handler */
+ if (test_ok != 2)
+ test_ok = 0;
+out:
+ event_base_free(base);
+ cleanup_test();
+ return;
+}
+
+static void
+signal_cb_swp(int sig, short event, void *arg)
+{
+ called++;
+ if (called < 5)
+ kill(getpid(), sig);
+ else
+ event_loopexit(NULL);
+}
+static void
+timeout_cb_swp(evutil_socket_t fd, short event, void *arg)
+{
+ if (called == -1) {
+ struct timeval tv = {5, 0};
+
+ called = 0;
+ evtimer_add((struct event *)arg, &tv);
+ kill(getpid(), SIGUSR1);
+ return;
+ }
+ test_ok = 0;
+ event_loopexit(NULL);
+}
+
+static void
+test_signal_while_processing(void)
+{
+ struct event_base *base = event_init();
+ struct event ev, ev_timer;
+ struct timeval tv = {0, 0};
+
+ setup_test("Receiving a signal while processing other signal: ");
+
+ called = -1;
+ test_ok = 1;
+ signal_set(&ev, SIGUSR1, signal_cb_swp, NULL);
+ signal_add(&ev, NULL);
+ evtimer_set(&ev_timer, timeout_cb_swp, &ev_timer);
+ evtimer_add(&ev_timer, &tv);
+ event_dispatch();
+
+ event_base_free(base);
+ cleanup_test();
+ return;
+}
+#endif
+
+static void
+test_free_active_base(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base1;
+ struct event ev1;
+
+ base1 = event_init();
+ tt_assert(base1);
+ event_assign(&ev1, base1, data->pair[1], EV_READ, dummy_read_cb, NULL);
+ event_add(&ev1, NULL);
+ event_base_free(base1); /* should not crash */
+
+ base1 = event_init();
+ tt_assert(base1);
+ event_assign(&ev1, base1, data->pair[0], 0, dummy_read_cb, NULL);
+ event_active(&ev1, EV_READ, 1);
+ event_base_free(base1);
+end:
+ ;
+}
+
+static void
+test_manipulate_active_events(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event ev1;
+
+ event_assign(&ev1, base, -1, EV_TIMEOUT, dummy_read_cb, NULL);
+
+ /* Make sure an active event is pending. */
+ event_active(&ev1, EV_READ, 1);
+ tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
+ ==, EV_READ);
+
+ /* Make sure that activating an event twice works. */
+ event_active(&ev1, EV_WRITE, 1);
+ tt_int_op(event_pending(&ev1, EV_READ|EV_TIMEOUT|EV_WRITE, NULL),
+ ==, EV_READ|EV_WRITE);
+
+end:
+ event_del(&ev1);
+}
+
+static void
+event_selfarg_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct event *ev = arg;
+ struct event_base *base = event_get_base(ev);
+ event_base_assert_ok_(base);
+ event_base_loopexit(base, NULL);
+ tt_want(ev == event_base_get_running_event(base));
+}
+
+static void
+test_event_new_selfarg(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event *ev = event_new(base, -1, EV_READ, event_selfarg_cb,
+ event_self_cbarg());
+
+ event_active(ev, EV_READ, 1);
+ event_base_dispatch(base);
+
+ event_free(ev);
+}
+
+static void
+test_event_assign_selfarg(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event ev;
+
+ event_assign(&ev, base, -1, EV_READ, event_selfarg_cb,
+ event_self_cbarg());
+ event_active(&ev, EV_READ, 1);
+ event_base_dispatch(base);
+}
+
+static void
+test_event_base_get_num_events(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event ev;
+ int event_count_active;
+ int event_count_virtual;
+ int event_count_added;
+ int event_count_active_virtual;
+ int event_count_active_added;
+ int event_count_virtual_added;
+ int event_count_active_added_virtual;
+
+ struct timeval qsec = {0, 100000};
+
+ event_assign(&ev, base, -1, EV_READ, event_selfarg_cb,
+ event_self_cbarg());
+
+ event_add(&ev, &qsec);
+ event_count_active = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE);
+ event_count_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL);
+ event_count_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ADDED);
+ event_count_active_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_VIRTUAL);
+ event_count_active_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_ADDED);
+ event_count_virtual_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL|EVENT_BASE_COUNT_ADDED);
+ event_count_active_added_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|
+ EVENT_BASE_COUNT_ADDED|
+ EVENT_BASE_COUNT_VIRTUAL);
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 0);
+ /* libevent itself adds a timeout event, so the event_count is 2 here */
+ tt_int_op(event_count_added, ==, 2);
+ tt_int_op(event_count_active_virtual, ==, 0);
+ tt_int_op(event_count_active_added, ==, 2);
+ tt_int_op(event_count_virtual_added, ==, 2);
+ tt_int_op(event_count_active_added_virtual, ==, 2);
+
+ event_active(&ev, EV_READ, 1);
+ event_count_active = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE);
+ event_count_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL);
+ event_count_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ADDED);
+ event_count_active_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_VIRTUAL);
+ event_count_active_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_ADDED);
+ event_count_virtual_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL|EVENT_BASE_COUNT_ADDED);
+ event_count_active_added_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|
+ EVENT_BASE_COUNT_ADDED|
+ EVENT_BASE_COUNT_VIRTUAL);
+ tt_int_op(event_count_active, ==, 1);
+ tt_int_op(event_count_virtual, ==, 0);
+ tt_int_op(event_count_added, ==, 3);
+ tt_int_op(event_count_active_virtual, ==, 1);
+ tt_int_op(event_count_active_added, ==, 4);
+ tt_int_op(event_count_virtual_added, ==, 3);
+ tt_int_op(event_count_active_added_virtual, ==, 4);
+
+ event_base_loop(base, 0);
+ event_count_active = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE);
+ event_count_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL);
+ event_count_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ADDED);
+ event_count_active_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_VIRTUAL);
+ event_count_active_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_ADDED);
+ event_count_virtual_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL|EVENT_BASE_COUNT_ADDED);
+ event_count_active_added_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|
+ EVENT_BASE_COUNT_ADDED|
+ EVENT_BASE_COUNT_VIRTUAL);
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 0);
+ tt_int_op(event_count_added, ==, 0);
+ tt_int_op(event_count_active_virtual, ==, 0);
+ tt_int_op(event_count_active_added, ==, 0);
+ tt_int_op(event_count_virtual_added, ==, 0);
+ tt_int_op(event_count_active_added_virtual, ==, 0);
+
+ event_base_add_virtual_(base);
+ event_count_active = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE);
+ event_count_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL);
+ event_count_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ADDED);
+ event_count_active_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_VIRTUAL);
+ event_count_active_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|EVENT_BASE_COUNT_ADDED);
+ event_count_virtual_added = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_VIRTUAL|EVENT_BASE_COUNT_ADDED);
+ event_count_active_added_virtual = event_base_get_num_events(base,
+ EVENT_BASE_COUNT_ACTIVE|
+ EVENT_BASE_COUNT_ADDED|
+ EVENT_BASE_COUNT_VIRTUAL);
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 1);
+ tt_int_op(event_count_added, ==, 0);
+ tt_int_op(event_count_active_virtual, ==, 1);
+ tt_int_op(event_count_active_added, ==, 0);
+ tt_int_op(event_count_virtual_added, ==, 1);
+ tt_int_op(event_count_active_added_virtual, ==, 1);
+
+end:
+ ;
+}
+
+static void
+test_event_base_get_max_events(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event ev;
+ struct event ev2;
+ int event_count_active;
+ int event_count_virtual;
+ int event_count_added;
+ int event_count_active_virtual;
+ int event_count_active_added;
+ int event_count_virtual_added;
+ int event_count_active_added_virtual;
+
+ struct timeval qsec = {0, 100000};
+
+ event_assign(&ev, base, -1, EV_READ, event_selfarg_cb,
+ event_self_cbarg());
+ event_assign(&ev2, base, -1, EV_READ, event_selfarg_cb,
+ event_self_cbarg());
+
+ event_add(&ev, &qsec);
+ event_add(&ev2, &qsec);
+ event_del(&ev2);
+
+ event_count_active = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE, 0);
+ event_count_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_active_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_virtual_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_added_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE |
+ EVENT_BASE_COUNT_ADDED |
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 0);
+ /* libevent itself adds a timeout event, so the event_count is 4 here */
+ tt_int_op(event_count_added, ==, 4);
+ tt_int_op(event_count_active_virtual, ==, 0);
+ tt_int_op(event_count_active_added, ==, 4);
+ tt_int_op(event_count_virtual_added, ==, 4);
+ tt_int_op(event_count_active_added_virtual, ==, 4);
+
+ event_active(&ev, EV_READ, 1);
+ event_count_active = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE, 0);
+ event_count_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_active_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_virtual_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_added_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE |
+ EVENT_BASE_COUNT_ADDED |
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+
+ tt_int_op(event_count_active, ==, 1);
+ tt_int_op(event_count_virtual, ==, 0);
+ tt_int_op(event_count_added, ==, 4);
+ tt_int_op(event_count_active_virtual, ==, 1);
+ tt_int_op(event_count_active_added, ==, 5);
+ tt_int_op(event_count_virtual_added, ==, 4);
+ tt_int_op(event_count_active_added_virtual, ==, 5);
+
+ event_base_loop(base, 0);
+ event_count_active = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE, 1);
+ event_count_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL, 1);
+ event_count_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ADDED, 1);
+ event_count_active_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_active_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_virtual_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_added_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE |
+ EVENT_BASE_COUNT_ADDED |
+ EVENT_BASE_COUNT_VIRTUAL, 1);
+
+ tt_int_op(event_count_active, ==, 1);
+ tt_int_op(event_count_virtual, ==, 0);
+ tt_int_op(event_count_added, ==, 4);
+ tt_int_op(event_count_active_virtual, ==, 0);
+ tt_int_op(event_count_active_added, ==, 0);
+ tt_int_op(event_count_virtual_added, ==, 0);
+ tt_int_op(event_count_active_added_virtual, ==, 0);
+
+ event_count_active = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE, 0);
+ event_count_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ADDED, 0);
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 0);
+ tt_int_op(event_count_added, ==, 0);
+
+ event_base_add_virtual_(base);
+ event_count_active = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE, 0);
+ event_count_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_VIRTUAL, 0);
+ event_count_active_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_virtual_added = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_VIRTUAL | EVENT_BASE_COUNT_ADDED, 0);
+ event_count_active_added_virtual = event_base_get_max_events(base,
+ EVENT_BASE_COUNT_ACTIVE |
+ EVENT_BASE_COUNT_ADDED |
+ EVENT_BASE_COUNT_VIRTUAL, 0);
+
+ tt_int_op(event_count_active, ==, 0);
+ tt_int_op(event_count_virtual, ==, 1);
+ tt_int_op(event_count_added, ==, 0);
+ tt_int_op(event_count_active_virtual, ==, 1);
+ tt_int_op(event_count_active_added, ==, 0);
+ tt_int_op(event_count_virtual_added, ==, 1);
+ tt_int_op(event_count_active_added_virtual, ==, 1);
+
+end:
+ ;
+}
+
+static void
+test_bad_assign(void *ptr)
+{
+ struct event ev;
+ int r;
+ /* READ|SIGNAL is not allowed */
+ r = event_assign(&ev, NULL, -1, EV_SIGNAL|EV_READ, dummy_read_cb, NULL);
+ tt_int_op(r,==,-1);
+
+end:
+ ;
+}
+
+static int reentrant_cb_run = 0;
+
+static void
+bad_reentrant_run_loop_cb(evutil_socket_t fd, short what, void *ptr)
+{
+ struct event_base *base = ptr;
+ int r;
+ reentrant_cb_run = 1;
+ /* This reentrant call to event_base_loop should be detected and
+ * should fail */
+ r = event_base_loop(base, 0);
+ tt_int_op(r, ==, -1);
+end:
+ ;
+}
+
+static void
+test_bad_reentrant(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event ev;
+ int r;
+ event_assign(&ev, base, -1,
+ 0, bad_reentrant_run_loop_cb, base);
+
+ event_active(&ev, EV_WRITE, 1);
+ r = event_base_loop(base, 0);
+ tt_int_op(r, ==, 1);
+ tt_int_op(reentrant_cb_run, ==, 1);
+end:
+ ;
+}
+
+static int n_write_a_byte_cb=0;
+static int n_read_and_drain_cb=0;
+static int n_activate_other_event_cb=0;
+static void
+write_a_byte_cb(evutil_socket_t fd, short what, void *arg)
+{
+ char buf[] = "x";
+ if (write(fd, buf, 1) == 1)
+ ++n_write_a_byte_cb;
+}
+static void
+read_and_drain_cb(evutil_socket_t fd, short what, void *arg)
+{
+ char buf[128];
+ int n;
+ ++n_read_and_drain_cb;
+ while ((n = read(fd, buf, sizeof(buf))) > 0)
+ ;
+}
+
+static void
+activate_other_event_cb(evutil_socket_t fd, short what, void *other_)
+{
+ struct event *ev_activate = other_;
+ ++n_activate_other_event_cb;
+ event_active_later_(ev_activate, EV_READ);
+}
+
+static void
+test_active_later(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event *ev1 = NULL, *ev2 = NULL;
+ struct event ev3, ev4;
+ struct timeval qsec = {0, 100000};
+ ev1 = event_new(data->base, data->pair[0], EV_READ|EV_PERSIST, read_and_drain_cb, NULL);
+ ev2 = event_new(data->base, data->pair[1], EV_WRITE|EV_PERSIST, write_a_byte_cb, NULL);
+ event_assign(&ev3, data->base, -1, 0, activate_other_event_cb, &ev4);
+ event_assign(&ev4, data->base, -1, 0, activate_other_event_cb, &ev3);
+ event_add(ev1, NULL);
+ event_add(ev2, NULL);
+ event_active_later_(&ev3, EV_READ);
+
+ event_base_loopexit(data->base, &qsec);
+
+ event_base_loop(data->base, 0);
+
+ TT_BLATHER(("%d write calls, %d read calls, %d activate-other calls.",
+ n_write_a_byte_cb, n_read_and_drain_cb, n_activate_other_event_cb));
+ event_del(&ev3);
+ event_del(&ev4);
+
+ tt_int_op(n_write_a_byte_cb, ==, n_activate_other_event_cb);
+ tt_int_op(n_write_a_byte_cb, >, 100);
+ tt_int_op(n_read_and_drain_cb, >, 100);
+ tt_int_op(n_activate_other_event_cb, >, 100);
+
+ event_active_later_(&ev4, EV_READ);
+ event_active(&ev4, EV_READ, 1); /* This should make the event
+ active immediately. */
+ tt_assert((ev4.ev_flags & EVLIST_ACTIVE) != 0);
+ tt_assert((ev4.ev_flags & EVLIST_ACTIVE_LATER) == 0);
+
+ /* Now leave this one around, so that event_free sees it and removes
+ * it. */
+ event_active_later_(&ev3, EV_READ);
+ event_base_assert_ok_(data->base);
+
+end:
+ if (ev1)
+ event_free(ev1);
+ if (ev2)
+ event_free(ev2);
+
+ event_base_free(data->base);
+ data->base = NULL;
+}
+
+
+static void incr_arg_cb(evutil_socket_t fd, short what, void *arg)
+{
+ int *intptr = arg;
+ (void) fd; (void) what;
+ ++*intptr;
+}
+static void remove_timers_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct event **ep = arg;
+ (void) fd; (void) what;
+ event_remove_timer(ep[0]);
+ event_remove_timer(ep[1]);
+}
+static void send_a_byte_cb(evutil_socket_t fd, short what, void *arg)
+{
+ evutil_socket_t *sockp = arg;
+ (void) fd; (void) what;
+ if (write(*sockp, "A", 1) < 0)
+ tt_fail_perror("write");
+}
+struct read_not_timeout_param
+{
+ struct event **ev;
+ int events;
+ int count;
+};
+static void read_not_timeout_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct read_not_timeout_param *rntp = arg;
+ char c;
+ ev_ssize_t n;
+ (void) fd; (void) what;
+ n = read(fd, &c, 1);
+ tt_int_op(n, ==, 1);
+ rntp->events |= what;
+ ++rntp->count;
+ if(2 == rntp->count) event_del(rntp->ev[0]);
+end:
+ ;
+}
+
+static void
+test_event_remove_timeout(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = data->base;
+ struct event *ev[5];
+ int ev1_fired=0;
+ struct timeval ms25 = { 0, 25*1000 },
+ ms40 = { 0, 40*1000 },
+ ms75 = { 0, 75*1000 },
+ ms125 = { 0, 125*1000 };
+ struct read_not_timeout_param rntp = { ev, 0, 0 };
+
+ event_base_assert_ok_(base);
+
+ ev[0] = event_new(base, data->pair[0], EV_READ|EV_PERSIST,
+ read_not_timeout_cb, &rntp);
+ ev[1] = evtimer_new(base, incr_arg_cb, &ev1_fired);
+ ev[2] = evtimer_new(base, remove_timers_cb, ev);
+ ev[3] = evtimer_new(base, send_a_byte_cb, &data->pair[1]);
+ ev[4] = evtimer_new(base, send_a_byte_cb, &data->pair[1]);
+ tt_assert(base);
+ event_add(ev[2], &ms25); /* remove timers */
+ event_add(ev[4], &ms40); /* write to test if timer re-activates */
+ event_add(ev[0], &ms75); /* read */
+ event_add(ev[1], &ms75); /* timer */
+ event_add(ev[3], &ms125); /* timeout. */
+ event_base_assert_ok_(base);
+
+ event_base_dispatch(base);
+
+ tt_int_op(ev1_fired, ==, 0);
+ tt_int_op(rntp.events, ==, EV_READ);
+
+ event_base_assert_ok_(base);
+end:
+ event_free(ev[0]);
+ event_free(ev[1]);
+ event_free(ev[2]);
+ event_free(ev[3]);
+ event_free(ev[4]);
+}
+
+static void
+test_event_base_new(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_base *base = 0;
+ struct event ev1;
+ struct basic_cb_args args;
+
+ int towrite = (int)strlen(TEST1)+1;
+ int len = write(data->pair[0], TEST1, towrite);
+
+ if (len < 0)
+ tt_abort_perror("initial write");
+ else if (len != towrite)
+ tt_abort_printf(("initial write fell short (%d of %d bytes)",
+ len, towrite));
+
+ if (shutdown(data->pair[0], EVUTIL_SHUT_WR))
+ tt_abort_perror("initial write shutdown");
+
+ base = event_base_new();
+ if (!base)
+ tt_abort_msg("failed to create event base");
+
+ args.eb = base;
+ args.ev = &ev1;
+ args.callcount = 0;
+ event_assign(&ev1, base, data->pair[1],
+ EV_READ|EV_PERSIST, basic_read_cb, &args);
+
+ if (event_add(&ev1, NULL))
+ tt_abort_perror("initial event_add");
+
+ if (event_base_loop(base, 0))
+ tt_abort_msg("unsuccessful exit from event loop");
+
+end:
+ if (base)
+ event_base_free(base);
+}
+
+static void
+test_loopexit(void)
+{
+ struct timeval tv, tv_start, tv_end;
+ struct event ev;
+
+ setup_test("Loop exit: ");
+
+ tv.tv_usec = 0;
+ tv.tv_sec = 60*60*24;
+ evtimer_set(&ev, timeout_cb, NULL);
+ evtimer_add(&ev, &tv);
+
+ tv.tv_usec = 300*1000;
+ tv.tv_sec = 0;
+ event_loopexit(&tv);
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_dispatch();
+ evutil_gettimeofday(&tv_end, NULL);
+
+ evtimer_del(&ev);
+
+ tt_assert(event_base_got_exit(global_base));
+ tt_assert(!event_base_got_break(global_base));
+
+ test_timeval_diff_eq(&tv_start, &tv_end, 300);
+
+ test_ok = 1;
+end:
+ cleanup_test();
+}
+
+static void
+test_loopexit_multiple(void)
+{
+ struct timeval tv, tv_start, tv_end;
+ struct event_base *base;
+
+ setup_test("Loop Multiple exit: ");
+
+ base = event_base_new();
+
+ tv.tv_usec = 200*1000;
+ tv.tv_sec = 0;
+ event_base_loopexit(base, &tv);
+
+ tv.tv_usec = 0;
+ tv.tv_sec = 3;
+ event_base_loopexit(base, &tv);
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_base_dispatch(base);
+ evutil_gettimeofday(&tv_end, NULL);
+
+ tt_assert(event_base_got_exit(base));
+ tt_assert(!event_base_got_break(base));
+
+ event_base_free(base);
+
+ test_timeval_diff_eq(&tv_start, &tv_end, 200);
+
+ test_ok = 1;
+
+end:
+ cleanup_test();
+}
+
+static void
+break_cb(evutil_socket_t fd, short events, void *arg)
+{
+ test_ok = 1;
+ event_loopbreak();
+}
+
+static void
+fail_cb(evutil_socket_t fd, short events, void *arg)
+{
+ test_ok = 0;
+}
+
+static void
+test_loopbreak(void)
+{
+ struct event ev1, ev2;
+ struct timeval tv;
+
+ setup_test("Loop break: ");
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 0;
+ evtimer_set(&ev1, break_cb, NULL);
+ evtimer_add(&ev1, &tv);
+ evtimer_set(&ev2, fail_cb, NULL);
+ evtimer_add(&ev2, &tv);
+
+ event_dispatch();
+
+ tt_assert(!event_base_got_exit(global_base));
+ tt_assert(event_base_got_break(global_base));
+
+ evtimer_del(&ev1);
+ evtimer_del(&ev2);
+
+end:
+ cleanup_test();
+}
+
+static struct event *readd_test_event_last_added = NULL;
+static void
+re_add_read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[256];
+ struct event *ev_other = arg;
+ ev_ssize_t n_read;
+
+ readd_test_event_last_added = ev_other;
+
+ n_read = read(fd, buf, sizeof(buf));
+
+ if (n_read < 0) {
+ tt_fail_perror("read");
+ event_base_loopbreak(event_get_base(ev_other));
+ } else {
+ event_add(ev_other, NULL);
+ ++test_ok;
+ }
+}
+static void
+test_nonpersist_readd(void *_data)
+{
+ struct event ev1, ev2;
+ struct basic_test_data *data = _data;
+
+ memset(&ev1, 0, sizeof(ev1));
+ memset(&ev2, 0, sizeof(ev2));
+
+ tt_assert(!event_assign(&ev1, data->base, data->pair[0], EV_READ, re_add_read_cb, &ev2));
+ tt_assert(!event_assign(&ev2, data->base, data->pair[1], EV_READ, re_add_read_cb, &ev1));
+
+ tt_int_op(write(data->pair[0], "Hello", 5), ==, 5);
+ tt_int_op(write(data->pair[1], "Hello", 5), ==, 5);
+
+ tt_int_op(event_add(&ev1, NULL), ==, 0);
+ tt_int_op(event_add(&ev2, NULL), ==, 0);
+ tt_int_op(event_base_loop(data->base, EVLOOP_ONCE), ==, 0);
+ tt_int_op(test_ok, ==, 2);
+
+ /* At this point, we executed both callbacks. Whichever one got
+ * called first added the second, but the second then immediately got
+ * deleted before its callback was called. At this point, though, it
+ * re-added the first.
+ */
+ tt_assert(readd_test_event_last_added);
+ if (readd_test_event_last_added == &ev1) {
+ tt_assert(event_pending(&ev1, EV_READ, NULL) && !event_pending(&ev2, EV_READ, NULL));
+ } else {
+ tt_assert(event_pending(&ev2, EV_READ, NULL) && !event_pending(&ev1, EV_READ, NULL));
+ }
+
+end:
+ if (event_initialized(&ev1))
+ event_del(&ev1);
+ if (event_initialized(&ev2))
+ event_del(&ev2);
+}
+
+struct test_pri_event {
+ struct event ev;
+ int count;
+};
+
+static void
+test_priorities_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct test_pri_event *pri = arg;
+ struct timeval tv;
+
+ if (pri->count == 3) {
+ event_loopexit(NULL);
+ return;
+ }
+
+ pri->count++;
+
+ evutil_timerclear(&tv);
+ event_add(&pri->ev, &tv);
+}
+
+static void
+test_priorities_impl(int npriorities)
+{
+ struct test_pri_event one, two;
+ struct timeval tv;
+
+ TT_BLATHER(("Testing Priorities %d: ", npriorities));
+
+ event_base_priority_init(global_base, npriorities);
+
+ memset(&one, 0, sizeof(one));
+ memset(&two, 0, sizeof(two));
+
+ timeout_set(&one.ev, test_priorities_cb, &one);
+ if (event_priority_set(&one.ev, 0) == -1) {
+ fprintf(stderr, "%s: failed to set priority", __func__);
+ exit(1);
+ }
+
+ timeout_set(&two.ev, test_priorities_cb, &two);
+ if (event_priority_set(&two.ev, npriorities - 1) == -1) {
+ fprintf(stderr, "%s: failed to set priority", __func__);
+ exit(1);
+ }
+
+ evutil_timerclear(&tv);
+
+ if (event_add(&one.ev, &tv) == -1)
+ exit(1);
+ if (event_add(&two.ev, &tv) == -1)
+ exit(1);
+
+ event_dispatch();
+
+ event_del(&one.ev);
+ event_del(&two.ev);
+
+ if (npriorities == 1) {
+ if (one.count == 3 && two.count == 3)
+ test_ok = 1;
+ } else if (npriorities == 2) {
+ /* Two is called once because event_loopexit is priority 1 */
+ if (one.count == 3 && two.count == 1)
+ test_ok = 1;
+ } else {
+ if (one.count == 3 && two.count == 0)
+ test_ok = 1;
+ }
+}
+
+static void
+test_priorities(void)
+{
+ test_priorities_impl(1);
+ if (test_ok)
+ test_priorities_impl(2);
+ if (test_ok)
+ test_priorities_impl(3);
+}
+
+/* priority-active-inversion: activate a higher-priority event, and make sure
+ * it keeps us from running a lower-priority event first. */
+static int n_pai_calls = 0;
+static struct event pai_events[3];
+
+static void
+prio_active_inversion_cb(evutil_socket_t fd, short what, void *arg)
+{
+ int *call_order = arg;
+ *call_order = n_pai_calls++;
+ if (n_pai_calls == 1) {
+ /* This should activate later, even though it shares a
+ priority with us. */
+ event_active(&pai_events[1], EV_READ, 1);
+ /* This should activate next, since its priority is higher,
+ even though we activated it second. */
+ event_active(&pai_events[2], EV_TIMEOUT, 1);
+ }
+}
+
+static void
+test_priority_active_inversion(void *data_)
+{
+ struct basic_test_data *data = data_;
+ struct event_base *base = data->base;
+ int call_order[3];
+ int i;
+ tt_int_op(event_base_priority_init(base, 8), ==, 0);
+
+ n_pai_calls = 0;
+ memset(call_order, 0, sizeof(call_order));
+
+ for (i=0;i<3;++i) {
+ event_assign(&pai_events[i], data->base, -1, 0,
+ prio_active_inversion_cb, &call_order[i]);
+ }
+
+ event_priority_set(&pai_events[0], 4);
+ event_priority_set(&pai_events[1], 4);
+ event_priority_set(&pai_events[2], 0);
+
+ event_active(&pai_events[0], EV_WRITE, 1);
+
+ event_base_dispatch(base);
+ tt_int_op(n_pai_calls, ==, 3);
+ tt_int_op(call_order[0], ==, 0);
+ tt_int_op(call_order[1], ==, 2);
+ tt_int_op(call_order[2], ==, 1);
+end:
+ ;
+}
+
+
+static void
+test_multiple_cb(evutil_socket_t fd, short event, void *arg)
+{
+ if (event & EV_READ)
+ test_ok |= 1;
+ else if (event & EV_WRITE)
+ test_ok |= 2;
+}
+
+static void
+test_multiple_events_for_same_fd(void)
+{
+ struct event e1, e2;
+
+ setup_test("Multiple events for same fd: ");
+
+ event_set(&e1, pair[0], EV_READ, test_multiple_cb, NULL);
+ event_add(&e1, NULL);
+ event_set(&e2, pair[0], EV_WRITE, test_multiple_cb, NULL);
+ event_add(&e2, NULL);
+ event_loop(EVLOOP_ONCE);
+ event_del(&e2);
+
+ if (write(pair[1], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ event_loop(EVLOOP_ONCE);
+ event_del(&e1);
+
+ if (test_ok != 3)
+ test_ok = 0;
+
+ cleanup_test();
+}
+
+int evtag_decode_int(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+int evtag_decode_int64(ev_uint64_t *pnumber, struct evbuffer *evbuf);
+int evtag_encode_tag(struct evbuffer *evbuf, ev_uint32_t number);
+int evtag_decode_tag(ev_uint32_t *pnumber, struct evbuffer *evbuf);
+
+static void
+read_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[256];
+ int len;
+
+ len = read(fd, buf, sizeof(buf));
+
+ if (called) {
+ test_ok = 0;
+ } else if (len) {
+ /* Assumes global pair[0] can be used for writing */
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ test_ok = 0;
+ } else {
+ test_ok = 1;
+ }
+ }
+
+ called++;
+}
+
+static void
+test_want_only_once(void)
+{
+ struct event ev;
+ struct timeval tv;
+
+ /* Very simple read test */
+ setup_test("Want read only once: ");
+
+ if (write(pair[0], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ /* Setup the loop termination */
+ evutil_timerclear(&tv);
+ tv.tv_usec = 300*1000;
+ event_loopexit(&tv);
+
+ event_set(&ev, pair[1], EV_READ, read_once_cb, &ev);
+ if (event_add(&ev, NULL) == -1)
+ exit(1);
+ event_dispatch();
+
+ cleanup_test();
+}
+
+#define TEST_MAX_INT 6
+
+static void
+evtag_int_test(void *ptr)
+{
+ struct evbuffer *tmp = evbuffer_new();
+ ev_uint32_t integers[TEST_MAX_INT] = {
+ 0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
+ };
+ ev_uint32_t integer;
+ ev_uint64_t big_int;
+ int i;
+
+ evtag_init();
+
+ for (i = 0; i < TEST_MAX_INT; i++) {
+ int oldlen, newlen;
+ oldlen = (int)EVBUFFER_LENGTH(tmp);
+ evtag_encode_int(tmp, integers[i]);
+ newlen = (int)EVBUFFER_LENGTH(tmp);
+ TT_BLATHER(("encoded 0x%08x with %d bytes",
+ (unsigned)integers[i], newlen - oldlen));
+ big_int = integers[i];
+ big_int *= 1000000000; /* 1 billion */
+ evtag_encode_int64(tmp, big_int);
+ }
+
+ for (i = 0; i < TEST_MAX_INT; i++) {
+ tt_int_op(evtag_decode_int(&integer, tmp), !=, -1);
+ tt_uint_op(integer, ==, integers[i]);
+ tt_int_op(evtag_decode_int64(&big_int, tmp), !=, -1);
+ tt_assert((big_int / 1000000000) == integers[i]);
+ }
+
+ tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
+end:
+ evbuffer_free(tmp);
+}
+
+static void
+evtag_fuzz(void *ptr)
+{
+ unsigned char buffer[4096];
+ struct evbuffer *tmp = evbuffer_new();
+ struct timeval tv;
+ int i, j;
+
+ int not_failed = 0;
+
+ evtag_init();
+
+ for (j = 0; j < 100; j++) {
+ for (i = 0; i < (int)sizeof(buffer); i++)
+ buffer[i] = test_weakrand();
+ evbuffer_drain(tmp, -1);
+ evbuffer_add(tmp, buffer, sizeof(buffer));
+
+ if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1)
+ not_failed++;
+ }
+
+ /* The majority of decodes should fail */
+ tt_int_op(not_failed, <, 10);
+
+ /* Now insert some corruption into the tag length field */
+ evbuffer_drain(tmp, -1);
+ evutil_timerclear(&tv);
+ tv.tv_sec = 1;
+ evtag_marshal_timeval(tmp, 0, &tv);
+ evbuffer_add(tmp, buffer, sizeof(buffer));
+
+ ((char *)EVBUFFER_DATA(tmp))[1] = '\xff';
+ if (evtag_unmarshal_timeval(tmp, 0, &tv) != -1) {
+ tt_abort_msg("evtag_unmarshal_timeval should have failed");
+ }
+
+end:
+ evbuffer_free(tmp);
+}
+
+static void
+evtag_tag_encoding(void *ptr)
+{
+ struct evbuffer *tmp = evbuffer_new();
+ ev_uint32_t integers[TEST_MAX_INT] = {
+ 0xaf0, 0x1000, 0x1, 0xdeadbeef, 0x00, 0xbef000
+ };
+ ev_uint32_t integer;
+ int i;
+
+ evtag_init();
+
+ for (i = 0; i < TEST_MAX_INT; i++) {
+ int oldlen, newlen;
+ oldlen = (int)EVBUFFER_LENGTH(tmp);
+ evtag_encode_tag(tmp, integers[i]);
+ newlen = (int)EVBUFFER_LENGTH(tmp);
+ TT_BLATHER(("encoded 0x%08x with %d bytes",
+ (unsigned)integers[i], newlen - oldlen));
+ }
+
+ for (i = 0; i < TEST_MAX_INT; i++) {
+ tt_int_op(evtag_decode_tag(&integer, tmp), !=, -1);
+ tt_uint_op(integer, ==, integers[i]);
+ }
+
+ tt_uint_op(EVBUFFER_LENGTH(tmp), ==, 0);
+
+end:
+ evbuffer_free(tmp);
+}
+
+static void
+evtag_test_peek(void *ptr)
+{
+ struct evbuffer *tmp = evbuffer_new();
+ ev_uint32_t u32;
+
+ evtag_marshal_int(tmp, 30, 0);
+ evtag_marshal_string(tmp, 40, "Hello world");
+
+ tt_int_op(evtag_peek(tmp, &u32), ==, 1);
+ tt_int_op(u32, ==, 30);
+ tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
+ tt_int_op(u32, ==, 1+1+1);
+ tt_int_op(evtag_consume(tmp), ==, 0);
+
+ tt_int_op(evtag_peek(tmp, &u32), ==, 1);
+ tt_int_op(u32, ==, 40);
+ tt_int_op(evtag_peek_length(tmp, &u32), ==, 0);
+ tt_int_op(u32, ==, 1+1+11);
+ tt_int_op(evtag_payload_length(tmp, &u32), ==, 0);
+ tt_int_op(u32, ==, 11);
+
+end:
+ evbuffer_free(tmp);
+}
+
+
+static void
+test_methods(void *ptr)
+{
+ const char **methods = event_get_supported_methods();
+ struct event_config *cfg = NULL;
+ struct event_base *base = NULL;
+ const char *backend;
+ int n_methods = 0;
+
+ tt_assert(methods);
+
+ backend = methods[0];
+ while (*methods != NULL) {
+ TT_BLATHER(("Support method: %s", *methods));
+ ++methods;
+ ++n_methods;
+ }
+
+ cfg = event_config_new();
+ assert(cfg != NULL);
+
+ tt_int_op(event_config_avoid_method(cfg, backend), ==, 0);
+ event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
+
+ base = event_base_new_with_config(cfg);
+ if (n_methods > 1) {
+ tt_assert(base);
+ tt_str_op(backend, !=, event_base_get_method(base));
+ } else {
+ tt_assert(base == NULL);
+ }
+
+end:
+ if (base)
+ event_base_free(base);
+ if (cfg)
+ event_config_free(cfg);
+}
+
+static void
+test_version(void *arg)
+{
+ const char *vstr;
+ ev_uint32_t vint;
+ int major, minor, patch, n;
+
+ vstr = event_get_version();
+ vint = event_get_version_number();
+
+ tt_assert(vstr);
+ tt_assert(vint);
+
+ tt_str_op(vstr, ==, LIBEVENT_VERSION);
+ tt_int_op(vint, ==, LIBEVENT_VERSION_NUMBER);
+
+ n = sscanf(vstr, "%d.%d.%d", &major, &minor, &patch);
+ tt_assert(3 == n);
+ tt_int_op((vint&0xffffff00), ==, ((major<<24)|(minor<<16)|(patch<<8)));
+end:
+ ;
+}
+
+static void
+test_base_features(void *arg)
+{
+ struct event_base *base = NULL;
+ struct event_config *cfg = NULL;
+
+ cfg = event_config_new();
+
+ tt_assert(0 == event_config_require_features(cfg, EV_FEATURE_ET));
+
+ base = event_base_new_with_config(cfg);
+ if (base) {
+ tt_int_op(EV_FEATURE_ET, ==,
+ event_base_get_features(base) & EV_FEATURE_ET);
+ } else {
+ base = event_base_new();
+ tt_int_op(0, ==, event_base_get_features(base) & EV_FEATURE_ET);
+ }
+
+end:
+ if (base)
+ event_base_free(base);
+ if (cfg)
+ event_config_free(cfg);
+}
+
+#ifdef EVENT__HAVE_SETENV
+#define SETENV_OK
+#elif !defined(EVENT__HAVE_SETENV) && defined(EVENT__HAVE_PUTENV)
+static void setenv(const char *k, const char *v, int o_)
+{
+ char b[256];
+ evutil_snprintf(b, sizeof(b), "%s=%s",k,v);
+ putenv(b);
+}
+#define SETENV_OK
+#endif
+
+#ifdef EVENT__HAVE_UNSETENV
+#define UNSETENV_OK
+#elif !defined(EVENT__HAVE_UNSETENV) && defined(EVENT__HAVE_PUTENV)
+static void unsetenv(const char *k)
+{
+ char b[256];
+ evutil_snprintf(b, sizeof(b), "%s=",k);
+ putenv(b);
+}
+#define UNSETENV_OK
+#endif
+
+#if defined(SETENV_OK) && defined(UNSETENV_OK)
+static void
+methodname_to_envvar(const char *mname, char *buf, size_t buflen)
+{
+ char *cp;
+ evutil_snprintf(buf, buflen, "EVENT_NO%s", mname);
+ for (cp = buf; *cp; ++cp) {
+ *cp = EVUTIL_TOUPPER_(*cp);
+ }
+}
+#endif
+
+static void
+test_base_environ(void *arg)
+{
+ struct event_base *base = NULL;
+ struct event_config *cfg = NULL;
+
+#if defined(SETENV_OK) && defined(UNSETENV_OK)
+ const char **basenames;
+ int i, n_methods=0;
+ char varbuf[128];
+ const char *defaultname, *ignoreenvname;
+
+ /* See if unsetenv works before we rely on it. */
+ setenv("EVENT_NOWAFFLES", "1", 1);
+ unsetenv("EVENT_NOWAFFLES");
+ if (getenv("EVENT_NOWAFFLES") != NULL) {
+#ifndef EVENT__HAVE_UNSETENV
+ TT_DECLARE("NOTE", ("Can't fake unsetenv; skipping test"));
+#else
+ TT_DECLARE("NOTE", ("unsetenv doesn't work; skipping test"));
+#endif
+ tt_skip();
+ }
+
+ basenames = event_get_supported_methods();
+ for (i = 0; basenames[i]; ++i) {
+ methodname_to_envvar(basenames[i], varbuf, sizeof(varbuf));
+ unsetenv(varbuf);
+ ++n_methods;
+ }
+
+ base = event_base_new();
+ tt_assert(base);
+
+ defaultname = event_base_get_method(base);
+ TT_BLATHER(("default is <%s>", defaultname));
+ event_base_free(base);
+ base = NULL;
+
+ /* Can we disable the method with EVENT_NOfoo ? */
+ if (!strcmp(defaultname, "epoll (with changelist)")) {
+ setenv("EVENT_NOEPOLL", "1", 1);
+ ignoreenvname = "epoll";
+ } else {
+ methodname_to_envvar(defaultname, varbuf, sizeof(varbuf));
+ setenv(varbuf, "1", 1);
+ ignoreenvname = defaultname;
+ }
+
+ /* Use an empty cfg rather than NULL so a failure doesn't exit() */
+ cfg = event_config_new();
+ base = event_base_new_with_config(cfg);
+ event_config_free(cfg);
+ cfg = NULL;
+ if (n_methods == 1) {
+ tt_assert(!base);
+ } else {
+ tt_assert(base);
+ tt_str_op(defaultname, !=, event_base_get_method(base));
+ event_base_free(base);
+ base = NULL;
+ }
+
+ /* Can we disable looking at the environment with IGNORE_ENV ? */
+ cfg = event_config_new();
+ event_config_set_flag(cfg, EVENT_BASE_FLAG_IGNORE_ENV);
+ base = event_base_new_with_config(cfg);
+ tt_assert(base);
+ tt_str_op(ignoreenvname, ==, event_base_get_method(base));
+#else
+ tt_skip();
+#endif
+
+end:
+ if (base)
+ event_base_free(base);
+ if (cfg)
+ event_config_free(cfg);
+}
+
+static void
+read_called_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+ tt_int_op(event, ==, EV_READ);
+ called += 1;
+end:
+ ;
+}
+
+static void
+timeout_called_once_cb(evutil_socket_t fd, short event, void *arg)
+{
+ tt_int_op(event, ==, EV_TIMEOUT);
+ called += 100;
+end:
+ ;
+}
+
+static void
+immediate_called_twice_cb(evutil_socket_t fd, short event, void *arg)
+{
+ tt_int_op(event, ==, EV_TIMEOUT);
+ called += 1000;
+end:
+ ;
+}
+
+static void
+test_event_once(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct timeval tv;
+ int r;
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 50*1000;
+ called = 0;
+ r = event_base_once(data->base, data->pair[0], EV_READ,
+ read_called_once_cb, NULL, NULL);
+ tt_int_op(r, ==, 0);
+ r = event_base_once(data->base, -1, EV_TIMEOUT,
+ timeout_called_once_cb, NULL, &tv);
+ tt_int_op(r, ==, 0);
+ r = event_base_once(data->base, -1, 0, NULL, NULL, NULL);
+ tt_int_op(r, <, 0);
+ r = event_base_once(data->base, -1, EV_TIMEOUT,
+ immediate_called_twice_cb, NULL, NULL);
+ tt_int_op(r, ==, 0);
+ tv.tv_sec = 0;
+ tv.tv_usec = 0;
+ r = event_base_once(data->base, -1, EV_TIMEOUT,
+ immediate_called_twice_cb, NULL, &tv);
+ tt_int_op(r, ==, 0);
+
+ if (write(data->pair[1], TEST1, strlen(TEST1)+1) < 0) {
+ tt_fail_perror("write");
+ }
+
+ shutdown(data->pair[1], EVUTIL_SHUT_WR);
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(called, ==, 2101);
+end:
+ ;
+}
+
+static void
+test_event_once_never(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct timeval tv;
+
+ /* Have one trigger in 10 seconds (don't worry, because) */
+ tv.tv_sec = 10;
+ tv.tv_usec = 0;
+ called = 0;
+ event_base_once(data->base, -1, EV_TIMEOUT,
+ timeout_called_once_cb, NULL, &tv);
+
+ /* But shut down the base in 75 msec. */
+ tv.tv_sec = 0;
+ tv.tv_usec = 75*1000;
+ event_base_loopexit(data->base, &tv);
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(called, ==, 0);
+end:
+ ;
+}
+
+static void
+test_event_pending(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event *r=NULL, *w=NULL, *t=NULL;
+ struct timeval tv, now, tv2;
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 500 * 1000;
+ r = event_new(data->base, data->pair[0], EV_READ, simple_read_cb,
+ NULL);
+ w = event_new(data->base, data->pair[1], EV_WRITE, simple_write_cb,
+ NULL);
+ t = evtimer_new(data->base, timeout_cb, NULL);
+
+ tt_assert(r);
+ tt_assert(w);
+ tt_assert(t);
+
+ evutil_gettimeofday(&now, NULL);
+ event_add(r, NULL);
+ event_add(t, &tv);
+
+ tt_assert( event_pending(r, EV_READ, NULL));
+ tt_assert(!event_pending(w, EV_WRITE, NULL));
+ tt_assert(!event_pending(r, EV_WRITE, NULL));
+ tt_assert( event_pending(r, EV_READ|EV_WRITE, NULL));
+ tt_assert(!event_pending(r, EV_TIMEOUT, NULL));
+ tt_assert( event_pending(t, EV_TIMEOUT, NULL));
+ tt_assert( event_pending(t, EV_TIMEOUT, &tv2));
+
+ tt_assert(evutil_timercmp(&tv2, &now, >));
+
+ test_timeval_diff_eq(&now, &tv2, 500);
+
+end:
+ if (r) {
+ event_del(r);
+ event_free(r);
+ }
+ if (w) {
+ event_del(w);
+ event_free(w);
+ }
+ if (t) {
+ event_del(t);
+ event_free(t);
+ }
+}
+
+static void
+dfd_cb(evutil_socket_t fd, short e, void *data)
+{
+ *(int*)data = (int)e;
+}
+
+static void
+test_event_closed_fd_poll(void *arg)
+{
+ struct timeval tv;
+ struct event *e;
+ struct basic_test_data *data = (struct basic_test_data *)arg;
+ int i = 0;
+
+ if (strcmp(event_base_get_method(data->base), "poll")) {
+ tinytest_set_test_skipped_();
+ return;
+ }
+
+ e = event_new(data->base, data->pair[0], EV_READ, dfd_cb, &i);
+ tt_assert(e);
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 500 * 1000;
+ event_add(e, &tv);
+ tt_assert(event_pending(e, EV_READ, NULL));
+ close(data->pair[0]);
+ data->pair[0] = -1; /** avoids double-close */
+ event_base_loop(data->base, EVLOOP_ONCE);
+ tt_int_op(i, ==, EV_READ);
+
+end:
+ if (e) {
+ event_del(e);
+ event_free(e);
+ }
+}
+
+#ifndef _WIN32
+/* You can't do this test on windows, since dup2 doesn't work on sockets */
+
+/* Regression test for our workaround for a fun epoll/linux related bug
+ * where fd2 = dup(fd1); add(fd2); close(fd2); dup2(fd1,fd2); add(fd2)
+ * will get you an EEXIST */
+static void
+test_dup_fd(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev1=NULL, *ev2=NULL;
+ int fd, dfd=-1;
+ int ev1_got, ev2_got;
+
+ tt_int_op(write(data->pair[0], "Hello world",
+ strlen("Hello world")), >, 0);
+ fd = data->pair[1];
+
+ dfd = dup(fd);
+ tt_int_op(dfd, >=, 0);
+
+ ev1 = event_new(base, fd, EV_READ|EV_PERSIST, dfd_cb, &ev1_got);
+ ev2 = event_new(base, dfd, EV_READ|EV_PERSIST, dfd_cb, &ev2_got);
+ ev1_got = ev2_got = 0;
+ event_add(ev1, NULL);
+ event_add(ev2, NULL);
+ event_base_loop(base, EVLOOP_ONCE);
+ tt_int_op(ev1_got, ==, EV_READ);
+ tt_int_op(ev2_got, ==, EV_READ);
+
+ /* Now close and delete dfd then dispatch. We need to do the
+ * dispatch here so that when we add it later, we think there
+ * was an intermediate delete. */
+ close(dfd);
+ event_del(ev2);
+ ev1_got = ev2_got = 0;
+ event_base_loop(base, EVLOOP_ONCE);
+ tt_want_int_op(ev1_got, ==, EV_READ);
+ tt_int_op(ev2_got, ==, 0);
+
+ /* Re-duplicate the fd. We need to get the same duplicated
+ * value that we closed to provoke the epoll quirk. Also, we
+ * need to change the events to write, or else the old lingering
+ * read event will make the test pass whether the change was
+ * successful or not. */
+ tt_int_op(dup2(fd, dfd), ==, dfd);
+ event_free(ev2);
+ ev2 = event_new(base, dfd, EV_WRITE|EV_PERSIST, dfd_cb, &ev2_got);
+ event_add(ev2, NULL);
+ ev1_got = ev2_got = 0;
+ event_base_loop(base, EVLOOP_ONCE);
+ tt_want_int_op(ev1_got, ==, EV_READ);
+ tt_int_op(ev2_got, ==, EV_WRITE);
+
+end:
+ if (ev1)
+ event_free(ev1);
+ if (ev2)
+ event_free(ev2);
+ if (dfd >= 0)
+ close(dfd);
+}
+#endif
+
+#ifdef EVENT__DISABLE_MM_REPLACEMENT
+static void
+test_mm_functions(void *arg)
+{
+ tinytest_set_test_skipped_();
+}
+#else
+static int
+check_dummy_mem_ok(void *mem_)
+{
+ char *mem = mem_;
+ mem -= 16;
+ return !memcmp(mem, "{[<guardedram>]}", 16);
+}
+
+static void *
+dummy_malloc(size_t len)
+{
+ char *mem = malloc(len+16);
+ memcpy(mem, "{[<guardedram>]}", 16);
+ return mem+16;
+}
+
+static void *
+dummy_realloc(void *mem_, size_t len)
+{
+ char *mem = mem_;
+ if (!mem)
+ return dummy_malloc(len);
+ tt_want(check_dummy_mem_ok(mem_));
+ mem -= 16;
+ mem = realloc(mem, len+16);
+ return mem+16;
+}
+
+static void
+dummy_free(void *mem_)
+{
+ char *mem = mem_;
+ tt_want(check_dummy_mem_ok(mem_));
+ mem -= 16;
+ free(mem);
+}
+
+static void
+test_mm_functions(void *arg)
+{
+ struct event_base *b = NULL;
+ struct event_config *cfg = NULL;
+ event_set_mem_functions(dummy_malloc, dummy_realloc, dummy_free);
+ cfg = event_config_new();
+ event_config_avoid_method(cfg, "Nonesuch");
+ b = event_base_new_with_config(cfg);
+ tt_assert(b);
+ tt_assert(check_dummy_mem_ok(b));
+end:
+ if (cfg)
+ event_config_free(cfg);
+ if (b)
+ event_base_free(b);
+}
+#endif
+
+static void
+many_event_cb(evutil_socket_t fd, short event, void *arg)
+{
+ int *calledp = arg;
+ *calledp += 1;
+}
+
+static void
+test_many_events(void *arg)
+{
+ /* Try 70 events that should all be ready at once. This will
+ * exercise the "resize" code on most of the backends, and will make
+ * sure that we can get past the 64-handle limit of some windows
+ * functions. */
+#define MANY 70
+
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ int one_at_a_time = data->setup_data != NULL;
+ evutil_socket_t sock[MANY];
+ struct event *ev[MANY];
+ int called[MANY];
+ int i;
+ int loopflags = EVLOOP_NONBLOCK, evflags=0;
+ if (one_at_a_time) {
+ loopflags |= EVLOOP_ONCE;
+ evflags = EV_PERSIST;
+ }
+
+ memset(sock, 0xff, sizeof(sock));
+ memset(ev, 0, sizeof(ev));
+ memset(called, 0, sizeof(called));
+
+ for (i = 0; i < MANY; ++i) {
+ /* We need an event that will hit the backend, and that will
+ * be ready immediately. "Send a datagram" is an easy
+ * instance of that. */
+ sock[i] = socket(AF_INET, SOCK_DGRAM, 0);
+ tt_assert(sock[i] >= 0);
+ tt_assert(!evutil_make_socket_nonblocking(sock[i]));
+ called[i] = 0;
+ ev[i] = event_new(base, sock[i], EV_WRITE|evflags,
+ many_event_cb, &called[i]);
+ event_add(ev[i], NULL);
+ if (one_at_a_time)
+ event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+ }
+
+ event_base_loop(base, loopflags);
+
+ for (i = 0; i < MANY; ++i) {
+ if (one_at_a_time)
+ tt_int_op(called[i], ==, MANY - i + 1);
+ else
+ tt_int_op(called[i], ==, 1);
+ }
+
+end:
+ for (i = 0; i < MANY; ++i) {
+ if (ev[i])
+ event_free(ev[i]);
+ if (sock[i] >= 0)
+ evutil_closesocket(sock[i]);
+ }
+#undef MANY
+}
+
+static void
+test_struct_event_size(void *arg)
+{
+ tt_int_op(event_get_struct_event_size(), <=, sizeof(struct event));
+end:
+ ;
+}
+
+static void
+test_get_assignment(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev1 = NULL;
+ const char *str = "foo";
+
+ struct event_base *b;
+ evutil_socket_t s;
+ short what;
+ event_callback_fn cb;
+ void *cb_arg;
+
+ ev1 = event_new(base, data->pair[1], EV_READ, dummy_read_cb, (void*)str);
+ event_get_assignment(ev1, &b, &s, &what, &cb, &cb_arg);
+
+ tt_ptr_op(b, ==, base);
+ tt_fd_op(s, ==, data->pair[1]);
+ tt_int_op(what, ==, EV_READ);
+ tt_ptr_op(cb, ==, dummy_read_cb);
+ tt_ptr_op(cb_arg, ==, str);
+
+ /* Now make sure this doesn't crash. */
+ event_get_assignment(ev1, NULL, NULL, NULL, NULL, NULL);
+
+end:
+ if (ev1)
+ event_free(ev1);
+}
+
+struct foreach_helper {
+ int count;
+ const struct event *ev;
+};
+
+static int
+foreach_count_cb(const struct event_base *base, const struct event *ev, void *arg)
+{
+ struct foreach_helper *h = event_get_callback_arg(ev);
+ struct timeval *tv = arg;
+ if (event_get_callback(ev) != timeout_cb)
+ return 0;
+ tt_ptr_op(event_get_base(ev), ==, base);
+ tt_int_op(tv->tv_sec, ==, 10);
+ h->ev = ev;
+ h->count++;
+ return 0;
+end:
+ return -1;
+}
+
+static int
+foreach_find_cb(const struct event_base *base, const struct event *ev, void *arg)
+{
+ const struct event **ev_out = arg;
+ struct foreach_helper *h = event_get_callback_arg(ev);
+ if (event_get_callback(ev) != timeout_cb)
+ return 0;
+ if (h->count == 99) {
+ *ev_out = ev;
+ return 101;
+ }
+ return 0;
+}
+
+static void
+test_event_foreach(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev[5];
+ struct foreach_helper visited[5];
+ int i;
+ struct timeval ten_sec = {10,0};
+ const struct event *ev_found = NULL;
+
+ for (i = 0; i < 5; ++i) {
+ visited[i].count = 0;
+ visited[i].ev = NULL;
+ ev[i] = event_new(base, -1, 0, timeout_cb, &visited[i]);
+ }
+
+ tt_int_op(-1, ==, event_base_foreach_event(NULL, foreach_count_cb, NULL));
+ tt_int_op(-1, ==, event_base_foreach_event(base, NULL, NULL));
+
+ event_add(ev[0], &ten_sec);
+ event_add(ev[1], &ten_sec);
+ event_active(ev[1], EV_TIMEOUT, 1);
+ event_active(ev[2], EV_TIMEOUT, 1);
+ event_add(ev[3], &ten_sec);
+ /* Don't touch ev[4]. */
+
+ tt_int_op(0, ==, event_base_foreach_event(base, foreach_count_cb,
+ &ten_sec));
+ tt_int_op(1, ==, visited[0].count);
+ tt_int_op(1, ==, visited[1].count);
+ tt_int_op(1, ==, visited[2].count);
+ tt_int_op(1, ==, visited[3].count);
+ tt_ptr_op(ev[0], ==, visited[0].ev);
+ tt_ptr_op(ev[1], ==, visited[1].ev);
+ tt_ptr_op(ev[2], ==, visited[2].ev);
+ tt_ptr_op(ev[3], ==, visited[3].ev);
+
+ visited[2].count = 99;
+ tt_int_op(101, ==, event_base_foreach_event(base, foreach_find_cb,
+ &ev_found));
+ tt_ptr_op(ev_found, ==, ev[2]);
+
+end:
+ for (i=0; i<5; ++i) {
+ event_free(ev[i]);
+ }
+}
+
+static struct event_base *cached_time_base = NULL;
+static int cached_time_reset = 0;
+static int cached_time_sleep = 0;
+static void
+cache_time_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct timeval *tv = arg;
+ tt_int_op(0, ==, event_base_gettimeofday_cached(cached_time_base, tv));
+ if (cached_time_sleep) {
+ struct timeval delay = { 0, 30*1000 };
+ evutil_usleep_(&delay);
+ }
+ if (cached_time_reset) {
+ event_base_update_cache_time(cached_time_base);
+ }
+end:
+ ;
+}
+
+static void
+test_gettimeofday_cached(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_config *cfg = NULL;
+ struct event_base *base = NULL;
+ struct timeval tv1, tv2, tv3, now;
+ struct event *ev1=NULL, *ev2=NULL, *ev3=NULL;
+ int cached_time_disable = strstr(data->setup_data, "disable") != NULL;
+
+ cfg = event_config_new();
+ if (cached_time_disable) {
+ event_config_set_flag(cfg, EVENT_BASE_FLAG_NO_CACHE_TIME);
+ }
+ cached_time_base = base = event_base_new_with_config(cfg);
+ tt_assert(base);
+
+ /* Try gettimeofday_cached outside of an event loop. */
+ evutil_gettimeofday(&now, NULL);
+ tt_int_op(0, ==, event_base_gettimeofday_cached(NULL, &tv1));
+ tt_int_op(0, ==, event_base_gettimeofday_cached(base, &tv2));
+ tt_int_op(timeval_msec_diff(&tv1, &tv2), <, 10);
+ tt_int_op(timeval_msec_diff(&tv1, &now), <, 10);
+
+ cached_time_reset = strstr(data->setup_data, "reset") != NULL;
+ cached_time_sleep = strstr(data->setup_data, "sleep") != NULL;
+
+ ev1 = event_new(base, -1, 0, cache_time_cb, &tv1);
+ ev2 = event_new(base, -1, 0, cache_time_cb, &tv2);
+ ev3 = event_new(base, -1, 0, cache_time_cb, &tv3);
+
+ event_active(ev1, EV_TIMEOUT, 1);
+ event_active(ev2, EV_TIMEOUT, 1);
+ event_active(ev3, EV_TIMEOUT, 1);
+
+ event_base_dispatch(base);
+
+ if (cached_time_reset && cached_time_sleep) {
+ tt_int_op(labs(timeval_msec_diff(&tv1,&tv2)), >, 10);
+ tt_int_op(labs(timeval_msec_diff(&tv2,&tv3)), >, 10);
+ } else if (cached_time_disable && cached_time_sleep) {
+ tt_int_op(labs(timeval_msec_diff(&tv1,&tv2)), >, 10);
+ tt_int_op(labs(timeval_msec_diff(&tv2,&tv3)), >, 10);
+ } else if (! cached_time_disable) {
+ tt_assert(evutil_timercmp(&tv1, &tv2, ==));
+ tt_assert(evutil_timercmp(&tv2, &tv3, ==));
+ }
+
+end:
+ if (ev1)
+ event_free(ev1);
+ if (ev2)
+ event_free(ev2);
+ if (ev3)
+ event_free(ev3);
+ if (base)
+ event_base_free(base);
+ if (cfg)
+ event_config_free(cfg);
+}
+
+static void
+tabf_cb(evutil_socket_t fd, short what, void *arg)
+{
+ int *ptr = arg;
+ *ptr = what;
+ *ptr += 0x10000;
+}
+
+static void
+test_evmap_invalid_slots(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev1 = NULL, *ev2 = NULL;
+ int e1, e2;
+#ifndef _WIN32
+ struct event *ev3 = NULL, *ev4 = NULL;
+ int e3, e4;
+#endif
+
+ ev1 = evsignal_new(base, -1, dummy_read_cb, (void *)base);
+ ev2 = evsignal_new(base, NSIG, dummy_read_cb, (void *)base);
+ tt_assert(ev1);
+ tt_assert(ev2);
+ e1 = event_add(ev1, NULL);
+ e2 = event_add(ev2, NULL);
+ tt_int_op(e1, !=, 0);
+ tt_int_op(e2, !=, 0);
+#ifndef _WIN32
+ ev3 = event_new(base, INT_MAX, EV_READ, dummy_read_cb, (void *)base);
+ ev4 = event_new(base, INT_MAX / 2, EV_READ, dummy_read_cb, (void *)base);
+ tt_assert(ev3);
+ tt_assert(ev4);
+ e3 = event_add(ev3, NULL);
+ e4 = event_add(ev4, NULL);
+ tt_int_op(e3, !=, 0);
+ tt_int_op(e4, !=, 0);
+#endif
+
+end:
+ event_free(ev1);
+ event_free(ev2);
+#ifndef _WIN32
+ event_free(ev3);
+ event_free(ev4);
+#endif
+}
+
+static void
+test_active_by_fd(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev1 = NULL, *ev2 = NULL, *ev3 = NULL, *ev4 = NULL;
+ int e1,e2,e3,e4;
+#ifndef _WIN32
+ struct event *evsig = NULL;
+ int es;
+#endif
+ struct timeval tenmin = { 600, 0 };
+
+ /* Ensure no crash on nonexistent FD. */
+ event_base_active_by_fd(base, 1000, EV_READ);
+
+ /* Ensure no crash on bogus FD. */
+ event_base_active_by_fd(base, -1, EV_READ);
+
+ /* Ensure no crash on nonexistent/bogus signal. */
+ event_base_active_by_signal(base, 1000);
+ event_base_active_by_signal(base, -1);
+
+ event_base_assert_ok_(base);
+
+ e1 = e2 = e3 = e4 = 0;
+ ev1 = event_new(base, data->pair[0], EV_READ, tabf_cb, &e1);
+ ev2 = event_new(base, data->pair[0], EV_WRITE, tabf_cb, &e2);
+ ev3 = event_new(base, data->pair[1], EV_READ, tabf_cb, &e3);
+ ev4 = event_new(base, data->pair[1], EV_READ, tabf_cb, &e4);
+ tt_assert(ev1);
+ tt_assert(ev2);
+ tt_assert(ev3);
+ tt_assert(ev4);
+#ifndef _WIN32
+ evsig = event_new(base, SIGHUP, EV_SIGNAL, tabf_cb, &es);
+ tt_assert(evsig);
+ event_add(evsig, &tenmin);
+#endif
+
+ event_add(ev1, &tenmin);
+ event_add(ev2, NULL);
+ event_add(ev3, NULL);
+ event_add(ev4, &tenmin);
+
+
+ event_base_assert_ok_(base);
+
+ /* Trigger 2, 3, 4 */
+ event_base_active_by_fd(base, data->pair[0], EV_WRITE);
+ event_base_active_by_fd(base, data->pair[1], EV_READ);
+ event_base_active_by_fd(base, data->pair[1], EV_TIMEOUT);
+#ifndef _WIN32
+ event_base_active_by_signal(base, SIGHUP);
+#endif
+
+ event_base_assert_ok_(base);
+
+ event_base_loop(base, EVLOOP_ONCE);
+
+ tt_int_op(e1, ==, 0);
+ tt_int_op(e2, ==, EV_WRITE | 0x10000);
+ tt_int_op(e3, ==, EV_READ | 0x10000);
+ /* Mask out EV_WRITE here, since it could be genuinely writeable. */
+ tt_int_op((e4 & ~EV_WRITE), ==, EV_READ | EV_TIMEOUT | 0x10000);
+#ifndef _WIN32
+ tt_int_op(es, ==, EV_SIGNAL | 0x10000);
+#endif
+
+end:
+ if (ev1)
+ event_free(ev1);
+ if (ev2)
+ event_free(ev2);
+ if (ev3)
+ event_free(ev3);
+ if (ev4)
+ event_free(ev4);
+#ifndef _WIN32
+ if (evsig)
+ event_free(evsig);
+#endif
+}
+
+struct testcase_t main_testcases[] = {
+ /* Some converted-over tests */
+ { "methods", test_methods, TT_FORK, NULL, NULL },
+ { "version", test_version, 0, NULL, NULL },
+ BASIC(base_features, TT_FORK|TT_NO_LOGS),
+ { "base_environ", test_base_environ, TT_FORK, NULL, NULL },
+
+ BASIC(event_base_new, TT_FORK|TT_NEED_SOCKETPAIR),
+ BASIC(free_active_base, TT_FORK|TT_NEED_SOCKETPAIR),
+
+ BASIC(manipulate_active_events, TT_FORK|TT_NEED_BASE),
+ BASIC(event_new_selfarg, TT_FORK|TT_NEED_BASE),
+ BASIC(event_assign_selfarg, TT_FORK|TT_NEED_BASE),
+ BASIC(event_base_get_num_events, TT_FORK|TT_NEED_BASE),
+ BASIC(event_base_get_max_events, TT_FORK|TT_NEED_BASE),
+ BASIC(evmap_invalid_slots, TT_FORK|TT_NEED_BASE),
+
+ BASIC(bad_assign, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
+ BASIC(bad_reentrant, TT_FORK|TT_NEED_BASE|TT_NO_LOGS),
+ BASIC(active_later, TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR|TT_RETRIABLE),
+ BASIC(event_remove_timeout, TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR),
+
+ /* These are still using the old API */
+ LEGACY(persistent_timeout, TT_FORK|TT_NEED_BASE),
+ { "persistent_timeout_jump", test_persistent_timeout_jump, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "persistent_active_timeout", test_persistent_active_timeout,
+ TT_FORK|TT_NEED_BASE|TT_RETRIABLE, &basic_setup, NULL },
+ LEGACY(priorities, TT_FORK|TT_NEED_BASE),
+ BASIC(priority_active_inversion, TT_FORK|TT_NEED_BASE),
+ { "common_timeout", test_common_timeout, TT_FORK|TT_NEED_BASE,
+ &basic_setup, NULL },
+
+ /* These legacy tests may not all need all of these flags. */
+ LEGACY(simpleread, TT_ISOLATED),
+ LEGACY(simpleread_multiple, TT_ISOLATED),
+ LEGACY(simplewrite, TT_ISOLATED),
+ { "simpleclose_rw", test_simpleclose_rw, TT_FORK, &basic_setup, NULL },
+ /* simpleclose */
+ { "simpleclose_close", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"close" },
+ { "simpleclose_shutdown", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"shutdown" },
+ /* simpleclose_*_persist */
+ { "simpleclose_close_persist", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"close_persist" },
+ { "simpleclose_shutdown_persist", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"shutdown_persist" },
+ /* simpleclose_*_et */
+ { "simpleclose_close_et", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"close_ET" },
+ { "simpleclose_shutdown_et", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"shutdown_ET" },
+ /* simpleclose_*_persist_et */
+ { "simpleclose_close_persist_et", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"close_persist_ET" },
+ { "simpleclose_shutdown_persist_et", test_simpleclose,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE,
+ &basic_setup, (void *)"shutdown_persist_ET" },
+ LEGACY(multiple, TT_ISOLATED),
+ LEGACY(persistent, TT_ISOLATED),
+ LEGACY(combined, TT_ISOLATED),
+ LEGACY(simpletimeout, TT_ISOLATED),
+ LEGACY(loopbreak, TT_ISOLATED),
+ LEGACY(loopexit, TT_ISOLATED),
+ LEGACY(loopexit_multiple, TT_ISOLATED),
+ { "nonpersist_readd", test_nonpersist_readd, TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE, &basic_setup, NULL },
+ LEGACY(multiple_events_for_same_fd, TT_ISOLATED),
+ LEGACY(want_only_once, TT_ISOLATED),
+ { "event_once", test_event_once, TT_ISOLATED, &basic_setup, NULL },
+ { "event_once_never", test_event_once_never, TT_ISOLATED, &basic_setup, NULL },
+ { "event_pending", test_event_pending, TT_ISOLATED, &basic_setup,
+ NULL },
+ { "event_closed_fd_poll", test_event_closed_fd_poll, TT_ISOLATED, &basic_setup,
+ NULL },
+
+#ifndef _WIN32
+ { "dup_fd", test_dup_fd, TT_ISOLATED, &basic_setup, NULL },
+#endif
+ { "mm_functions", test_mm_functions, TT_FORK, NULL, NULL },
+ { "many_events", test_many_events, TT_ISOLATED, &basic_setup, NULL },
+ { "many_events_slow_add", test_many_events, TT_ISOLATED, &basic_setup, (void*)1 },
+
+ { "struct_event_size", test_struct_event_size, 0, NULL, NULL },
+ BASIC(get_assignment, TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR),
+
+ BASIC(event_foreach, TT_FORK|TT_NEED_BASE),
+ { "gettimeofday_cached", test_gettimeofday_cached, TT_FORK, &basic_setup, (void*)"" },
+ { "gettimeofday_cached_sleep", test_gettimeofday_cached, TT_FORK, &basic_setup, (void*)"sleep" },
+ { "gettimeofday_cached_reset", test_gettimeofday_cached, TT_FORK, &basic_setup, (void*)"sleep reset" },
+ { "gettimeofday_cached_disabled", test_gettimeofday_cached, TT_FORK, &basic_setup, (void*)"sleep disable" },
+ { "gettimeofday_cached_disabled_nosleep", test_gettimeofday_cached, TT_FORK, &basic_setup, (void*)"disable" },
+
+ BASIC(active_by_fd, TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR),
+
+#ifndef _WIN32
+ LEGACY(fork, TT_ISOLATED),
+#endif
+
+#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
+ LEGACY(del_wait, TT_ISOLATED|TT_NEED_THREADS|TT_RETRIABLE),
+ LEGACY(del_notify, TT_ISOLATED|TT_NEED_THREADS),
+#endif
+
+ END_OF_TESTCASES
+};
+
+struct testcase_t evtag_testcases[] = {
+ { "int", evtag_int_test, TT_FORK, NULL, NULL },
+ { "fuzz", evtag_fuzz, TT_FORK, NULL, NULL },
+ { "encoding", evtag_tag_encoding, TT_FORK, NULL, NULL },
+ { "peek", evtag_test_peek, 0, NULL, NULL },
+
+ END_OF_TESTCASES
+};
+
+struct testcase_t signal_testcases[] = {
+#ifndef _WIN32
+ LEGACY(simplestsignal, TT_ISOLATED),
+ LEGACY(simplesignal, TT_ISOLATED),
+ LEGACY(multiplesignal, TT_ISOLATED),
+ LEGACY(immediatesignal, TT_ISOLATED),
+ LEGACY(signal_dealloc, TT_ISOLATED),
+ LEGACY(signal_pipeloss, TT_ISOLATED),
+ LEGACY(signal_switchbase, TT_ISOLATED|TT_NO_LOGS),
+ LEGACY(signal_restore, TT_ISOLATED),
+ LEGACY(signal_assert, TT_ISOLATED),
+ LEGACY(signal_while_processing, TT_ISOLATED),
+#endif
+ END_OF_TESTCASES
+};
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress.h b/ipc/chromium/src/third_party/libevent/test/regress.h
new file mode 100644
index 0000000000..43cb4eaf1e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress.h
@@ -0,0 +1,149 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef REGRESS_H_INCLUDED_
+#define REGRESS_H_INCLUDED_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+extern struct testcase_t main_testcases[];
+extern struct testcase_t evtag_testcases[];
+extern struct testcase_t evbuffer_testcases[];
+extern struct testcase_t finalize_testcases[];
+extern struct testcase_t bufferevent_testcases[];
+extern struct testcase_t bufferevent_iocp_testcases[];
+extern struct testcase_t util_testcases[];
+extern struct testcase_t signal_testcases[];
+extern struct testcase_t http_testcases[];
+extern struct testcase_t http_iocp_testcases[];
+extern struct testcase_t dns_testcases[];
+extern struct testcase_t rpc_testcases[];
+extern struct testcase_t edgetriggered_testcases[];
+extern struct testcase_t minheap_testcases[];
+extern struct testcase_t iocp_testcases[];
+extern struct testcase_t ssl_testcases[];
+extern struct testcase_t listener_testcases[];
+extern struct testcase_t listener_iocp_testcases[];
+extern struct testcase_t thread_testcases[];
+
+extern struct evutil_weakrand_state test_weakrand_state;
+
+#define test_weakrand() (evutil_weakrand_(&test_weakrand_state))
+
+void regress_threads(void *);
+void test_bufferevent_zlib(void *);
+
+/* Helpers to wrap old testcases */
+extern evutil_socket_t pair[2];
+extern int test_ok;
+extern int called;
+extern struct event_base *global_base;
+extern int in_legacy_test_wrapper;
+
+int regress_make_tmpfile(const void *data, size_t datalen, char **filename_out);
+
+struct basic_test_data {
+ struct event_base *base;
+ evutil_socket_t pair[2];
+
+ void (*legacy_test_fn)(void);
+
+ void *setup_data;
+};
+extern const struct testcase_setup_t basic_setup;
+
+
+extern const struct testcase_setup_t legacy_setup;
+void run_legacy_test_fn(void *ptr);
+
+extern int libevent_tests_running_in_debug_mode;
+
+/* A couple of flags that basic/legacy_setup can support. */
+#define TT_NEED_SOCKETPAIR TT_FIRST_USER_FLAG
+#define TT_NEED_BASE (TT_FIRST_USER_FLAG<<1)
+#define TT_NEED_DNS (TT_FIRST_USER_FLAG<<2)
+#define TT_LEGACY (TT_FIRST_USER_FLAG<<3)
+#define TT_NEED_THREADS (TT_FIRST_USER_FLAG<<4)
+#define TT_NO_LOGS (TT_FIRST_USER_FLAG<<5)
+#define TT_ENABLE_IOCP_FLAG (TT_FIRST_USER_FLAG<<6)
+#define TT_ENABLE_IOCP (TT_ENABLE_IOCP_FLAG|TT_NEED_THREADS)
+#define TT_ENABLE_DEBUG_MODE (TT_ENABLE_IOCP_FLAG<<7)
+
+/* All the flags that a legacy test needs. */
+#define TT_ISOLATED TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_BASE
+
+
+#define BASIC(name,flags) \
+ { #name, test_## name, flags, &basic_setup, NULL }
+
+#define LEGACY(name,flags) \
+ { #name, run_legacy_test_fn, flags|TT_LEGACY, &legacy_setup, \
+ test_## name }
+
+struct evutil_addrinfo;
+struct evutil_addrinfo *ai_find_by_family(struct evutil_addrinfo *ai, int f);
+struct evutil_addrinfo *ai_find_by_protocol(struct evutil_addrinfo *ai, int p);
+int test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+ int socktype, int protocol, int line);
+
+#define test_ai_eq(ai, str, s, p) do { \
+ if (test_ai_eq_((ai), (str), (s), (p), __LINE__)<0) \
+ goto end; \
+ } while (0)
+
+#define test_timeval_diff_leq(tv1, tv2, diff, tolerance) \
+ tt_int_op(labs(timeval_msec_diff((tv1), (tv2)) - diff), <=, tolerance)
+
+#define test_timeval_diff_eq(tv1, tv2, diff) \
+ test_timeval_diff_leq((tv1), (tv2), (diff), 50)
+
+long timeval_msec_diff(const struct timeval *start, const struct timeval *end);
+
+#ifndef _WIN32
+pid_t regress_fork(void);
+#endif
+
+#ifdef EVENT__HAVE_OPENSSL
+#include <openssl/ssl.h>
+EVP_PKEY *ssl_getkey(void);
+X509 *ssl_getcert(EVP_PKEY *key);
+SSL_CTX *get_ssl_ctx(void);
+void init_ssl(void);
+#endif
+
+void * basic_test_setup(const struct testcase_t *testcase);
+int basic_test_cleanup(const struct testcase_t *testcase, void *ptr);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* REGRESS_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/test/regress.rpc b/ipc/chromium/src/third_party/libevent/test/regress.rpc
new file mode 100644
index 0000000000..0ee904e913
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress.rpc
@@ -0,0 +1,25 @@
+/* tests data packing and unpacking */
+
+struct msg {
+ string /* sender */ from_name = 1; /* be verbose */
+ string to_name = 2;
+ optional struct[kill] attack = 3;
+ array struct[run] run = 4;
+}
+
+struct kill {
+ string weapon = 0x10121;
+ string action = 2;
+ array int how_often = 3;
+}
+
+struct run {
+ string how = 1;
+ optional bytes some_bytes = 2;
+
+ bytes fixed_bytes[24] = 3;
+ array string notes = 4;
+
+ optional int64 large_number = 5;
+ array int other_numbers = 6;
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_buffer.c b/ipc/chromium/src/third_party/libevent/test/regress_buffer.c
new file mode 100644
index 0000000000..f259b924bf
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_buffer.c
@@ -0,0 +1,2870 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#include "event2/event.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/util.h"
+
+#include "defer-internal.h"
+#include "evbuffer-internal.h"
+#include "log-internal.h"
+
+#include "regress.h"
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+
+/* Validates that an evbuffer is good. Returns false if it isn't, true if it
+ * is*/
+static int
+evbuffer_validate_(struct evbuffer *buf)
+{
+ struct evbuffer_chain *chain;
+ size_t sum = 0;
+ int found_last_with_datap = 0;
+
+ if (buf->first == NULL) {
+ tt_assert(buf->last == NULL);
+ tt_assert(buf->total_len == 0);
+ }
+
+ chain = buf->first;
+
+ tt_assert(buf->last_with_datap);
+ if (buf->last_with_datap == &buf->first)
+ found_last_with_datap = 1;
+
+ while (chain != NULL) {
+ if (&chain->next == buf->last_with_datap)
+ found_last_with_datap = 1;
+ sum += chain->off;
+ if (chain->next == NULL) {
+ tt_assert(buf->last == chain);
+ }
+ tt_assert(chain->buffer_len >= chain->misalign + chain->off);
+ chain = chain->next;
+ }
+
+ if (buf->first)
+ tt_assert(*buf->last_with_datap);
+
+ if (*buf->last_with_datap) {
+ chain = *buf->last_with_datap;
+ if (chain->off == 0 || buf->total_len == 0) {
+ tt_assert(chain->off == 0)
+ tt_assert(chain == buf->first);
+ tt_assert(buf->total_len == 0);
+ }
+ chain = chain->next;
+ while (chain != NULL) {
+ tt_assert(chain->off == 0);
+ chain = chain->next;
+ }
+ } else {
+ tt_assert(buf->last_with_datap == &buf->first);
+ }
+ tt_assert(found_last_with_datap);
+
+ tt_assert(sum == buf->total_len);
+ return 1;
+ end:
+ return 0;
+}
+
+static void
+evbuffer_get_waste(struct evbuffer *buf, size_t *allocatedp, size_t *wastedp, size_t *usedp)
+{
+ struct evbuffer_chain *chain;
+ size_t a, w, u;
+ int n = 0;
+ u = a = w = 0;
+
+ chain = buf->first;
+ /* skip empty at start */
+ while (chain && chain->off==0) {
+ ++n;
+ a += chain->buffer_len;
+ chain = chain->next;
+ }
+ /* first nonempty chain: stuff at the end only is wasted. */
+ if (chain) {
+ ++n;
+ a += chain->buffer_len;
+ u += chain->off;
+ if (chain->next && chain->next->off)
+ w += (size_t)(chain->buffer_len - (chain->misalign + chain->off));
+ chain = chain->next;
+ }
+ /* subsequent nonempty chains */
+ while (chain && chain->off) {
+ ++n;
+ a += chain->buffer_len;
+ w += (size_t)chain->misalign;
+ u += chain->off;
+ if (chain->next && chain->next->off)
+ w += (size_t) (chain->buffer_len - (chain->misalign + chain->off));
+ chain = chain->next;
+ }
+ /* subsequent empty chains */
+ while (chain) {
+ ++n;
+ a += chain->buffer_len;
+ }
+ *allocatedp = a;
+ *wastedp = w;
+ *usedp = u;
+}
+
+#define evbuffer_validate(buf) \
+ TT_STMT_BEGIN if (!evbuffer_validate_(buf)) TT_DIE(("Buffer format invalid")); TT_STMT_END
+
+static void
+test_evbuffer(void *ptr)
+{
+ static char buffer[512], *tmp;
+ struct evbuffer *evb = evbuffer_new();
+ struct evbuffer *evb_two = evbuffer_new();
+ size_t sz_tmp;
+ int i;
+
+ evbuffer_validate(evb);
+ evbuffer_add_printf(evb, "%s/%d", "hello", 1);
+ evbuffer_validate(evb);
+
+ tt_assert(evbuffer_get_length(evb) == 7);
+ tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "hello/1", 1));
+
+ evbuffer_add_buffer(evb, evb_two);
+ evbuffer_validate(evb);
+
+ evbuffer_drain(evb, strlen("hello/"));
+ evbuffer_validate(evb);
+ tt_assert(evbuffer_get_length(evb) == 1);
+ tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "1", 1));
+
+ evbuffer_add_printf(evb_two, "%s", "/hello");
+ evbuffer_validate(evb);
+ evbuffer_add_buffer(evb, evb_two);
+ evbuffer_validate(evb);
+
+ tt_assert(evbuffer_get_length(evb_two) == 0);
+ tt_assert(evbuffer_get_length(evb) == 7);
+ tt_assert(!memcmp((char*)EVBUFFER_DATA(evb), "1/hello", 7));
+
+ memset(buffer, 0, sizeof(buffer));
+ evbuffer_add(evb, buffer, sizeof(buffer));
+ evbuffer_validate(evb);
+ tt_assert(evbuffer_get_length(evb) == 7 + 512);
+
+ tmp = (char *)evbuffer_pullup(evb, 7 + 512);
+ tt_assert(tmp);
+ tt_assert(!strncmp(tmp, "1/hello", 7));
+ tt_assert(!memcmp(tmp + 7, buffer, sizeof(buffer)));
+ evbuffer_validate(evb);
+
+ evbuffer_prepend(evb, "something", 9);
+ evbuffer_validate(evb);
+ evbuffer_prepend(evb, "else", 4);
+ evbuffer_validate(evb);
+
+ tmp = (char *)evbuffer_pullup(evb, 4 + 9 + 7);
+ tt_assert(!strncmp(tmp, "elsesomething1/hello", 4 + 9 + 7));
+ evbuffer_validate(evb);
+
+ evbuffer_drain(evb, -1);
+ evbuffer_validate(evb);
+ evbuffer_drain(evb_two, -1);
+ evbuffer_validate(evb);
+
+ for (i = 0; i < 3; ++i) {
+ evbuffer_add(evb_two, buffer, sizeof(buffer));
+ evbuffer_validate(evb_two);
+ evbuffer_add_buffer(evb, evb_two);
+ evbuffer_validate(evb);
+ evbuffer_validate(evb_two);
+ }
+
+ tt_assert(evbuffer_get_length(evb_two) == 0);
+ tt_assert(evbuffer_get_length(evb) == i * sizeof(buffer));
+
+ /* test remove buffer */
+ sz_tmp = (size_t)(sizeof(buffer)*2.5);
+ evbuffer_remove_buffer(evb, evb_two, sz_tmp);
+ tt_assert(evbuffer_get_length(evb_two) == sz_tmp);
+ tt_assert(evbuffer_get_length(evb) == sizeof(buffer) / 2);
+ evbuffer_validate(evb);
+
+ if (memcmp(evbuffer_pullup(
+ evb, -1), buffer, sizeof(buffer) / 2) != 0 ||
+ memcmp(evbuffer_pullup(
+ evb_two, -1), buffer, sizeof(buffer)) != 0)
+ tt_abort_msg("Pullup did not preserve content");
+
+ evbuffer_validate(evb);
+
+
+ /* testing one-vector reserve and commit */
+ {
+ struct evbuffer_iovec v[1];
+ char *buf;
+ int i, j, r;
+
+ for (i = 0; i < 3; ++i) {
+ r = evbuffer_reserve_space(evb, 10000, v, 1);
+ tt_int_op(r, ==, 1);
+ tt_assert(v[0].iov_len >= 10000);
+ tt_assert(v[0].iov_base != NULL);
+
+ evbuffer_validate(evb);
+ buf = v[0].iov_base;
+ for (j = 0; j < 10000; ++j) {
+ buf[j] = j;
+ }
+ evbuffer_validate(evb);
+
+ tt_int_op(evbuffer_commit_space(evb, v, 1), ==, 0);
+ evbuffer_validate(evb);
+
+ tt_assert(evbuffer_get_length(evb) >= 10000);
+
+ evbuffer_drain(evb, j * 5000);
+ evbuffer_validate(evb);
+ }
+ }
+
+ end:
+ evbuffer_free(evb);
+ evbuffer_free(evb_two);
+}
+
+static void
+no_cleanup(const void *data, size_t datalen, void *extra)
+{
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ char buf[2] = { 'A', 'A' };
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ /* setup the buffers */
+ /* we need more data in src than we will move later */
+ evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+ evbuffer_add_reference(src, buf, sizeof(buf), no_cleanup, NULL);
+ /* we need one buffer in dst and one empty buffer at the end */
+ evbuffer_add(dst, buf, sizeof(buf));
+ evbuffer_add_reference(dst, buf, 0, no_cleanup, NULL);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "AAAA", 4);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "AA", 2);
+
+ /* move three bytes over */
+ evbuffer_remove_buffer(src, dst, 3);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "A", 1);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "AAAAA", 5);
+
+ end:
+ evbuffer_free(src);
+ evbuffer_free(dst);
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty2(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ struct evbuffer *buf = evbuffer_new();
+
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, "foo", 3, NULL, NULL);
+
+ evbuffer_add_reference(src, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(src, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(src, buf);
+
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, "foo", 3, NULL, NULL);
+
+ evbuffer_add_reference(dst, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(dst, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(dst, buf);
+
+ tt_int_op(evbuffer_get_length(src), ==, 9);
+ tt_int_op(evbuffer_get_length(dst), ==, 9);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "foofoofoo", 9);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "foofoofoo", 9);
+
+ evbuffer_remove_buffer(src, dst, 8);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_int_op(evbuffer_get_length(src), ==, 1);
+ tt_int_op(evbuffer_get_length(dst), ==, 17);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "o", 1);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "foofoofoofoofoofo", 17);
+
+ end:
+ evbuffer_free(src);
+ evbuffer_free(dst);
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty3(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ struct evbuffer *buf = evbuffer_new();
+
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, NULL, 0, NULL, NULL);
+
+ evbuffer_add_reference(src, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(src, NULL, 0, NULL, NULL);
+ evbuffer_prepend_buffer(src, buf);
+
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, NULL, 0, NULL, NULL);
+
+ evbuffer_add_reference(dst, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(dst, NULL, 0, NULL, NULL);
+ evbuffer_prepend_buffer(dst, buf);
+
+ tt_int_op(evbuffer_get_length(src), ==, 6);
+ tt_int_op(evbuffer_get_length(dst), ==, 6);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "foofoo", 6);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "foofoo", 6);
+
+ evbuffer_remove_buffer(src, dst, 5);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_int_op(evbuffer_get_length(src), ==, 1);
+ tt_int_op(evbuffer_get_length(dst), ==, 11);
+
+ tt_mem_op(evbuffer_pullup(src, -1), ==, "o", 1);
+ tt_mem_op(evbuffer_pullup(dst, -1), ==, "foofoofoofo", 11);
+
+ end:
+ evbuffer_free(src);
+ evbuffer_free(dst);
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_pullup_with_empty(void *ptr)
+{
+ struct evbuffer *buf = NULL;
+
+ buf = evbuffer_new();
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, NULL, 0, NULL, NULL);
+ evbuffer_validate(buf);
+ tt_int_op(evbuffer_get_length(buf), ==, 3);
+ tt_mem_op(evbuffer_pullup(buf, -1), ==, "foo", 3);
+
+ evbuffer_free(buf);
+ buf = evbuffer_new();
+ evbuffer_validate(buf);
+ tt_int_op(evbuffer_get_length(buf), ==, 0);
+ tt_int_op(evbuffer_pullup(buf, -1), ==, NULL);
+
+ evbuffer_free(buf);
+ buf = evbuffer_new();
+ evbuffer_add(buf, "foo", 3);
+ evbuffer_add_reference(buf, NULL, 0, NULL, NULL);
+ evbuffer_validate(buf);
+ tt_mem_op(evbuffer_pullup(buf, 3), ==, "foo", 3);
+
+ end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_remove_buffer_with_empty_front(void *ptr)
+{
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ tt_int_op(evbuffer_add_reference(buf1, "foo", 3, NULL, NULL), ==, 0);
+ tt_int_op(evbuffer_prepend(buf1, "", 0), ==, 0);
+ tt_int_op(evbuffer_remove_buffer(buf1, buf2, 1), ==, 1);
+ tt_int_op(evbuffer_add(buf1, "bar", 3), ==, 0);
+ tt_mem_op(evbuffer_pullup(buf1, -1), ==, "oobar", 5);
+
+ evbuffer_validate(buf1);
+ evbuffer_validate(buf2);
+
+ end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_remove_buffer_adjust_last_with_datap_with_empty(void *ptr)
+{
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ tt_int_op(evbuffer_add(buf1, "aaaaaa", 6), ==, 0);
+
+ // buf1: aaaaaab
+ // buf2:
+ {
+ struct evbuffer_iovec iovecs[2];
+ /** we want two chains, to leave one chain empty */
+ tt_int_op(evbuffer_reserve_space(buf1, 971, iovecs, 2), ==, 2);
+ tt_int_op(iovecs[0].iov_len, >=, 1);
+ tt_int_op(iovecs[1].iov_len, >=, 1);
+ tt_assert(*(char *)(iovecs[0].iov_base) = 'b');
+ tt_assert(iovecs[0].iov_len = 1);
+ tt_int_op(evbuffer_commit_space(buf1, iovecs, 1), ==, 0);
+ }
+
+ // buf1: aaaaaab
+ // buf2: dddcc
+ tt_int_op(evbuffer_add(buf2, "cc", 2), ==, 0);
+ tt_int_op(evbuffer_prepend(buf2, "ddd", 3), ==, 0);
+
+ // buf1:
+ // buf2: aaaaaabdddcc
+ tt_int_op(evbuffer_prepend_buffer(buf2, buf1), ==, 0);
+
+ // buf1: aaaaaabdddcc
+ // buf2:
+ tt_int_op(evbuffer_add_buffer(buf1, buf2), ==, 0);
+
+ // buf1: c
+ // buf2: aaaaaabdddc
+ tt_int_op(evbuffer_remove_buffer(buf1, buf2, 11), ==, 11);
+
+ // This fails today, we observe "aaaaaabcddd" instead!
+ tt_mem_op(evbuffer_pullup(buf2, -1), ==, "aaaaaabdddc", 11);
+
+ evbuffer_validate(buf1);
+ evbuffer_validate(buf2);
+
+ end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_add_buffer_with_empty(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ struct evbuffer *buf = evbuffer_new();
+
+ evbuffer_add(buf, "foo", 3);
+
+ evbuffer_add_reference(src, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(src, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(src, buf);
+
+ evbuffer_add(buf, "foo", 3);
+
+ evbuffer_add_reference(dst, "foo", 3, NULL, NULL);
+ evbuffer_add_reference(dst, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(dst, buf);
+
+ tt_int_op(evbuffer_get_length(src), ==, 6);
+ tt_int_op(evbuffer_get_length(dst), ==, 6);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ end:
+ evbuffer_free(src);
+ evbuffer_free(dst);
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_add_buffer_with_empty2(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ struct evbuffer *buf = evbuffer_new();
+
+ evbuffer_add(buf, "foo", 3);
+
+ evbuffer_add_reference(src, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(src, buf);
+
+ evbuffer_add(buf, "foo", 3);
+
+ evbuffer_add_reference(dst, NULL, 0, NULL, NULL);
+ evbuffer_add_buffer(dst, buf);
+
+ tt_int_op(evbuffer_get_length(src), ==, 3);
+ tt_int_op(evbuffer_get_length(dst), ==, 3);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ end:
+ evbuffer_free(src);
+ evbuffer_free(dst);
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_reserve2(void *ptr)
+{
+ /* Test the two-vector cases of reserve/commit. */
+ struct evbuffer *buf = evbuffer_new();
+ int n, i;
+ struct evbuffer_iovec v[2];
+ size_t remaining;
+ char *cp, *cp2;
+
+ /* First chunk will necessarily be one chunk. Use 512 bytes of it.*/
+ n = evbuffer_reserve_space(buf, 1024, v, 2);
+ tt_int_op(n, ==, 1);
+ tt_int_op(evbuffer_get_length(buf), ==, 0);
+ tt_assert(v[0].iov_base != NULL);
+ tt_int_op(v[0].iov_len, >=, 1024);
+ memset(v[0].iov_base, 'X', 512);
+ cp = v[0].iov_base;
+ remaining = v[0].iov_len - 512;
+ v[0].iov_len = 512;
+ evbuffer_validate(buf);
+ tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+ tt_int_op(evbuffer_get_length(buf), ==, 512);
+ evbuffer_validate(buf);
+
+ /* Ask for another same-chunk request, in an existing chunk. Use 8
+ * bytes of it. */
+ n = evbuffer_reserve_space(buf, 32, v, 2);
+ tt_int_op(n, ==, 1);
+ tt_assert(cp + 512 == v[0].iov_base);
+ tt_int_op(remaining, ==, v[0].iov_len);
+ memset(v[0].iov_base, 'Y', 8);
+ v[0].iov_len = 8;
+ tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+ tt_int_op(evbuffer_get_length(buf), ==, 520);
+ remaining -= 8;
+ evbuffer_validate(buf);
+
+ /* Now ask for a request that will be split. Use only one byte of it,
+ though. */
+ n = evbuffer_reserve_space(buf, remaining+64, v, 2);
+ tt_int_op(n, ==, 2);
+ tt_assert(cp + 520 == v[0].iov_base);
+ tt_int_op(remaining, ==, v[0].iov_len);
+ tt_assert(v[1].iov_base);
+ tt_assert(v[1].iov_len >= 64);
+ cp2 = v[1].iov_base;
+ memset(v[0].iov_base, 'Z', 1);
+ v[0].iov_len = 1;
+ tt_int_op(0, ==, evbuffer_commit_space(buf, v, 1));
+ tt_int_op(evbuffer_get_length(buf), ==, 521);
+ remaining -= 1;
+ evbuffer_validate(buf);
+
+ /* Now ask for a request that will be split. Use some of the first
+ * part and some of the second. */
+ n = evbuffer_reserve_space(buf, remaining+64, v, 2);
+ evbuffer_validate(buf);
+ tt_int_op(n, ==, 2);
+ tt_assert(cp + 521 == v[0].iov_base);
+ tt_int_op(remaining, ==, v[0].iov_len);
+ tt_assert(v[1].iov_base == cp2);
+ tt_assert(v[1].iov_len >= 64);
+ memset(v[0].iov_base, 'W', 400);
+ v[0].iov_len = 400;
+ memset(v[1].iov_base, 'x', 60);
+ v[1].iov_len = 60;
+ tt_int_op(0, ==, evbuffer_commit_space(buf, v, 2));
+ tt_int_op(evbuffer_get_length(buf), ==, 981);
+ evbuffer_validate(buf);
+
+ /* Now peek to make sure stuff got made how we like. */
+ memset(v,0,sizeof(v));
+ n = evbuffer_peek(buf, -1, NULL, v, 2);
+ tt_int_op(n, ==, 2);
+ tt_int_op(v[0].iov_len, ==, 921);
+ tt_int_op(v[1].iov_len, ==, 60);
+
+ cp = v[0].iov_base;
+ for (i=0; i<512; ++i)
+ tt_int_op(cp[i], ==, 'X');
+ for (i=512; i<520; ++i)
+ tt_int_op(cp[i], ==, 'Y');
+ for (i=520; i<521; ++i)
+ tt_int_op(cp[i], ==, 'Z');
+ for (i=521; i<921; ++i)
+ tt_int_op(cp[i], ==, 'W');
+
+ cp = v[1].iov_base;
+ for (i=0; i<60; ++i)
+ tt_int_op(cp[i], ==, 'x');
+
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_reserve_many(void *ptr)
+{
+ /* This is a glass-box test to handle expanding a buffer with more
+ * chunks and reallocating chunks as needed */
+ struct evbuffer *buf = evbuffer_new();
+ struct evbuffer_iovec v[8];
+ int n;
+ size_t sz;
+ int add_data = ptr && !strcmp(ptr, "add");
+ int fill_first = ptr && !strcmp(ptr, "fill");
+ char *cp1, *cp2;
+
+ /* When reserving the the first chunk, we just allocate it */
+ n = evbuffer_reserve_space(buf, 128, v, 2);
+ evbuffer_validate(buf);
+ tt_int_op(n, ==, 1);
+ tt_assert(v[0].iov_len >= 128);
+ sz = v[0].iov_len;
+ cp1 = v[0].iov_base;
+ if (add_data) {
+ *(char*)v[0].iov_base = 'X';
+ v[0].iov_len = 1;
+ n = evbuffer_commit_space(buf, v, 1);
+ tt_int_op(n, ==, 0);
+ } else if (fill_first) {
+ memset(v[0].iov_base, 'X', v[0].iov_len);
+ n = evbuffer_commit_space(buf, v, 1);
+ tt_int_op(n, ==, 0);
+ n = evbuffer_reserve_space(buf, 128, v, 2);
+ tt_int_op(n, ==, 1);
+ sz = v[0].iov_len;
+ tt_assert(v[0].iov_base != cp1);
+ cp1 = v[0].iov_base;
+ }
+
+ /* Make another chunk get added. */
+ n = evbuffer_reserve_space(buf, sz+128, v, 2);
+ evbuffer_validate(buf);
+ tt_int_op(n, ==, 2);
+ sz = v[0].iov_len + v[1].iov_len;
+ tt_int_op(sz, >=, v[0].iov_len+128);
+ if (add_data) {
+ tt_assert(v[0].iov_base == cp1 + 1);
+ } else {
+ tt_assert(v[0].iov_base == cp1);
+ }
+ cp1 = v[0].iov_base;
+ cp2 = v[1].iov_base;
+
+ /* And a third chunk. */
+ n = evbuffer_reserve_space(buf, sz+128, v, 3);
+ evbuffer_validate(buf);
+ tt_int_op(n, ==, 3);
+ tt_assert(cp1 == v[0].iov_base);
+ tt_assert(cp2 == v[1].iov_base);
+ sz = v[0].iov_len + v[1].iov_len + v[2].iov_len;
+
+ /* Now force a reallocation by asking for more space in only 2
+ * buffers. */
+ n = evbuffer_reserve_space(buf, sz+128, v, 2);
+ evbuffer_validate(buf);
+ if (add_data) {
+ tt_int_op(n, ==, 2);
+ tt_assert(cp1 == v[0].iov_base);
+ } else {
+ tt_int_op(n, ==, 1);
+ }
+
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_reserve_with_empty(void *ptr)
+{
+ struct evbuffer *buf;
+ struct evbuffer_iovec v[2];
+
+ tt_assert(buf = evbuffer_new());
+ evbuffer_add(buf, "a", 1);
+ tt_int_op(evbuffer_reserve_space(buf, 1<<12, v, 2), ==, 2);
+ v[0].iov_len = 1;
+ *(char *)v[0].iov_base = 'b';
+ tt_int_op(evbuffer_commit_space(buf, v, 1), ==, 0);
+ evbuffer_add(buf, "c", 1);
+ tt_mem_op(evbuffer_pullup(buf, -1), ==, "abc", 2);
+
+ evbuffer_validate(buf);
+
+ end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+/* regression for evbuffer_expand_fast_() with invalid last_with_datap that has
+ * been left after evbuffer_prepend() with empty chain in it */
+static void
+test_evbuffer_reserve_invalid_last_with_datap(void *ptr)
+{
+ struct evbuffer *buf = NULL;
+ struct evbuffer_iovec vec[2];
+ const int nvec = ARRAY_SIZE(vec);
+ int i, avec;
+
+ buf = evbuffer_new();
+ tt_assert(buf);
+
+ /* prepend with an empty chain */
+ evbuffer_add_reference(buf, "", 0, NULL, NULL);
+ evbuffer_prepend(buf, "foo", 3);
+ /* after invalid last_with_datap will create new chain */
+ evbuffer_add(buf, "", 0);
+ /* we need to create at least 2 "used" (in evbuffer_expand_fast_()) chains */
+ tt_int_op(avec = evbuffer_reserve_space(buf, 1<<12, vec, nvec), >=, 1);
+ for (i = 0; i < avec; ++i)
+ vec[i].iov_len = 0;
+ tt_int_op(evbuffer_commit_space(buf, vec, avec), ==, 0);
+
+ /* and an actual problem, that triggers an assert(chain == buf->first) in
+ * evbuffer_expand_fast_() */
+ tt_int_op(evbuffer_reserve_space(buf, 1<<13, vec, nvec), >=, 1);
+
+ evbuffer_validate(buf);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_expand(void *ptr)
+{
+ char data[4096];
+ struct evbuffer *buf;
+ size_t a,w,u;
+ void *buffer;
+
+ memset(data, 'X', sizeof(data));
+
+ /* Make sure that expand() works on an empty buffer */
+ buf = evbuffer_new();
+ tt_int_op(evbuffer_expand(buf, 20000), ==, 0);
+ evbuffer_validate(buf);
+ a=w=u=0;
+ evbuffer_get_waste(buf, &a,&w,&u);
+ tt_assert(w == 0);
+ tt_assert(u == 0);
+ tt_assert(a >= 20000);
+ tt_assert(buf->first);
+ tt_assert(buf->first == buf->last);
+ tt_assert(buf->first->off == 0);
+ tt_assert(buf->first->buffer_len >= 20000);
+
+ /* Make sure that expand() works as a no-op when there's enough
+ * contiguous space already. */
+ buffer = buf->first->buffer;
+ evbuffer_add(buf, data, 1024);
+ tt_int_op(evbuffer_expand(buf, 1024), ==, 0);
+ tt_assert(buf->first->buffer == buffer);
+ evbuffer_validate(buf);
+ evbuffer_free(buf);
+
+ /* Make sure that expand() can work by moving misaligned data
+ * when it makes sense to do so. */
+ buf = evbuffer_new();
+ evbuffer_add(buf, data, 400);
+ {
+ int n = (int)(buf->first->buffer_len - buf->first->off - 1);
+ tt_assert(n < (int)sizeof(data));
+ evbuffer_add(buf, data, n);
+ }
+ tt_assert(buf->first == buf->last);
+ tt_assert(buf->first->off == buf->first->buffer_len - 1);
+ evbuffer_drain(buf, buf->first->off - 1);
+ tt_assert(1 == evbuffer_get_length(buf));
+ tt_assert(buf->first->misalign > 0);
+ tt_assert(buf->first->off == 1);
+ buffer = buf->first->buffer;
+ tt_assert(evbuffer_expand(buf, 40) == 0);
+ tt_assert(buf->first == buf->last);
+ tt_assert(buf->first->off == 1);
+ tt_assert(buf->first->buffer == buffer);
+ tt_assert(buf->first->misalign == 0);
+ evbuffer_validate(buf);
+ evbuffer_free(buf);
+
+ /* add, expand, pull-up: This used to crash libevent. */
+ buf = evbuffer_new();
+
+ evbuffer_add(buf, data, sizeof(data));
+ evbuffer_add(buf, data, sizeof(data));
+ evbuffer_add(buf, data, sizeof(data));
+
+ evbuffer_validate(buf);
+ evbuffer_expand(buf, 1024);
+ evbuffer_validate(buf);
+ evbuffer_pullup(buf, -1);
+ evbuffer_validate(buf);
+
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_expand_overflow(void *ptr)
+{
+ struct evbuffer *buf;
+
+ buf = evbuffer_new();
+ evbuffer_add(buf, "1", 1);
+ evbuffer_expand(buf, EVBUFFER_CHAIN_MAX);
+ evbuffer_validate(buf);
+
+ evbuffer_expand(buf, EV_SIZE_MAX);
+ evbuffer_validate(buf);
+
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_add1(void *ptr)
+{
+ struct evbuffer *buf;
+ char *str;
+
+ buf = evbuffer_new();
+ evbuffer_add(buf, "1", 1);
+ evbuffer_validate(buf);
+ evbuffer_expand(buf, 2048);
+ evbuffer_validate(buf);
+ evbuffer_add(buf, "2", 1);
+ evbuffer_validate(buf);
+ evbuffer_add_printf(buf, "3");
+ evbuffer_validate(buf);
+
+ tt_assert(evbuffer_get_length(buf) == 3);
+ str = (char *)evbuffer_pullup(buf, -1);
+ tt_assert(str[0] == '1');
+ tt_assert(str[1] == '2');
+ tt_assert(str[2] == '3');
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_add2(void *ptr)
+{
+ struct evbuffer *buf;
+ static char data[4096];
+ int data_len = MIN_BUFFER_SIZE-EVBUFFER_CHAIN_SIZE-10;
+ char *str;
+ int len;
+
+ memset(data, 'P', sizeof(data));
+ buf = evbuffer_new();
+ evbuffer_add(buf, data, data_len);
+ evbuffer_validate(buf);
+ evbuffer_expand(buf, 100);
+ evbuffer_validate(buf);
+ evbuffer_add(buf, "2", 1);
+ evbuffer_validate(buf);
+ evbuffer_add_printf(buf, "3");
+ evbuffer_validate(buf);
+
+ len = evbuffer_get_length(buf);
+ tt_assert(len == data_len+2);
+ str = (char *)evbuffer_pullup(buf, -1);
+ tt_assert(str[len-3] == 'P');
+ tt_assert(str[len-2] == '2');
+ tt_assert(str[len-1] == '3');
+end:
+ evbuffer_free(buf);
+}
+
+static int reference_cb_called;
+static void
+reference_cb(const void *data, size_t len, void *extra)
+{
+ tt_str_op(data, ==, "this is what we add as read-only memory.");
+ tt_int_op(len, ==, strlen(data));
+ tt_want(extra == (void *)0xdeadaffe);
+ ++reference_cb_called;
+end:
+ ;
+}
+
+static void
+test_evbuffer_reference(void *ptr)
+{
+ struct evbuffer *src = evbuffer_new();
+ struct evbuffer *dst = evbuffer_new();
+ struct evbuffer_iovec v[1];
+ const char *data = "this is what we add as read-only memory.";
+ reference_cb_called = 0;
+
+ tt_assert(evbuffer_add_reference(src, data, strlen(data),
+ reference_cb, (void *)0xdeadaffe) != -1);
+
+ evbuffer_reserve_space(dst, strlen(data), v, 1);
+ tt_assert(evbuffer_remove(src, v[0].iov_base, 10) != -1);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ /* make sure that we don't write data at the beginning */
+ evbuffer_prepend(src, "aaaaa", 5);
+ evbuffer_validate(src);
+ evbuffer_drain(src, 5);
+
+ tt_assert(evbuffer_remove(src, ((char*)(v[0].iov_base)) + 10,
+ strlen(data) - 10) != -1);
+
+ v[0].iov_len = strlen(data);
+
+ evbuffer_commit_space(dst, v, 1);
+ evbuffer_validate(src);
+ evbuffer_validate(dst);
+
+ tt_int_op(reference_cb_called, ==, 1);
+
+ tt_assert(!memcmp(evbuffer_pullup(dst, strlen(data)),
+ data, strlen(data)));
+ evbuffer_validate(dst);
+
+ end:
+ evbuffer_free(dst);
+ evbuffer_free(src);
+}
+
+static void
+test_evbuffer_reference2(void *ptr)
+{
+ struct evbuffer *buf;
+ static char data[4096];
+ int data_len = MIN_BUFFER_SIZE-EVBUFFER_CHAIN_SIZE-10;
+ char *str;
+ int len;
+
+ memset(data, 'P', sizeof(data));
+ buf = evbuffer_new();
+ evbuffer_add(buf, data, data_len);
+ evbuffer_validate(buf);
+ evbuffer_expand(buf, 100);
+ evbuffer_validate(buf);
+ evbuffer_add_reference(buf, "2", 1, no_cleanup, NULL);
+ evbuffer_validate(buf);
+ evbuffer_add_printf(buf, "3");
+ evbuffer_validate(buf);
+
+ len = evbuffer_get_length(buf);
+ tt_assert(len == data_len+2);
+ str = (char *)evbuffer_pullup(buf, -1);
+ tt_assert(str[len-3] == 'P');
+ tt_assert(str[len-2] == '2');
+ tt_assert(str[len-1] == '3');
+end:
+ evbuffer_free(buf);
+}
+
+static struct event_base *addfile_test_event_base;
+static int addfile_test_done_writing;
+static int addfile_test_total_written;
+static int addfile_test_total_read;
+
+static void
+addfile_test_writecb(evutil_socket_t fd, short what, void *arg)
+{
+ struct evbuffer *b = arg;
+ int r;
+ evbuffer_validate(b);
+ while (evbuffer_get_length(b)) {
+ r = evbuffer_write(b, fd);
+ if (r > 0) {
+ addfile_test_total_written += r;
+ TT_BLATHER(("Wrote %d/%d bytes", r, addfile_test_total_written));
+ } else {
+ int e = evutil_socket_geterror(fd);
+ if (EVUTIL_ERR_RW_RETRIABLE(e))
+ return;
+ tt_fail_perror("write");
+ event_base_loopexit(addfile_test_event_base,NULL);
+ }
+ evbuffer_validate(b);
+ }
+ addfile_test_done_writing = 1;
+ return;
+end:
+ event_base_loopexit(addfile_test_event_base,NULL);
+}
+
+static void
+addfile_test_readcb(evutil_socket_t fd, short what, void *arg)
+{
+ struct evbuffer *b = arg;
+ int e, r = 0;
+ do {
+ r = evbuffer_read(b, fd, 1024);
+ if (r > 0) {
+ addfile_test_total_read += r;
+ TT_BLATHER(("Read %d/%d bytes", r, addfile_test_total_read));
+ }
+ } while (r > 0);
+ if (r < 0) {
+ e = evutil_socket_geterror(fd);
+ if (! EVUTIL_ERR_RW_RETRIABLE(e)) {
+ tt_fail_perror("read");
+ event_base_loopexit(addfile_test_event_base,NULL);
+ }
+ }
+ if (addfile_test_done_writing &&
+ addfile_test_total_read >= addfile_test_total_written) {
+ event_base_loopexit(addfile_test_event_base,NULL);
+ }
+}
+
+static void
+test_evbuffer_add_file(void *ptr)
+{
+ struct basic_test_data *testdata = ptr;
+ const char *impl = testdata->setup_data;
+ struct evbuffer *src = evbuffer_new(), *dest = evbuffer_new();
+ char *tmpfilename = NULL;
+ char *data = NULL;
+ const char *expect_data;
+ size_t datalen, expect_len;
+ const char *compare;
+ int fd = -1;
+ int want_ismapping = -1, want_cansendfile = -1;
+ unsigned flags = 0;
+ int use_segment = 1, use_bigfile = 0, map_from_offset = 0,
+ view_from_offset = 0;
+ struct evbuffer_file_segment *seg = NULL;
+ ev_off_t starting_offset = 0, mapping_len = -1;
+ ev_off_t segment_offset = 0, segment_len = -1;
+ struct event *rev=NULL, *wev=NULL;
+ struct event_base *base = testdata->base;
+ evutil_socket_t pair[2] = {-1, -1};
+ struct evutil_weakrand_state seed = { 123456789U };
+
+ /* This test is highly parameterized based on substrings of its
+ * argument. The strings are: */
+ tt_assert(impl);
+ if (strstr(impl, "nosegment")) {
+ /* If nosegment is set, use the older evbuffer_add_file
+ * interface */
+ use_segment = 0;
+ }
+ if (strstr(impl, "bigfile")) {
+ /* If bigfile is set, use a 512K file. Else use a smaller
+ * one. */
+ use_bigfile = 1;
+ }
+ if (strstr(impl, "map_offset")) {
+ /* If map_offset is set, we build the file segment starting
+ * from a point other than byte 0 and ending somewhere other
+ * than the last byte. Otherwise we map the whole thing */
+ map_from_offset = 1;
+ }
+ if (strstr(impl, "offset_in_segment")) {
+ /* If offset_in_segment is set, we add a subsection of the
+ * file semgment starting from a point other than byte 0 of
+ * the segment. */
+ view_from_offset = 1;
+ }
+ if (strstr(impl, "sendfile")) {
+ /* If sendfile is set, we try to use a sendfile/splice style
+ * backend. */
+ flags = EVBUF_FS_DISABLE_MMAP;
+ want_cansendfile = 1;
+ want_ismapping = 0;
+ } else if (strstr(impl, "mmap")) {
+ /* If sendfile is set, we try to use a mmap/CreateFileMapping
+ * style backend. */
+ flags = EVBUF_FS_DISABLE_SENDFILE;
+ want_ismapping = 1;
+ want_cansendfile = 0;
+ } else if (strstr(impl, "linear")) {
+ /* If linear is set, we try to use a read-the-whole-thing
+ * backend. */
+ flags = EVBUF_FS_DISABLE_SENDFILE|EVBUF_FS_DISABLE_MMAP;
+ want_ismapping = 0;
+ want_cansendfile = 0;
+ } else if (strstr(impl, "default")) {
+ /* The caller doesn't care which backend we use. */
+ ;
+ } else {
+ /* The caller must choose a backend. */
+ TT_DIE(("Didn't recognize the implementation"));
+ }
+
+ if (use_bigfile) {
+ unsigned int i;
+ datalen = 1024*512;
+ data = malloc(1024*512);
+ tt_assert(data);
+ for (i = 0; i < datalen; ++i)
+ data[i] = (char)evutil_weakrand_(&seed);
+ } else {
+ data = strdup("here is a relatively small string.");
+ tt_assert(data);
+ datalen = strlen(data);
+ }
+
+ fd = regress_make_tmpfile(data, datalen, &tmpfilename);
+
+ if (map_from_offset) {
+ starting_offset = datalen/4 + 1;
+ mapping_len = datalen / 2 - 1;
+ expect_data = data + starting_offset;
+ expect_len = mapping_len;
+ } else {
+ expect_data = data;
+ expect_len = datalen;
+ }
+ if (view_from_offset) {
+ tt_assert(use_segment); /* Can't do this with add_file*/
+ segment_offset = expect_len / 3;
+ segment_len = expect_len / 2;
+ expect_data = expect_data + segment_offset;
+ expect_len = segment_len;
+ }
+
+ if (use_segment) {
+ seg = evbuffer_file_segment_new(fd, starting_offset,
+ mapping_len, flags);
+ tt_assert(seg);
+ if (want_ismapping >= 0) {
+ if (seg->is_mapping != (unsigned)want_ismapping)
+ tt_skip();
+ }
+ if (want_cansendfile >= 0) {
+ if (seg->can_sendfile != (unsigned)want_cansendfile)
+ tt_skip();
+ }
+ }
+
+ /* Say that it drains to a fd so that we can use sendfile. */
+ evbuffer_set_flags(src, EVBUFFER_FLAG_DRAINS_TO_FD);
+
+#if defined(EVENT__HAVE_SENDFILE) && defined(__sun__) && defined(__svr4__)
+ /* We need to use a pair of AF_INET sockets, since Solaris
+ doesn't support sendfile() over AF_UNIX. */
+ if (evutil_ersatz_socketpair_(AF_INET, SOCK_STREAM, 0, pair) == -1)
+ tt_abort_msg("ersatz_socketpair failed");
+#else
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+ tt_abort_msg("socketpair failed");
+#endif
+ evutil_make_socket_nonblocking(pair[0]);
+ evutil_make_socket_nonblocking(pair[1]);
+
+ tt_assert(fd != -1);
+
+ if (use_segment) {
+ tt_assert(evbuffer_add_file_segment(src, seg,
+ segment_offset, segment_len)!=-1);
+ } else {
+ tt_assert(evbuffer_add_file(src, fd, starting_offset,
+ mapping_len) != -1);
+ }
+
+ evbuffer_validate(src);
+
+ addfile_test_event_base = base;
+ addfile_test_done_writing = 0;
+ addfile_test_total_written = 0;
+ addfile_test_total_read = 0;
+
+ wev = event_new(base, pair[0], EV_WRITE|EV_PERSIST,
+ addfile_test_writecb, src);
+ rev = event_new(base, pair[1], EV_READ|EV_PERSIST,
+ addfile_test_readcb, dest);
+
+ event_add(wev, NULL);
+ event_add(rev, NULL);
+ event_base_dispatch(base);
+
+ evbuffer_validate(src);
+ evbuffer_validate(dest);
+
+ tt_assert(addfile_test_done_writing);
+ tt_int_op(addfile_test_total_written, ==, expect_len);
+ tt_int_op(addfile_test_total_read, ==, expect_len);
+
+ compare = (char *)evbuffer_pullup(dest, expect_len);
+ tt_assert(compare != NULL);
+ if (memcmp(compare, expect_data, expect_len)) {
+ tt_abort_msg("Data from add_file differs.");
+ }
+
+ evbuffer_validate(dest);
+ end:
+ if (data)
+ free(data);
+ if (seg)
+ evbuffer_file_segment_free(seg);
+ if (src)
+ evbuffer_free(src);
+ if (dest)
+ evbuffer_free(dest);
+ if (pair[0] >= 0)
+ evutil_closesocket(pair[0]);
+ if (pair[1] >= 0)
+ evutil_closesocket(pair[1]);
+ if (wev)
+ event_free(wev);
+ if (rev)
+ event_free(rev);
+ if (tmpfilename) {
+ unlink(tmpfilename);
+ free(tmpfilename);
+ }
+}
+
+static int file_segment_cleanup_cb_called_count = 0;
+static struct evbuffer_file_segment const* file_segment_cleanup_cb_called_with = NULL;
+static int file_segment_cleanup_cb_called_with_flags = 0;
+static void* file_segment_cleanup_cb_called_with_arg = NULL;
+static void
+file_segment_cleanup_cp(struct evbuffer_file_segment const* seg, int flags, void* arg)
+{
+ ++file_segment_cleanup_cb_called_count;
+ file_segment_cleanup_cb_called_with = seg;
+ file_segment_cleanup_cb_called_with_flags = flags;
+ file_segment_cleanup_cb_called_with_arg = arg;
+}
+
+static void
+test_evbuffer_file_segment_add_cleanup_cb(void* ptr)
+{
+ char *tmpfilename = NULL;
+ int fd = -1;
+ struct evbuffer *evb = NULL;
+ struct evbuffer_file_segment *seg = NULL, *segptr;
+ char const* arg = "token";
+
+ fd = regress_make_tmpfile("file_segment_test_file", 22, &tmpfilename);
+ tt_int_op(fd, >=, 0);
+
+ evb = evbuffer_new();
+ tt_assert(evb);
+
+ segptr = seg = evbuffer_file_segment_new(fd, 0, -1, 0);
+ tt_assert(seg);
+
+ evbuffer_file_segment_add_cleanup_cb(
+ seg, &file_segment_cleanup_cp, (void*)arg);
+
+ tt_assert(fd != -1);
+
+ tt_assert(evbuffer_add_file_segment(evb, seg, 0, -1)!=-1);
+
+ evbuffer_validate(evb);
+
+ tt_int_op(file_segment_cleanup_cb_called_count, ==, 0);
+ evbuffer_file_segment_free(seg);
+ seg = NULL; /* Prevent double-free. */
+
+ tt_int_op(file_segment_cleanup_cb_called_count, ==, 0);
+ evbuffer_free(evb);
+ evb = NULL; /* pevent double-free */
+
+ tt_int_op(file_segment_cleanup_cb_called_count, ==, 1);
+ tt_assert(file_segment_cleanup_cb_called_with == segptr);
+ tt_assert(file_segment_cleanup_cb_called_with_flags == 0);
+ tt_assert(file_segment_cleanup_cb_called_with_arg == (void*)arg);
+
+end:
+ if (evb)
+ evbuffer_free(evb);
+ if (seg)
+ evbuffer_file_segment_free(seg);
+ if (tmpfilename) {
+ unlink(tmpfilename);
+ free(tmpfilename);
+ }
+}
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+static void *
+failing_malloc(size_t how_much)
+{
+ errno = ENOMEM;
+ return NULL;
+}
+#endif
+
+static void
+test_evbuffer_readln(void *ptr)
+{
+ struct evbuffer *evb = evbuffer_new();
+ struct evbuffer *evb_tmp = evbuffer_new();
+ const char *s;
+ char *cp = NULL;
+ size_t sz;
+
+#define tt_line_eq(content) \
+ TT_STMT_BEGIN \
+ if (!cp || sz != strlen(content) || strcmp(cp, content)) { \
+ TT_DIE(("Wanted %s; got %s [%d]", content, cp, (int)sz)); \
+ } \
+ TT_STMT_END
+
+ /* Test EOL_ANY. */
+ s = "complex silly newline\r\n\n\r\n\n\rmore\0\n";
+ evbuffer_add(evb, s, strlen(s)+2);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+ tt_line_eq("complex silly newline");
+ free(cp);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+ if (!cp || sz != 5 || memcmp(cp, "more\0\0", 6))
+ tt_abort_msg("Not as expected");
+ tt_uint_op(evbuffer_get_length(evb), ==, 0);
+ evbuffer_validate(evb);
+ s = "\nno newline";
+ evbuffer_add(evb, s, strlen(s));
+ free(cp);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+ tt_line_eq("");
+ free(cp);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_ANY);
+ tt_assert(!cp);
+ evbuffer_validate(evb);
+ evbuffer_drain(evb, evbuffer_get_length(evb));
+ tt_assert(evbuffer_get_length(evb) == 0);
+ evbuffer_validate(evb);
+
+ /* Test EOL_CRLF */
+ s = "Line with\rin the middle\nLine with good crlf\r\n\nfinal\n";
+ evbuffer_add(evb, s, strlen(s));
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+ tt_line_eq("Line with\rin the middle");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+ tt_line_eq("Line with good crlf");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+ tt_line_eq("");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+ tt_line_eq("final");
+ s = "x";
+ evbuffer_validate(evb);
+ evbuffer_add(evb, s, 1);
+ evbuffer_validate(evb);
+ free(cp);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF);
+ tt_assert(!cp);
+ evbuffer_validate(evb);
+
+ /* Test CRLF_STRICT */
+ s = " and a bad crlf\nand a good one\r\n\r\nMore\r";
+ evbuffer_add(evb, s, strlen(s));
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("x and a bad crlf\nand a good one");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_assert(!cp);
+ evbuffer_validate(evb);
+ evbuffer_add(evb, "\n", 1);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("More");
+ free(cp);
+ tt_assert(evbuffer_get_length(evb) == 0);
+ evbuffer_validate(evb);
+
+ s = "An internal CR\r is not an eol\r\nNor is a lack of one";
+ evbuffer_add(evb, s, strlen(s));
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("An internal CR\r is not an eol");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_assert(!cp);
+ evbuffer_validate(evb);
+
+ evbuffer_add(evb, "\r\n", 2);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("Nor is a lack of one");
+ free(cp);
+ tt_assert(evbuffer_get_length(evb) == 0);
+ evbuffer_validate(evb);
+
+ /* Test LF */
+ s = "An\rand a nl\n\nText";
+ evbuffer_add(evb, s, strlen(s));
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_line_eq("An\rand a nl");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_line_eq("");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_assert(!cp);
+ free(cp);
+ evbuffer_add(evb, "\n", 1);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_line_eq("Text");
+ free(cp);
+ evbuffer_validate(evb);
+
+ /* Test NUL */
+ tt_int_op(evbuffer_get_length(evb), ==, 0);
+ {
+ char x[] =
+ "NUL\n\0\0"
+ "The all-zeros character which may serve\0"
+ "to accomplish time fill\0and media fill";
+ /* Add all but the final NUL of x. */
+ evbuffer_add(evb, x, sizeof(x)-1);
+ }
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+ tt_line_eq("NUL\n");
+ free(cp);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+ tt_line_eq("");
+ free(cp);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+ tt_line_eq("The all-zeros character which may serve");
+ free(cp);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+ tt_line_eq("to accomplish time fill");
+ free(cp);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_NUL);
+ tt_ptr_op(cp, ==, NULL);
+ evbuffer_drain(evb, -1);
+
+ /* Test CRLF_STRICT - across boundaries*/
+ s = " and a bad crlf\nand a good one\r";
+ evbuffer_add(evb_tmp, s, strlen(s));
+ evbuffer_validate(evb);
+ evbuffer_add_buffer(evb, evb_tmp);
+ evbuffer_validate(evb);
+ s = "\n\r";
+ evbuffer_add(evb_tmp, s, strlen(s));
+ evbuffer_validate(evb);
+ evbuffer_add_buffer(evb, evb_tmp);
+ evbuffer_validate(evb);
+ s = "\nMore\r";
+ evbuffer_add(evb_tmp, s, strlen(s));
+ evbuffer_validate(evb);
+ evbuffer_add_buffer(evb, evb_tmp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq(" and a bad crlf\nand a good one");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("");
+ free(cp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_assert(!cp);
+ free(cp);
+ evbuffer_validate(evb);
+ evbuffer_add(evb, "\n", 1);
+ evbuffer_validate(evb);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_CRLF_STRICT);
+ tt_line_eq("More");
+ free(cp); cp = NULL;
+ evbuffer_validate(evb);
+ tt_assert(evbuffer_get_length(evb) == 0);
+
+ /* Test memory problem*/
+ s = "one line\ntwo line\nblue line";
+ evbuffer_add(evb_tmp, s, strlen(s));
+ evbuffer_validate(evb);
+ evbuffer_add_buffer(evb, evb_tmp);
+ evbuffer_validate(evb);
+
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_line_eq("one line");
+ free(cp); cp = NULL;
+ evbuffer_validate(evb);
+
+ /* the next call to readline should fail */
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+ event_set_mem_functions(failing_malloc, realloc, free);
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_assert(cp == NULL);
+ evbuffer_validate(evb);
+
+ /* now we should get the next line back */
+ event_set_mem_functions(malloc, realloc, free);
+#endif
+ cp = evbuffer_readln(evb, &sz, EVBUFFER_EOL_LF);
+ tt_line_eq("two line");
+ free(cp); cp = NULL;
+ evbuffer_validate(evb);
+
+ end:
+ evbuffer_free(evb);
+ evbuffer_free(evb_tmp);
+ if (cp) free(cp);
+}
+
+static void
+test_evbuffer_search_eol(void *ptr)
+{
+ struct evbuffer *buf = evbuffer_new();
+ struct evbuffer_ptr ptr1, ptr2;
+ const char *s;
+ size_t eol_len;
+
+ s = "string! \r\n\r\nx\n";
+ evbuffer_add(buf, s, strlen(s));
+ eol_len = -1;
+ ptr1 = evbuffer_search_eol(buf, NULL, &eol_len, EVBUFFER_EOL_CRLF);
+ tt_int_op(ptr1.pos, ==, 8);
+ tt_int_op(eol_len, ==, 2);
+
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF);
+ tt_int_op(ptr2.pos, ==, 8);
+ tt_int_op(eol_len, ==, 2);
+
+ evbuffer_ptr_set(buf, &ptr1, 1, EVBUFFER_PTR_ADD);
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF);
+ tt_int_op(ptr2.pos, ==, 9);
+ tt_int_op(eol_len, ==, 1);
+
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_CRLF_STRICT);
+ tt_int_op(ptr2.pos, ==, 10);
+ tt_int_op(eol_len, ==, 2);
+
+ eol_len = -1;
+ ptr1 = evbuffer_search_eol(buf, NULL, &eol_len, EVBUFFER_EOL_LF);
+ tt_int_op(ptr1.pos, ==, 9);
+ tt_int_op(eol_len, ==, 1);
+
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_LF);
+ tt_int_op(ptr2.pos, ==, 9);
+ tt_int_op(eol_len, ==, 1);
+
+ evbuffer_ptr_set(buf, &ptr1, 1, EVBUFFER_PTR_ADD);
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_LF);
+ tt_int_op(ptr2.pos, ==, 11);
+ tt_int_op(eol_len, ==, 1);
+
+ tt_assert(evbuffer_ptr_set(buf, &ptr1, evbuffer_get_length(buf), EVBUFFER_PTR_SET) == 0);
+ eol_len = -1;
+ ptr2 = evbuffer_search_eol(buf, &ptr1, &eol_len, EVBUFFER_EOL_LF);
+ tt_int_op(ptr2.pos, ==, -1);
+ tt_int_op(eol_len, ==, 0);
+
+end:
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_iterative(void *ptr)
+{
+ struct evbuffer *buf = evbuffer_new();
+ const char *abc = "abcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyzabcdefghijklmnopqrstvuwxyz";
+ unsigned i, j, sum, n;
+
+ sum = 0;
+ n = 0;
+ for (i = 0; i < 1000; ++i) {
+ for (j = 1; j < strlen(abc); ++j) {
+ char format[32];
+ evutil_snprintf(format, sizeof(format), "%%%u.%us", j, j);
+ evbuffer_add_printf(buf, format, abc);
+
+ /* Only check for rep violations every so often.
+ Walking over the whole list of chains can get
+ pretty expensive as it gets long.
+ */
+ if ((n % 337) == 0)
+ evbuffer_validate(buf);
+
+ sum += j;
+ n++;
+ }
+ }
+ evbuffer_validate(buf);
+
+ tt_uint_op(sum, ==, evbuffer_get_length(buf));
+
+ {
+ size_t a,w,u;
+ a=w=u=0;
+ evbuffer_get_waste(buf, &a, &w, &u);
+ if (0)
+ printf("Allocated: %u.\nWasted: %u.\nUsed: %u.",
+ (unsigned)a, (unsigned)w, (unsigned)u);
+ tt_assert( ((double)w)/a < .125);
+ }
+ end:
+ evbuffer_free(buf);
+
+}
+
+static void
+test_evbuffer_find(void *ptr)
+{
+ unsigned char* p;
+ const char* test1 = "1234567890\r\n";
+ const char* test2 = "1234567890\r";
+#define EVBUFFER_INITIAL_LENGTH 256
+ char test3[EVBUFFER_INITIAL_LENGTH];
+ unsigned int i;
+ struct evbuffer * buf = evbuffer_new();
+
+ tt_assert(buf);
+
+ /* make sure evbuffer_find doesn't match past the end of the buffer */
+ evbuffer_add(buf, (unsigned char*)test1, strlen(test1));
+ evbuffer_validate(buf);
+ evbuffer_drain(buf, strlen(test1));
+ evbuffer_validate(buf);
+ evbuffer_add(buf, (unsigned char*)test2, strlen(test2));
+ evbuffer_validate(buf);
+ p = evbuffer_find(buf, (unsigned char*)"\r\n", 2);
+ tt_want(p == NULL);
+
+ /*
+ * drain the buffer and do another find; in r309 this would
+ * read past the allocated buffer causing a valgrind error.
+ */
+ evbuffer_drain(buf, strlen(test2));
+ evbuffer_validate(buf);
+ for (i = 0; i < EVBUFFER_INITIAL_LENGTH; ++i)
+ test3[i] = 'a';
+ test3[EVBUFFER_INITIAL_LENGTH - 1] = 'x';
+ evbuffer_add(buf, (unsigned char *)test3, EVBUFFER_INITIAL_LENGTH);
+ evbuffer_validate(buf);
+ p = evbuffer_find(buf, (unsigned char *)"xy", 2);
+ tt_want(p == NULL);
+
+ /* simple test for match at end of allocated buffer */
+ p = evbuffer_find(buf, (unsigned char *)"ax", 2);
+ tt_assert(p != NULL);
+ tt_want(strncmp((char*)p, "ax", 2) == 0);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_ptr_set(void *ptr)
+{
+ struct evbuffer *buf = evbuffer_new();
+ struct evbuffer_ptr pos;
+ struct evbuffer_iovec v[1];
+
+ tt_assert(buf);
+
+ tt_int_op(evbuffer_get_length(buf), ==, 0);
+
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ tt_assert(pos.pos == 0);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 1, EVBUFFER_PTR_ADD) == -1);
+ tt_assert(pos.pos == -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 1, EVBUFFER_PTR_SET) == -1);
+ tt_assert(pos.pos == -1);
+
+ /* create some chains */
+ evbuffer_reserve_space(buf, 5000, v, 1);
+ v[0].iov_len = 5000;
+ memset(v[0].iov_base, 1, v[0].iov_len);
+ evbuffer_commit_space(buf, v, 1);
+ evbuffer_validate(buf);
+
+ evbuffer_reserve_space(buf, 4000, v, 1);
+ v[0].iov_len = 4000;
+ memset(v[0].iov_base, 2, v[0].iov_len);
+ evbuffer_commit_space(buf, v, 1);
+
+ evbuffer_reserve_space(buf, 3000, v, 1);
+ v[0].iov_len = 3000;
+ memset(v[0].iov_base, 3, v[0].iov_len);
+ evbuffer_commit_space(buf, v, 1);
+ evbuffer_validate(buf);
+
+ tt_int_op(evbuffer_get_length(buf), ==, 12000);
+
+ tt_assert(evbuffer_ptr_set(buf, &pos, 13000, EVBUFFER_PTR_SET) == -1);
+ tt_assert(pos.pos == -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ tt_assert(pos.pos == 0);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 13000, EVBUFFER_PTR_ADD) == -1);
+
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ tt_assert(pos.pos == 0);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 10000, EVBUFFER_PTR_ADD) == 0);
+ tt_assert(pos.pos == 10000);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 1000, EVBUFFER_PTR_ADD) == 0);
+ tt_assert(pos.pos == 11000);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 1000, EVBUFFER_PTR_ADD) == 0);
+ tt_assert(pos.pos == 12000);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 1000, EVBUFFER_PTR_ADD) == -1);
+ tt_assert(pos.pos == -1);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+static void
+test_evbuffer_search(void *ptr)
+{
+ struct evbuffer *buf = evbuffer_new();
+ struct evbuffer *tmp = evbuffer_new();
+ struct evbuffer_ptr pos, end;
+
+ tt_assert(buf);
+ tt_assert(tmp);
+
+ pos = evbuffer_search(buf, "x", 1, NULL);
+ tt_int_op(pos.pos, ==, -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search(buf, "x", 1, &pos);
+ tt_int_op(pos.pos, ==, -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search_range(buf, "x", 1, &pos, &pos);
+ tt_int_op(pos.pos, ==, -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 0, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search_range(buf, "x", 1, &pos, NULL);
+ tt_int_op(pos.pos, ==, -1);
+
+ /* set up our chains */
+ evbuffer_add_printf(tmp, "hello"); /* 5 chars */
+ evbuffer_add_buffer(buf, tmp);
+ evbuffer_add_printf(tmp, "foo"); /* 3 chars */
+ evbuffer_add_buffer(buf, tmp);
+ evbuffer_add_printf(tmp, "cat"); /* 3 chars */
+ evbuffer_add_buffer(buf, tmp);
+ evbuffer_add_printf(tmp, "attack");
+ evbuffer_add_buffer(buf, tmp);
+
+ pos = evbuffer_search(buf, "attack", 6, NULL);
+ tt_int_op(pos.pos, ==, 11);
+ pos = evbuffer_search(buf, "attacker", 8, NULL);
+ tt_int_op(pos.pos, ==, -1);
+
+ /* test continuing search */
+ pos = evbuffer_search(buf, "oc", 2, NULL);
+ tt_int_op(pos.pos, ==, 7);
+ pos = evbuffer_search(buf, "cat", 3, &pos);
+ tt_int_op(pos.pos, ==, 8);
+ pos = evbuffer_search(buf, "tacking", 7, &pos);
+ tt_int_op(pos.pos, ==, -1);
+
+ evbuffer_ptr_set(buf, &pos, 5, EVBUFFER_PTR_SET);
+ pos = evbuffer_search(buf, "foo", 3, &pos);
+ tt_int_op(pos.pos, ==, 5);
+
+ evbuffer_ptr_set(buf, &pos, 2, EVBUFFER_PTR_ADD);
+ pos = evbuffer_search(buf, "tat", 3, &pos);
+ tt_int_op(pos.pos, ==, 10);
+
+ /* test bounded search. */
+ /* Set "end" to the first t in "attack". */
+ evbuffer_ptr_set(buf, &end, 12, EVBUFFER_PTR_SET);
+ pos = evbuffer_search_range(buf, "foo", 3, NULL, &end);
+ tt_int_op(pos.pos, ==, 5);
+ pos = evbuffer_search_range(buf, "foocata", 7, NULL, &end);
+ tt_int_op(pos.pos, ==, 5);
+ pos = evbuffer_search_range(buf, "foocatat", 8, NULL, &end);
+ tt_int_op(pos.pos, ==, -1);
+ pos = evbuffer_search_range(buf, "ack", 3, NULL, &end);
+ tt_int_op(pos.pos, ==, -1);
+
+ /* Set "end" after the last byte in the buffer. */
+ tt_assert(evbuffer_ptr_set(buf, &end, 17, EVBUFFER_PTR_SET) == 0);
+
+ pos = evbuffer_search_range(buf, "attack", 6, NULL, &end);
+ tt_int_op(pos.pos, ==, 11);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 11, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search_range(buf, "attack", 6, &pos, &end);
+ tt_int_op(pos.pos, ==, 11);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 17, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search_range(buf, "attack", 6, &pos, &end);
+ tt_int_op(pos.pos, ==, -1);
+ tt_assert(evbuffer_ptr_set(buf, &pos, 17, EVBUFFER_PTR_SET) == 0);
+ pos = evbuffer_search_range(buf, "attack", 6, &pos, NULL);
+ tt_int_op(pos.pos, ==, -1);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+ if (tmp)
+ evbuffer_free(tmp);
+}
+
+static void
+log_change_callback(struct evbuffer *buffer,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+
+ size_t old_len = cbinfo->orig_size;
+ size_t new_len = old_len + cbinfo->n_added - cbinfo->n_deleted;
+ struct evbuffer *out = arg;
+ evbuffer_add_printf(out, "%lu->%lu; ", (unsigned long)old_len,
+ (unsigned long)new_len);
+}
+static void
+self_draining_callback(struct evbuffer *evbuffer, size_t old_len,
+ size_t new_len, void *arg)
+{
+ if (new_len > old_len)
+ evbuffer_drain(evbuffer, new_len);
+}
+
+static void
+test_evbuffer_callbacks(void *ptr)
+{
+ struct evbuffer *buf = evbuffer_new();
+ struct evbuffer *buf_out1 = evbuffer_new();
+ struct evbuffer *buf_out2 = evbuffer_new();
+ struct evbuffer_cb_entry *cb1, *cb2;
+
+ tt_assert(buf);
+ tt_assert(buf_out1);
+ tt_assert(buf_out2);
+
+ cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+ cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+
+ /* Let's run through adding and deleting some stuff from the buffer
+ * and turning the callbacks on and off and removing them. The callback
+ * adds a summary of length changes to buf_out1/buf_out2 when called. */
+ /* size: 0-> 36. */
+ evbuffer_add_printf(buf, "The %d magic words are spotty pudding", 2);
+ evbuffer_validate(buf);
+ evbuffer_cb_clear_flags(buf, cb2, EVBUFFER_CB_ENABLED);
+ evbuffer_drain(buf, 10); /*36->26*/
+ evbuffer_validate(buf);
+ evbuffer_prepend(buf, "Hello", 5);/*26->31*/
+ evbuffer_cb_set_flags(buf, cb2, EVBUFFER_CB_ENABLED);
+ evbuffer_add_reference(buf, "Goodbye", 7, NULL, NULL); /*31->38*/
+ evbuffer_remove_cb_entry(buf, cb1);
+ evbuffer_validate(buf);
+ evbuffer_drain(buf, evbuffer_get_length(buf)); /*38->0*/;
+ tt_assert(-1 == evbuffer_remove_cb(buf, log_change_callback, NULL));
+ evbuffer_add(buf, "X", 1); /* 0->1 */
+ tt_assert(!evbuffer_remove_cb(buf, log_change_callback, buf_out2));
+ evbuffer_validate(buf);
+
+ tt_str_op((const char *) evbuffer_pullup(buf_out1, -1), ==,
+ "0->36; 36->26; 26->31; 31->38; ");
+ tt_str_op((const char *) evbuffer_pullup(buf_out2, -1), ==,
+ "0->36; 31->38; 38->0; 0->1; ");
+ evbuffer_drain(buf_out1, evbuffer_get_length(buf_out1));
+ evbuffer_drain(buf_out2, evbuffer_get_length(buf_out2));
+ /* Let's test the obsolete buffer_setcb function too. */
+ cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+ tt_assert(cb1 != NULL);
+ cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+ tt_assert(cb2 != NULL);
+ tt_int_op(evbuffer_setcb(buf, self_draining_callback, NULL), ==, 0);
+ evbuffer_add_printf(buf, "This should get drained right away.");
+ tt_uint_op(evbuffer_get_length(buf), ==, 0);
+ tt_uint_op(evbuffer_get_length(buf_out1), ==, 0);
+ tt_uint_op(evbuffer_get_length(buf_out2), ==, 0);
+ tt_int_op(evbuffer_setcb(buf, NULL, NULL), ==, 0);
+ evbuffer_add_printf(buf, "This will not.");
+ tt_str_op((const char *) evbuffer_pullup(buf, -1), ==, "This will not.");
+ evbuffer_validate(buf);
+ evbuffer_drain(buf, evbuffer_get_length(buf));
+ evbuffer_validate(buf);
+#if 0
+ /* Now let's try a suspended callback. */
+ cb1 = evbuffer_add_cb(buf, log_change_callback, buf_out1);
+ cb2 = evbuffer_add_cb(buf, log_change_callback, buf_out2);
+ evbuffer_cb_suspend(buf,cb2);
+ evbuffer_prepend(buf,"Hello world",11); /*0->11*/
+ evbuffer_validate(buf);
+ evbuffer_cb_suspend(buf,cb1);
+ evbuffer_add(buf,"more",4); /* 11->15 */
+ evbuffer_cb_unsuspend(buf,cb2);
+ evbuffer_drain(buf, 4); /* 15->11 */
+ evbuffer_cb_unsuspend(buf,cb1);
+ evbuffer_drain(buf, evbuffer_get_length(buf)); /* 11->0 */
+
+ tt_str_op(evbuffer_pullup(buf_out1, -1), ==,
+ "0->11; 11->11; 11->0; ");
+ tt_str_op(evbuffer_pullup(buf_out2, -1), ==,
+ "0->15; 15->11; 11->0; ");
+#endif
+
+ /* the next call to readline should fail */
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+ event_set_mem_functions(failing_malloc, realloc, free);
+ tt_int_op(evbuffer_setcb(buf, self_draining_callback, NULL), ==, -1);
+ evbuffer_validate(buf);
+ event_set_mem_functions(malloc, realloc, free);
+#endif
+
+ end:
+ if (buf)
+ evbuffer_free(buf);
+ if (buf_out1)
+ evbuffer_free(buf_out1);
+ if (buf_out2)
+ evbuffer_free(buf_out2);
+}
+
+static int ref_done_cb_called_count = 0;
+static void *ref_done_cb_called_with = NULL;
+static const void *ref_done_cb_called_with_data = NULL;
+static size_t ref_done_cb_called_with_len = 0;
+static void ref_done_cb(const void *data, size_t len, void *info)
+{
+ ++ref_done_cb_called_count;
+ ref_done_cb_called_with = info;
+ ref_done_cb_called_with_data = data;
+ ref_done_cb_called_with_len = len;
+}
+
+static void
+test_evbuffer_add_reference(void *ptr)
+{
+ const char chunk1[] = "If you have found the answer to such a problem";
+ const char chunk2[] = "you ought to write it up for publication";
+ /* -- Knuth's "Notes on the Exercises" from TAOCP */
+ char tmp[16];
+ size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ evbuffer_add_reference(buf1, chunk1, len1, ref_done_cb, (void*)111);
+ evbuffer_add(buf1, ", ", 2);
+ evbuffer_add_reference(buf1, chunk2, len2, ref_done_cb, (void*)222);
+ tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+ /* Make sure we can drain a little from a reference. */
+ tt_int_op(evbuffer_remove(buf1, tmp, 6), ==, 6);
+ tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+ tt_int_op(evbuffer_remove(buf1, tmp, 5), ==, 5);
+ tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+ /* Make sure that prepending does not meddle with immutable data */
+ tt_int_op(evbuffer_prepend(buf1, "I have ", 7), ==, 0);
+ tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+ evbuffer_validate(buf1);
+
+ /* Make sure that when the chunk is over, the callback is invoked. */
+ evbuffer_drain(buf1, 7); /* Remove prepended stuff. */
+ evbuffer_drain(buf1, len1-11-1); /* remove all but one byte of chunk1 */
+ tt_int_op(ref_done_cb_called_count, ==, 0);
+ evbuffer_remove(buf1, tmp, 1);
+ tt_int_op(tmp[0], ==, 'm');
+ tt_assert(ref_done_cb_called_with == (void*)111);
+ tt_assert(ref_done_cb_called_with_data == chunk1);
+ tt_assert(ref_done_cb_called_with_len == len1);
+ tt_int_op(ref_done_cb_called_count, ==, 1);
+ evbuffer_validate(buf1);
+
+ /* Drain some of the remaining chunk, then add it to another buffer */
+ evbuffer_drain(buf1, 6); /* Remove the ", you ". */
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+ tt_int_op(ref_done_cb_called_count, ==, 1);
+ evbuffer_add(buf2, "I ", 2);
+
+ evbuffer_add_buffer(buf2, buf1);
+ tt_int_op(ref_done_cb_called_count, ==, 1);
+ evbuffer_remove(buf2, tmp, 16);
+ tt_int_op(memcmp("I ought to write", tmp, 16), ==, 0);
+ evbuffer_drain(buf2, evbuffer_get_length(buf2));
+ tt_int_op(ref_done_cb_called_count, ==, 2);
+ tt_assert(ref_done_cb_called_with == (void*)222);
+ evbuffer_validate(buf2);
+
+ /* Now add more stuff to buf1 and make sure that it gets removed on
+ * free. */
+ evbuffer_add(buf1, "You shake and shake the ", 24);
+ evbuffer_add_reference(buf1, "ketchup bottle", 14, ref_done_cb,
+ (void*)3333);
+ evbuffer_add(buf1, ". Nothing comes and then a lot'll.", 35);
+ evbuffer_free(buf1);
+ buf1 = NULL;
+ tt_int_op(ref_done_cb_called_count, ==, 3);
+ tt_assert(ref_done_cb_called_with == (void*)3333);
+
+end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_multicast(void *ptr)
+{
+ const char chunk1[] = "If you have found the answer to such a problem";
+ const char chunk2[] = "you ought to write it up for publication";
+ /* -- Knuth's "Notes on the Exercises" from TAOCP */
+ char tmp[16];
+ size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ evbuffer_add(buf1, chunk1, len1);
+ evbuffer_add(buf1, ", ", 2);
+ evbuffer_add(buf1, chunk2, len2);
+ tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ tt_int_op(evbuffer_add_buffer_reference(buf2, buf1), ==, 0);
+ /* nested references are not allowed */
+ tt_int_op(evbuffer_add_buffer_reference(buf2, buf2), ==, -1);
+ tt_int_op(evbuffer_add_buffer_reference(buf1, buf2), ==, -1);
+
+ /* both buffers contain the same amount of data */
+ tt_int_op(evbuffer_get_length(buf1), ==, evbuffer_get_length(buf1));
+
+ /* Make sure we can drain a little from the first buffer. */
+ tt_int_op(evbuffer_remove(buf1, tmp, 6), ==, 6);
+ tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+ tt_int_op(evbuffer_remove(buf1, tmp, 5), ==, 5);
+ tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+ /* Make sure that prepending does not meddle with immutable data */
+ tt_int_op(evbuffer_prepend(buf1, "I have ", 7), ==, 0);
+ tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+ evbuffer_validate(buf1);
+
+ /* Make sure we can drain a little from the second buffer. */
+ tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+ tt_int_op(memcmp(tmp, "If you", 6), ==, 0);
+ tt_int_op(evbuffer_remove(buf2, tmp, 5), ==, 5);
+ tt_int_op(memcmp(tmp, " have", 5), ==, 0);
+
+ /* Make sure that prepending does not meddle with immutable data */
+ tt_int_op(evbuffer_prepend(buf2, "I have ", 7), ==, 0);
+ tt_int_op(memcmp(chunk1, "If you", 6), ==, 0);
+ evbuffer_validate(buf2);
+
+ /* Make sure the data can be read from the second buffer when the first is freed */
+ evbuffer_free(buf1);
+ buf1 = NULL;
+
+ tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+ tt_int_op(memcmp(tmp, "I have", 6), ==, 0);
+
+ tt_int_op(evbuffer_remove(buf2, tmp, 6), ==, 6);
+ tt_int_op(memcmp(tmp, " foun", 6), ==, 0);
+
+end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_multicast_drain(void *ptr)
+{
+ const char chunk1[] = "If you have found the answer to such a problem";
+ const char chunk2[] = "you ought to write it up for publication";
+ /* -- Knuth's "Notes on the Exercises" from TAOCP */
+ size_t len1 = strlen(chunk1), len2=strlen(chunk2);
+
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ evbuffer_add(buf1, chunk1, len1);
+ evbuffer_add(buf1, ", ", 2);
+ evbuffer_add(buf1, chunk2, len2);
+ tt_int_op(evbuffer_get_length(buf1), ==, len1+len2+2);
+
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ tt_int_op(evbuffer_add_buffer_reference(buf2, buf1), ==, 0);
+ tt_int_op(evbuffer_get_length(buf2), ==, len1+len2+2);
+ tt_int_op(evbuffer_drain(buf1, evbuffer_get_length(buf1)), ==, 0);
+ tt_int_op(evbuffer_get_length(buf2), ==, len1+len2+2);
+ tt_int_op(evbuffer_drain(buf2, evbuffer_get_length(buf2)), ==, 0);
+ evbuffer_validate(buf1);
+ evbuffer_validate(buf2);
+
+end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+check_prepend(struct evbuffer *buffer,
+ const struct evbuffer_cb_info *cbinfo,
+ void *arg)
+{
+ tt_int_op(cbinfo->orig_size, ==, 3);
+ tt_int_op(cbinfo->n_added, ==, 8096);
+ tt_int_op(cbinfo->n_deleted, ==, 0);
+end:
+ ;
+}
+/* Some cases that we didn't get in test_evbuffer() above, for more coverage. */
+static void
+test_evbuffer_prepend(void *ptr)
+{
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+ char tmp[128], *buffer = malloc(8096);
+ int n;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+
+ /* Case 0: The evbuffer is entirely empty. */
+ evbuffer_prepend(buf1, "This string has 29 characters", 29);
+ evbuffer_validate(buf1);
+
+ /* Case 1: Prepend goes entirely in new chunk. */
+ evbuffer_prepend(buf1, "Short.", 6);
+ evbuffer_validate(buf1);
+
+ /* Case 2: prepend goes entirely in first chunk. */
+ evbuffer_drain(buf1, 6+11);
+ evbuffer_prepend(buf1, "it", 2);
+ evbuffer_validate(buf1);
+ tt_assert(!memcmp(buf1->first->buffer+buf1->first->misalign,
+ "it has", 6));
+
+ /* Case 3: prepend is split over multiple chunks. */
+ evbuffer_prepend(buf1, "It is no longer true to say ", 28);
+ evbuffer_validate(buf1);
+ n = evbuffer_remove(buf1, tmp, sizeof(tmp)-1);
+ tt_int_op(n, >=, 0);
+ tmp[n]='\0';
+ tt_str_op(tmp,==,"It is no longer true to say it has 29 characters");
+
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ /* Case 4: prepend a buffer to an empty buffer. */
+ n = 999;
+ evbuffer_add_printf(buf1, "Here is string %d. ", n++);
+ evbuffer_prepend_buffer(buf2, buf1);
+ evbuffer_validate(buf2);
+
+ /* Case 5: prepend a buffer to a nonempty buffer. */
+ evbuffer_add_printf(buf1, "Here is string %d. ", n++);
+ evbuffer_prepend_buffer(buf2, buf1);
+ evbuffer_validate(buf2);
+ evbuffer_validate(buf1);
+ n = evbuffer_remove(buf2, tmp, sizeof(tmp)-1);
+ tt_int_op(n, >=, 0);
+ tmp[n]='\0';
+ tt_str_op(tmp,==,"Here is string 1000. Here is string 999. ");
+
+ /* Case 5: evbuffer_prepend() will need a new buffer, with callbacks */
+ memset(buffer, 'A', 8096);
+ evbuffer_free(buf2);
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+ evbuffer_prepend(buf2, "foo", 3);
+ evbuffer_add_cb(buf2, check_prepend, NULL);
+ evbuffer_prepend(buf2, buffer, 8096);
+ evbuffer_remove_cb(buf2, check_prepend, NULL);
+ evbuffer_validate(buf2);
+ tt_nstr_op(8096,(char *)evbuffer_pullup(buf2, 8096),==,buffer);
+ evbuffer_drain(buf2, 8096);
+ tt_nstr_op(3,(char *)evbuffer_pullup(buf2, 3),==,"foo");
+ evbuffer_drain(buf2, 3);
+
+end:
+ free(buffer);
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+
+}
+
+static void
+test_evbuffer_empty_reference_prepend(void *ptr)
+{
+ struct evbuffer *buf = NULL;
+
+ buf = evbuffer_new();
+ tt_assert(buf);
+
+ /** empty chain could leave invalid last_with_datap */
+ evbuffer_add_reference(buf, "", 0, NULL, NULL);
+ evbuffer_validate(buf);
+ evbuffer_prepend(buf, "foo", 3);
+
+ evbuffer_validate(buf);
+ tt_assert(!strncmp((char *)evbuffer_pullup(buf, -1), "foo", 3));
+ evbuffer_validate(buf);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+}
+static void
+test_evbuffer_empty_reference_prepend_buffer(void *ptr)
+{
+ struct evbuffer *buf1 = NULL, *buf2 = NULL;
+
+ buf1 = evbuffer_new();
+ tt_assert(buf1);
+ buf2 = evbuffer_new();
+ tt_assert(buf2);
+
+ /** empty chain could leave invalid last_with_datap */
+ evbuffer_add_reference(buf1, "", 0, NULL, NULL);
+ evbuffer_validate(buf1);
+ evbuffer_add(buf2, "foo", 3);
+ evbuffer_validate(buf2);
+ evbuffer_prepend_buffer(buf2, buf1);
+ evbuffer_validate(buf2);
+
+ tt_assert(!strncmp((char *)evbuffer_pullup(buf2, -1), "foo", 3));
+ evbuffer_validate(buf2);
+
+ tt_assert(evbuffer_pullup(buf1, -1) == NULL);
+ evbuffer_validate(buf2);
+
+end:
+ if (buf1)
+ evbuffer_free(buf1);
+ if (buf2)
+ evbuffer_free(buf2);
+}
+
+static void
+test_evbuffer_peek_first_gt(void *info)
+{
+ struct evbuffer *buf = NULL, *tmp_buf = NULL;
+ struct evbuffer_ptr ptr;
+ struct evbuffer_iovec v[2];
+
+ buf = evbuffer_new();
+ tmp_buf = evbuffer_new();
+ evbuffer_add_printf(tmp_buf, "Contents of chunk 100\n");
+ evbuffer_add_buffer(buf, tmp_buf);
+ evbuffer_add_printf(tmp_buf, "Contents of chunk 1\n");
+ evbuffer_add_buffer(buf, tmp_buf);
+
+ evbuffer_ptr_set(buf, &ptr, 0, EVBUFFER_PTR_SET);
+
+ /** The only case that matters*/
+ tt_int_op(evbuffer_peek(buf, -1, &ptr, NULL, 0), ==, 2);
+ /** Just in case */
+ tt_int_op(evbuffer_peek(buf, -1, &ptr, v, 2), ==, 2);
+
+ evbuffer_ptr_set(buf, &ptr, 20, EVBUFFER_PTR_ADD);
+ tt_int_op(evbuffer_peek(buf, -1, &ptr, NULL, 0), ==, 2);
+ tt_int_op(evbuffer_peek(buf, -1, &ptr, v, 2), ==, 2);
+ tt_int_op(evbuffer_peek(buf, 2, &ptr, NULL, 0), ==, 1);
+ tt_int_op(evbuffer_peek(buf, 2, &ptr, v, 2), ==, 1);
+ tt_int_op(evbuffer_peek(buf, 3, &ptr, NULL, 0), ==, 2);
+ tt_int_op(evbuffer_peek(buf, 3, &ptr, v, 2), ==, 2);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+ if (tmp_buf)
+ evbuffer_free(tmp_buf);
+}
+
+static void
+test_evbuffer_peek(void *info)
+{
+ struct evbuffer *buf = NULL, *tmp_buf = NULL;
+ int i;
+ struct evbuffer_iovec v[20];
+ struct evbuffer_ptr ptr;
+
+#define tt_iov_eq(v, s) \
+ tt_int_op((v)->iov_len, ==, strlen(s)); \
+ tt_assert(!memcmp((v)->iov_base, (s), strlen(s)))
+
+ /* Let's make a very fragmented buffer. */
+ buf = evbuffer_new();
+ tmp_buf = evbuffer_new();
+ for (i = 0; i < 16; ++i) {
+ evbuffer_add_printf(tmp_buf, "Contents of chunk [%d]\n", i);
+ evbuffer_add_buffer(buf, tmp_buf);
+ }
+
+ /* How many chunks do we need for everything? */
+ i = evbuffer_peek(buf, -1, NULL, NULL, 0);
+ tt_int_op(i, ==, 16);
+
+ /* Simple peek: get everything. */
+ i = evbuffer_peek(buf, -1, NULL, v, 20);
+ tt_int_op(i, ==, 16); /* we used only 16 chunks. */
+ tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+ tt_iov_eq(&v[3], "Contents of chunk [3]\n");
+ tt_iov_eq(&v[12], "Contents of chunk [12]\n");
+ tt_iov_eq(&v[15], "Contents of chunk [15]\n");
+
+ /* Just get one chunk worth. */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(buf, -1, NULL, v, 1);
+ tt_int_op(i, ==, 1);
+ tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+ tt_assert(v[1].iov_base == NULL);
+
+ /* Suppose we want at least the first 40 bytes. */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(buf, 40, NULL, v, 16);
+ tt_int_op(i, ==, 2);
+ tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+ tt_iov_eq(&v[1], "Contents of chunk [1]\n");
+ tt_assert(v[2].iov_base == NULL);
+
+ /* How many chunks do we need for 100 bytes? */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(buf, 100, NULL, NULL, 0);
+ tt_int_op(i, ==, 5);
+ tt_assert(v[0].iov_base == NULL);
+
+ /* Now we ask for more bytes than we provide chunks for */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(buf, 60, NULL, v, 1);
+ tt_int_op(i, ==, 3);
+ tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+ tt_assert(v[1].iov_base == NULL);
+
+ /* Now we ask for more bytes than the buffer has. */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(buf, 65536, NULL, v, 20);
+ tt_int_op(i, ==, 16); /* we used only 16 chunks. */
+ tt_iov_eq(&v[0], "Contents of chunk [0]\n");
+ tt_iov_eq(&v[3], "Contents of chunk [3]\n");
+ tt_iov_eq(&v[12], "Contents of chunk [12]\n");
+ tt_iov_eq(&v[15], "Contents of chunk [15]\n");
+ tt_assert(v[16].iov_base == NULL);
+
+ /* What happens if we try an empty buffer? */
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(tmp_buf, -1, NULL, v, 20);
+ tt_int_op(i, ==, 0);
+ tt_assert(v[0].iov_base == NULL);
+ memset(v, 0, sizeof(v));
+ i = evbuffer_peek(tmp_buf, 50, NULL, v, 20);
+ tt_int_op(i, ==, 0);
+ tt_assert(v[0].iov_base == NULL);
+
+ /* Okay, now time to have fun with pointers. */
+ memset(v, 0, sizeof(v));
+ evbuffer_ptr_set(buf, &ptr, 30, EVBUFFER_PTR_SET);
+ i = evbuffer_peek(buf, 50, &ptr, v, 20);
+ tt_int_op(i, ==, 3);
+ tt_iov_eq(&v[0], " of chunk [1]\n");
+ tt_iov_eq(&v[1], "Contents of chunk [2]\n");
+ tt_iov_eq(&v[2], "Contents of chunk [3]\n"); /*more than we asked for*/
+
+ /* advance to the start of another chain. */
+ memset(v, 0, sizeof(v));
+ evbuffer_ptr_set(buf, &ptr, 14, EVBUFFER_PTR_ADD);
+ i = evbuffer_peek(buf, 44, &ptr, v, 20);
+ tt_int_op(i, ==, 2);
+ tt_iov_eq(&v[0], "Contents of chunk [2]\n");
+ tt_iov_eq(&v[1], "Contents of chunk [3]\n"); /*more than we asked for*/
+
+ /* peek at the end of the buffer */
+ memset(v, 0, sizeof(v));
+ tt_assert(evbuffer_ptr_set(buf, &ptr, evbuffer_get_length(buf), EVBUFFER_PTR_SET) == 0);
+ i = evbuffer_peek(buf, 44, &ptr, v, 20);
+ tt_int_op(i, ==, 0);
+ tt_assert(v[0].iov_base == NULL);
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+ if (tmp_buf)
+ evbuffer_free(tmp_buf);
+}
+
+/* Check whether evbuffer freezing works right. This is called twice,
+ once with the argument "start" and once with the argument "end".
+ When we test "start", we freeze the start of an evbuffer and make sure
+ that modifying the start of the buffer doesn't work. When we test
+ "end", we freeze the end of an evbuffer and make sure that modifying
+ the end of the buffer doesn't work.
+ */
+static void
+test_evbuffer_freeze(void *ptr)
+{
+ struct basic_test_data *testdata = ptr;
+ evutil_socket_t *pair = testdata->pair;
+ struct evbuffer *buf = NULL, *buf_two = NULL, *tmp_buf = NULL;
+ const char string[] = /* Year's End, Richard Wilbur */
+ "I've known the wind by water banks to shake\n"
+ "The late leaves down, which frozen where they fell\n"
+ "And held in ice as dancers in a spell\n"
+ "Fluttered all winter long into a lake...";
+ const int start = !strcmp(testdata->setup_data, "start");
+ const char tmpfilecontent[] = "file_freeze_test_file";
+ char *cp;
+ char charbuf[128];
+ char *tmpfilename = NULL;
+ int fd = -1;
+ int r;
+ size_t orig_length, len;
+ struct evbuffer_iovec v[1];
+
+ if (!start)
+ tt_str_op(testdata->setup_data, ==, "end");
+
+ buf = evbuffer_new();
+ buf_two = evbuffer_new();
+ tmp_buf = evbuffer_new();
+ tt_assert(tmp_buf);
+
+ evbuffer_add(buf, string, strlen(string));
+ evbuffer_add(buf_two, "abc", 3);
+ evbuffer_add(tmp_buf, "xyz", 3);
+ evbuffer_freeze(buf, start); /* Freeze the start or the end.*/
+ evbuffer_freeze(buf_two, start);
+
+#define FREEZE_EQ(a, startcase, endcase) \
+ do { \
+ if (start) { \
+ tt_int_op((a), ==, (startcase)); \
+ } else { \
+ tt_int_op((a), ==, (endcase)); \
+ } \
+ } while (0)
+
+
+ orig_length = evbuffer_get_length(buf);
+
+ /* These functions all manipulate the end of buf. */
+ r = evbuffer_add(buf, "abc", 0);
+ FREEZE_EQ(r, 0, -1);
+ r = evbuffer_reserve_space(buf, 10, v, 1);
+ FREEZE_EQ(r, 1, -1);
+ if (r == 1) {
+ memset(v[0].iov_base, 'X', 10);
+ v[0].iov_len = 10;
+ }
+ r = evbuffer_commit_space(buf, v, 1);
+ FREEZE_EQ(r, 0, -1);
+ r = evbuffer_add_reference(buf, string, 5, NULL, NULL);
+ FREEZE_EQ(r, 0, -1);
+ r = evbuffer_add_printf(buf, "Hello %s", "world");
+ FREEZE_EQ(r, 11, -1);
+
+ r = evbuffer_add_buffer(buf, tmp_buf);
+ FREEZE_EQ(r, 0, -1);
+ len = strlen(tmpfilecontent);
+ fd = regress_make_tmpfile(tmpfilecontent, len, &tmpfilename);
+ r = evbuffer_add_file(buf, fd, 0, len);
+ FREEZE_EQ(r, 0, -1);
+
+ if (start)
+ evbuffer_add(tmp_buf, "xyz", 3);
+
+ tt_assert(evbuffer_get_length(tmp_buf));
+ len = evbuffer_get_length(tmp_buf);
+ evbuffer_write(tmp_buf, pair[0]);
+ r = evbuffer_read(buf, pair[1], -1);
+ FREEZE_EQ(r, len, -1);
+
+ if (!start)
+ tt_int_op(orig_length, ==, evbuffer_get_length(buf));
+
+ orig_length = evbuffer_get_length(buf);
+
+ /* These functions all manipulate the start of buf. */
+ r = evbuffer_remove(buf, charbuf, 1);
+ FREEZE_EQ(r, -1, 1);
+ r = evbuffer_drain(buf, 3);
+ FREEZE_EQ(r, -1, 0);
+ r = evbuffer_prepend(buf, "dummy", 5);
+ FREEZE_EQ(r, -1, 0);
+ cp = evbuffer_readln(buf, NULL, EVBUFFER_EOL_LF);
+ FREEZE_EQ(cp==NULL, 1, 0);
+ if (cp)
+ free(cp);
+
+ evbuffer_add(tmp_buf, "xyz", 3);
+ tt_assert(evbuffer_get_length(tmp_buf));
+ r = evbuffer_remove_buffer(buf, tmp_buf, 3);
+ FREEZE_EQ(r, -1, 3);
+ r = evbuffer_drain(buf, 3);
+ FREEZE_EQ(r, -1, 0);
+ r = evbuffer_prepend_buffer(buf, tmp_buf);
+ FREEZE_EQ(r, -1, 0);
+
+ len = evbuffer_get_length(buf);
+ r = evbuffer_write(buf, pair[0]);
+ evbuffer_read(tmp_buf, pair[1], -1);
+ FREEZE_EQ(r, -1, len);
+ len = evbuffer_get_length(buf_two);
+ r = evbuffer_write_atmost(buf_two, pair[0], -1);
+ evbuffer_read(tmp_buf, pair[1], -1);
+ FREEZE_EQ(r, -1, len);
+
+ if (start)
+ tt_int_op(orig_length, ==, evbuffer_get_length(buf));
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+
+ if (buf_two)
+ evbuffer_free(buf_two);
+
+ if (tmp_buf)
+ evbuffer_free(tmp_buf);
+
+ if (tmpfilename) {
+ unlink(tmpfilename);
+ free(tmpfilename);
+ }
+}
+
+static void
+test_evbuffer_add_iovec(void * ptr)
+{
+ struct evbuffer * buf = NULL;
+ struct evbuffer_iovec vec[4];
+ const char * data[] = {
+ "Guilt resembles a sword with two edges.",
+ "On the one hand, it cuts for Justice, imposing practical morality upon those who fear it.",
+ "Conscience does not always adhere to rational judgment.",
+ "Guilt is always a self-imposed burden, but it is not always rightly imposed."
+ /* -- R.A. Salvatore, _Sojurn_ */
+ };
+ size_t expected_length = 0;
+ size_t returned_length = 0;
+ int i;
+
+ buf = evbuffer_new();
+
+ tt_assert(buf);
+
+ for (i = 0; i < 4; i++) {
+ vec[i].iov_len = strlen(data[i]);
+ vec[i].iov_base = (char*) data[i];
+ expected_length += vec[i].iov_len;
+ }
+
+ returned_length = evbuffer_add_iovec(buf, vec, 4);
+
+ tt_int_op(returned_length, ==, evbuffer_get_length(buf));
+ tt_int_op(evbuffer_get_length(buf), ==, expected_length);
+
+ for (i = 0; i < 4; i++) {
+ char charbuf[1024];
+
+ memset(charbuf, 0, 1024);
+ evbuffer_remove(buf, charbuf, strlen(data[i]));
+ tt_assert(strcmp(charbuf, data[i]) == 0);
+ }
+
+ tt_assert(evbuffer_get_length(buf) == 0);
+end:
+ if (buf) {
+ evbuffer_free(buf);
+ }
+}
+
+static void
+test_evbuffer_copyout(void *dummy)
+{
+ const char string[] =
+ "Still they skirmish to and fro, men my messmates on the snow "
+ "When we headed off the aurochs turn for turn; "
+ "When the rich Allobrogenses never kept amanuenses, "
+ "And our only plots were piled in lakes at Berne.";
+ /* -- Kipling, "In The Neolithic Age" */
+ char tmp[1024];
+ struct evbuffer_ptr ptr;
+ struct evbuffer *buf;
+
+ (void)dummy;
+
+ buf = evbuffer_new();
+ tt_assert(buf);
+
+ tt_int_op(strlen(string), ==, 206);
+
+ /* Ensure separate chains */
+ evbuffer_add_reference(buf, string, 80, no_cleanup, NULL);
+ evbuffer_add_reference(buf, string+80, 80, no_cleanup, NULL);
+ evbuffer_add(buf, string+160, strlen(string)-160);
+
+ tt_int_op(206, ==, evbuffer_get_length(buf));
+
+ /* First, let's test plain old copyout. */
+
+ /* Copy a little from the beginning. */
+ tt_int_op(10, ==, evbuffer_copyout(buf, tmp, 10));
+ tt_int_op(0, ==, memcmp(tmp, "Still they", 10));
+
+ /* Now copy more than a little from the beginning */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(100, ==, evbuffer_copyout(buf, tmp, 100));
+ tt_int_op(0, ==, memcmp(tmp, string, 100));
+
+ /* Copy too much; ensure truncation. */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(206, ==, evbuffer_copyout(buf, tmp, 230));
+ tt_int_op(0, ==, memcmp(tmp, string, 206));
+
+ /* That was supposed to be nondestructive, btw */
+ tt_int_op(206, ==, evbuffer_get_length(buf));
+
+ /* Now it's time to test copyout_from! First, let's start in the
+ * first chain. */
+ evbuffer_ptr_set(buf, &ptr, 15, EVBUFFER_PTR_SET);
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(10, ==, evbuffer_copyout_from(buf, &ptr, tmp, 10));
+ tt_int_op(0, ==, memcmp(tmp, "mish to an", 10));
+
+ /* Right up to the end of the first chain */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(65, ==, evbuffer_copyout_from(buf, &ptr, tmp, 65));
+ tt_int_op(0, ==, memcmp(tmp, string+15, 65));
+
+ /* Span into the second chain */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(90, ==, evbuffer_copyout_from(buf, &ptr, tmp, 90));
+ tt_int_op(0, ==, memcmp(tmp, string+15, 90));
+
+ /* Span into the third chain */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(160, ==, evbuffer_copyout_from(buf, &ptr, tmp, 160));
+ tt_int_op(0, ==, memcmp(tmp, string+15, 160));
+
+ /* Overrun */
+ memset(tmp, 0, sizeof(tmp));
+ tt_int_op(206-15, ==, evbuffer_copyout_from(buf, &ptr, tmp, 999));
+ tt_int_op(0, ==, memcmp(tmp, string+15, 206-15));
+
+ /* That was supposed to be nondestructive, too */
+ tt_int_op(206, ==, evbuffer_get_length(buf));
+
+end:
+ if (buf)
+ evbuffer_free(buf);
+}
+
+static void *
+setup_passthrough(const struct testcase_t *testcase)
+{
+ return testcase->setup_data;
+}
+static int
+cleanup_passthrough(const struct testcase_t *testcase, void *ptr)
+{
+ (void) ptr;
+ return 1;
+}
+
+static const struct testcase_setup_t nil_setup = {
+ setup_passthrough,
+ cleanup_passthrough
+};
+
+struct testcase_t evbuffer_testcases[] = {
+ { "evbuffer", test_evbuffer, 0, NULL, NULL },
+ { "remove_buffer_with_empty", test_evbuffer_remove_buffer_with_empty, 0, NULL, NULL },
+ { "remove_buffer_with_empty2", test_evbuffer_remove_buffer_with_empty2, 0, NULL, NULL },
+ { "remove_buffer_with_empty3", test_evbuffer_remove_buffer_with_empty3, 0, NULL, NULL },
+ { "remove_buffer_with_empty_front", test_evbuffer_remove_buffer_with_empty_front, 0, NULL, NULL },
+ { "remove_buffer_adjust_last_with_datap_with_empty",
+ test_evbuffer_remove_buffer_adjust_last_with_datap_with_empty, 0, NULL, NULL },
+ { "add_buffer_with_empty", test_evbuffer_add_buffer_with_empty, 0, NULL, NULL },
+ { "add_buffer_with_empty2", test_evbuffer_add_buffer_with_empty2, 0, NULL, NULL },
+ { "reserve2", test_evbuffer_reserve2, 0, NULL, NULL },
+ { "reserve_many", test_evbuffer_reserve_many, 0, NULL, NULL },
+ { "reserve_many2", test_evbuffer_reserve_many, 0, &nil_setup, (void*)"add" },
+ { "reserve_many3", test_evbuffer_reserve_many, 0, &nil_setup, (void*)"fill" },
+ { "reserve_with_empty", test_evbuffer_reserve_with_empty, 0, NULL, NULL },
+ { "reserve_invalid_last_with_datap", test_evbuffer_reserve_invalid_last_with_datap, TT_FORK, NULL, NULL },
+ { "expand", test_evbuffer_expand, 0, NULL, NULL },
+ { "expand_overflow", test_evbuffer_expand_overflow, 0, NULL, NULL },
+ { "add1", test_evbuffer_add1, 0, NULL, NULL },
+ { "add2", test_evbuffer_add2, 0, NULL, NULL },
+ { "reference", test_evbuffer_reference, 0, NULL, NULL },
+ { "reference2", test_evbuffer_reference2, 0, NULL, NULL },
+ { "iterative", test_evbuffer_iterative, 0, NULL, NULL },
+ { "readln", test_evbuffer_readln, TT_NO_LOGS, &basic_setup, NULL },
+ { "search_eol", test_evbuffer_search_eol, 0, NULL, NULL },
+ { "find", test_evbuffer_find, 0, NULL, NULL },
+ { "ptr_set", test_evbuffer_ptr_set, 0, NULL, NULL },
+ { "search", test_evbuffer_search, 0, NULL, NULL },
+ { "callbacks", test_evbuffer_callbacks, 0, NULL, NULL },
+ { "add_reference", test_evbuffer_add_reference, 0, NULL, NULL },
+ { "multicast", test_evbuffer_multicast, 0, NULL, NULL },
+ { "multicast_drain", test_evbuffer_multicast_drain, 0, NULL, NULL },
+ { "prepend", test_evbuffer_prepend, TT_FORK, NULL, NULL },
+ { "empty_reference_prepend", test_evbuffer_empty_reference_prepend, TT_FORK, NULL, NULL },
+ { "empty_reference_prepend_buffer", test_evbuffer_empty_reference_prepend_buffer, TT_FORK, NULL, NULL },
+ { "peek", test_evbuffer_peek, 0, NULL, NULL },
+ { "peek_first_gt", test_evbuffer_peek_first_gt, 0, NULL, NULL },
+ { "freeze_start", test_evbuffer_freeze, TT_NEED_SOCKETPAIR, &basic_setup, (void*)"start" },
+ { "freeze_end", test_evbuffer_freeze, TT_NEED_SOCKETPAIR, &basic_setup, (void*)"end" },
+ { "add_iovec", test_evbuffer_add_iovec, 0, NULL, NULL},
+ { "copyout", test_evbuffer_copyout, 0, NULL, NULL},
+ { "file_segment_add_cleanup_cb", test_evbuffer_file_segment_add_cleanup_cb, 0, NULL, NULL },
+ { "pullup_with_empty", test_evbuffer_pullup_with_empty, 0, NULL, NULL },
+
+#define ADDFILE_TEST(name, parameters) \
+ { name, test_evbuffer_add_file, TT_FORK|TT_NEED_BASE, \
+ &basic_setup, (void*)(parameters) }
+
+#define ADDFILE_TEST_GROUP(name, parameters) \
+ ADDFILE_TEST(name "_sendfile", "sendfile " parameters), \
+ ADDFILE_TEST(name "_mmap", "mmap " parameters), \
+ ADDFILE_TEST(name "_linear", "linear " parameters)
+
+ ADDFILE_TEST_GROUP("add_file", ""),
+ ADDFILE_TEST("add_file_nosegment", "default nosegment"),
+
+ ADDFILE_TEST_GROUP("add_big_file", "bigfile"),
+ ADDFILE_TEST("add_big_file_nosegment", "default nosegment bigfile"),
+
+ ADDFILE_TEST_GROUP("add_file_offset", "bigfile map_offset"),
+ ADDFILE_TEST("add_file_offset_nosegment",
+ "default nosegment bigfile map_offset"),
+
+ ADDFILE_TEST_GROUP("add_file_offset2", "bigfile offset_in_segment"),
+
+ ADDFILE_TEST_GROUP("add_file_offset3",
+ "bigfile offset_in_segment map_offset"),
+
+ END_OF_TESTCASES
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_bufferevent.c b/ipc/chromium/src/third_party/libevent/test/regress_bufferevent.c
new file mode 100644
index 0000000000..c276a0e5d1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_bufferevent.c
@@ -0,0 +1,1467 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+/**
+ * - clang supports __has_feature
+ * - gcc supports __SANITIZE_ADDRESS__
+ *
+ * Let's set __SANITIZE_ADDRESS__ if __has_feature(address_sanitizer)
+ */
+#ifndef __has_feature
+#define __has_feature(x) 0
+#endif
+#if !defined(__SANITIZE_ADDRESS__) && __has_feature(address_sanitizer)
+#define __SANITIZE_ADDRESS__
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#endif
+#include <fcntl.h>
+#include <signal.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#ifdef EVENT__HAVE_ARPA_INET_H
+#include <arpa/inet.h>
+#endif
+
+#include "event2/event-config.h"
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/tag.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_compat.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/listener.h"
+#include "event2/util.h"
+
+#include "bufferevent-internal.h"
+#include "evthread-internal.h"
+#include "util-internal.h"
+#ifdef _WIN32
+#include "iocp-internal.h"
+#endif
+
+#include "regress.h"
+#include "regress_testutils.h"
+
+/*
+ * simple bufferevent test
+ */
+
+static void
+readcb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bev->input) == 8333) {
+ struct evbuffer *evbuf = evbuffer_new();
+ assert(evbuf != NULL);
+
+ /* gratuitous test of bufferevent_read_buffer */
+ bufferevent_read_buffer(bev, evbuf);
+
+ bufferevent_disable(bev, EV_READ);
+
+ if (evbuffer_get_length(evbuf) == 8333) {
+ test_ok++;
+ }
+
+ evbuffer_free(evbuf);
+ }
+}
+
+static void
+writecb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bev->output) == 0) {
+ test_ok++;
+ }
+}
+
+static void
+errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ test_ok = -2;
+}
+
+static void
+test_bufferevent_impl(int use_pair, int flush)
+{
+ struct bufferevent *bev1 = NULL, *bev2 = NULL;
+ char buffer[8333];
+ int i;
+ int expected = 2;
+
+ if (use_pair) {
+ struct bufferevent *pair[2];
+ tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+ bev1 = pair[0];
+ bev2 = pair[1];
+ bufferevent_setcb(bev1, readcb, writecb, errorcb, bev1);
+ bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
+ tt_fd_op(bufferevent_getfd(bev1), ==, EVUTIL_INVALID_SOCKET);
+ tt_ptr_op(bufferevent_get_underlying(bev1), ==, NULL);
+ tt_ptr_op(bufferevent_pair_get_partner(bev1), ==, bev2);
+ tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, bev1);
+ } else {
+ bev1 = bufferevent_new(pair[0], readcb, writecb, errorcb, NULL);
+ bev2 = bufferevent_new(pair[1], readcb, writecb, errorcb, NULL);
+ tt_fd_op(bufferevent_getfd(bev1), ==, pair[0]);
+ tt_ptr_op(bufferevent_get_underlying(bev1), ==, NULL);
+ tt_ptr_op(bufferevent_pair_get_partner(bev1), ==, NULL);
+ tt_ptr_op(bufferevent_pair_get_partner(bev2), ==, NULL);
+ }
+
+ {
+ /* Test getcb. */
+ bufferevent_data_cb r, w;
+ bufferevent_event_cb e;
+ void *a;
+ bufferevent_getcb(bev1, &r, &w, &e, &a);
+ tt_ptr_op(r, ==, readcb);
+ tt_ptr_op(w, ==, writecb);
+ tt_ptr_op(e, ==, errorcb);
+ tt_ptr_op(a, ==, use_pair ? bev1 : NULL);
+ }
+
+ bufferevent_disable(bev1, EV_READ);
+ bufferevent_enable(bev2, EV_READ);
+
+ tt_int_op(bufferevent_get_enabled(bev1), ==, EV_WRITE);
+ tt_int_op(bufferevent_get_enabled(bev2), ==, EV_WRITE|EV_READ);
+
+ for (i = 0; i < (int)sizeof(buffer); i++)
+ buffer[i] = i;
+
+ bufferevent_write(bev1, buffer, sizeof(buffer));
+ if (flush >= 0) {
+ tt_int_op(bufferevent_flush(bev1, EV_WRITE, flush), >=, 0);
+ }
+
+ event_dispatch();
+
+ bufferevent_free(bev2);
+ tt_ptr_op(bufferevent_pair_get_partner(bev1), ==, NULL);
+ bufferevent_free(bev1);
+
+ /** Only pair call errorcb for BEV_FINISHED */
+ if (use_pair && flush == BEV_FINISHED) {
+ expected = -1;
+ }
+ if (test_ok != expected)
+ test_ok = 0;
+end:
+ ;
+}
+
+static void test_bufferevent(void) { test_bufferevent_impl(0, -1); }
+static void test_bufferevent_pair(void) { test_bufferevent_impl(1, -1); }
+
+static void test_bufferevent_flush_normal(void) { test_bufferevent_impl(0, BEV_NORMAL); }
+static void test_bufferevent_flush_flush(void) { test_bufferevent_impl(0, BEV_FLUSH); }
+static void test_bufferevent_flush_finished(void) { test_bufferevent_impl(0, BEV_FINISHED); }
+
+static void test_bufferevent_pair_flush_normal(void) { test_bufferevent_impl(1, BEV_NORMAL); }
+static void test_bufferevent_pair_flush_flush(void) { test_bufferevent_impl(1, BEV_FLUSH); }
+static void test_bufferevent_pair_flush_finished(void) { test_bufferevent_impl(1, BEV_FINISHED); }
+
+#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED) && !defined(__SANITIZE_ADDRESS__)
+/**
+ * Trace lock/unlock/alloc/free for locks.
+ * (More heavier then evthread_debug*)
+ */
+typedef struct
+{
+ void *lock;
+ enum {
+ ALLOC, FREE,
+ } status;
+ size_t locked /** allow recursive locking */;
+} lock_wrapper;
+struct lock_unlock_base
+{
+ /* Original callbacks */
+ struct evthread_lock_callbacks cbs;
+ /* Map of locks */
+ lock_wrapper *locks;
+ size_t nr_locks;
+} lu_base = {
+ .locks = NULL,
+};
+
+static lock_wrapper *lu_find(void *lock_)
+{
+ size_t i;
+ for (i = 0; i < lu_base.nr_locks; ++i) {
+ lock_wrapper *lock = &lu_base.locks[i];
+ if (lock->lock == lock_)
+ return lock;
+ }
+ return NULL;
+}
+
+static void *trace_lock_alloc(unsigned locktype)
+{
+ void *lock;
+ ++lu_base.nr_locks;
+ lu_base.locks = realloc(lu_base.locks,
+ sizeof(lock_wrapper) * lu_base.nr_locks);
+ lock = lu_base.cbs.alloc(locktype);
+ lu_base.locks[lu_base.nr_locks - 1] = (lock_wrapper){ lock, ALLOC, 0 };
+ return lock;
+}
+static void trace_lock_free(void *lock_, unsigned locktype)
+{
+ lock_wrapper *lock = lu_find(lock_);
+ if (!lock || lock->status == FREE || lock->locked) {
+ TT_FAIL(("lock: free error"));
+ } else {
+ lock->status = FREE;
+ lu_base.cbs.free(lock_, locktype);
+ }
+}
+static int trace_lock_lock(unsigned mode, void *lock_)
+{
+ lock_wrapper *lock = lu_find(lock_);
+ if (!lock || lock->status == FREE) {
+ TT_FAIL(("lock: lock error"));
+ return -1;
+ } else {
+ ++lock->locked;
+ return lu_base.cbs.lock(mode, lock_);
+ }
+}
+static int trace_lock_unlock(unsigned mode, void *lock_)
+{
+ lock_wrapper *lock = lu_find(lock_);
+ if (!lock || lock->status == FREE || !lock->locked) {
+ TT_FAIL(("lock: unlock error"));
+ return -1;
+ } else {
+ --lock->locked;
+ return lu_base.cbs.unlock(mode, lock_);
+ }
+}
+static void lock_unlock_free_thread_cbs(void)
+{
+ event_base_free(NULL);
+
+ if (libevent_tests_running_in_debug_mode)
+ libevent_global_shutdown();
+
+ /** drop immutable flag */
+ evthread_set_lock_callbacks(NULL);
+ /** avoid calling of event_global_setup_locks_() for new cbs */
+ libevent_global_shutdown();
+ /** drop immutable flag for non-debug ops (since called after shutdown) */
+ evthread_set_lock_callbacks(NULL);
+}
+
+static int use_lock_unlock_profiler(void)
+{
+ struct evthread_lock_callbacks cbs = {
+ EVTHREAD_LOCK_API_VERSION,
+ EVTHREAD_LOCKTYPE_RECURSIVE,
+ trace_lock_alloc,
+ trace_lock_free,
+ trace_lock_lock,
+ trace_lock_unlock,
+ };
+ memcpy(&lu_base.cbs, evthread_get_lock_callbacks(),
+ sizeof(lu_base.cbs));
+ {
+ lock_unlock_free_thread_cbs();
+
+ evthread_set_lock_callbacks(&cbs);
+ /** re-create debug locks correctly */
+ evthread_enable_lock_debugging();
+
+ event_init();
+ }
+ return 0;
+}
+static void free_lock_unlock_profiler(struct basic_test_data *data)
+{
+ /** fix "held_by" for kqueue */
+ evthread_set_lock_callbacks(NULL);
+
+ lock_unlock_free_thread_cbs();
+ free(lu_base.locks);
+ data->base = NULL;
+}
+
+static void test_bufferevent_pair_release_lock(void *arg)
+{
+ struct basic_test_data *data = arg;
+ use_lock_unlock_profiler();
+ {
+ struct bufferevent *pair[2];
+ if (!bufferevent_pair_new(NULL, BEV_OPT_THREADSAFE, pair)) {
+ bufferevent_free(pair[0]);
+ bufferevent_free(pair[1]);
+ } else
+ tt_abort_perror("bufferevent_pair_new");
+ }
+ free_lock_unlock_profiler(data);
+end:
+ ;
+}
+#endif
+
+/*
+ * test watermarks and bufferevent
+ */
+
+static void
+wm_readcb(struct bufferevent *bev, void *arg)
+{
+ struct evbuffer *evbuf = evbuffer_new();
+ int len = (int)evbuffer_get_length(bev->input);
+ static int nread;
+
+ assert(len >= 10 && len <= 20);
+
+ assert(evbuf != NULL);
+
+ /* gratuitous test of bufferevent_read_buffer */
+ bufferevent_read_buffer(bev, evbuf);
+
+ nread += len;
+ if (nread == 65000) {
+ bufferevent_disable(bev, EV_READ);
+ test_ok++;
+ }
+
+ evbuffer_free(evbuf);
+}
+
+static void
+wm_writecb(struct bufferevent *bev, void *arg)
+{
+ assert(evbuffer_get_length(bev->output) <= 100);
+ if (evbuffer_get_length(bev->output) == 0) {
+ evbuffer_drain(bev->output, evbuffer_get_length(bev->output));
+ test_ok++;
+ }
+}
+
+static void
+wm_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ test_ok = -2;
+}
+
+static void
+test_bufferevent_watermarks_impl(int use_pair)
+{
+ struct bufferevent *bev1 = NULL, *bev2 = NULL;
+ char buffer[65000];
+ size_t low, high;
+ int i;
+ test_ok = 0;
+
+ if (use_pair) {
+ struct bufferevent *pair[2];
+ tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+ bev1 = pair[0];
+ bev2 = pair[1];
+ bufferevent_setcb(bev1, NULL, wm_writecb, errorcb, NULL);
+ bufferevent_setcb(bev2, wm_readcb, NULL, errorcb, NULL);
+ } else {
+ bev1 = bufferevent_new(pair[0], NULL, wm_writecb, wm_errorcb, NULL);
+ bev2 = bufferevent_new(pair[1], wm_readcb, NULL, wm_errorcb, NULL);
+ }
+ tt_assert(bev1);
+ tt_assert(bev2);
+ bufferevent_disable(bev1, EV_READ);
+ bufferevent_enable(bev2, EV_READ);
+
+ /* By default, low watermarks are set to 0 */
+ bufferevent_getwatermark(bev1, EV_READ, &low, NULL);
+ tt_int_op(low, ==, 0);
+ bufferevent_getwatermark(bev2, EV_WRITE, &low, NULL);
+ tt_int_op(low, ==, 0);
+
+ for (i = 0; i < (int)sizeof(buffer); i++)
+ buffer[i] = (char)i;
+
+ /* limit the reading on the receiving bufferevent */
+ bufferevent_setwatermark(bev2, EV_READ, 10, 20);
+
+ bufferevent_getwatermark(bev2, EV_READ, &low, &high);
+ tt_int_op(low, ==, 10);
+ tt_int_op(high, ==, 20);
+
+ /* Tell the sending bufferevent not to notify us till it's down to
+ 100 bytes. */
+ bufferevent_setwatermark(bev1, EV_WRITE, 100, 2000);
+
+ bufferevent_getwatermark(bev1, EV_WRITE, &low, &high);
+ tt_int_op(low, ==, 100);
+ tt_int_op(high, ==, 2000);
+
+ {
+ int r = bufferevent_getwatermark(bev1, EV_WRITE | EV_READ, &low, &high);
+ tt_int_op(r, !=, 0);
+ }
+
+ bufferevent_write(bev1, buffer, sizeof(buffer));
+
+ event_dispatch();
+
+ tt_int_op(test_ok, ==, 2);
+
+ /* The write callback drained all the data from outbuf, so we
+ * should have removed the write event... */
+ tt_assert(!event_pending(&bev2->ev_write, EV_WRITE, NULL));
+
+end:
+ if (bev1)
+ bufferevent_free(bev1);
+ if (bev2)
+ bufferevent_free(bev2);
+}
+
+static void
+test_bufferevent_watermarks(void)
+{
+ test_bufferevent_watermarks_impl(0);
+}
+
+static void
+test_bufferevent_pair_watermarks(void)
+{
+ test_bufferevent_watermarks_impl(1);
+}
+
+/*
+ * Test bufferevent filters
+ */
+
+/* strip an 'x' from each byte */
+
+static enum bufferevent_filter_result
+bufferevent_input_filter(struct evbuffer *src, struct evbuffer *dst,
+ ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+ const unsigned char *buffer;
+ unsigned i;
+
+ buffer = evbuffer_pullup(src, evbuffer_get_length(src));
+ for (i = 0; i < evbuffer_get_length(src); i += 2) {
+ if (buffer[i] == '-')
+ continue;
+
+ assert(buffer[i] == 'x');
+ evbuffer_add(dst, buffer + i + 1, 1);
+ }
+
+ evbuffer_drain(src, i);
+ return (BEV_OK);
+}
+
+/* add an 'x' before each byte */
+
+static enum bufferevent_filter_result
+bufferevent_output_filter(struct evbuffer *src, struct evbuffer *dst,
+ ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+ const unsigned char *buffer;
+ unsigned i;
+ struct bufferevent **bevp = ctx;
+
+ ++test_ok;
+
+ if (test_ok == 1) {
+ buffer = evbuffer_pullup(src, evbuffer_get_length(src));
+ for (i = 0; i < evbuffer_get_length(src); ++i) {
+ evbuffer_add(dst, "x", 1);
+ evbuffer_add(dst, buffer + i, 1);
+ }
+ evbuffer_drain(src, evbuffer_get_length(src));
+ } else {
+ return BEV_ERROR;
+ }
+
+ if (bevp && test_ok == 1) {
+ int prev = ++test_ok;
+ bufferevent_write(*bevp, "-", 1);
+ /* check that during this bufferevent_write()
+ * bufferevent_output_filter() will not be called again */
+ assert(test_ok == prev);
+ --test_ok;
+ }
+
+ return (BEV_OK);
+}
+
+static void
+test_bufferevent_filters_impl(int use_pair, int disable)
+{
+ struct bufferevent *bev1 = NULL, *bev2 = NULL;
+ struct bufferevent *bev1_base = NULL, *bev2_base = NULL;
+ char buffer[8333];
+ int i;
+
+ test_ok = 0;
+
+ if (use_pair) {
+ struct bufferevent *pair[2];
+ tt_assert(0 == bufferevent_pair_new(NULL, 0, pair));
+ bev1 = pair[0];
+ bev2 = pair[1];
+ } else {
+ bev1 = bufferevent_socket_new(NULL, pair[0], 0);
+ bev2 = bufferevent_socket_new(NULL, pair[1], 0);
+ }
+ bev1_base = bev1;
+ bev2_base = bev2;
+
+ for (i = 0; i < (int)sizeof(buffer); i++)
+ buffer[i] = i;
+
+ bev1 = bufferevent_filter_new(bev1, NULL, bufferevent_output_filter,
+ BEV_OPT_CLOSE_ON_FREE, NULL,
+ disable ? &bev1 : NULL);
+
+ bev2 = bufferevent_filter_new(bev2, bufferevent_input_filter,
+ NULL, BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+ bufferevent_setcb(bev1, NULL, writecb, errorcb, NULL);
+ bufferevent_setcb(bev2, readcb, NULL, errorcb, NULL);
+
+ tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev1_base);
+ tt_ptr_op(bufferevent_get_underlying(bev2), ==, bev2_base);
+ tt_fd_op(bufferevent_getfd(bev1), ==, bufferevent_getfd(bev1_base));
+ tt_fd_op(bufferevent_getfd(bev2), ==, bufferevent_getfd(bev2_base));
+
+ bufferevent_disable(bev1, EV_READ);
+ bufferevent_enable(bev2, EV_READ);
+ /* insert some filters */
+ bufferevent_write(bev1, buffer, sizeof(buffer));
+
+ event_dispatch();
+
+ if (test_ok != 3 + !!disable)
+ test_ok = 0;
+
+end:
+ if (bev1)
+ bufferevent_free(bev1);
+ if (bev2)
+ bufferevent_free(bev2);
+
+}
+
+static void test_bufferevent_filters(void)
+{ test_bufferevent_filters_impl(0, 0); }
+static void test_bufferevent_pair_filters(void)
+{ test_bufferevent_filters_impl(1, 0); }
+static void test_bufferevent_filters_disable(void)
+{ test_bufferevent_filters_impl(0, 1); }
+static void test_bufferevent_pair_filters_disable(void)
+{ test_bufferevent_filters_impl(1, 1); }
+
+
+static void
+sender_writecb(struct bufferevent *bev, void *ctx)
+{
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ bufferevent_disable(bev,EV_READ|EV_WRITE);
+ TT_BLATHER(("Flushed %d: freeing it.", (int)bufferevent_getfd(bev)));
+ bufferevent_free(bev);
+ }
+}
+
+static void
+sender_errorcb(struct bufferevent *bev, short what, void *ctx)
+{
+ TT_FAIL(("Got sender error %d",(int)what));
+}
+
+static int bufferevent_connect_test_flags = 0;
+static int bufferevent_trigger_test_flags = 0;
+static int n_strings_read = 0;
+static int n_reads_invoked = 0;
+static int n_events_invoked = 0;
+
+#define TEST_STR "Now is the time for all good events to signal for " \
+ "the good of their protocol"
+static void
+listen_cb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *sa, int socklen, void *arg)
+{
+ struct event_base *base = arg;
+ struct bufferevent *bev;
+ const char s[] = TEST_STR;
+ TT_BLATHER(("Got a request on socket %d", (int)fd ));
+ bev = bufferevent_socket_new(base, fd, bufferevent_connect_test_flags);
+ tt_assert(bev);
+ bufferevent_setcb(bev, NULL, sender_writecb, sender_errorcb, NULL);
+ bufferevent_write(bev, s, sizeof(s));
+end:
+ ;
+}
+
+static evutil_socket_t
+fake_listener_create(struct sockaddr_in *localhost)
+{
+ struct sockaddr *sa = (struct sockaddr *)localhost;
+ evutil_socket_t fd = -1;
+ ev_socklen_t slen = sizeof(*localhost);
+
+ memset(localhost, 0, sizeof(*localhost));
+ localhost->sin_port = 0; /* have the kernel pick a port */
+ localhost->sin_addr.s_addr = htonl(0x7f000001L);
+ localhost->sin_family = AF_INET;
+
+ /* bind, but don't listen or accept. should trigger
+ "Connection refused" reliably on most platforms. */
+ fd = socket(localhost->sin_family, SOCK_STREAM, 0);
+ tt_assert(fd >= 0);
+ tt_assert(bind(fd, sa, slen) == 0);
+ tt_assert(getsockname(fd, sa, &slen) == 0);
+
+ return fd;
+
+end:
+ return -1;
+}
+
+static void
+reader_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ struct event_base *base = ctx;
+ if (what & BEV_EVENT_ERROR) {
+ perror("foobar");
+ TT_FAIL(("got connector error %d", (int)what));
+ return;
+ }
+ if (what & BEV_EVENT_CONNECTED) {
+ TT_BLATHER(("connected on %d", (int)bufferevent_getfd(bev)));
+ bufferevent_enable(bev, EV_READ);
+ }
+ if (what & BEV_EVENT_EOF) {
+ char buf[512];
+ size_t n;
+ n = bufferevent_read(bev, buf, sizeof(buf)-1);
+ tt_int_op(n, >=, 0);
+ buf[n] = '\0';
+ tt_str_op(buf, ==, TEST_STR);
+ if (++n_strings_read == 2)
+ event_base_loopexit(base, NULL);
+ TT_BLATHER(("EOF on %d: %d strings read.",
+ (int)bufferevent_getfd(bev), n_strings_read));
+ }
+end:
+ ;
+}
+
+static void
+reader_eventcb_simple(struct bufferevent *bev, short what, void *ctx)
+{
+ TT_BLATHER(("Read eventcb simple invoked on %d.",
+ (int)bufferevent_getfd(bev)));
+ n_events_invoked++;
+}
+
+static void
+reader_readcb(struct bufferevent *bev, void *ctx)
+{
+ TT_BLATHER(("Read invoked on %d.", (int)bufferevent_getfd(bev)));
+ n_reads_invoked++;
+}
+
+static void
+test_bufferevent_connect(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evconnlistener *lev=NULL;
+ struct bufferevent *bev1=NULL, *bev2=NULL;
+ struct sockaddr_in localhost;
+ struct sockaddr_storage ss;
+ struct sockaddr *sa;
+ ev_socklen_t slen;
+
+ int be_flags=BEV_OPT_CLOSE_ON_FREE;
+
+ if (strstr((char*)data->setup_data, "defer")) {
+ be_flags |= BEV_OPT_DEFER_CALLBACKS;
+ }
+ if (strstr((char*)data->setup_data, "unlocked")) {
+ be_flags |= BEV_OPT_UNLOCK_CALLBACKS;
+ }
+ if (strstr((char*)data->setup_data, "lock")) {
+ be_flags |= BEV_OPT_THREADSAFE;
+ }
+ bufferevent_connect_test_flags = be_flags;
+#ifdef _WIN32
+ if (!strcmp((char*)data->setup_data, "unset_connectex")) {
+ struct win32_extension_fns *ext =
+ (struct win32_extension_fns *)
+ event_get_win32_extension_fns_();
+ ext->ConnectEx = NULL;
+ }
+#endif
+
+ memset(&localhost, 0, sizeof(localhost));
+
+ localhost.sin_port = 0; /* pick-a-port */
+ localhost.sin_addr.s_addr = htonl(0x7f000001L);
+ localhost.sin_family = AF_INET;
+ sa = (struct sockaddr *)&localhost;
+ lev = evconnlistener_new_bind(data->base, listen_cb, data->base,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+ 16, sa, sizeof(localhost));
+ tt_assert(lev);
+
+ sa = (struct sockaddr *)&ss;
+ slen = sizeof(ss);
+ if (regress_get_listener_addr(lev, sa, &slen) < 0) {
+ tt_abort_perror("getsockname");
+ }
+
+ tt_assert(!evconnlistener_enable(lev));
+ bev1 = bufferevent_socket_new(data->base, -1, be_flags);
+ bev2 = bufferevent_socket_new(data->base, -1, be_flags);
+ tt_assert(bev1);
+ tt_assert(bev2);
+ bufferevent_setcb(bev1, reader_readcb,NULL, reader_eventcb, data->base);
+ bufferevent_setcb(bev2, reader_readcb,NULL, reader_eventcb, data->base);
+
+ bufferevent_enable(bev1, EV_READ);
+ bufferevent_enable(bev2, EV_READ);
+
+ tt_want(!bufferevent_socket_connect(bev1, sa, sizeof(localhost)));
+ tt_want(!bufferevent_socket_connect(bev2, sa, sizeof(localhost)));
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(n_strings_read, ==, 2);
+ tt_int_op(n_reads_invoked, >=, 2);
+end:
+ if (lev)
+ evconnlistener_free(lev);
+
+ if (bev1)
+ bufferevent_free(bev1);
+
+ if (bev2)
+ bufferevent_free(bev2);
+}
+
+static void
+close_socket_cb(evutil_socket_t fd, short what, void *arg)
+{
+ evutil_socket_t *fdp = arg;
+ if (*fdp >= 0) {
+ evutil_closesocket(*fdp);
+ *fdp = -1;
+ }
+}
+
+static void
+test_bufferevent_connect_fail_eventcb(void *arg)
+{
+ struct basic_test_data *data = arg;
+ int flags = BEV_OPT_CLOSE_ON_FREE | (long)data->setup_data;
+ struct event close_listener_event;
+ struct bufferevent *bev = NULL;
+ struct evconnlistener *lev = NULL;
+ struct sockaddr_in localhost;
+ struct timeval close_timeout = { 0, 300000 };
+ ev_socklen_t slen = sizeof(localhost);
+ evutil_socket_t fake_listener = -1;
+ int r;
+
+ fake_listener = fake_listener_create(&localhost);
+
+ tt_int_op(n_events_invoked, ==, 0);
+
+ bev = bufferevent_socket_new(data->base, -1, flags);
+ tt_assert(bev);
+ bufferevent_setcb(bev, reader_readcb, reader_readcb,
+ reader_eventcb_simple, data->base);
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+ tt_int_op(n_events_invoked, ==, 0);
+ tt_int_op(n_reads_invoked, ==, 0);
+
+ /** @see also test_bufferevent_connect_fail() */
+ r = bufferevent_socket_connect(bev, (struct sockaddr *)&localhost, slen);
+ /* XXXX we'd like to test the '0' case everywhere, but FreeBSD tells
+ * detects the error immediately, which is not really wrong of it. */
+ tt_want(r == 0 || r == -1);
+
+ tt_int_op(n_events_invoked, ==, 0);
+ tt_int_op(n_reads_invoked, ==, 0);
+
+ /* Close the listener socket after a delay. This should trigger
+ "connection refused" on some other platforms, including OSX. */
+ evtimer_assign(&close_listener_event, data->base, close_socket_cb,
+ &fake_listener);
+ event_add(&close_listener_event, &close_timeout);
+
+ event_base_dispatch(data->base);
+ tt_int_op(n_events_invoked, ==, 1);
+ tt_int_op(n_reads_invoked, ==, 0);
+
+end:
+ if (lev)
+ evconnlistener_free(lev);
+ if (bev)
+ bufferevent_free(bev);
+ if (fake_listener >= 0)
+ evutil_closesocket(fake_listener);
+}
+
+static void
+want_fail_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ struct event_base *base = ctx;
+ const char *err;
+ evutil_socket_t s;
+
+ if (what & BEV_EVENT_ERROR) {
+ s = bufferevent_getfd(bev);
+ err = evutil_socket_error_to_string(evutil_socket_geterror(s));
+ TT_BLATHER(("connection failure on "EV_SOCK_FMT": %s",
+ EV_SOCK_ARG(s), err));
+ test_ok = 1;
+ } else {
+ TT_FAIL(("didn't fail? what %hd", what));
+ }
+
+ event_base_loopexit(base, NULL);
+}
+
+static void
+test_bufferevent_connect_fail(void *arg)
+{
+ struct basic_test_data *data = (struct basic_test_data *)arg;
+ struct bufferevent *bev=NULL;
+ struct event close_listener_event;
+ int close_listener_event_added = 0;
+ struct timeval close_timeout = { 0, 300000 };
+ struct sockaddr_in localhost;
+ ev_socklen_t slen = sizeof(localhost);
+ evutil_socket_t fake_listener = -1;
+ int r;
+
+ test_ok = 0;
+
+ fake_listener = fake_listener_create(&localhost);
+ bev = bufferevent_socket_new(data->base, -1,
+ BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS);
+ tt_assert(bev);
+ bufferevent_setcb(bev, NULL, NULL, want_fail_eventcb, data->base);
+
+ r = bufferevent_socket_connect(bev, (struct sockaddr *)&localhost, slen);
+ /* XXXX we'd like to test the '0' case everywhere, but FreeBSD tells
+ * detects the error immediately, which is not really wrong of it. */
+ tt_want(r == 0 || r == -1);
+
+ /* Close the listener socket after a delay. This should trigger
+ "connection refused" on some other platforms, including OSX. */
+ evtimer_assign(&close_listener_event, data->base, close_socket_cb,
+ &fake_listener);
+ event_add(&close_listener_event, &close_timeout);
+ close_listener_event_added = 1;
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 1);
+
+end:
+ if (fake_listener >= 0)
+ evutil_closesocket(fake_listener);
+
+ if (bev)
+ bufferevent_free(bev);
+
+ if (close_listener_event_added)
+ event_del(&close_listener_event);
+}
+
+struct timeout_cb_result {
+ struct timeval read_timeout_at;
+ struct timeval write_timeout_at;
+ struct timeval last_wrote_at;
+ struct timeval last_read_at;
+ int n_read_timeouts;
+ int n_write_timeouts;
+ int total_calls;
+};
+
+static void
+bev_timeout_read_cb(struct bufferevent *bev, void *arg)
+{
+ struct timeout_cb_result *res = arg;
+ evutil_gettimeofday(&res->last_read_at, NULL);
+}
+static void
+bev_timeout_write_cb(struct bufferevent *bev, void *arg)
+{
+ struct timeout_cb_result *res = arg;
+ evutil_gettimeofday(&res->last_wrote_at, NULL);
+}
+static void
+bev_timeout_event_cb(struct bufferevent *bev, short what, void *arg)
+{
+ struct timeout_cb_result *res = arg;
+ ++res->total_calls;
+
+ if ((what & (BEV_EVENT_READING|BEV_EVENT_TIMEOUT))
+ == (BEV_EVENT_READING|BEV_EVENT_TIMEOUT)) {
+ evutil_gettimeofday(&res->read_timeout_at, NULL);
+ ++res->n_read_timeouts;
+ }
+ if ((what & (BEV_EVENT_WRITING|BEV_EVENT_TIMEOUT))
+ == (BEV_EVENT_WRITING|BEV_EVENT_TIMEOUT)) {
+ evutil_gettimeofday(&res->write_timeout_at, NULL);
+ ++res->n_write_timeouts;
+ }
+}
+
+static void
+test_bufferevent_timeouts(void *arg)
+{
+ /* "arg" is a string containing "pair" and/or "filter". */
+ struct bufferevent *bev1 = NULL, *bev2 = NULL;
+ struct basic_test_data *data = arg;
+ int use_pair = 0, use_filter = 0;
+ struct timeval tv_w, tv_r, started_at;
+ struct timeout_cb_result res1, res2;
+
+ memset(&res1, 0, sizeof(res1));
+ memset(&res2, 0, sizeof(res2));
+
+ if (strstr((char*)data->setup_data, "pair"))
+ use_pair = 1;
+ if (strstr((char*)data->setup_data, "filter"))
+ use_filter = 1;
+
+ if (use_pair) {
+ struct bufferevent *p[2];
+ tt_int_op(0, ==, bufferevent_pair_new(data->base, 0, p));
+ bev1 = p[0];
+ bev2 = p[1];
+ } else {
+ bev1 = bufferevent_socket_new(data->base, data->pair[0], 0);
+ bev2 = bufferevent_socket_new(data->base, data->pair[1], 0);
+ }
+ tt_assert(bev1);
+ tt_assert(bev2);
+
+ if (use_filter) {
+ struct bufferevent *bevf1, *bevf2;
+ bevf1 = bufferevent_filter_new(bev1, NULL, NULL,
+ BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+ bevf2 = bufferevent_filter_new(bev2, NULL, NULL,
+ BEV_OPT_CLOSE_ON_FREE, NULL, NULL);
+ tt_assert(bevf1);
+ tt_assert(bevf2);
+ bev1 = bevf1;
+ bev2 = bevf2;
+ }
+
+ /* Do this nice and early. */
+ bufferevent_disable(bev2, EV_READ);
+
+ /* bev1 will try to write and read. Both will time out. */
+ evutil_gettimeofday(&started_at, NULL);
+ tv_w.tv_sec = tv_r.tv_sec = 0;
+ tv_w.tv_usec = 100*1000;
+ tv_r.tv_usec = 150*1000;
+ bufferevent_setcb(bev1, bev_timeout_read_cb, bev_timeout_write_cb,
+ bev_timeout_event_cb, &res1);
+ bufferevent_set_timeouts(bev1, &tv_r, &tv_w);
+ bufferevent_write(bev1, "ABCDEFG", 7);
+ bufferevent_enable(bev1, EV_READ|EV_WRITE);
+
+ /* bev2 has nothing to say, and isn't listening. */
+ bufferevent_setcb(bev2, bev_timeout_read_cb, bev_timeout_write_cb,
+ bev_timeout_event_cb, &res2);
+ tv_w.tv_sec = tv_r.tv_sec = 0;
+ tv_w.tv_usec = 200*1000;
+ tv_r.tv_usec = 100*1000;
+ bufferevent_set_timeouts(bev2, &tv_r, &tv_w);
+ bufferevent_enable(bev2, EV_WRITE);
+
+ tv_r.tv_sec = 0;
+ tv_r.tv_usec = 350000;
+
+ event_base_loopexit(data->base, &tv_r);
+ event_base_dispatch(data->base);
+
+ /* XXXX Test that actually reading or writing a little resets the
+ * timeouts. */
+
+ tt_want(res1.total_calls == 2);
+ tt_want(res1.n_read_timeouts == 1);
+ tt_want(res1.n_write_timeouts == 1);
+ tt_want(res2.total_calls == !(use_pair && !use_filter));
+ tt_want(res2.n_write_timeouts == !(use_pair && !use_filter));
+ tt_want(!res2.n_read_timeouts);
+
+ test_timeval_diff_eq(&started_at, &res1.read_timeout_at, 150);
+ test_timeval_diff_eq(&started_at, &res1.write_timeout_at, 100);
+
+#define tt_assert_timeval_empty(tv) do { \
+ tt_int_op((tv).tv_sec, ==, 0); \
+ tt_int_op((tv).tv_usec, ==, 0); \
+} while(0)
+ tt_assert_timeval_empty(res1.last_read_at);
+ tt_assert_timeval_empty(res2.last_read_at);
+ tt_assert_timeval_empty(res2.last_wrote_at);
+ tt_assert_timeval_empty(res2.last_wrote_at);
+#undef tt_assert_timeval_empty
+
+end:
+ if (bev1)
+ bufferevent_free(bev1);
+ if (bev2)
+ bufferevent_free(bev2);
+}
+
+static void
+trigger_failure_cb(evutil_socket_t fd, short what, void *ctx)
+{
+ TT_FAIL(("The triggered callback did not fire or the machine is really slow (try increasing timeout)."));
+}
+
+static void
+trigger_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ struct event_base *base = ctx;
+ if (what == ~0) {
+ TT_BLATHER(("Event successfully triggered."));
+ event_base_loopexit(base, NULL);
+ return;
+ }
+ reader_eventcb(bev, what, ctx);
+}
+
+static void
+trigger_readcb_triggered(struct bufferevent *bev, void *ctx)
+{
+ TT_BLATHER(("Read successfully triggered."));
+ n_reads_invoked++;
+ bufferevent_trigger_event(bev, ~0, bufferevent_trigger_test_flags);
+}
+
+static void
+trigger_readcb(struct bufferevent *bev, void *ctx)
+{
+ struct timeval timeout = { 30, 0 };
+ struct event_base *base = ctx;
+ size_t low, high, len;
+ int expected_reads;
+
+ TT_BLATHER(("Read invoked on %d.", (int)bufferevent_getfd(bev)));
+ expected_reads = ++n_reads_invoked;
+
+ bufferevent_setcb(bev, trigger_readcb_triggered, NULL, trigger_eventcb, ctx);
+
+ bufferevent_getwatermark(bev, EV_READ, &low, &high);
+ len = evbuffer_get_length(bufferevent_get_input(bev));
+
+ bufferevent_setwatermark(bev, EV_READ, len + 1, 0);
+ bufferevent_trigger(bev, EV_READ, bufferevent_trigger_test_flags);
+ /* no callback expected */
+ tt_int_op(n_reads_invoked, ==, expected_reads);
+
+ if ((bufferevent_trigger_test_flags & BEV_TRIG_DEFER_CALLBACKS) ||
+ (bufferevent_connect_test_flags & BEV_OPT_DEFER_CALLBACKS)) {
+ /* will be deferred */
+ } else {
+ expected_reads++;
+ }
+
+ event_base_once(base, -1, EV_TIMEOUT, trigger_failure_cb, NULL, &timeout);
+
+ bufferevent_trigger(bev, EV_READ,
+ bufferevent_trigger_test_flags | BEV_TRIG_IGNORE_WATERMARKS);
+ tt_int_op(n_reads_invoked, ==, expected_reads);
+
+ bufferevent_setwatermark(bev, EV_READ, low, high);
+end:
+ ;
+}
+
+static void
+test_bufferevent_trigger(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evconnlistener *lev=NULL;
+ struct bufferevent *bev=NULL;
+ struct sockaddr_in localhost;
+ struct sockaddr_storage ss;
+ struct sockaddr *sa;
+ ev_socklen_t slen;
+
+ int be_flags=BEV_OPT_CLOSE_ON_FREE;
+ int trig_flags=0;
+
+ if (strstr((char*)data->setup_data, "defer")) {
+ be_flags |= BEV_OPT_DEFER_CALLBACKS;
+ }
+ bufferevent_connect_test_flags = be_flags;
+
+ if (strstr((char*)data->setup_data, "postpone")) {
+ trig_flags |= BEV_TRIG_DEFER_CALLBACKS;
+ }
+ bufferevent_trigger_test_flags = trig_flags;
+
+ memset(&localhost, 0, sizeof(localhost));
+
+ localhost.sin_port = 0; /* pick-a-port */
+ localhost.sin_addr.s_addr = htonl(0x7f000001L);
+ localhost.sin_family = AF_INET;
+ sa = (struct sockaddr *)&localhost;
+ lev = evconnlistener_new_bind(data->base, listen_cb, data->base,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+ 16, sa, sizeof(localhost));
+ tt_assert(lev);
+
+ sa = (struct sockaddr *)&ss;
+ slen = sizeof(ss);
+ if (regress_get_listener_addr(lev, sa, &slen) < 0) {
+ tt_abort_perror("getsockname");
+ }
+
+ tt_assert(!evconnlistener_enable(lev));
+ bev = bufferevent_socket_new(data->base, -1, be_flags);
+ tt_assert(bev);
+ bufferevent_setcb(bev, trigger_readcb, NULL, trigger_eventcb, data->base);
+
+ bufferevent_enable(bev, EV_READ);
+
+ tt_want(!bufferevent_socket_connect(bev, sa, sizeof(localhost)));
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(n_reads_invoked, ==, 2);
+end:
+ if (lev)
+ evconnlistener_free(lev);
+
+ if (bev)
+ bufferevent_free(bev);
+}
+
+static void
+test_bufferevent_socket_filter_inactive(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev = NULL, *bevf = NULL;
+
+ bev = bufferevent_socket_new(data->base, -1, 0);
+ tt_assert(bev);
+ bevf = bufferevent_filter_new(bev, NULL, NULL, 0, NULL, NULL);
+ tt_assert(bevf);
+
+end:
+ if (bevf)
+ bufferevent_free(bevf);
+ if (bev)
+ bufferevent_free(bev);
+}
+
+static void
+pair_flush_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ int *callback_what = ctx;
+ *callback_what = what;
+}
+
+static void
+test_bufferevent_pair_flush(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *pair[2];
+ struct bufferevent *bev1 = NULL;
+ struct bufferevent *bev2 = NULL;
+ int callback_what = 0;
+
+ tt_assert(0 == bufferevent_pair_new(data->base, 0, pair));
+ bev1 = pair[0];
+ bev2 = pair[1];
+ tt_assert(0 == bufferevent_enable(bev1, EV_WRITE));
+ tt_assert(0 == bufferevent_enable(bev2, EV_READ));
+
+ bufferevent_setcb(bev2, NULL, NULL, pair_flush_eventcb, &callback_what);
+
+ bufferevent_flush(bev1, EV_WRITE, BEV_FINISHED);
+
+ event_base_loop(data->base, EVLOOP_ONCE);
+
+ tt_assert(callback_what == (BEV_EVENT_READING | BEV_EVENT_EOF));
+
+end:
+ if (bev1)
+ bufferevent_free(bev1);
+ if (bev2)
+ bufferevent_free(bev2);
+}
+
+struct bufferevent_filter_data_stuck {
+ size_t header_size;
+ size_t total_read;
+};
+
+static void
+bufferevent_filter_data_stuck_readcb(struct bufferevent *bev, void *arg)
+{
+ struct bufferevent_filter_data_stuck *filter_data = arg;
+ struct evbuffer *input = bufferevent_get_input(bev);
+ size_t read_size = evbuffer_get_length(input);
+ evbuffer_drain(input, read_size);
+ filter_data->total_read += read_size;
+}
+
+/**
+ * This filter prepends header once before forwarding data.
+ */
+static enum bufferevent_filter_result
+bufferevent_filter_data_stuck_inputcb(
+ struct evbuffer *src, struct evbuffer *dst, ev_ssize_t dst_limit,
+ enum bufferevent_flush_mode mode, void *ctx)
+{
+ struct bufferevent_filter_data_stuck *filter_data = ctx;
+ static int header_inserted = 0;
+ size_t payload_size;
+ size_t header_size = 0;
+
+ if (!header_inserted) {
+ char *header = calloc(filter_data->header_size, 1);
+ evbuffer_add(dst, header, filter_data->header_size);
+ free(header);
+ header_size = filter_data->header_size;
+ header_inserted = 1;
+ }
+
+ payload_size = evbuffer_get_length(src);
+ if (payload_size > dst_limit - header_size) {
+ payload_size = dst_limit - header_size;
+ }
+
+ tt_int_op(payload_size, ==, evbuffer_remove_buffer(src, dst, payload_size));
+
+end:
+ return BEV_OK;
+}
+
+static void
+test_bufferevent_filter_data_stuck(void *arg)
+{
+ const size_t read_high_wm = 4096;
+ struct bufferevent_filter_data_stuck filter_data;
+ struct basic_test_data *data = arg;
+ struct bufferevent *pair[2];
+ struct bufferevent *filter = NULL;
+
+ int options = BEV_OPT_CLOSE_ON_FREE | BEV_OPT_DEFER_CALLBACKS;
+
+ char payload[4096];
+ int payload_size = sizeof(payload);
+
+ memset(&filter_data, 0, sizeof(filter_data));
+ filter_data.header_size = 20;
+
+ tt_assert(bufferevent_pair_new(data->base, options, pair) == 0);
+
+ bufferevent_setwatermark(pair[0], EV_READ, 0, read_high_wm);
+ bufferevent_setwatermark(pair[1], EV_READ, 0, read_high_wm);
+
+ tt_assert(
+ filter =
+ bufferevent_filter_new(pair[1],
+ bufferevent_filter_data_stuck_inputcb,
+ NULL,
+ options,
+ NULL,
+ &filter_data));
+
+ bufferevent_setcb(filter,
+ bufferevent_filter_data_stuck_readcb,
+ NULL,
+ NULL,
+ &filter_data);
+
+ tt_assert(bufferevent_enable(filter, EV_READ|EV_WRITE) == 0);
+
+ bufferevent_setwatermark(filter, EV_READ, 0, read_high_wm);
+
+ tt_assert(bufferevent_write(pair[0], payload, sizeof(payload)) == 0);
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(filter_data.total_read, ==, payload_size + filter_data.header_size);
+end:
+ if (pair[0])
+ bufferevent_free(pair[0]);
+ if (filter)
+ bufferevent_free(filter);
+}
+
+struct testcase_t bufferevent_testcases[] = {
+
+ LEGACY(bufferevent, TT_ISOLATED),
+ LEGACY(bufferevent_pair, TT_ISOLATED),
+ LEGACY(bufferevent_flush_normal, TT_ISOLATED),
+ LEGACY(bufferevent_flush_flush, TT_ISOLATED),
+ LEGACY(bufferevent_flush_finished, TT_ISOLATED),
+ LEGACY(bufferevent_pair_flush_normal, TT_ISOLATED),
+ LEGACY(bufferevent_pair_flush_flush, TT_ISOLATED),
+ LEGACY(bufferevent_pair_flush_finished, TT_ISOLATED),
+#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED) && !defined(__SANITIZE_ADDRESS__)
+ { "bufferevent_pair_release_lock", test_bufferevent_pair_release_lock,
+ TT_FORK|TT_ISOLATED|TT_NEED_THREADS|TT_NEED_BASE|TT_LEGACY|TT_NO_LOGS,
+ &basic_setup, NULL },
+#endif
+ LEGACY(bufferevent_watermarks, TT_ISOLATED),
+ LEGACY(bufferevent_pair_watermarks, TT_ISOLATED),
+ LEGACY(bufferevent_filters, TT_ISOLATED),
+ LEGACY(bufferevent_pair_filters, TT_ISOLATED),
+ LEGACY(bufferevent_filters_disable, TT_ISOLATED),
+ LEGACY(bufferevent_pair_filters_disable, TT_ISOLATED),
+ { "bufferevent_connect", test_bufferevent_connect, TT_FORK|TT_NEED_BASE,
+ &basic_setup, (void*)"" },
+ { "bufferevent_connect_defer", test_bufferevent_connect,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"defer" },
+ { "bufferevent_connect_lock", test_bufferevent_connect,
+ TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup, (void*)"lock" },
+ { "bufferevent_connect_lock_defer", test_bufferevent_connect,
+ TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+ (void*)"defer lock" },
+ { "bufferevent_connect_unlocked_cbs", test_bufferevent_connect,
+ TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+ (void*)"lock defer unlocked" },
+ { "bufferevent_connect_fail", test_bufferevent_connect_fail,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "bufferevent_timeout", test_bufferevent_timeouts,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"" },
+ { "bufferevent_timeout_pair", test_bufferevent_timeouts,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"pair" },
+ { "bufferevent_timeout_filter", test_bufferevent_timeouts,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter" },
+ { "bufferevent_timeout_filter_pair", test_bufferevent_timeouts,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"filter pair" },
+ { "bufferevent_trigger", test_bufferevent_trigger, TT_FORK|TT_NEED_BASE,
+ &basic_setup, (void*)"" },
+ { "bufferevent_trigger_defer", test_bufferevent_trigger,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)"defer" },
+ { "bufferevent_trigger_postpone", test_bufferevent_trigger,
+ TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+ (void*)"postpone" },
+ { "bufferevent_trigger_defer_postpone", test_bufferevent_trigger,
+ TT_FORK|TT_NEED_BASE|TT_NEED_THREADS, &basic_setup,
+ (void*)"defer postpone" },
+#ifdef EVENT__HAVE_LIBZ
+ LEGACY(bufferevent_zlib, TT_ISOLATED),
+#else
+ { "bufferevent_zlib", NULL, TT_SKIP, NULL, NULL },
+#endif
+
+ { "bufferevent_connect_fail_eventcb_defer",
+ test_bufferevent_connect_fail_eventcb,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (void*)BEV_OPT_DEFER_CALLBACKS },
+ { "bufferevent_connect_fail_eventcb",
+ test_bufferevent_connect_fail_eventcb,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+
+ { "bufferevent_socket_filter_inactive",
+ test_bufferevent_socket_filter_inactive,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "bufferevent_pair_flush",
+ test_bufferevent_pair_flush,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "bufferevent_filter_data_stuck",
+ test_bufferevent_filter_data_stuck,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+
+ END_OF_TESTCASES,
+};
+
+#define TT_IOCP (TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP)
+#define TT_IOCP_LEGACY (TT_ISOLATED|TT_ENABLE_IOCP)
+struct testcase_t bufferevent_iocp_testcases[] = {
+ LEGACY(bufferevent, TT_IOCP_LEGACY),
+ LEGACY(bufferevent_flush_normal, TT_ISOLATED),
+ LEGACY(bufferevent_flush_flush, TT_ISOLATED),
+ LEGACY(bufferevent_flush_finished, TT_ISOLATED),
+ LEGACY(bufferevent_watermarks, TT_IOCP_LEGACY),
+ LEGACY(bufferevent_filters, TT_IOCP_LEGACY),
+ LEGACY(bufferevent_filters_disable, TT_IOCP_LEGACY),
+
+ { "bufferevent_connect", test_bufferevent_connect,
+ TT_IOCP, &basic_setup, (void*)"" },
+ { "bufferevent_connect_defer", test_bufferevent_connect,
+ TT_IOCP, &basic_setup, (void*)"defer" },
+ { "bufferevent_connect_lock", test_bufferevent_connect,
+ TT_IOCP, &basic_setup, (void*)"lock" },
+ { "bufferevent_connect_lock_defer", test_bufferevent_connect,
+ TT_IOCP, &basic_setup, (void*)"defer lock" },
+ { "bufferevent_connect_fail", test_bufferevent_connect_fail,
+ TT_IOCP, &basic_setup, NULL },
+ { "bufferevent_connect_nonblocking", test_bufferevent_connect,
+ TT_IOCP, &basic_setup, (void*)"unset_connectex" },
+
+ { "bufferevent_connect_fail_eventcb_defer",
+ test_bufferevent_connect_fail_eventcb,
+ TT_IOCP, &basic_setup, (void*)BEV_OPT_DEFER_CALLBACKS },
+ { "bufferevent_connect_fail_eventcb",
+ test_bufferevent_connect_fail_eventcb, TT_IOCP, &basic_setup, NULL },
+
+ END_OF_TESTCASES,
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_dns.c b/ipc/chromium/src/third_party/libevent/test/regress_dns.c
new file mode 100644
index 0000000000..9a8bff4f15
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_dns.c
@@ -0,0 +1,2518 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#ifdef EVENT__HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+
+#include "event2/dns.h"
+#include "event2/dns_compat.h"
+#include "event2/dns_struct.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/event_struct.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/bufferevent.h"
+#include <event2/thread.h>
+#include "log-internal.h"
+#include "evthread-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+#include "regress_thread.h"
+
+#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
+
+static int dns_ok = 0;
+static int dns_got_cancel = 0;
+static int dns_err = 0;
+
+
+static void
+dns_gethostbyname_cb(int result, char type, int count, int ttl,
+ void *addresses, void *arg)
+{
+ dns_ok = dns_err = 0;
+
+ if (result == DNS_ERR_TIMEOUT) {
+ printf("[Timed out] ");
+ dns_err = result;
+ goto out;
+ }
+
+ if (result != DNS_ERR_NONE) {
+ printf("[Error code %d] ", result);
+ goto out;
+ }
+
+ TT_BLATHER(("type: %d, count: %d, ttl: %d: ", type, count, ttl));
+
+ switch (type) {
+ case DNS_IPv6_AAAA: {
+#if defined(EVENT__HAVE_STRUCT_IN6_ADDR) && defined(EVENT__HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+ struct in6_addr *in6_addrs = addresses;
+ char buf[INET6_ADDRSTRLEN+1];
+ int i;
+ /* a resolution that's not valid does not help */
+ if (ttl < 0)
+ goto out;
+ for (i = 0; i < count; ++i) {
+ const char *b = evutil_inet_ntop(AF_INET6, &in6_addrs[i], buf,sizeof(buf));
+ if (b)
+ TT_BLATHER(("%s ", b));
+ else
+ TT_BLATHER(("%s ", strerror(errno)));
+ }
+#endif
+ break;
+ }
+ case DNS_IPv4_A: {
+ struct in_addr *in_addrs = addresses;
+ int i;
+ /* a resolution that's not valid does not help */
+ if (ttl < 0)
+ goto out;
+ for (i = 0; i < count; ++i)
+ TT_BLATHER(("%s ", inet_ntoa(in_addrs[i])));
+ break;
+ }
+ case DNS_PTR:
+ /* may get at most one PTR */
+ if (count != 1)
+ goto out;
+
+ TT_BLATHER(("%s ", *(char **)addresses));
+ break;
+ default:
+ goto out;
+ }
+
+ dns_ok = type;
+
+out:
+ if (arg == NULL)
+ event_loopexit(NULL);
+ else
+ event_base_loopexit((struct event_base *)arg, NULL);
+}
+
+static void
+dns_gethostbyname(void)
+{
+ dns_ok = 0;
+ evdns_resolve_ipv4("www.monkey.org", 0, dns_gethostbyname_cb, NULL);
+ event_dispatch();
+
+ tt_int_op(dns_ok, ==, DNS_IPv4_A);
+ test_ok = dns_ok;
+end:
+ ;
+}
+
+static void
+dns_gethostbyname6(void)
+{
+ dns_ok = 0;
+ evdns_resolve_ipv6("www.ietf.org", 0, dns_gethostbyname_cb, NULL);
+ event_dispatch();
+
+ if (!dns_ok && dns_err == DNS_ERR_TIMEOUT) {
+ tt_skip();
+ }
+
+ tt_int_op(dns_ok, ==, DNS_IPv6_AAAA);
+ test_ok = 1;
+end:
+ ;
+}
+
+static void
+dns_gethostbyaddr(void)
+{
+ struct in_addr in;
+ in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
+ dns_ok = 0;
+ evdns_resolve_reverse(&in, 0, dns_gethostbyname_cb, NULL);
+ event_dispatch();
+
+ tt_int_op(dns_ok, ==, DNS_PTR);
+ test_ok = dns_ok;
+end:
+ ;
+}
+
+static void
+dns_resolve_reverse(void *ptr)
+{
+ struct in_addr in;
+ struct event_base *base = event_base_new();
+ struct evdns_base *dns = evdns_base_new(base, EVDNS_BASE_INITIALIZE_NAMESERVERS);
+ struct evdns_request *req = NULL;
+
+ tt_assert(base);
+ tt_assert(dns);
+ in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
+ dns_ok = 0;
+
+ req = evdns_base_resolve_reverse(
+ dns, &in, 0, dns_gethostbyname_cb, base);
+ tt_assert(req);
+
+ event_base_dispatch(base);
+
+ tt_int_op(dns_ok, ==, DNS_PTR);
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+ if (base)
+ event_base_free(base);
+}
+
+static int n_server_responses = 0;
+
+static void
+dns_server_request_cb(struct evdns_server_request *req, void *data)
+{
+ int i, r;
+ const char TEST_ARPA[] = "11.11.168.192.in-addr.arpa";
+ const char TEST_IN6[] =
+ "f.e.f.e." "0.0.0.0." "0.0.0.0." "1.1.1.1."
+ "a.a.a.a." "0.0.0.0." "0.0.0.0." "0.f.f.f.ip6.arpa";
+
+ for (i = 0; i < req->nquestions; ++i) {
+ const int qtype = req->questions[i]->type;
+ const int qclass = req->questions[i]->dns_question_class;
+ const char *qname = req->questions[i]->name;
+
+ struct in_addr ans;
+ ans.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
+ if (qtype == EVDNS_TYPE_A &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
+ r = evdns_server_request_add_a_reply(req, qname,
+ 1, &ans.s_addr, 12345);
+ if (r<0)
+ dns_ok = 0;
+ } else if (qtype == EVDNS_TYPE_AAAA &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
+ char addr6[17] = "abcdefghijklmnop";
+ r = evdns_server_request_add_aaaa_reply(req,
+ qname, 1, addr6, 123);
+ if (r<0)
+ dns_ok = 0;
+ } else if (qtype == EVDNS_TYPE_PTR &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, TEST_ARPA)) {
+ r = evdns_server_request_add_ptr_reply(req, NULL,
+ qname, "ZZ.EXAMPLE.COM", 54321);
+ if (r<0)
+ dns_ok = 0;
+ } else if (qtype == EVDNS_TYPE_PTR &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, TEST_IN6)){
+ r = evdns_server_request_add_ptr_reply(req, NULL,
+ qname,
+ "ZZ-INET6.EXAMPLE.COM", 54322);
+ if (r<0)
+ dns_ok = 0;
+ } else if (qtype == EVDNS_TYPE_A &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, "drop.example.com")) {
+ if (evdns_server_request_drop(req)<0)
+ dns_ok = 0;
+ return;
+ } else {
+ printf("Unexpected question %d %d \"%s\" ",
+ qtype, qclass, qname);
+ dns_ok = 0;
+ }
+ }
+ r = evdns_server_request_respond(req, 0);
+ if (r<0) {
+ printf("Couldn't send reply. ");
+ dns_ok = 0;
+ }
+}
+
+static void
+dns_server_gethostbyname_cb(int result, char type, int count, int ttl,
+ void *addresses, void *arg)
+{
+ if (result == DNS_ERR_CANCEL) {
+ if (arg != (void*)(char*)90909) {
+ printf("Unexpected cancelation");
+ dns_ok = 0;
+ }
+ dns_got_cancel = 1;
+ goto out;
+ }
+ if (result != DNS_ERR_NONE) {
+ printf("Unexpected result %d. ", result);
+ dns_ok = 0;
+ goto out;
+ }
+ if (count != 1) {
+ printf("Unexpected answer count %d. ", count);
+ dns_ok = 0;
+ goto out;
+ }
+ switch (type) {
+ case DNS_IPv4_A: {
+ struct in_addr *in_addrs = addresses;
+ if (in_addrs[0].s_addr != htonl(0xc0a80b0bUL) || ttl != 12345) {
+ printf("Bad IPv4 response \"%s\" %d. ",
+ inet_ntoa(in_addrs[0]), ttl);
+ dns_ok = 0;
+ goto out;
+ }
+ break;
+ }
+ case DNS_IPv6_AAAA: {
+#if defined (EVENT__HAVE_STRUCT_IN6_ADDR) && defined(EVENT__HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
+ struct in6_addr *in6_addrs = addresses;
+ char buf[INET6_ADDRSTRLEN+1];
+ if (memcmp(&in6_addrs[0].s6_addr, "abcdefghijklmnop", 16)
+ || ttl != 123) {
+ const char *b = evutil_inet_ntop(AF_INET6, &in6_addrs[0],buf,sizeof(buf));
+ printf("Bad IPv6 response \"%s\" %d. ", b, ttl);
+ dns_ok = 0;
+ goto out;
+ }
+#endif
+ break;
+ }
+ case DNS_PTR: {
+ char **addrs = addresses;
+ if (arg != (void*)6) {
+ if (strcmp(addrs[0], "ZZ.EXAMPLE.COM") ||
+ ttl != 54321) {
+ printf("Bad PTR response \"%s\" %d. ",
+ addrs[0], ttl);
+ dns_ok = 0;
+ goto out;
+ }
+ } else {
+ if (strcmp(addrs[0], "ZZ-INET6.EXAMPLE.COM") ||
+ ttl != 54322) {
+ printf("Bad ipv6 PTR response \"%s\" %d. ",
+ addrs[0], ttl);
+ dns_ok = 0;
+ goto out;
+ }
+ }
+ break;
+ }
+ default:
+ printf("Bad response type %d. ", type);
+ dns_ok = 0;
+ }
+ out:
+ if (++n_server_responses == 3) {
+ event_loopexit(NULL);
+ }
+}
+
+static void
+dns_server(void)
+{
+ evutil_socket_t sock=-1;
+ struct sockaddr_in my_addr;
+ struct sockaddr_storage ss;
+ ev_socklen_t slen;
+ struct evdns_server_port *port=NULL;
+ struct in_addr resolve_addr;
+ struct in6_addr resolve_addr6;
+ struct evdns_base *base=NULL;
+ struct evdns_request *req=NULL;
+
+ dns_ok = 1;
+
+ base = evdns_base_new(NULL, 0);
+
+ /* Now configure a nameserver port. */
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock<0) {
+ tt_abort_perror("socket");
+ }
+
+ evutil_make_socket_nonblocking(sock);
+
+ memset(&my_addr, 0, sizeof(my_addr));
+ my_addr.sin_family = AF_INET;
+ my_addr.sin_port = 0; /* kernel picks */
+ my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
+ if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
+ tt_abort_perror("bind");
+ }
+ slen = sizeof(ss);
+ if (getsockname(sock, (struct sockaddr*)&ss, &slen) < 0) {
+ tt_abort_perror("getsockname");
+ }
+
+ port = evdns_add_server_port(sock, 0, dns_server_request_cb, NULL);
+
+ /* Add ourself as the only nameserver, and make sure we really are
+ * the only nameserver. */
+ evdns_base_nameserver_sockaddr_add(base, (struct sockaddr*)&ss, slen, 0);
+ tt_int_op(evdns_base_count_nameservers(base), ==, 1);
+ {
+ struct sockaddr_storage ss2;
+ int slen2;
+
+ memset(&ss2, 0, sizeof(ss2));
+
+ slen2 = evdns_base_get_nameserver_addr(base, 0, (struct sockaddr *)&ss2, 3);
+ tt_int_op(slen2, ==, slen);
+ tt_int_op(ss2.ss_family, ==, 0);
+ slen2 = evdns_base_get_nameserver_addr(base, 0, (struct sockaddr *)&ss2, sizeof(ss2));
+ tt_int_op(slen2, ==, slen);
+ tt_mem_op(&ss2, ==, &ss, slen);
+
+ slen2 = evdns_base_get_nameserver_addr(base, 1, (struct sockaddr *)&ss2, sizeof(ss2));
+ tt_int_op(-1, ==, slen2);
+ }
+
+ /* Send some queries. */
+ evdns_base_resolve_ipv4(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
+ dns_server_gethostbyname_cb, NULL);
+ evdns_base_resolve_ipv6(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
+ dns_server_gethostbyname_cb, NULL);
+ resolve_addr.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
+ evdns_base_resolve_reverse(base, &resolve_addr, 0,
+ dns_server_gethostbyname_cb, NULL);
+ memcpy(resolve_addr6.s6_addr,
+ "\xff\xf0\x00\x00\x00\x00\xaa\xaa"
+ "\x11\x11\x00\x00\x00\x00\xef\xef", 16);
+ evdns_base_resolve_reverse_ipv6(base, &resolve_addr6, 0,
+ dns_server_gethostbyname_cb, (void*)6);
+
+ req = evdns_base_resolve_ipv4(base,
+ "drop.example.com", DNS_QUERY_NO_SEARCH,
+ dns_server_gethostbyname_cb, (void*)(char*)90909);
+
+ evdns_cancel_request(base, req);
+
+ event_dispatch();
+
+ tt_assert(dns_got_cancel);
+ test_ok = dns_ok;
+
+end:
+ if (port)
+ evdns_close_server_port(port);
+ if (sock >= 0)
+ evutil_closesocket(sock);
+ if (base)
+ evdns_base_free(base, 0);
+}
+
+static int n_replies_left;
+static struct event_base *exit_base;
+static struct evdns_server_port *exit_port;
+
+struct generic_dns_callback_result {
+ int result;
+ char type;
+ int count;
+ int ttl;
+ size_t addrs_len;
+ void *addrs;
+ char addrs_buf[256];
+};
+
+static void
+generic_dns_callback(int result, char type, int count, int ttl, void *addresses,
+ void *arg)
+{
+ size_t len;
+ struct generic_dns_callback_result *res = arg;
+ res->result = result;
+ res->type = type;
+ res->count = count;
+ res->ttl = ttl;
+
+ if (type == DNS_IPv4_A)
+ len = count * 4;
+ else if (type == DNS_IPv6_AAAA)
+ len = count * 16;
+ else if (type == DNS_PTR)
+ len = strlen(addresses)+1;
+ else {
+ res->addrs_len = len = 0;
+ res->addrs = NULL;
+ }
+ if (len) {
+ res->addrs_len = len;
+ if (len > 256)
+ len = 256;
+ memcpy(res->addrs_buf, addresses, len);
+ res->addrs = res->addrs_buf;
+ }
+
+ --n_replies_left;
+ if (n_replies_left == 0) {
+ if (exit_port) {
+ evdns_close_server_port(exit_port);
+ exit_port = NULL;
+ } else
+ event_base_loopexit(exit_base, NULL);
+ }
+}
+
+static struct regress_dns_server_table search_table[] = {
+ { "host.a.example.com", "err", "3", 0, 0 },
+ { "host.b.example.com", "err", "3", 0, 0 },
+ { "host.c.example.com", "A", "11.22.33.44", 0, 0 },
+ { "host2.a.example.com", "err", "3", 0, 0 },
+ { "host2.b.example.com", "A", "200.100.0.100", 0, 0 },
+ { "host2.c.example.com", "err", "3", 0, 0 },
+ { "hostn.a.example.com", "errsoa", "0", 0, 0 },
+ { "hostn.b.example.com", "errsoa", "3", 0, 0 },
+ { "hostn.c.example.com", "err", "0", 0, 0 },
+
+ { "host", "err", "3", 0, 0 },
+ { "host2", "err", "3", 0, 0 },
+ { "*", "err", "3", 0, 0 },
+ { NULL, NULL, NULL, 0, 0 }
+};
+static void
+dns_search_test_impl(void *arg, int lower)
+{
+ struct regress_dns_server_table table[ARRAY_SIZE(search_table)];
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+
+ struct generic_dns_callback_result r[8];
+ size_t i;
+
+ for (i = 0; i < ARRAY_SIZE(table); ++i) {
+ table[i] = search_table[i];
+ table[i].lower = lower;
+ }
+
+ tt_assert(regress_dnsserver(base, &portnum, table));
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, 0);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+ evdns_base_search_add(dns, "a.example.com");
+ evdns_base_search_add(dns, "b.example.com");
+ evdns_base_search_add(dns, "c.example.com");
+
+ n_replies_left = ARRAY_SIZE(r);
+ exit_base = base;
+
+ evdns_base_resolve_ipv4(dns, "host", 0, generic_dns_callback, &r[0]);
+ evdns_base_resolve_ipv4(dns, "host2", 0, generic_dns_callback, &r[1]);
+ evdns_base_resolve_ipv4(dns, "host", DNS_NO_SEARCH, generic_dns_callback, &r[2]);
+ evdns_base_resolve_ipv4(dns, "host2", DNS_NO_SEARCH, generic_dns_callback, &r[3]);
+ evdns_base_resolve_ipv4(dns, "host3", 0, generic_dns_callback, &r[4]);
+ evdns_base_resolve_ipv4(dns, "hostn.a.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[5]);
+ evdns_base_resolve_ipv4(dns, "hostn.b.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[6]);
+ evdns_base_resolve_ipv4(dns, "hostn.c.example.com", DNS_NO_SEARCH, generic_dns_callback, &r[7]);
+
+ event_base_dispatch(base);
+
+ tt_int_op(r[0].type, ==, DNS_IPv4_A);
+ tt_int_op(r[0].count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r[0].addrs)[0], ==, htonl(0x0b16212c));
+ tt_int_op(r[1].type, ==, DNS_IPv4_A);
+ tt_int_op(r[1].count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r[1].addrs)[0], ==, htonl(0xc8640064));
+ tt_int_op(r[2].result, ==, DNS_ERR_NOTEXIST);
+ tt_int_op(r[3].result, ==, DNS_ERR_NOTEXIST);
+ tt_int_op(r[4].result, ==, DNS_ERR_NOTEXIST);
+ tt_int_op(r[5].result, ==, DNS_ERR_NODATA);
+ tt_int_op(r[5].ttl, ==, 42);
+ tt_int_op(r[6].result, ==, DNS_ERR_NOTEXIST);
+ tt_int_op(r[6].ttl, ==, 42);
+ tt_int_op(r[7].result, ==, DNS_ERR_NODATA);
+ tt_int_op(r[7].ttl, ==, 0);
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+
+ regress_clean_dnsserver();
+}
+static void
+dns_search_empty_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+
+ dns = evdns_base_new(base, 0);
+
+ evdns_base_search_add(dns, "whatever.example.com");
+
+ n_replies_left = 1;
+ exit_base = base;
+
+ tt_ptr_op(evdns_base_resolve_ipv4(dns, "", 0, generic_dns_callback, NULL), ==, NULL);
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+}
+static void dns_search_test(void *arg) { dns_search_test_impl(arg, 0); }
+static void dns_search_lower_test(void *arg) { dns_search_test_impl(arg, 1); }
+
+static int request_count = 0;
+static struct evdns_request *current_req = NULL;
+
+static void
+search_cancel_server_cb(struct evdns_server_request *req, void *data)
+{
+ const char *question;
+
+ if (req->nquestions != 1)
+ TT_DIE(("Only handling one question at a time; got %d",
+ req->nquestions));
+
+ question = req->questions[0]->name;
+
+ TT_BLATHER(("got question, %s", question));
+
+ tt_assert(request_count > 0);
+ tt_assert(!evdns_server_request_respond(req, 3));
+
+ if (!--request_count)
+ evdns_cancel_request(NULL, current_req);
+
+end:
+ ;
+}
+
+static void
+dns_search_cancel_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+ struct evdns_server_port *port = NULL;
+ ev_uint16_t portnum = 0;
+ struct generic_dns_callback_result r1;
+ char buf[64];
+
+ port = regress_get_dnsserver(base, &portnum, NULL,
+ search_cancel_server_cb, NULL);
+ tt_assert(port);
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, 0);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+ evdns_base_search_add(dns, "a.example.com");
+ evdns_base_search_add(dns, "b.example.com");
+ evdns_base_search_add(dns, "c.example.com");
+ evdns_base_search_add(dns, "d.example.com");
+
+ exit_base = base;
+ request_count = 3;
+ n_replies_left = 1;
+
+ current_req = evdns_base_resolve_ipv4(dns, "host", 0,
+ generic_dns_callback, &r1);
+ event_base_dispatch(base);
+
+ tt_int_op(r1.result, ==, DNS_ERR_CANCEL);
+
+end:
+ if (port)
+ evdns_close_server_port(port);
+ if (dns)
+ evdns_base_free(dns, 0);
+}
+
+static void
+fail_server_cb(struct evdns_server_request *req, void *data)
+{
+ const char *question;
+ int *count = data;
+ struct in_addr in;
+
+ /* Drop the first N requests that we get. */
+ if (*count > 0) {
+ --*count;
+ tt_want(! evdns_server_request_drop(req));
+ return;
+ }
+
+ if (req->nquestions != 1)
+ TT_DIE(("Only handling one question at a time; got %d",
+ req->nquestions));
+
+ question = req->questions[0]->name;
+
+ if (!evutil_ascii_strcasecmp(question, "google.com")) {
+ /* Detect a probe, and get out of the loop. */
+ event_base_loopexit(exit_base, NULL);
+ }
+
+ tt_assert(evutil_inet_pton(AF_INET, "16.32.64.128", &in));
+ evdns_server_request_add_a_reply(req, question, 1, &in.s_addr,
+ 100);
+ tt_assert(! evdns_server_request_respond(req, 0))
+ return;
+end:
+ tt_want(! evdns_server_request_drop(req));
+}
+
+static void
+dns_retry_test_impl(void *arg, int flags)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_server_port *port = NULL;
+ struct evdns_base *dns = NULL;
+ int drop_count = 2;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+
+ struct generic_dns_callback_result r1;
+
+ port = regress_get_dnsserver(base, &portnum, NULL,
+ fail_server_cb, &drop_count);
+ tt_assert(port);
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, flags);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+ tt_assert(! evdns_base_set_option(dns, "timeout", "0.2"));
+ tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "10"));
+ tt_assert(! evdns_base_set_option(dns, "initial-probe-timeout", "0.1"));
+
+ evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+ generic_dns_callback, &r1);
+
+ n_replies_left = 1;
+ exit_base = base;
+
+ event_base_dispatch(base);
+
+ tt_int_op(drop_count, ==, 0);
+
+ tt_int_op(r1.type, ==, DNS_IPv4_A);
+ tt_int_op(r1.count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
+
+ /* Now try again, but this time have the server get treated as
+ * failed, so we can send it a test probe. */
+ drop_count = 4;
+ tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "2"));
+ tt_assert(! evdns_base_set_option(dns, "attempts:", "3"));
+ memset(&r1, 0, sizeof(r1));
+
+ evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+ generic_dns_callback, &r1);
+
+ n_replies_left = 2;
+
+ /* This will run until it answers the "google.com" probe request. */
+ event_base_dispatch(base);
+
+ /* We'll treat the server as failed here. */
+ tt_int_op(r1.result, ==, DNS_ERR_TIMEOUT);
+
+ /* It should work this time. */
+ tt_int_op(drop_count, ==, 0);
+ evdns_base_resolve_ipv4(dns, "host.example.com", 0,
+ generic_dns_callback, &r1);
+
+ event_base_dispatch(base);
+ tt_int_op(r1.result, ==, DNS_ERR_NONE);
+ tt_int_op(r1.type, ==, DNS_IPv4_A);
+ tt_int_op(r1.count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+ if (port)
+ evdns_close_server_port(port);
+}
+static void
+dns_retry_test(void *arg)
+{
+ dns_retry_test_impl(arg, 0);
+}
+static void
+dns_retry_disable_when_inactive_test(void *arg)
+{
+ dns_retry_test_impl(arg, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+}
+
+static struct regress_dns_server_table internal_error_table[] = {
+ /* Error 4 (NOTIMPL) makes us reissue the request to another server
+ if we can.
+
+ XXXX we should reissue under a much wider set of circumstances!
+ */
+ { "foof.example.com", "err", "4", 0, 0 },
+ { NULL, NULL, NULL, 0, 0 }
+};
+
+static struct regress_dns_server_table reissue_table[] = {
+ { "foof.example.com", "A", "240.15.240.15", 0, 0 },
+ { NULL, NULL, NULL, 0, 0 }
+};
+
+static void
+dns_reissue_test_impl(void *arg, int flags)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_server_port *port1 = NULL, *port2 = NULL;
+ struct evdns_base *dns = NULL;
+ struct generic_dns_callback_result r1;
+ ev_uint16_t portnum1 = 0, portnum2=0;
+ char buf1[64], buf2[64];
+
+ port1 = regress_get_dnsserver(base, &portnum1, NULL,
+ regress_dns_server_cb, internal_error_table);
+ tt_assert(port1);
+ port2 = regress_get_dnsserver(base, &portnum2, NULL,
+ regress_dns_server_cb, reissue_table);
+ tt_assert(port2);
+ evutil_snprintf(buf1, sizeof(buf1), "127.0.0.1:%d", (int)portnum1);
+ evutil_snprintf(buf2, sizeof(buf2), "127.0.0.1:%d", (int)portnum2);
+
+ dns = evdns_base_new(base, flags);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf1));
+ tt_assert(! evdns_base_set_option(dns, "timeout:", "0.3"));
+ tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "2"));
+ tt_assert(! evdns_base_set_option(dns, "attempts:", "5"));
+
+ memset(&r1, 0, sizeof(r1));
+ evdns_base_resolve_ipv4(dns, "foof.example.com", 0,
+ generic_dns_callback, &r1);
+
+ /* Add this after, so that we are sure to get a reissue. */
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf2));
+
+ n_replies_left = 1;
+ exit_base = base;
+
+ event_base_dispatch(base);
+ tt_int_op(r1.result, ==, DNS_ERR_NONE);
+ tt_int_op(r1.type, ==, DNS_IPv4_A);
+ tt_int_op(r1.count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0xf00ff00f));
+
+ /* Make sure we dropped at least once. */
+ tt_int_op(internal_error_table[0].seen, >, 0);
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+ if (port1)
+ evdns_close_server_port(port1);
+ if (port2)
+ evdns_close_server_port(port2);
+}
+static void
+dns_reissue_test(void *arg)
+{
+ dns_reissue_test_impl(arg, 0);
+}
+static void
+dns_reissue_disable_when_inactive_test(void *arg)
+{
+ dns_reissue_test_impl(arg, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+}
+
+#if 0
+static void
+dumb_bytes_fn(char *p, size_t n)
+{
+ unsigned i;
+ /* This gets us 6 bits of entropy per transaction ID, which means we
+ * will have probably have collisions and need to pick again. */
+ for (i=0;i<n;++i)
+ p[i] = (char)(rand() & 7);
+}
+#endif
+
+static void
+dns_inflight_test_impl(void *arg, int flags)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+ struct evdns_server_port *dns_port = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+ int disable_when_inactive = flags & EVDNS_BASE_DISABLE_WHEN_INACTIVE;
+
+ struct generic_dns_callback_result r[20];
+ int i;
+
+ dns_port = regress_get_dnsserver(base, &portnum, NULL,
+ regress_dns_server_cb, reissue_table);
+ tt_assert(dns_port);
+ if (disable_when_inactive) {
+ exit_port = dns_port;
+ }
+
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, flags);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+ tt_assert(! evdns_base_set_option(dns, "max-inflight:", "3"));
+ tt_assert(! evdns_base_set_option(dns, "randomize-case:", "0"));
+
+ for (i=0;i<20;++i)
+ evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r[i]);
+
+ n_replies_left = 20;
+ exit_base = base;
+
+ event_base_dispatch(base);
+
+ for (i=0;i<20;++i) {
+ tt_int_op(r[i].type, ==, DNS_IPv4_A);
+ tt_int_op(r[i].count, ==, 1);
+ tt_int_op(((ev_uint32_t*)r[i].addrs)[0], ==, htonl(0xf00ff00f));
+ }
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+ if (exit_port) {
+ evdns_close_server_port(exit_port);
+ exit_port = NULL;
+ } else if (! disable_when_inactive) {
+ evdns_close_server_port(dns_port);
+ }
+}
+
+static void
+dns_inflight_test(void *arg)
+{
+ dns_inflight_test_impl(arg, 0);
+}
+
+static void
+dns_disable_when_inactive_test(void *arg)
+{
+ dns_inflight_test_impl(arg, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+}
+
+static void
+dns_disable_when_inactive_no_ns_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base, *inactive_base;
+ struct evdns_base *dns = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+ struct generic_dns_callback_result r;
+
+ inactive_base = event_base_new();
+ tt_assert(inactive_base);
+
+ /** Create dns server with inactive base, to avoid replying to clients */
+ tt_assert(regress_dnsserver(inactive_base, &portnum, search_table));
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+ tt_assert(! evdns_base_set_option(dns, "timeout:", "0.1"));
+
+ evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r);
+ n_replies_left = 1;
+ exit_base = base;
+
+ event_base_dispatch(base);
+
+ tt_int_op(n_replies_left, ==, 0);
+
+ tt_int_op(r.result, ==, DNS_ERR_TIMEOUT);
+ tt_int_op(r.count, ==, 0);
+ tt_ptr_op(r.addrs, ==, NULL);
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+ regress_clean_dnsserver();
+ if (inactive_base)
+ event_base_free(inactive_base);
+}
+
+static void
+dns_initialize_nameservers_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+
+ dns = evdns_base_new(base, 0);
+ tt_assert(dns);
+ tt_int_op(evdns_base_get_nameserver_addr(dns, 0, NULL, 0), ==, -1);
+ evdns_base_free(dns, 0);
+
+ dns = evdns_base_new(base, EVDNS_BASE_INITIALIZE_NAMESERVERS);
+ tt_assert(dns);
+ tt_int_op(evdns_base_get_nameserver_addr(dns, 0, NULL, 0), ==, sizeof(struct sockaddr));
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+}
+#ifndef _WIN32
+#define RESOLV_FILE "empty-resolv.conf"
+static void
+dns_nameservers_no_default_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+ int ok = access(RESOLV_FILE, R_OK);
+
+ tt_assert(ok);
+
+ dns = evdns_base_new(base, 0);
+ tt_assert(dns);
+ tt_int_op(evdns_base_get_nameserver_addr(dns, 0, NULL, 0), ==, -1);
+
+ /* We cannot test
+ * EVDNS_BASE_INITIALIZE_NAMESERVERS|EVDNS_BASE_NAMESERVERS_NO_DEFAULT
+ * because we cannot mock "/etc/resolv.conf" (yet). */
+
+ evdns_base_resolv_conf_parse(dns,
+ DNS_OPTIONS_ALL|DNS_OPTION_NAMESERVERS_NO_DEFAULT, RESOLV_FILE);
+ tt_int_op(evdns_base_get_nameserver_addr(dns, 0, NULL, 0), ==, -1);
+
+ evdns_base_resolv_conf_parse(dns, DNS_OPTIONS_ALL, RESOLV_FILE);
+ tt_int_op(evdns_base_get_nameserver_addr(dns, 0, NULL, 0), ==, sizeof(struct sockaddr));
+
+end:
+ if (dns)
+ evdns_base_free(dns, 0);
+}
+#endif
+
+/* === Test for bufferevent_socket_connect_hostname */
+
+static int total_connected_or_failed = 0;
+static int total_n_accepted = 0;
+static struct event_base *be_connect_hostname_base = NULL;
+
+/* Implements a DNS server for the connect_hostname test and the
+ * getaddrinfo_async test */
+static void
+be_getaddrinfo_server_cb(struct evdns_server_request *req, void *data)
+{
+ int i;
+ int *n_got_p=data;
+ int added_any=0;
+ ++*n_got_p;
+
+ for (i = 0; i < req->nquestions; ++i) {
+ const int qtype = req->questions[i]->type;
+ const int qclass = req->questions[i]->dns_question_class;
+ const char *qname = req->questions[i]->name;
+ struct in_addr ans;
+ struct in6_addr ans6;
+ memset(&ans6, 0, sizeof(ans6));
+
+ TT_BLATHER(("Got question about %s, type=%d", qname, qtype));
+
+ if (qtype == EVDNS_TYPE_A &&
+ qclass == EVDNS_CLASS_INET &&
+ !evutil_ascii_strcasecmp(qname, "nobodaddy.example.com")) {
+ ans.s_addr = htonl(0x7f000001);
+ evdns_server_request_add_a_reply(req, qname,
+ 1, &ans.s_addr, 2000);
+ added_any = 1;
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "nosuchplace.example.com")) {
+ /* ok, just say notfound. */
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "both.example.com")) {
+ if (qtype == EVDNS_TYPE_A) {
+ ans.s_addr = htonl(0x50502020);
+ evdns_server_request_add_a_reply(req, qname,
+ 1, &ans.s_addr, 2000);
+ added_any = 1;
+ } else if (qtype == EVDNS_TYPE_AAAA) {
+ ans6.s6_addr[0] = 0x80;
+ ans6.s6_addr[1] = 0xff;
+ ans6.s6_addr[14] = 0xbb;
+ ans6.s6_addr[15] = 0xbb;
+ evdns_server_request_add_aaaa_reply(req, qname,
+ 1, &ans6.s6_addr, 2000);
+ added_any = 1;
+ }
+ evdns_server_request_add_cname_reply(req, qname,
+ "both-canonical.example.com", 1000);
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v4only.example.com") ||
+ !evutil_ascii_strcasecmp(qname, "v4assert.example.com")) {
+ if (qtype == EVDNS_TYPE_A) {
+ ans.s_addr = htonl(0x12345678);
+ evdns_server_request_add_a_reply(req, qname,
+ 1, &ans.s_addr, 2000);
+ added_any = 1;
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v4assert.example.com")) {
+ TT_FAIL(("Got an AAAA request for v4assert"));
+ }
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v6only.example.com") ||
+ !evutil_ascii_strcasecmp(qname, "v6assert.example.com")) {
+ if (qtype == EVDNS_TYPE_AAAA) {
+ ans6.s6_addr[0] = 0x0b;
+ ans6.s6_addr[1] = 0x0b;
+ ans6.s6_addr[14] = 0xf0;
+ ans6.s6_addr[15] = 0x0d;
+ evdns_server_request_add_aaaa_reply(req, qname,
+ 1, &ans6.s6_addr, 2000);
+ added_any = 1;
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v6assert.example.com")) {
+ TT_FAIL(("Got a A request for v6assert"));
+ }
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v6timeout.example.com")) {
+ if (qtype == EVDNS_TYPE_A) {
+ ans.s_addr = htonl(0xabcdef01);
+ evdns_server_request_add_a_reply(req, qname,
+ 1, &ans.s_addr, 2000);
+ added_any = 1;
+ } else if (qtype == EVDNS_TYPE_AAAA) {
+ /* Let the v6 request time out.*/
+ evdns_server_request_drop(req);
+ return;
+ }
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v4timeout.example.com")) {
+ if (qtype == EVDNS_TYPE_AAAA) {
+ ans6.s6_addr[0] = 0x0a;
+ ans6.s6_addr[1] = 0x0a;
+ ans6.s6_addr[14] = 0xff;
+ ans6.s6_addr[15] = 0x01;
+ evdns_server_request_add_aaaa_reply(req, qname,
+ 1, &ans6.s6_addr, 2000);
+ added_any = 1;
+ } else if (qtype == EVDNS_TYPE_A) {
+ /* Let the v4 request time out.*/
+ evdns_server_request_drop(req);
+ return;
+ }
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "v6timeout-nonexist.example.com")) {
+ if (qtype == EVDNS_TYPE_A) {
+ /* Fall through, give an nexist. */
+ } else if (qtype == EVDNS_TYPE_AAAA) {
+ /* Let the v6 request time out.*/
+ evdns_server_request_drop(req);
+ return;
+ }
+ } else if (!evutil_ascii_strcasecmp(qname,
+ "all-timeout.example.com")) {
+ /* drop all requests */
+ evdns_server_request_drop(req);
+ return;
+ } else {
+ TT_GRIPE(("Got weird request for %s",qname));
+ }
+ }
+ if (added_any) {
+ TT_BLATHER(("answering"));
+ evdns_server_request_respond(req, 0);
+ } else {
+ TT_BLATHER(("saying nexist."));
+ evdns_server_request_respond(req, 3);
+ }
+}
+
+/* Implements a listener for connect_hostname test. */
+static void
+nil_accept_cb(struct evconnlistener *l, evutil_socket_t fd, struct sockaddr *s,
+ int socklen, void *arg)
+{
+ int *p = arg;
+ (*p)++;
+ ++total_n_accepted;
+ /* don't do anything with the socket; let it close when we exit() */
+ if (total_n_accepted >= 3 && total_connected_or_failed >= 5)
+ event_base_loopexit(be_connect_hostname_base,
+ NULL);
+}
+
+struct be_conn_hostname_result {
+ int dnserr;
+ int what;
+};
+
+/* Bufferevent event callback for the connect_hostname test: remembers what
+ * event we got. */
+static void
+be_connect_hostname_event_cb(struct bufferevent *bev, short what, void *ctx)
+{
+ struct be_conn_hostname_result *got = ctx;
+
+ if (got->what) {
+ TT_FAIL(("Two events on one bufferevent. %d,%d",
+ got->what, (int)what));
+ }
+
+ TT_BLATHER(("Got a bufferevent event %d", what));
+ got->what = what;
+
+ if ((what & BEV_EVENT_CONNECTED) || (what & BEV_EVENT_ERROR)) {
+ int expected = 3;
+ int r = bufferevent_socket_get_dns_error(bev);
+
+ if (r) {
+ got->dnserr = r;
+ TT_BLATHER(("DNS error %d: %s", r,
+ evutil_gai_strerror(r)));
+ }
+ ++total_connected_or_failed;
+ TT_BLATHER(("Got %d connections or errors.", total_connected_or_failed));
+
+ /** emfile test */
+ if (errno == EMFILE) {
+ expected = 0;
+ }
+
+ if (total_n_accepted >= expected && total_connected_or_failed >= 5)
+ event_base_loopexit(be_connect_hostname_base,
+ NULL);
+ }
+}
+
+static void
+test_bufferevent_connect_hostname(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evconnlistener *listener = NULL;
+ struct bufferevent *be[5];
+ struct be_conn_hostname_result be_outcome[ARRAY_SIZE(be)];
+ int expect_err;
+ struct evdns_base *dns=NULL;
+ struct evdns_server_port *port=NULL;
+ struct sockaddr_in sin;
+ int listener_port=-1;
+ ev_uint16_t dns_port=0;
+ int n_accept=0, n_dns=0;
+ char buf[128];
+ int emfile = data->setup_data && !strcmp(data->setup_data, "emfile");
+ unsigned i;
+ int ret;
+
+ be_connect_hostname_base = data->base;
+
+ /* Bind an address and figure out what port it's on. */
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+ sin.sin_port = 0;
+ listener = evconnlistener_new_bind(data->base, nil_accept_cb,
+ &n_accept,
+ LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC,
+ -1, (struct sockaddr *)&sin, sizeof(sin));
+ tt_assert(listener);
+ listener_port = regress_get_socket_port(
+ evconnlistener_get_fd(listener));
+
+ port = regress_get_dnsserver(data->base, &dns_port, NULL,
+ be_getaddrinfo_server_cb, &n_dns);
+ tt_assert(port);
+ tt_int_op(dns_port, >=, 0);
+
+ /* Start an evdns_base that uses the server as its resolver. */
+ dns = evdns_base_new(data->base, 0);
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)dns_port);
+ evdns_base_nameserver_ip_add(dns, buf);
+
+#ifdef EVENT__HAVE_SETRLIMIT
+ if (emfile) {
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ struct rlimit file = { fd, fd };
+
+ tt_int_op(fd, >=, 0);
+ tt_assert(!close(fd));
+
+ tt_assert(!setrlimit(RLIMIT_NOFILE, &file));
+ }
+#endif
+
+ /* Now, finally, at long last, launch the bufferevents. One should do
+ * a failing lookup IP, one should do a successful lookup by IP,
+ * and one should do a successful lookup by hostname. */
+ for (i = 0; i < ARRAY_SIZE(be); ++i) {
+ memset(&be_outcome[i], 0, sizeof(be_outcome[i]));
+ be[i] = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(be[i], NULL, NULL, be_connect_hostname_event_cb,
+ &be_outcome[i]);
+ }
+
+ /* Use the blocking resolver. This one will fail if your resolver
+ * can't resolve localhost to 127.0.0.1 */
+ tt_assert(!bufferevent_socket_connect_hostname(be[3], NULL, AF_INET,
+ "localhost", listener_port));
+ /* Use the blocking resolver with a nonexistent hostname. */
+ tt_assert(!bufferevent_socket_connect_hostname(be[4], NULL, AF_INET,
+ "nonesuch.nowhere.example.com", 80));
+ {
+ /* The blocking resolver will use the system nameserver, which
+ * might tell us anything. (Yes, some twits even pretend that
+ * example.com is real.) Let's see what answer to expect. */
+ struct evutil_addrinfo hints, *ai = NULL;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_protocol = IPPROTO_TCP;
+ expect_err = evutil_getaddrinfo(
+ "nonesuch.nowhere.example.com", "80", &hints, &ai);
+ }
+ /* Launch an async resolve that will fail. */
+ tt_assert(!bufferevent_socket_connect_hostname(be[0], dns, AF_INET,
+ "nosuchplace.example.com", listener_port));
+ /* Connect to the IP without resolving. */
+ tt_assert(!bufferevent_socket_connect_hostname(be[1], dns, AF_INET,
+ "127.0.0.1", listener_port));
+ /* Launch an async resolve that will succeed. */
+ tt_assert(!bufferevent_socket_connect_hostname(be[2], dns, AF_INET,
+ "nobodaddy.example.com", listener_port));
+
+ ret = event_base_dispatch(data->base);
+#ifdef __sun__
+ if (emfile && !strcmp(event_base_get_method(data->base), "devpoll")) {
+ tt_int_op(ret, ==, -1);
+ /** DP_POLL failed */
+ tt_skip();
+ } else
+#endif
+ {
+ tt_int_op(ret, ==, 0);
+ }
+
+ tt_int_op(be_outcome[0].what, ==, BEV_EVENT_ERROR);
+ tt_int_op(be_outcome[0].dnserr, ==, EVUTIL_EAI_NONAME);
+ tt_int_op(be_outcome[1].what, ==, !emfile ? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR);
+ tt_int_op(be_outcome[1].dnserr, ==, 0);
+ tt_int_op(be_outcome[2].what, ==, !emfile ? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR);
+ tt_int_op(be_outcome[2].dnserr, ==, 0);
+ tt_int_op(be_outcome[3].what, ==, !emfile ? BEV_EVENT_CONNECTED : BEV_EVENT_ERROR);
+ if (!emfile) {
+ tt_int_op(be_outcome[3].dnserr, ==, 0);
+ } else {
+ tt_int_op(be_outcome[3].dnserr, !=, 0);
+ }
+ if (expect_err) {
+ tt_int_op(be_outcome[4].what, ==, BEV_EVENT_ERROR);
+ tt_int_op(be_outcome[4].dnserr, ==, expect_err);
+ }
+
+ if (emfile) {
+ tt_int_op(n_accept, ==, 0);
+ } else {
+ tt_int_op(n_accept, ==, 3);
+ }
+ tt_int_op(n_dns, ==, 2);
+
+end:
+ if (listener)
+ evconnlistener_free(listener);
+ if (port)
+ evdns_close_server_port(port);
+ if (dns)
+ evdns_base_free(dns, 0);
+ for (i = 0; i < ARRAY_SIZE(be); ++i) {
+ if (be[i])
+ bufferevent_free(be[i]);
+ }
+}
+
+
+struct gai_outcome {
+ int err;
+ struct evutil_addrinfo *ai;
+};
+
+static int n_gai_results_pending = 0;
+static struct event_base *exit_base_on_no_pending_results = NULL;
+
+static void
+gai_cb(int err, struct evutil_addrinfo *res, void *ptr)
+{
+ struct gai_outcome *go = ptr;
+ go->err = err;
+ go->ai = res;
+ if (--n_gai_results_pending <= 0 && exit_base_on_no_pending_results)
+ event_base_loopexit(exit_base_on_no_pending_results, NULL);
+ if (n_gai_results_pending < 900)
+ TT_BLATHER(("Got an answer; expecting %d more.",
+ n_gai_results_pending));
+}
+
+static void
+cancel_gai_cb(evutil_socket_t fd, short what, void *ptr)
+{
+ struct evdns_getaddrinfo_request *r = ptr;
+ evdns_getaddrinfo_cancel(r);
+}
+
+static void
+test_getaddrinfo_async(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evutil_addrinfo hints, *a;
+ struct gai_outcome local_outcome;
+ struct gai_outcome a_out[12];
+ unsigned i;
+ struct evdns_getaddrinfo_request *r;
+ char buf[128];
+ struct evdns_server_port *port = NULL;
+ ev_uint16_t dns_port = 0;
+ int n_dns_questions = 0;
+ struct evdns_base *dns_base;
+
+ memset(a_out, 0, sizeof(a_out));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+
+ dns_base = evdns_base_new(data->base, 0);
+ tt_assert(dns_base);
+
+ /* for localhost */
+ evdns_base_load_hosts(dns_base, NULL);
+
+ tt_assert(! evdns_base_set_option(dns_base, "timeout", "0.3"));
+ tt_assert(! evdns_base_set_option(dns_base, "getaddrinfo-allow-skew", "0.2"));
+
+ n_gai_results_pending = 10000; /* don't think about exiting yet. */
+
+ /* 1. Try some cases that will never hit the asynchronous resolver. */
+ /* 1a. Simple case with a symbolic service name */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ r = evdns_getaddrinfo(dns_base, "1.2.3.4", "http",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(! r);
+ if (!local_outcome.err) {
+ tt_ptr_op(local_outcome.ai,!=,NULL);
+ test_ai_eq(local_outcome.ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+ } else {
+ TT_BLATHER(("Apparently we have no getservbyname."));
+ }
+
+ /* 1b. EVUTIL_AI_NUMERICHOST is set */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ r = evdns_getaddrinfo(dns_base, "www.google.com", "80",
+ &hints, gai_cb, &local_outcome);
+ tt_ptr_op(r,==,NULL);
+ tt_int_op(local_outcome.err,==,EVUTIL_EAI_NONAME);
+ tt_ptr_op(local_outcome.ai,==,NULL);
+
+ /* 1c. We give a numeric address (ipv6) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_protocol = IPPROTO_TCP;
+ r = evdns_getaddrinfo(dns_base, "f::f", "8008",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(!r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ tt_ptr_op(local_outcome.ai->ai_next,==,NULL);
+ test_ai_eq(local_outcome.ai, "[f::f]:8008", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 1d. We give a numeric address (ipv4) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_UNSPEC;
+ r = evdns_getaddrinfo(dns_base, "5.6.7.8", NULL,
+ &hints, gai_cb, &local_outcome);
+ tt_assert(!r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ a = ai_find_by_protocol(local_outcome.ai, IPPROTO_TCP);
+ tt_assert(a);
+ test_ai_eq(a, "5.6.7.8", SOCK_STREAM, IPPROTO_TCP);
+ a = ai_find_by_protocol(local_outcome.ai, IPPROTO_UDP);
+ tt_assert(a);
+ test_ai_eq(a, "5.6.7.8", SOCK_DGRAM, IPPROTO_UDP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 1e. nodename is NULL (bind) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_DGRAM;
+ hints.ai_flags = EVUTIL_AI_PASSIVE;
+ r = evdns_getaddrinfo(dns_base, NULL, "9090",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(!r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ /* we should get a v4 address of 0.0.0.0... */
+ a = ai_find_by_family(local_outcome.ai, PF_INET);
+ tt_assert(a);
+ test_ai_eq(a, "0.0.0.0:9090", SOCK_DGRAM, IPPROTO_UDP);
+ /* ... and a v6 address of ::0 */
+ a = ai_find_by_family(local_outcome.ai, PF_INET6);
+ tt_assert(a);
+ test_ai_eq(a, "[::]:9090", SOCK_DGRAM, IPPROTO_UDP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 1f. nodename is NULL (connect) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evdns_getaddrinfo(dns_base, NULL, "2",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(!r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ /* we should get a v4 address of 127.0.0.1 .... */
+ a = ai_find_by_family(local_outcome.ai, PF_INET);
+ tt_assert(a);
+ test_ai_eq(a, "127.0.0.1:2", SOCK_STREAM, IPPROTO_TCP);
+ /* ... and a v6 address of ::1 */
+ a = ai_find_by_family(local_outcome.ai, PF_INET6);
+ tt_assert(a);
+ test_ai_eq(a, "[::1]:2", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 1g. We find localhost immediately. (pf_unspec) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evdns_getaddrinfo(dns_base, "LOCALHOST", "80",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(!r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ /* we should get a v4 address of 127.0.0.1 .... */
+ a = ai_find_by_family(local_outcome.ai, PF_INET);
+ tt_assert(a);
+ test_ai_eq(a, "127.0.0.1:80", SOCK_STREAM, IPPROTO_TCP);
+ /* ... and a v6 address of ::1 */
+ a = ai_find_by_family(local_outcome.ai, PF_INET6);
+ tt_assert(a);
+ test_ai_eq(a, "[::1]:80", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 1g. We find localhost immediately. (pf_inet6) */
+ memset(&hints, 0, sizeof(hints));
+ memset(&local_outcome, 0, sizeof(local_outcome));
+ hints.ai_family = PF_INET6;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evdns_getaddrinfo(dns_base, "LOCALHOST", "9999",
+ &hints, gai_cb, &local_outcome);
+ tt_assert(! r);
+ tt_int_op(local_outcome.err,==,0);
+ tt_assert(local_outcome.ai);
+ a = local_outcome.ai;
+ test_ai_eq(a, "[::1]:9999", SOCK_STREAM, IPPROTO_TCP);
+ tt_ptr_op(a->ai_next, ==, NULL);
+ evutil_freeaddrinfo(local_outcome.ai);
+ local_outcome.ai = NULL;
+
+ /* 2. Okay, now we can actually test the asynchronous resolver. */
+ /* Start a dummy local dns server... */
+ port = regress_get_dnsserver(data->base, &dns_port, NULL,
+ be_getaddrinfo_server_cb, &n_dns_questions);
+ tt_assert(port);
+ tt_int_op(dns_port, >=, 0);
+ /* ... and tell the evdns_base about it. */
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", dns_port);
+ evdns_base_nameserver_ip_add(dns_base, buf);
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = EVUTIL_AI_CANONNAME;
+ /* 0: Request for both.example.com should return both addresses. */
+ r = evdns_getaddrinfo(dns_base, "both.example.com", "8000",
+ &hints, gai_cb, &a_out[0]);
+ tt_assert(r);
+
+ /* 1: Request for v4only.example.com should return one address. */
+ r = evdns_getaddrinfo(dns_base, "v4only.example.com", "8001",
+ &hints, gai_cb, &a_out[1]);
+ tt_assert(r);
+
+ /* 2: Request for v6only.example.com should return one address. */
+ hints.ai_flags = 0;
+ r = evdns_getaddrinfo(dns_base, "v6only.example.com", "8002",
+ &hints, gai_cb, &a_out[2]);
+ tt_assert(r);
+
+ /* 3: PF_INET request for v4assert.example.com should not generate a
+ * v6 request. The server will fail the test if it does. */
+ hints.ai_family = PF_INET;
+ r = evdns_getaddrinfo(dns_base, "v4assert.example.com", "8003",
+ &hints, gai_cb, &a_out[3]);
+ tt_assert(r);
+
+ /* 4: PF_INET6 request for v6assert.example.com should not generate a
+ * v4 request. The server will fail the test if it does. */
+ hints.ai_family = PF_INET6;
+ r = evdns_getaddrinfo(dns_base, "v6assert.example.com", "8004",
+ &hints, gai_cb, &a_out[4]);
+ tt_assert(r);
+
+ /* 5: PF_INET request for nosuchplace.example.com should give NEXIST. */
+ hints.ai_family = PF_INET;
+ r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8005",
+ &hints, gai_cb, &a_out[5]);
+ tt_assert(r);
+
+ /* 6: PF_UNSPEC request for nosuchplace.example.com should give NEXIST.
+ */
+ hints.ai_family = PF_UNSPEC;
+ r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8006",
+ &hints, gai_cb, &a_out[6]);
+ tt_assert(r);
+
+ /* 7: PF_UNSPEC request for v6timeout.example.com should give an ipv4
+ * address only. */
+ hints.ai_family = PF_UNSPEC;
+ r = evdns_getaddrinfo(dns_base, "v6timeout.example.com", "8007",
+ &hints, gai_cb, &a_out[7]);
+ tt_assert(r);
+
+ /* 8: PF_UNSPEC request for v6timeout-nonexist.example.com should give
+ * a NEXIST */
+ hints.ai_family = PF_UNSPEC;
+ r = evdns_getaddrinfo(dns_base, "v6timeout-nonexist.example.com",
+ "8008", &hints, gai_cb, &a_out[8]);
+ tt_assert(r);
+
+ /* 9: AI_ADDRCONFIG should at least not crash. Can't test it more
+ * without knowing what kind of internet we have. */
+ hints.ai_flags |= EVUTIL_AI_ADDRCONFIG;
+ r = evdns_getaddrinfo(dns_base, "both.example.com",
+ "8009", &hints, gai_cb, &a_out[9]);
+ tt_assert(r);
+
+ /* 10: PF_UNSPEC for v4timeout.example.com should give an ipv6 address
+ * only. */
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_flags = 0;
+ r = evdns_getaddrinfo(dns_base, "v4timeout.example.com", "8010",
+ &hints, gai_cb, &a_out[10]);
+ tt_assert(r);
+
+ /* 11: timeout.example.com: cancel it after 100 msec. */
+ r = evdns_getaddrinfo(dns_base, "all-timeout.example.com", "8011",
+ &hints, gai_cb, &a_out[11]);
+ tt_assert(r);
+ {
+ struct timeval tv;
+ tv.tv_sec = 0;
+ tv.tv_usec = 100*1000; /* 100 msec */
+ event_base_once(data->base, -1, EV_TIMEOUT, cancel_gai_cb,
+ r, &tv);
+ }
+
+ /* XXXXX There are more tests we could do, including:
+
+ - A test to elicit NODATA.
+
+ */
+
+ n_gai_results_pending = 12;
+ exit_base_on_no_pending_results = data->base;
+
+ event_base_dispatch(data->base);
+
+ /* 0: both.example.com */
+ tt_int_op(a_out[0].err, ==, 0);
+ tt_assert(a_out[0].ai);
+ tt_assert(a_out[0].ai->ai_next);
+ tt_assert(!a_out[0].ai->ai_next->ai_next);
+ a = ai_find_by_family(a_out[0].ai, PF_INET);
+ tt_assert(a);
+ test_ai_eq(a, "80.80.32.32:8000", SOCK_STREAM, IPPROTO_TCP);
+ a = ai_find_by_family(a_out[0].ai, PF_INET6);
+ tt_assert(a);
+ test_ai_eq(a, "[80ff::bbbb]:8000", SOCK_STREAM, IPPROTO_TCP);
+ tt_assert(a_out[0].ai->ai_canonname);
+ tt_str_op(a_out[0].ai->ai_canonname, ==, "both-canonical.example.com");
+
+ /* 1: v4only.example.com */
+ tt_int_op(a_out[1].err, ==, 0);
+ tt_assert(a_out[1].ai);
+ tt_assert(! a_out[1].ai->ai_next);
+ test_ai_eq(a_out[1].ai, "18.52.86.120:8001", SOCK_STREAM, IPPROTO_TCP);
+ tt_assert(a_out[1].ai->ai_canonname == NULL);
+
+
+ /* 2: v6only.example.com */
+ tt_int_op(a_out[2].err, ==, 0);
+ tt_assert(a_out[2].ai);
+ tt_assert(! a_out[2].ai->ai_next);
+ test_ai_eq(a_out[2].ai, "[b0b::f00d]:8002", SOCK_STREAM, IPPROTO_TCP);
+
+ /* 3: v4assert.example.com */
+ tt_int_op(a_out[3].err, ==, 0);
+ tt_assert(a_out[3].ai);
+ tt_assert(! a_out[3].ai->ai_next);
+ test_ai_eq(a_out[3].ai, "18.52.86.120:8003", SOCK_STREAM, IPPROTO_TCP);
+
+ /* 4: v6assert.example.com */
+ tt_int_op(a_out[4].err, ==, 0);
+ tt_assert(a_out[4].ai);
+ tt_assert(! a_out[4].ai->ai_next);
+ test_ai_eq(a_out[4].ai, "[b0b::f00d]:8004", SOCK_STREAM, IPPROTO_TCP);
+
+ /* 5: nosuchplace.example.com (inet) */
+ tt_int_op(a_out[5].err, ==, EVUTIL_EAI_NONAME);
+ tt_assert(! a_out[5].ai);
+
+ /* 6: nosuchplace.example.com (unspec) */
+ tt_int_op(a_out[6].err, ==, EVUTIL_EAI_NONAME);
+ tt_assert(! a_out[6].ai);
+
+ /* 7: v6timeout.example.com */
+ tt_int_op(a_out[7].err, ==, 0);
+ tt_assert(a_out[7].ai);
+ tt_assert(! a_out[7].ai->ai_next);
+ test_ai_eq(a_out[7].ai, "171.205.239.1:8007", SOCK_STREAM, IPPROTO_TCP);
+
+ /* 8: v6timeout-nonexist.example.com */
+ tt_int_op(a_out[8].err, ==, EVUTIL_EAI_NONAME);
+ tt_assert(! a_out[8].ai);
+
+ /* 9: both (ADDRCONFIG) */
+ tt_int_op(a_out[9].err, ==, 0);
+ tt_assert(a_out[9].ai);
+ a = ai_find_by_family(a_out[9].ai, PF_INET);
+ if (a)
+ test_ai_eq(a, "80.80.32.32:8009", SOCK_STREAM, IPPROTO_TCP);
+ else
+ tt_assert(ai_find_by_family(a_out[9].ai, PF_INET6));
+ a = ai_find_by_family(a_out[9].ai, PF_INET6);
+ if (a)
+ test_ai_eq(a, "[80ff::bbbb]:8009", SOCK_STREAM, IPPROTO_TCP);
+ else
+ tt_assert(ai_find_by_family(a_out[9].ai, PF_INET));
+
+ /* 10: v4timeout.example.com */
+ tt_int_op(a_out[10].err, ==, 0);
+ tt_assert(a_out[10].ai);
+ tt_assert(! a_out[10].ai->ai_next);
+ test_ai_eq(a_out[10].ai, "[a0a::ff01]:8010", SOCK_STREAM, IPPROTO_TCP);
+
+ /* 11: cancelled request. */
+ tt_int_op(a_out[11].err, ==, EVUTIL_EAI_CANCEL);
+ tt_assert(a_out[11].ai == NULL);
+
+end:
+ if (local_outcome.ai)
+ evutil_freeaddrinfo(local_outcome.ai);
+ for (i = 0; i < ARRAY_SIZE(a_out); ++i) {
+ if (a_out[i].ai)
+ evutil_freeaddrinfo(a_out[i].ai);
+ }
+ if (port)
+ evdns_close_server_port(port);
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+}
+
+struct gaic_request_status {
+ int magic;
+ struct event_base *base;
+ struct evdns_base *dns_base;
+ struct evdns_getaddrinfo_request *request;
+ struct event cancel_event;
+ int canceled;
+};
+
+#define GAIC_MAGIC 0x1234abcd
+
+static int gaic_pending = 0;
+static int gaic_freed = 0;
+
+static void
+gaic_cancel_request_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct gaic_request_status *status = arg;
+
+ tt_assert(status->magic == GAIC_MAGIC);
+ status->canceled = 1;
+ evdns_getaddrinfo_cancel(status->request);
+ return;
+end:
+ event_base_loopexit(status->base, NULL);
+}
+
+static void
+gaic_server_cb(struct evdns_server_request *req, void *arg)
+{
+ ev_uint32_t answer = 0x7f000001;
+ tt_assert(req->nquestions);
+ evdns_server_request_add_a_reply(req, req->questions[0]->name, 1,
+ &answer, 100);
+ evdns_server_request_respond(req, 0);
+ return;
+end:
+ evdns_server_request_respond(req, DNS_ERR_REFUSED);
+}
+
+
+static void
+gaic_getaddrinfo_cb(int result, struct evutil_addrinfo *res, void *arg)
+{
+ struct gaic_request_status *status = arg;
+ struct event_base *base = status->base;
+ tt_assert(status->magic == GAIC_MAGIC);
+
+ if (result == EVUTIL_EAI_CANCEL) {
+ tt_assert(status->canceled);
+ }
+ event_del(&status->cancel_event);
+
+ memset(status, 0xf0, sizeof(*status));
+ free(status);
+
+end:
+ if (res)
+ {
+ TT_BLATHER(("evutil_freeaddrinfo(%p)", res));
+ evutil_freeaddrinfo(res);
+ ++gaic_freed;
+ }
+ if (--gaic_pending <= 0)
+ event_base_loopexit(base, NULL);
+}
+
+static void
+gaic_launch(struct event_base *base, struct evdns_base *dns_base)
+{
+ struct gaic_request_status *status = calloc(1,sizeof(*status));
+ struct timeval tv = { 0, 10000 };
+ status->magic = GAIC_MAGIC;
+ status->base = base;
+ status->dns_base = dns_base;
+ event_assign(&status->cancel_event, base, -1, 0, gaic_cancel_request_cb,
+ status);
+ status->request = evdns_getaddrinfo(dns_base,
+ "foobar.bazquux.example.com", "80", NULL, gaic_getaddrinfo_cb,
+ status);
+ event_add(&status->cancel_event, &tv);
+ ++gaic_pending;
+}
+
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+/* FIXME: We should move this to regress_main.c if anything else needs it.*/
+
+/* Trivial replacements for malloc/free/realloc to check for memory leaks.
+ * Not threadsafe. */
+static int allocated_chunks = 0;
+
+static void *
+cnt_malloc(size_t sz)
+{
+ allocated_chunks += 1;
+ return malloc(sz);
+}
+
+static void *
+cnt_realloc(void *old, size_t sz)
+{
+ if (!old)
+ allocated_chunks += 1;
+ if (!sz)
+ allocated_chunks -= 1;
+ return realloc(old, sz);
+}
+
+static void
+cnt_free(void *ptr)
+{
+ allocated_chunks -= 1;
+ free(ptr);
+}
+
+struct testleak_env_t {
+ struct event_base *base;
+ struct evdns_base *dns_base;
+ struct evdns_request *req;
+ struct generic_dns_callback_result r;
+};
+
+static void *
+testleak_setup(const struct testcase_t *testcase)
+{
+ struct testleak_env_t *env;
+
+ allocated_chunks = 0;
+
+ /* Reset allocation counter, to start allocations from the very beginning.
+ * (this will avoid false-positive negative numbers for allocated_chunks)
+ */
+ libevent_global_shutdown();
+
+ event_set_mem_functions(cnt_malloc, cnt_realloc, cnt_free);
+
+ event_enable_debug_mode();
+
+ /* not mm_calloc: we don't want to mess with the count. */
+ env = calloc(1, sizeof(struct testleak_env_t));
+ env->base = event_base_new();
+ env->dns_base = evdns_base_new(env->base, 0);
+ env->req = evdns_base_resolve_ipv4(
+ env->dns_base, "example.com", DNS_QUERY_NO_SEARCH,
+ generic_dns_callback, &env->r);
+ return env;
+}
+
+static int
+testleak_cleanup(const struct testcase_t *testcase, void *env_)
+{
+ int ok = 0;
+ struct testleak_env_t *env = env_;
+ tt_assert(env);
+#ifdef EVENT__DISABLE_DEBUG_MODE
+ tt_int_op(allocated_chunks, ==, 0);
+#else
+ libevent_global_shutdown();
+ tt_int_op(allocated_chunks, ==, 0);
+#endif
+ ok = 1;
+end:
+ if (env) {
+ if (env->dns_base)
+ evdns_base_free(env->dns_base, 0);
+ if (env->base)
+ event_base_free(env->base);
+ free(env);
+ }
+ return ok;
+}
+
+static struct testcase_setup_t testleak_funcs = {
+ testleak_setup, testleak_cleanup
+};
+
+static void
+test_dbg_leak_cancel(void *env_)
+{
+ /* cancel, loop, free/dns, free/base */
+ struct testleak_env_t *env = env_;
+ int send_err_shutdown = 1;
+ evdns_cancel_request(env->dns_base, env->req);
+ env->req = 0;
+
+ /* `req` is freed in callback, that's why one loop is required. */
+ event_base_loop(env->base, EVLOOP_NONBLOCK);
+
+ /* send_err_shutdown means nothing as soon as our request is
+ * already canceled */
+ evdns_base_free(env->dns_base, send_err_shutdown);
+ env->dns_base = 0;
+ event_base_free(env->base);
+ env->base = 0;
+}
+
+static void
+dbg_leak_resume(void *env_, int cancel, int send_err_shutdown)
+{
+ /* cancel, loop, free/dns, free/base */
+ struct testleak_env_t *env = env_;
+ if (cancel) {
+ evdns_cancel_request(env->dns_base, env->req);
+ tt_assert(!evdns_base_resume(env->dns_base));
+ } else {
+ /* TODO: No nameservers, request can't be processed, must be errored */
+ tt_assert(!evdns_base_resume(env->dns_base));
+ }
+
+ event_base_loop(env->base, EVLOOP_NONBLOCK);
+ /**
+ * Because we don't cancel request, and want our callback to recieve
+ * DNS_ERR_SHUTDOWN, we use deferred callback, and there was:
+ * - one extra malloc(),
+ * @see reply_schedule_callback()
+ * - and one missing free
+ * @see request_finished() (req->handle->pending_cb = 1)
+ * than we don't need to count in testleak_cleanup(), but we can clean them
+ * if we will run loop once again, but *after* evdns base freed.
+ */
+ evdns_base_free(env->dns_base, send_err_shutdown);
+ env->dns_base = 0;
+ event_base_loop(env->base, EVLOOP_NONBLOCK);
+
+end:
+ event_base_free(env->base);
+ env->base = 0;
+}
+
+#define IMPL_DBG_LEAK_RESUME(name, cancel, send_err_shutdown) \
+ static void \
+ test_dbg_leak_##name##_(void *env_) \
+ { \
+ dbg_leak_resume(env_, cancel, send_err_shutdown); \
+ }
+IMPL_DBG_LEAK_RESUME(resume, 0, 0)
+IMPL_DBG_LEAK_RESUME(cancel_and_resume, 1, 0)
+IMPL_DBG_LEAK_RESUME(resume_send_err, 0, 1)
+IMPL_DBG_LEAK_RESUME(cancel_and_resume_send_err, 1, 1)
+
+static void
+test_dbg_leak_shutdown(void *env_)
+{
+ /* free/dns, loop, free/base */
+ struct testleak_env_t *env = env_;
+ int send_err_shutdown = 1;
+
+ /* `req` is freed both with `send_err_shutdown` and without it,
+ * the only difference is `evdns_callback` call */
+ env->req = 0;
+
+ evdns_base_free(env->dns_base, send_err_shutdown);
+ env->dns_base = 0;
+
+ /* `req` is freed in callback, that's why one loop is required */
+ event_base_loop(env->base, EVLOOP_NONBLOCK);
+ event_base_free(env->base);
+ env->base = 0;
+}
+#endif
+
+static void
+test_getaddrinfo_async_cancel_stress(void *ptr)
+{
+ struct event_base *base;
+ struct evdns_base *dns_base = NULL;
+ struct evdns_server_port *server = NULL;
+ evutil_socket_t fd = -1;
+ struct sockaddr_in sin;
+ struct sockaddr_storage ss;
+ ev_socklen_t slen;
+ unsigned i;
+
+ base = event_base_new();
+ dns_base = evdns_base_new(base, 0);
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_port = 0;
+ sin.sin_addr.s_addr = htonl(0x7f000001);
+ if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+ tt_abort_perror("socket");
+ }
+ evutil_make_socket_nonblocking(fd);
+ if (bind(fd, (struct sockaddr*)&sin, sizeof(sin))<0) {
+ tt_abort_perror("bind");
+ }
+ server = evdns_add_server_port_with_base(base, fd, 0, gaic_server_cb,
+ base);
+
+ memset(&ss, 0, sizeof(ss));
+ slen = sizeof(ss);
+ if (getsockname(fd, (struct sockaddr*)&ss, &slen)<0) {
+ tt_abort_perror("getsockname");
+ }
+ evdns_base_nameserver_sockaddr_add(dns_base,
+ (struct sockaddr*)&ss, slen, 0);
+
+ for (i = 0; i < 1000; ++i) {
+ gaic_launch(base, dns_base);
+ }
+
+ event_base_dispatch(base);
+
+ // at least some was canceled via external event
+ tt_int_op(gaic_freed, !=, 1000);
+
+end:
+ if (dns_base)
+ evdns_base_free(dns_base, 1);
+ if (server)
+ evdns_close_server_port(server);
+ if (base)
+ event_base_free(base);
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static void
+dns_client_fail_requests_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ int limit_inflight = data->setup_data && !strcmp(data->setup_data, "limit-inflight");
+ struct evdns_base *dns = NULL;
+ struct evdns_server_port *dns_port = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+
+ struct generic_dns_callback_result r[20];
+ unsigned i;
+
+ dns_port = regress_get_dnsserver(base, &portnum, NULL,
+ regress_dns_server_cb, reissue_table);
+ tt_assert(dns_port);
+
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+ if (limit_inflight)
+ tt_assert(!evdns_base_set_option(dns, "max-inflight:", "11"));
+
+ for (i = 0; i < 20; ++i)
+ evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r[i]);
+
+ n_replies_left = 20;
+ exit_base = base;
+
+ evdns_base_free(dns, 1 /** fail requests */);
+ /** run defered callbacks, to trigger UAF */
+ event_base_dispatch(base);
+
+ tt_int_op(n_replies_left, ==, 0);
+ for (i = 0; i < 20; ++i)
+ tt_int_op(r[i].result, ==, DNS_ERR_SHUTDOWN);
+
+end:
+ evdns_close_server_port(dns_port);
+}
+
+static void
+getaddrinfo_cb(int err, struct evutil_addrinfo *res, void *ptr)
+{
+ generic_dns_callback(err, 0, 0, 0, NULL, ptr);
+}
+static void
+dns_client_fail_requests_getaddrinfo_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evdns_base *dns = NULL;
+ struct evdns_server_port *dns_port = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+
+ struct generic_dns_callback_result r[20];
+ int i;
+
+ dns_port = regress_get_dnsserver(base, &portnum, NULL,
+ regress_dns_server_cb, reissue_table);
+ tt_assert(dns_port);
+
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ dns = evdns_base_new(base, EVDNS_BASE_DISABLE_WHEN_INACTIVE);
+ tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
+
+ for (i = 0; i < 20; ++i)
+ tt_assert(evdns_getaddrinfo(dns, "foof.example.com", "80", NULL, getaddrinfo_cb, &r[i]));
+
+ n_replies_left = 20;
+ exit_base = base;
+
+ evdns_base_free(dns, 1 /** fail requests */);
+ /** run defered callbacks, to trigger UAF */
+ event_base_dispatch(base);
+
+ tt_int_op(n_replies_left, ==, 0);
+ for (i = 0; i < 20; ++i)
+ tt_int_op(r[i].result, ==, EVUTIL_EAI_FAIL);
+
+end:
+ evdns_close_server_port(dns_port);
+}
+
+#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
+struct race_param
+{
+ void *lock;
+ void *reqs_cmpl_cond;
+ int bw_threads;
+ void *bw_threads_exited_cond;
+ volatile int stopping;
+ void *base;
+ void *dns;
+
+ int locked;
+};
+static void *
+race_base_run(void *arg)
+{
+ struct race_param *rp = (struct race_param *)arg;
+ event_base_loop(rp->base, EVLOOP_NO_EXIT_ON_EMPTY);
+ THREAD_RETURN();
+}
+static void *
+race_busywait_run(void *arg)
+{
+ struct race_param *rp = (struct race_param *)arg;
+ struct sockaddr_storage ss;
+ while (!rp->stopping)
+ evdns_base_get_nameserver_addr(rp->dns, 0, (struct sockaddr *)&ss, sizeof(ss));
+ EVLOCK_LOCK(rp->lock, 0);
+ if (--rp->bw_threads == 0)
+ EVTHREAD_COND_SIGNAL(rp->bw_threads_exited_cond);
+ EVLOCK_UNLOCK(rp->lock, 0);
+ THREAD_RETURN();
+}
+static void
+race_gai_cb(int result, struct evutil_addrinfo *res, void *arg)
+{
+ struct race_param *rp = arg;
+ (void)result;
+ (void)res;
+
+ --n_replies_left;
+ if (n_replies_left == 0) {
+ EVLOCK_LOCK(rp->lock, 0);
+ EVTHREAD_COND_SIGNAL(rp->reqs_cmpl_cond);
+ EVLOCK_UNLOCK(rp->lock, 0);
+ }
+}
+static void
+getaddrinfo_race_gotresolve_test(void *arg)
+{
+ struct race_param rp;
+ struct evdns_server_port *dns_port = NULL;
+ ev_uint16_t portnum = 0;
+ char buf[64];
+ int i;
+
+ // Some stress is needed to yield inside getaddrinfo between resolve_ipv4 and resolve_ipv6
+ int n_reqs = 16384;
+#ifdef _SC_NPROCESSORS_ONLN
+ int n_threads = sysconf(_SC_NPROCESSORS_ONLN) + 1;
+#else
+ int n_threads = 17;
+#endif
+ THREAD_T thread[n_threads];
+ struct timeval tv;
+
+ (void)arg;
+
+ evthread_use_pthreads();
+
+ rp.base = event_base_new();
+ tt_assert(rp.base);
+ if (evthread_make_base_notifiable(rp.base) < 0)
+ tt_abort_msg("Couldn't make base notifiable!");
+
+ dns_port = regress_get_dnsserver(rp.base, &portnum, NULL,
+ regress_dns_server_cb, reissue_table);
+ tt_assert(dns_port);
+
+ evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
+
+ rp.dns = evdns_base_new(rp.base, 0);
+ tt_assert(!evdns_base_nameserver_ip_add(rp.dns, buf));
+
+ n_replies_left = n_reqs;
+
+ EVTHREAD_ALLOC_LOCK(rp.lock, 0);
+ EVTHREAD_ALLOC_COND(rp.reqs_cmpl_cond);
+ EVTHREAD_ALLOC_COND(rp.bw_threads_exited_cond);
+ tt_assert(rp.lock);
+ tt_assert(rp.reqs_cmpl_cond);
+ tt_assert(rp.bw_threads_exited_cond);
+ rp.bw_threads = 0;
+ rp.stopping = 0;
+
+ // Run resolver thread
+ THREAD_START(thread[0], race_base_run, &rp);
+ // Run busy-wait threads used to force yield this thread
+ for (i = 1; i < n_threads; i++) {
+ rp.bw_threads++;
+ THREAD_START(thread[i], race_busywait_run, &rp);
+ }
+
+ EVLOCK_LOCK(rp.lock, 0);
+ rp.locked = 1;
+
+ for (i = 0; i < n_reqs; ++i) {
+ tt_assert(evdns_getaddrinfo(rp.dns, "foof.example.com", "80", NULL, race_gai_cb, &rp));
+ // This magic along with busy-wait threads make this thread yield frequently
+ if (i % 100 == 0) {
+ tv.tv_sec = 0;
+ tv.tv_usec = 10000;
+ evutil_usleep_(&tv);
+ }
+ }
+
+ exit_base = rp.base;
+
+ // Wait for some time
+ tv.tv_sec = 5;
+ tv.tv_usec = 0;
+ EVTHREAD_COND_WAIT_TIMED(rp.reqs_cmpl_cond, rp.lock, &tv);
+
+ // Stop busy-wait threads
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+ rp.stopping = 1;
+ tt_assert(EVTHREAD_COND_WAIT_TIMED(rp.bw_threads_exited_cond, rp.lock, &tv) == 0);
+
+ EVLOCK_UNLOCK(rp.lock, 0);
+ rp.locked = 0;
+
+ evdns_base_free(rp.dns, 1 /** fail requests */);
+
+ tt_int_op(n_replies_left, ==, 0);
+
+end:
+ if (rp.locked)
+ EVLOCK_UNLOCK(rp.lock, 0);
+ EVTHREAD_FREE_LOCK(rp.lock, 0);
+ EVTHREAD_FREE_COND(rp.reqs_cmpl_cond);
+ EVTHREAD_FREE_COND(rp.bw_threads_exited_cond);
+ evdns_close_server_port(dns_port);
+ event_base_loopbreak(rp.base);
+ event_base_free(rp.base);
+}
+#endif
+
+static void
+test_set_so_rcvbuf_so_sndbuf(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evdns_base *dns_base;
+
+ dns_base = evdns_base_new(data->base, 0);
+ tt_assert(dns_base);
+
+ tt_assert(!evdns_base_set_option(dns_base, "so-rcvbuf", "10240"));
+ tt_assert(!evdns_base_set_option(dns_base, "so-sndbuf", "10240"));
+
+ /* actually check SO_RCVBUF/SO_SNDBUF not fails */
+ tt_assert(!evdns_base_nameserver_ip_add(dns_base, "127.0.0.1"));
+
+end:
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+}
+
+static void
+test_set_option(void *arg)
+{
+#define SUCCESS 0
+#define FAIL -1
+ struct basic_test_data *data = arg;
+ struct evdns_base *dns_base;
+ size_t i;
+ /* Option names are allowed to have ':' at the end.
+ * So all test option names come in pairs.
+ */
+ const char *int_options[] = {
+ "ndots", "ndots:",
+ "max-timeouts", "max-timeouts:",
+ "max-inflight", "max-inflight:",
+ "attempts", "attempts:",
+ "randomize-case", "randomize-case:",
+ "so-rcvbuf", "so-rcvbuf:",
+ "so-sndbuf", "so-sndbuf:",
+ };
+ const char *timeval_options[] = {
+ "timeout", "timeout:",
+ "getaddrinfo-allow-skew", "getaddrinfo-allow-skew:",
+ "initial-probe-timeout", "initial-probe-timeout:",
+ };
+ const char *addr_port_options[] = {
+ "bind-to", "bind-to:",
+ };
+
+ dns_base = evdns_base_new(data->base, 0);
+ tt_assert(dns_base);
+
+ for (i = 0; i < ARRAY_SIZE(int_options); ++i) {
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, int_options[i], "0"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, int_options[i], "1"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, int_options[i], "10000"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, int_options[i], "foo"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, int_options[i], "3.14"));
+ }
+
+ for (i = 0; i < ARRAY_SIZE(timeval_options); ++i) {
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, timeval_options[i], "1"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, timeval_options[i], "0.001"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, timeval_options[i], "3.14"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, timeval_options[i], "10000"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, timeval_options[i], "0"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, timeval_options[i], "foo"));
+ }
+
+ for (i = 0; i < ARRAY_SIZE(addr_port_options); ++i) {
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, addr_port_options[i], "8.8.8.8:80"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, addr_port_options[i], "1.2.3.4"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, addr_port_options[i], "::1:82"));
+ tt_assert(SUCCESS == evdns_base_set_option(dns_base, addr_port_options[i], "3::4"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, addr_port_options[i], "3.14"));
+ tt_assert(FAIL == evdns_base_set_option(dns_base, addr_port_options[i], "foo"));
+ }
+
+#undef SUCCESS
+#undef FAIL
+end:
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+}
+
+#define DNS_LEGACY(name, flags) \
+ { #name, run_legacy_test_fn, flags|TT_LEGACY, &legacy_setup, \
+ dns_##name }
+
+struct testcase_t dns_testcases[] = {
+ DNS_LEGACY(server, TT_FORK|TT_NEED_BASE),
+ DNS_LEGACY(gethostbyname, TT_FORK|TT_NEED_BASE|TT_NEED_DNS|TT_OFF_BY_DEFAULT),
+ DNS_LEGACY(gethostbyname6, TT_FORK|TT_NEED_BASE|TT_NEED_DNS|TT_OFF_BY_DEFAULT),
+ DNS_LEGACY(gethostbyaddr, TT_FORK|TT_NEED_BASE|TT_NEED_DNS|TT_OFF_BY_DEFAULT),
+ { "resolve_reverse", dns_resolve_reverse, TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
+ { "search_empty", dns_search_empty_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "search", dns_search_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "search_lower", dns_search_lower_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "search_cancel", dns_search_cancel_test,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "retry", dns_retry_test, TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+ { "retry_disable_when_inactive", dns_retry_disable_when_inactive_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+ { "reissue", dns_reissue_test, TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+ { "reissue_disable_when_inactive", dns_reissue_disable_when_inactive_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+ { "inflight", dns_inflight_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "bufferevent_connect_hostname", test_bufferevent_connect_hostname,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+#ifdef EVENT__HAVE_SETRLIMIT
+ { "bufferevent_connect_hostname_emfile", test_bufferevent_connect_hostname,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (char*)"emfile" },
+#endif
+ { "disable_when_inactive", dns_disable_when_inactive_test,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "disable_when_inactive_no_ns", dns_disable_when_inactive_no_ns_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+
+ { "initialize_nameservers", dns_initialize_nameservers_test,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+#ifndef _WIN32
+ { "nameservers_no_default", dns_nameservers_no_default_test,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+#endif
+
+ { "getaddrinfo_async", test_getaddrinfo_async,
+ TT_FORK|TT_NEED_BASE, &basic_setup, (char*)"" },
+ { "getaddrinfo_cancel_stress", test_getaddrinfo_async_cancel_stress,
+ TT_FORK, NULL, NULL },
+
+#ifdef EVENT_SET_MEM_FUNCTIONS_IMPLEMENTED
+ { "leak_shutdown", test_dbg_leak_shutdown, TT_FORK, &testleak_funcs, NULL },
+ { "leak_cancel", test_dbg_leak_cancel, TT_FORK, &testleak_funcs, NULL },
+
+ { "leak_resume", test_dbg_leak_resume_, TT_FORK, &testleak_funcs, NULL },
+ { "leak_cancel_and_resume", test_dbg_leak_cancel_and_resume_,
+ TT_FORK, &testleak_funcs, NULL },
+ { "leak_resume_send_err", test_dbg_leak_resume_send_err_,
+ TT_FORK, &testleak_funcs, NULL },
+ { "leak_cancel_and_resume_send_err", test_dbg_leak_cancel_and_resume_send_err_,
+ TT_FORK, &testleak_funcs, NULL },
+#endif
+
+ { "client_fail_requests", dns_client_fail_requests_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+ { "client_fail_waiting_requests", dns_client_fail_requests_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, (char*)"limit-inflight" },
+ { "client_fail_requests_getaddrinfo",
+ dns_client_fail_requests_getaddrinfo_test,
+ TT_FORK|TT_NEED_BASE|TT_NO_LOGS, &basic_setup, NULL },
+#ifdef EVTHREAD_USE_PTHREADS_IMPLEMENTED
+ { "getaddrinfo_race_gotresolve",
+ getaddrinfo_race_gotresolve_test,
+ TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
+#endif
+
+ { "set_SO_RCVBUF_SO_SNDBUF", test_set_so_rcvbuf_so_sndbuf,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+ { "set_options", test_set_option,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
+
+ END_OF_TESTCASES
+};
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_et.c b/ipc/chromium/src/third_party/libevent/test/regress_et.c
new file mode 100644
index 0000000000..1b1f819eda
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_et.c
@@ -0,0 +1,270 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef _WIN32
+#include <sys/time.h>
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "regress.h"
+
+static int was_et = 0;
+
+static int base_supports_et(struct event_base *base)
+{
+ return
+ (!strcmp(event_base_get_method(base), "epoll") ||
+ !strcmp(event_base_get_method(base), "epoll (with changelist)") ||
+ !strcmp(event_base_get_method(base), "kqueue"));
+}
+
+static void
+read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf;
+ int len;
+
+ len = recv(fd, &buf, sizeof(buf), 0);
+
+ called++;
+ if (event & EV_ET)
+ was_et = 1;
+
+ if (!len)
+ event_del(arg);
+}
+
+static void
+test_edgetriggered(void *data_)
+{
+ struct basic_test_data *data = data_;
+ struct event_base *base = data->base;
+ evutil_socket_t *pair = data->pair;
+ struct event *ev = NULL;
+ const char *test = "test string";
+ int supports_et;
+
+ /* On Linux 3.2.1 (at least, as patched by Fedora and tested by Nick),
+ * doing a "recv" on an AF_UNIX socket resets the readability of the
+ * socket, even though there is no state change, so we don't actually
+ * get edge-triggered behavior. Yuck! Linux 3.1.9 didn't have this
+ * problem.
+ */
+
+ called = was_et = 0;
+
+ tt_int_op(send(pair[0], test, (int)strlen(test)+1, 0), >, 0);
+ tt_int_op(shutdown(pair[0], EVUTIL_SHUT_WR), ==, 0);
+
+ supports_et = base_supports_et(base);
+ TT_BLATHER(("Checking for edge-triggered events with %s, which should %s"
+ "support edge-triggering", event_base_get_method(base),
+ supports_et?"":"not "));
+
+ /* Initialize one event */
+ ev = event_new(base, pair[1], EV_READ|EV_ET|EV_PERSIST, read_cb, &ev);
+ tt_assert(ev != NULL);
+ tt_int_op(event_add(ev, NULL), ==, 0);
+
+ /* We're going to call the dispatch function twice. The first invocation
+ * will read a single byte from pair[1] in either case. If we're edge
+ * triggered, we'll only see the event once (since we only see transitions
+ * from no data to data), so the second invocation of event_base_loop will
+ * do nothing. If we're level triggered, the second invocation of
+ * event_base_loop will also activate the event (because there's still
+ * data to read). */
+ tt_int_op(event_base_loop(base,EVLOOP_NONBLOCK|EVLOOP_ONCE), ==, 0);
+ tt_int_op(event_base_loop(base,EVLOOP_NONBLOCK|EVLOOP_ONCE), ==, 0);
+
+ if (supports_et) {
+ tt_int_op(called, ==, 1);
+ tt_assert(was_et);
+ } else {
+ tt_int_op(called, ==, 2);
+ tt_assert(!was_et);
+ }
+
+end:
+ if (ev) {
+ event_del(ev);
+ event_free(ev);
+ }
+}
+
+static void
+test_edgetriggered_mix_error(void *data_)
+{
+ struct basic_test_data *data = data_;
+ struct event_base *base = NULL;
+ struct event *ev_et=NULL, *ev_lt=NULL;
+
+#ifdef EVENT__DISABLE_DEBUG_MODE
+ if (1)
+ tt_skip();
+#endif
+
+ if (!libevent_tests_running_in_debug_mode)
+ event_enable_debug_mode();
+
+ base = event_base_new();
+
+ /* try mixing edge-triggered and level-triggered to make sure it fails*/
+ ev_et = event_new(base, data->pair[0], EV_READ|EV_ET, read_cb, ev_et);
+ tt_assert(ev_et);
+ ev_lt = event_new(base, data->pair[0], EV_READ, read_cb, ev_lt);
+ tt_assert(ev_lt);
+
+ /* Add edge-triggered, then level-triggered. Get an error. */
+ tt_int_op(0, ==, event_add(ev_et, NULL));
+ tt_int_op(-1, ==, event_add(ev_lt, NULL));
+ tt_int_op(EV_READ, ==, event_pending(ev_et, EV_READ, NULL));
+ tt_int_op(0, ==, event_pending(ev_lt, EV_READ, NULL));
+
+ tt_int_op(0, ==, event_del(ev_et));
+ /* Add level-triggered, then edge-triggered. Get an error. */
+ tt_int_op(0, ==, event_add(ev_lt, NULL));
+ tt_int_op(-1, ==, event_add(ev_et, NULL));
+ tt_int_op(EV_READ, ==, event_pending(ev_lt, EV_READ, NULL));
+ tt_int_op(0, ==, event_pending(ev_et, EV_READ, NULL));
+
+end:
+ if (ev_et)
+ event_free(ev_et);
+ if (ev_lt)
+ event_free(ev_lt);
+ if (base)
+ event_base_free(base);
+}
+
+static int read_notification_count;
+static int last_read_notification_was_et;
+static void
+read_notification_cb(evutil_socket_t fd, short event, void *arg)
+{
+ read_notification_count++;
+ last_read_notification_was_et = (event & EV_ET);
+}
+
+static int write_notification_count;
+static int last_write_notification_was_et;
+static void
+write_notification_cb(evutil_socket_t fd, short event, void *arg)
+{
+ write_notification_count++;
+ last_write_notification_was_et = (event & EV_ET);
+}
+
+/* After two or more events have been registered for the same
+ * file descriptor using EV_ET, if one of the events is
+ * deleted, then the epoll_ctl() call issued by libevent drops
+ * the EPOLLET flag resulting in level triggered
+ * notifications.
+ */
+static void
+test_edge_triggered_multiple_events(void *data_)
+{
+ struct basic_test_data *data = data_;
+ struct event *read_ev = NULL;
+ struct event *write_ev = NULL;
+ const char c = 'A';
+ struct event_base *base = data->base;
+ evutil_socket_t *pair = data->pair;
+
+ if (!base_supports_et(base)) {
+ tt_skip();
+ return;
+ }
+
+ read_notification_count = 0;
+ last_read_notification_was_et = 0;
+ write_notification_count = 0;
+ last_write_notification_was_et = 0;
+
+ /* Make pair[1] readable */
+ tt_int_op(send(pair[0], &c, 1, 0), >, 0);
+
+ read_ev = event_new(base, pair[1], EV_READ|EV_ET|EV_PERSIST,
+ read_notification_cb, NULL);
+ write_ev = event_new(base, pair[1], EV_WRITE|EV_ET|EV_PERSIST,
+ write_notification_cb, NULL);
+
+ event_add(read_ev, NULL);
+ event_add(write_ev, NULL);
+ event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+ event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+
+ tt_assert(last_read_notification_was_et);
+ tt_int_op(read_notification_count, ==, 1);
+ tt_assert(last_write_notification_was_et);
+ tt_int_op(write_notification_count, ==, 1);
+
+ event_del(read_ev);
+
+ /* trigger acitivity second time for the backend that can have multiple
+ * events for one fd (like kqueue) */
+ close(pair[0]);
+ pair[0] = -1;
+
+ /* Verify that we are still edge-triggered for write notifications */
+ event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+ event_base_loop(base, EVLOOP_NONBLOCK|EVLOOP_ONCE);
+ tt_assert(last_write_notification_was_et);
+ tt_int_op(write_notification_count, ==, 2);
+
+end:
+ if (read_ev)
+ event_free(read_ev);
+ if (write_ev)
+ event_free(write_ev);
+}
+
+struct testcase_t edgetriggered_testcases[] = {
+ { "et", test_edgetriggered,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR, &basic_setup, NULL },
+ { "et_mix_error", test_edgetriggered_mix_error,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NO_LOGS, &basic_setup, NULL },
+ { "et_multiple_events", test_edge_triggered_multiple_events,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR, &basic_setup, NULL },
+ END_OF_TESTCASES
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_finalize.c b/ipc/chromium/src/third_party/libevent/test/regress_finalize.c
new file mode 100644
index 0000000000..9e57188121
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_finalize.c
@@ -0,0 +1,395 @@
+/*
+ * Copyright (c) 2013 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include <stdlib.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event-internal.h"
+#include "defer-internal.h"
+
+#include "regress.h"
+#include "regress_thread.h"
+
+static void
+timer_callback(evutil_socket_t fd, short what, void *arg)
+{
+ int *int_arg = arg;
+ *int_arg += 1;
+ (void)fd;
+ (void)what;
+}
+static void
+simple_callback(struct event_callback *evcb, void *arg)
+{
+ int *int_arg = arg;
+ *int_arg += 1;
+ (void)evcb;
+}
+static void
+event_finalize_callback_1(struct event *ev, void *arg)
+{
+ int *int_arg = arg;
+ *int_arg += 100;
+ (void)ev;
+}
+static void
+callback_finalize_callback_1(struct event_callback *evcb, void *arg)
+{
+ int *int_arg = arg;
+ *int_arg += 100;
+ (void)evcb;
+}
+
+
+static void
+test_fin_cb_invoked(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+
+ struct event *ev;
+ struct event ev2;
+ struct event_callback evcb;
+ int cb_called = 0;
+ int ev_called = 0;
+
+ const struct timeval ten_sec = {10,0};
+
+ event_deferred_cb_init_(&evcb, 0, simple_callback, &cb_called);
+ ev = evtimer_new(base, timer_callback, &ev_called);
+ /* Just finalize them; don't bother adding. */
+ event_free_finalize(0, ev, event_finalize_callback_1);
+ event_callback_finalize_(base, 0, &evcb, callback_finalize_callback_1);
+
+ event_base_dispatch(base);
+
+ tt_int_op(cb_called, ==, 100);
+ tt_int_op(ev_called, ==, 100);
+
+ ev_called = cb_called = 0;
+ event_base_assert_ok_(base);
+
+ /* Now try it when they're active. (actually, don't finalize: make
+ * sure activation can happen! */
+ ev = evtimer_new(base, timer_callback, &ev_called);
+ event_deferred_cb_init_(&evcb, 0, simple_callback, &cb_called);
+
+ event_active(ev, EV_TIMEOUT, 1);
+ event_callback_activate_(base, &evcb);
+
+ event_base_dispatch(base);
+ tt_int_op(cb_called, ==, 1);
+ tt_int_op(ev_called, ==, 1);
+
+ ev_called = cb_called = 0;
+ event_base_assert_ok_(base);
+
+ /* Great, it worked. Now activate and finalize and make sure only
+ * finalizing happens. */
+ event_active(ev, EV_TIMEOUT, 1);
+ event_callback_activate_(base, &evcb);
+ event_free_finalize(0, ev, event_finalize_callback_1);
+ event_callback_finalize_(base, 0, &evcb, callback_finalize_callback_1);
+
+ event_base_dispatch(base);
+ tt_int_op(cb_called, ==, 100);
+ tt_int_op(ev_called, ==, 100);
+
+ ev_called = 0;
+
+ event_base_assert_ok_(base);
+
+ /* Okay, now add but don't have it become active, and make sure *that*
+ * works. */
+ ev = evtimer_new(base, timer_callback, &ev_called);
+ event_add(ev, &ten_sec);
+ event_free_finalize(0, ev, event_finalize_callback_1);
+
+ event_base_dispatch(base);
+ tt_int_op(ev_called, ==, 100);
+
+ ev_called = 0;
+ event_base_assert_ok_(base);
+
+ /* Now try adding and deleting after finalizing. */
+ ev = evtimer_new(base, timer_callback, &ev_called);
+ evtimer_assign(&ev2, base, timer_callback, &ev_called);
+ event_add(ev, &ten_sec);
+ event_free_finalize(0, ev, event_finalize_callback_1);
+ event_finalize(0, &ev2, event_finalize_callback_1);
+
+ event_add(&ev2, &ten_sec);
+ event_del(ev);
+ event_active(&ev2, EV_TIMEOUT, 1);
+
+ event_base_dispatch(base);
+ tt_int_op(ev_called, ==, 200);
+
+ event_base_assert_ok_(base);
+
+end:
+ ;
+}
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+static void *
+tfff_malloc(size_t n)
+{
+ return malloc(n);
+}
+static void *tfff_p1=NULL, *tfff_p2=NULL;
+static int tfff_p1_freed=0, tfff_p2_freed=0;
+static void
+tfff_free(void *p)
+{
+ if (! p)
+ return;
+ if (p == tfff_p1)
+ ++tfff_p1_freed;
+ if (p == tfff_p2)
+ ++tfff_p2_freed;
+ free(p);
+}
+static void *
+tfff_realloc(void *p, size_t sz)
+{
+ return realloc(p,sz);
+}
+#endif
+
+static void
+test_fin_free_finalize(void *arg)
+{
+#ifdef EVENT__DISABLE_MM_REPLACEMENT
+ tinytest_set_test_skipped_();
+#else
+ struct event_base *base = NULL;
+ struct event *ev, *ev2;
+ int ev_called = 0;
+ int ev2_called = 0;
+
+ (void)arg;
+
+ event_set_mem_functions(tfff_malloc, tfff_realloc, tfff_free);
+
+ base = event_base_new();
+ tt_assert(base);
+
+ ev = evtimer_new(base, timer_callback, &ev_called);
+ ev2 = evtimer_new(base, timer_callback, &ev2_called);
+ tfff_p1 = ev;
+ tfff_p2 = ev2;
+ event_free_finalize(0, ev, event_finalize_callback_1);
+ event_finalize(0, ev2, event_finalize_callback_1);
+
+ event_base_dispatch(base);
+
+ tt_int_op(ev_called, ==, 100);
+ tt_int_op(ev2_called, ==, 100);
+
+ event_base_assert_ok_(base);
+ tt_int_op(tfff_p1_freed, ==, 1);
+ tt_int_op(tfff_p2_freed, ==, 0);
+
+ event_free(ev2);
+
+end:
+ if (base)
+ event_base_free(base);
+#endif
+}
+
+/* For test_fin_within_cb */
+struct event_and_count {
+ struct event *ev;
+ struct event *ev2;
+ int count;
+};
+static void
+event_finalize_callback_2(struct event *ev, void *arg)
+{
+ struct event_and_count *evc = arg;
+ evc->count += 100;
+ event_free(ev);
+}
+static void
+timer_callback_2(evutil_socket_t fd, short what, void *arg)
+{
+ struct event_and_count *evc = arg;
+ event_finalize(0, evc->ev, event_finalize_callback_2);
+ event_finalize(0, evc->ev2, event_finalize_callback_2);
+ ++ evc->count;
+ (void)fd;
+ (void)what;
+}
+
+static void
+test_fin_within_cb(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+
+ struct event_and_count evc1, evc2;
+ evc1.count = evc2.count = 0;
+ evc2.ev2 = evc1.ev = evtimer_new(base, timer_callback_2, &evc1);
+ evc1.ev2 = evc2.ev = evtimer_new(base, timer_callback_2, &evc2);
+
+ /* Activate both. The first one will have its callback run, which
+ * will finalize both of them, preventing the second one's callback
+ * from running. */
+ event_active(evc1.ev, EV_TIMEOUT, 1);
+ event_active(evc2.ev, EV_TIMEOUT, 1);
+
+ event_base_dispatch(base);
+ tt_int_op(evc1.count, ==, 101);
+ tt_int_op(evc2.count, ==, 100);
+
+ event_base_assert_ok_(base);
+ /* Now try with EV_PERSIST events. */
+ evc1.count = evc2.count = 0;
+ evc2.ev2 = evc1.ev = event_new(base, -1, EV_PERSIST, timer_callback_2, &evc1);
+ evc1.ev2 = evc2.ev = event_new(base, -1, EV_PERSIST, timer_callback_2, &evc2);
+
+ event_active(evc1.ev, EV_TIMEOUT, 1);
+ event_active(evc2.ev, EV_TIMEOUT, 1);
+
+ event_base_dispatch(base);
+ tt_int_op(evc1.count, ==, 101);
+ tt_int_op(evc2.count, ==, 100);
+
+ event_base_assert_ok_(base);
+end:
+ ;
+}
+
+static void
+event_finalize_callback_free(struct event *ev, void *arg)
+{
+ struct event_base *base = arg;
+ int err;
+ if (base) {
+ err = event_assign(ev, base, -1, EV_TIMEOUT, NULL, NULL);
+ tt_int_op(err, ==, 0);
+ test_ok += 1;
+ } else {
+ free(ev);
+ test_ok += 1;
+ }
+
+end:
+ ;
+}
+static void
+test_fin_debug_use_after_free(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct event *ev;
+
+ tt_ptr_op(ev = event_new(base, -1, EV_TIMEOUT, NULL, base), !=, NULL);
+ tt_int_op(event_add(ev, NULL), ==, 0);
+ tt_int_op(event_finalize(0, ev, event_finalize_callback_free), ==, 0);
+
+ // Dispatch base to trigger callbacks
+ event_base_dispatch(base);
+ event_base_assert_ok_(base);
+ tt_int_op(test_ok, ==, 1);
+
+ // Now add again, since we did event_assign in event_finalize_callback_free
+ // This used to fail in event_debug_assert_is_setup_
+ tt_int_op(event_add(ev, NULL), ==, 0);
+
+ // Finalize and dispatch again
+ tt_int_op(event_finalize(0, ev, event_finalize_callback_free), ==, 0);
+ event_base_dispatch(base);
+ event_base_assert_ok_(base);
+ tt_int_op(test_ok, ==, 2);
+
+end:
+ ;
+}
+
+#if 0
+static void
+timer_callback_3(evutil_socket_t *fd, short what, void *arg)
+{
+ (void)fd;
+ (void)what;
+
+}
+static void
+test_fin_many(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+
+ struct event *ev1, *ev2;
+ struct event_callback evcb1, evcb2;
+ int ev1_count = 0, ev2_count = 0;
+ int evcb1_count = 0, evcb2_count = 0;
+ struct event_callback *array[4];
+
+ int n;
+
+ /* First attempt: call finalize_many with no events running */
+ ev1 = evtimer_new(base, timer_callback, &ev1_count);
+ ev1 = evtimer_new(base, timer_callback, &ev2_count);
+ event_deferred_cb_init_(&evcb1, 0, simple_callback, &evcb1_called);
+ event_deferred_cb_init_(&evcb2, 0, simple_callback, &evcb2_called);
+ array[0] = &ev1->ev_evcallback;
+ array[1] = &ev2->ev_evcallback;
+ array[2] = &evcb1;
+ array[3] = &evcb2;
+
+
+
+ n = event_callback_finalize_many(base, 4, array,
+ callback_finalize_callback_1);
+
+}
+#endif
+
+
+#define TEST(name, flags) \
+ { #name, test_fin_##name, (flags), &basic_setup, NULL }
+
+struct testcase_t finalize_testcases[] = {
+
+ TEST(cb_invoked, TT_FORK|TT_NEED_BASE),
+ TEST(free_finalize, TT_FORK),
+ TEST(within_cb, TT_FORK|TT_NEED_BASE),
+ TEST(debug_use_after_free, TT_FORK|TT_NEED_BASE|TT_ENABLE_DEBUG_MODE),
+// TEST(many, TT_FORK|TT_NEED_BASE),
+
+
+ END_OF_TESTCASES
+};
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_http.c b/ipc/chromium/src/third_party/libevent/test/regress_http.c
new file mode 100644
index 0000000000..4493907163
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_http.c
@@ -0,0 +1,4807 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/dns.h"
+
+#include "event2/event.h"
+#include "event2/http.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+#include "event2/bufferevent_ssl.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "log-internal.h"
+#include "http-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+
+#define ARRAY_SIZE(x) (sizeof(x)/sizeof((x)[0]))
+
+/* set if a test needs to call loopexit on a base */
+static struct event_base *exit_base;
+
+static char const BASIC_REQUEST_BODY[] = "This is funny";
+
+static void http_basic_cb(struct evhttp_request *req, void *arg);
+static void http_timeout_cb(struct evhttp_request *req, void *arg);
+static void http_large_cb(struct evhttp_request *req, void *arg);
+static void http_chunked_cb(struct evhttp_request *req, void *arg);
+static void http_post_cb(struct evhttp_request *req, void *arg);
+static void http_put_cb(struct evhttp_request *req, void *arg);
+static void http_delete_cb(struct evhttp_request *req, void *arg);
+static void http_delay_cb(struct evhttp_request *req, void *arg);
+static void http_large_delay_cb(struct evhttp_request *req, void *arg);
+static void http_badreq_cb(struct evhttp_request *req, void *arg);
+static void http_dispatcher_cb(struct evhttp_request *req, void *arg);
+static void http_on_complete_cb(struct evhttp_request *req, void *arg);
+
+#define HTTP_BIND_IPV6 1
+#define HTTP_BIND_SSL 2
+#define HTTP_SSL_FILTER 4
+static int
+http_bind(struct evhttp *myhttp, ev_uint16_t *pport, int mask)
+{
+ int port;
+ struct evhttp_bound_socket *sock;
+ int ipv6 = mask & HTTP_BIND_IPV6;
+
+ if (ipv6)
+ sock = evhttp_bind_socket_with_handle(myhttp, "::1", *pport);
+ else
+ sock = evhttp_bind_socket_with_handle(myhttp, "127.0.0.1", *pport);
+
+ if (sock == NULL) {
+ if (ipv6)
+ return -1;
+ else
+ event_errx(1, "Could not start web server");
+ }
+
+ port = regress_get_socket_port(evhttp_bound_socket_get_fd(sock));
+ if (port < 0)
+ return -1;
+ *pport = (ev_uint16_t) port;
+
+ return 0;
+}
+
+#ifdef EVENT__HAVE_OPENSSL
+static struct bufferevent *
+https_bev(struct event_base *base, void *arg)
+{
+ SSL *ssl = SSL_new(get_ssl_ctx());
+
+ SSL_use_certificate(ssl, ssl_getcert(ssl_getkey()));
+ SSL_use_PrivateKey(ssl, ssl_getkey());
+
+ return bufferevent_openssl_socket_new(
+ base, -1, ssl, BUFFEREVENT_SSL_ACCEPTING,
+ BEV_OPT_CLOSE_ON_FREE);
+}
+#endif
+static struct evhttp *
+http_setup_gencb(ev_uint16_t *pport, struct event_base *base, int mask,
+ void (*cb)(struct evhttp_request *, void *), void *cbarg)
+{
+ struct evhttp *myhttp;
+
+ /* Try a few different ports */
+ myhttp = evhttp_new(base);
+
+ if (http_bind(myhttp, pport, mask) < 0)
+ return NULL;
+#ifdef EVENT__HAVE_OPENSSL
+ if (mask & HTTP_BIND_SSL) {
+ init_ssl();
+ evhttp_set_bevcb(myhttp, https_bev, NULL);
+ }
+#endif
+
+ evhttp_set_gencb(myhttp, cb, cbarg);
+
+ /* Register a callback for certain types of requests */
+ evhttp_set_cb(myhttp, "/test", http_basic_cb, myhttp);
+ evhttp_set_cb(myhttp, "/test nonconformant", http_basic_cb, myhttp);
+ evhttp_set_cb(myhttp, "/timeout", http_timeout_cb, myhttp);
+ evhttp_set_cb(myhttp, "/large", http_large_cb, base);
+ evhttp_set_cb(myhttp, "/chunked", http_chunked_cb, base);
+ evhttp_set_cb(myhttp, "/streamed", http_chunked_cb, base);
+ evhttp_set_cb(myhttp, "/postit", http_post_cb, base);
+ evhttp_set_cb(myhttp, "/putit", http_put_cb, base);
+ evhttp_set_cb(myhttp, "/deleteit", http_delete_cb, base);
+ evhttp_set_cb(myhttp, "/delay", http_delay_cb, base);
+ evhttp_set_cb(myhttp, "/largedelay", http_large_delay_cb, base);
+ evhttp_set_cb(myhttp, "/badrequest", http_badreq_cb, base);
+ evhttp_set_cb(myhttp, "/oncomplete", http_on_complete_cb, base);
+ evhttp_set_cb(myhttp, "/", http_dispatcher_cb, base);
+ return (myhttp);
+}
+static struct evhttp *
+http_setup(ev_uint16_t *pport, struct event_base *base, int mask)
+{ return http_setup_gencb(pport, base, mask, NULL, NULL); }
+
+#ifndef NI_MAXSERV
+#define NI_MAXSERV 1024
+#endif
+
+static evutil_socket_t
+http_connect(const char *address, ev_uint16_t port)
+{
+ /* Stupid code for connecting */
+ struct evutil_addrinfo ai, *aitop;
+ char strport[NI_MAXSERV];
+
+ struct sockaddr *sa;
+ size_t slen;
+ evutil_socket_t fd;
+
+ memset(&ai, 0, sizeof(ai));
+ ai.ai_family = AF_INET;
+ ai.ai_socktype = SOCK_STREAM;
+ evutil_snprintf(strport, sizeof(strport), "%d", port);
+ if (evutil_getaddrinfo(address, strport, &ai, &aitop) != 0) {
+ event_warn("getaddrinfo");
+ return (-1);
+ }
+ sa = aitop->ai_addr;
+ slen = aitop->ai_addrlen;
+
+ fd = socket(AF_INET, SOCK_STREAM, 0);
+ if (fd == -1)
+ event_err(1, "socket failed");
+
+ evutil_make_socket_nonblocking(fd);
+ if (connect(fd, sa, slen) == -1) {
+#ifdef _WIN32
+ int tmp_err = WSAGetLastError();
+ if (tmp_err != WSAEINPROGRESS && tmp_err != WSAEINVAL &&
+ tmp_err != WSAEWOULDBLOCK)
+ event_err(1, "connect failed");
+#else
+ if (errno != EINPROGRESS)
+ event_err(1, "connect failed");
+#endif
+ }
+
+ evutil_freeaddrinfo(aitop);
+
+ return (fd);
+}
+
+/* Helper: do a strcmp on the contents of buf and the string s. */
+static int
+evbuffer_datacmp(struct evbuffer *buf, const char *s)
+{
+ size_t b_sz = evbuffer_get_length(buf);
+ size_t s_sz = strlen(s);
+ unsigned char *d;
+ int r;
+
+ if (b_sz < s_sz)
+ return -1;
+
+ d = evbuffer_pullup(buf, s_sz);
+ if (!d)
+ d = (unsigned char *)"";
+ if ((r = memcmp(d, s, s_sz)))
+ return r;
+
+ if (b_sz > s_sz)
+ return 1;
+ else
+ return 0;
+}
+
+/* Helper: Return true iff buf contains s */
+static int
+evbuffer_contains(struct evbuffer *buf, const char *s)
+{
+ struct evbuffer_ptr ptr;
+ ptr = evbuffer_search(buf, s, strlen(s), NULL);
+ return ptr.pos != -1;
+}
+
+static void
+http_readcb(struct bufferevent *bev, void *arg)
+{
+ const char *what = BASIC_REQUEST_BODY;
+ struct event_base *my_base = arg;
+
+ if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+ struct evhttp_request *req = evhttp_request_new(NULL, NULL);
+ enum message_read_status done;
+
+ /* req->kind = EVHTTP_RESPONSE; */
+ done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ if (done == 1 &&
+ evhttp_find_header(evhttp_request_get_input_headers(req),
+ "Content-Type") != NULL)
+ test_ok++;
+
+ out:
+ evhttp_request_free(req);
+ bufferevent_disable(bev, EV_READ);
+ if (exit_base)
+ event_base_loopexit(exit_base, NULL);
+ else if (my_base)
+ event_base_loopexit(my_base, NULL);
+ else {
+ fprintf(stderr, "No way to exit loop!\n");
+ exit(1);
+ }
+ }
+}
+
+static void
+http_writecb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ /* enable reading of the reply */
+ bufferevent_enable(bev, EV_READ);
+ test_ok++;
+ }
+}
+
+static void
+http_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ /** For ssl */
+ if (what & BEV_EVENT_CONNECTED)
+ return;
+ test_ok = -2;
+ event_base_loopexit(arg, NULL);
+}
+
+static int found_multi = 0;
+static int found_multi2 = 0;
+
+static void
+http_basic_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+ struct evhttp_connection *evcon;
+ int empty = evhttp_find_header(evhttp_request_get_input_headers(req), "Empty") != NULL;
+
+ TT_BLATHER(("%s: called\n", __func__));
+ evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+ evcon = evhttp_request_get_connection(req);
+ tt_assert(evhttp_connection_get_server(evcon) == arg);
+
+ {
+ const struct sockaddr *sa;
+ char addrbuf[128];
+
+ sa = evhttp_connection_get_addr(evcon);
+ tt_assert(sa);
+
+ if (sa->sa_family == AF_INET) {
+ evutil_format_sockaddr_port_((struct sockaddr *)sa, addrbuf, sizeof(addrbuf));
+ tt_assert(!strncmp(addrbuf, "127.0.0.1:", strlen("127.0.0.1:")));
+ } else if (sa->sa_family == AF_INET6) {
+ evutil_format_sockaddr_port_((struct sockaddr *)sa, addrbuf, sizeof(addrbuf));
+ tt_assert(!strncmp(addrbuf, "[::1]:", strlen("[::1]:")));
+ } else {
+ tt_fail_msg("Unsupported family");
+ }
+ }
+
+ /* For multi-line headers test */
+ {
+ const char *multi =
+ evhttp_find_header(evhttp_request_get_input_headers(req),"X-Multi");
+ if (multi) {
+ found_multi = !strcmp(multi,"aaaaaaaa a END");
+ if (strcmp("END", multi + strlen(multi) - 3) == 0)
+ test_ok++;
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "X-Last"))
+ test_ok++;
+ }
+ }
+ {
+ const char *multi2 =
+ evhttp_find_header(evhttp_request_get_input_headers(req),"X-Multi-Extra-WS");
+ if (multi2) {
+ found_multi2 = !strcmp(multi2,"libevent 2.1");
+ }
+ }
+
+
+ /* injecting a bad content-length */
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "X-Negative"))
+ evhttp_add_header(evhttp_request_get_output_headers(req),
+ "Content-Length", "-100");
+
+ /* allow sending of an empty reply */
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine",
+ !empty ? evb : NULL);
+
+end:
+ evbuffer_free(evb);
+}
+
+static void http_timeout_reply_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct evhttp_request *req = arg;
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", NULL);
+ test_ok++;
+}
+static void
+http_timeout_cb(struct evhttp_request *req, void *arg)
+{
+ struct timeval when = { 0, 100 };
+ event_base_once(exit_base, -1, EV_TIMEOUT,
+ http_timeout_reply_cb, req, &when);
+}
+
+static void
+http_large_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+ int i;
+
+ for (i = 0; i < 1<<20; ++i) {
+ evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+ }
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+ evbuffer_free(evb);
+}
+
+static char const* const CHUNKS[] = {
+ "This is funny",
+ "but not hilarious.",
+ "bwv 1052"
+};
+
+struct chunk_req_state {
+ struct event_base *base;
+ struct evhttp_request *req;
+ int i;
+};
+
+static void
+http_chunked_trickle_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+ struct chunk_req_state *state = arg;
+ struct timeval when = { 0, 0 };
+
+ evbuffer_add_printf(evb, "%s", CHUNKS[state->i]);
+ evhttp_send_reply_chunk(state->req, evb);
+ evbuffer_free(evb);
+
+ if (++state->i < (int) (sizeof(CHUNKS)/sizeof(CHUNKS[0]))) {
+ event_base_once(state->base, -1, EV_TIMEOUT,
+ http_chunked_trickle_cb, state, &when);
+ } else {
+ evhttp_send_reply_end(state->req);
+ free(state);
+ }
+}
+
+static void
+http_chunked_cb(struct evhttp_request *req, void *arg)
+{
+ struct timeval when = { 0, 0 };
+ struct chunk_req_state *state = malloc(sizeof(struct chunk_req_state));
+ TT_BLATHER(("%s: called\n", __func__));
+
+ memset(state, 0, sizeof(struct chunk_req_state));
+ state->req = req;
+ state->base = arg;
+
+ if (strcmp(evhttp_request_get_uri(req), "/streamed") == 0) {
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Length", "39");
+ }
+
+ /* generate a chunked/streamed reply */
+ evhttp_send_reply_start(req, HTTP_OK, "Everything is fine");
+
+ /* but trickle it across several iterations to ensure we're not
+ * assuming it comes all at once */
+ event_base_once(arg, -1, EV_TIMEOUT, http_chunked_trickle_cb, state, &when);
+}
+
+static struct bufferevent *
+create_bev(struct event_base *base, evutil_socket_t fd, int ssl_mask, int flags_)
+{
+ int flags = BEV_OPT_DEFER_CALLBACKS | flags_;
+ struct bufferevent *bev = NULL;
+
+ if (!ssl_mask) {
+ bev = bufferevent_socket_new(base, fd, flags);
+ } else {
+#ifdef EVENT__HAVE_OPENSSL
+ SSL *ssl = SSL_new(get_ssl_ctx());
+ if (ssl_mask & HTTP_SSL_FILTER) {
+ struct bufferevent *underlying =
+ bufferevent_socket_new(base, fd, flags);
+ bev = bufferevent_openssl_filter_new(
+ base, underlying, ssl, BUFFEREVENT_SSL_CONNECTING, flags);
+ } else {
+ bev = bufferevent_openssl_socket_new(
+ base, fd, ssl, BUFFEREVENT_SSL_CONNECTING, flags);
+ }
+ bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
+#endif
+ }
+
+ return bev;
+}
+
+static void
+http_half_writecb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ if (!test_ok) {
+ const char http_request[] = "host\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+ bufferevent_write(bev, http_request, strlen(http_request));
+ }
+ /* enable reading of the reply */
+ bufferevent_enable(bev, EV_READ);
+ test_ok++;
+ }
+}
+
+static void
+http_basic_test_impl(void *arg, int ssl, const char *request_line)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev = NULL;
+ evutil_socket_t fd;
+ const char *http_request;
+ ev_uint16_t port = 0, port2 = 0;
+ int server_flags = ssl ? HTTP_BIND_SSL : 0;
+ struct evhttp *http = http_setup(&port, data->base, server_flags);
+ struct evbuffer *out;
+
+ exit_base = data->base;
+
+ /* bind to a second socket */
+ if (http_bind(http, &port2, server_flags) == -1) {
+ fprintf(stdout, "FAILED (bind)\n");
+ exit(1);
+ }
+
+ fd = http_connect("127.0.0.1", port);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(data->base, fd, ssl, BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev, http_readcb, http_half_writecb,
+ http_errorcb, data->base);
+ out = bufferevent_get_output(bev);
+
+ /* first half of the http request */
+ evbuffer_add_printf(out,
+ "%s\r\n"
+ "Host: some", request_line);
+
+ test_ok = 0;
+ event_base_dispatch(data->base);
+ tt_int_op(test_ok, ==, 3);
+
+ /* connect to the second port */
+ bufferevent_free(bev);
+
+ fd = http_connect("127.0.0.1", port2);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(data->base, fd, ssl, BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, data->base);
+ out = bufferevent_get_output(bev);
+
+ evbuffer_add_printf(out,
+ "%s\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n", request_line);
+
+ test_ok = 0;
+ event_base_dispatch(data->base);
+ tt_int_op(test_ok, ==, 2);
+
+ /* Connect to the second port again. This time, send an absolute uri. */
+ bufferevent_free(bev);
+
+ fd = http_connect("127.0.0.1", port2);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(data->base, fd, ssl, BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ http_request =
+ "GET http://somehost.net/test HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ test_ok = 0;
+ event_base_dispatch(data->base);
+ tt_int_op(test_ok, ==, 2);
+
+ evhttp_free(http);
+end:
+ if (bev)
+ bufferevent_free(bev);
+}
+static void http_basic_test(void *arg)\
+{ http_basic_test_impl(arg, 0, "GET /test HTTP/1.1"); }
+static void http_basic_trailing_space_test(void *arg)
+{ http_basic_test_impl(arg, 0, "GET /test HTTP/1.1 "); }
+
+
+static void
+http_delay_reply(evutil_socket_t fd, short what, void *arg)
+{
+ struct evhttp_request *req = arg;
+
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", NULL);
+
+ ++test_ok;
+}
+
+static void
+http_delay_cb(struct evhttp_request *req, void *arg)
+{
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_sec = 0;
+ tv.tv_usec = 200 * 1000;
+
+ event_base_once(arg, -1, EV_TIMEOUT, http_delay_reply, req, &tv);
+}
+
+static void
+http_badreq_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *buf = evbuffer_new();
+
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Content-Type", "text/xml; charset=UTF-8");
+ evbuffer_add_printf(buf, "Hello, %s!", "127.0.0.1");
+
+ evhttp_send_reply(req, HTTP_OK, "OK", buf);
+ evbuffer_free(buf);
+}
+
+static void
+http_badreq_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ TT_BLATHER(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
+ /* ignore */
+}
+
+static void
+http_badreq_readcb(struct bufferevent *bev, void *arg)
+{
+ const char *what = "Hello, 127.0.0.1";
+ const char *bad_request = "400 Bad Request";
+
+ if (evbuffer_contains(bufferevent_get_input(bev), bad_request)) {
+ TT_FAIL(("%s:bad request detected", __func__));
+ bufferevent_disable(bev, EV_READ);
+ event_base_loopexit(arg, NULL);
+ return;
+ }
+
+ if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+ struct evhttp_request *req = evhttp_request_new(NULL, NULL);
+ enum message_read_status done;
+
+ /* req->kind = EVHTTP_RESPONSE; */
+ done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ if (done == 1 &&
+ evhttp_find_header(evhttp_request_get_input_headers(req),
+ "Content-Type") != NULL)
+ test_ok++;
+
+ out:
+ evhttp_request_free(req);
+ evbuffer_drain(bufferevent_get_input(bev), evbuffer_get_length(bufferevent_get_input(bev)));
+ }
+
+ shutdown(bufferevent_getfd(bev), EVUTIL_SHUT_WR);
+}
+
+static void
+http_badreq_successcb(evutil_socket_t fd, short what, void *arg)
+{
+ TT_BLATHER(("%s: called (what=%04x, arg=%p)", __func__, what, arg));
+ event_base_loopexit(exit_base, NULL);
+}
+
+static void
+http_bad_request_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct timeval tv;
+ struct bufferevent *bev = NULL;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ const char *http_request;
+ ev_uint16_t port=0, port2=0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+ exit_base = data->base;
+
+ /* bind to a second socket */
+ if (http_bind(http, &port2, 0) == -1)
+ TT_DIE(("Bind socket failed"));
+
+ /* NULL request test */
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_badreq_readcb, http_writecb,
+ http_badreq_errorcb, data->base);
+ bufferevent_enable(bev, EV_READ);
+
+ /* real NULL request */
+ http_request = "";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ shutdown(fd, EVUTIL_SHUT_WR);
+ timerclear(&tv);
+ tv.tv_usec = 10000;
+ event_base_once(data->base, -1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev);
+ evutil_closesocket(fd);
+
+ if (test_ok != 0) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ /* Second answer (BAD REQUEST) on connection close */
+
+ /* connect to the second port */
+ fd = http_connect("127.0.0.1", port2);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_badreq_readcb, http_writecb,
+ http_badreq_errorcb, data->base);
+ bufferevent_enable(bev, EV_READ);
+
+ /* first half of the http request */
+ http_request =
+ "GET /badrequest HTTP/1.0\r\n" \
+ "Connection: Keep-Alive\r\n" \
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ timerclear(&tv);
+ tv.tv_usec = 10000;
+ event_base_once(data->base, -1, EV_TIMEOUT, http_badreq_successcb, bev, &tv);
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 2);
+
+end:
+ evhttp_free(http);
+ if (bev)
+ bufferevent_free(bev);
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static struct evhttp_connection *delayed_client;
+
+static void
+http_large_delay_cb(struct evhttp_request *req, void *arg)
+{
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_usec = 500000;
+
+ event_base_once(arg, -1, EV_TIMEOUT, http_delay_reply, req, &tv);
+ evhttp_connection_fail_(delayed_client, EVREQ_HTTP_EOF);
+}
+
+/*
+ * HTTP DELETE test, just piggyback on the basic test
+ */
+
+static void
+http_delete_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+ int empty = evhttp_find_header(evhttp_request_get_input_headers(req), "Empty") != NULL;
+
+ /* Expecting a DELETE request */
+ if (evhttp_request_get_command(req) != EVHTTP_REQ_DELETE) {
+ fprintf(stdout, "FAILED (delete type)\n");
+ exit(1);
+ }
+
+ TT_BLATHER(("%s: called\n", __func__));
+ evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+ /* allow sending of an empty reply */
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine",
+ !empty ? evb : NULL);
+
+ evbuffer_free(evb);
+}
+
+static void
+http_delete_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ tt_assert(http);
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ http_request =
+ "DELETE /deleteit HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev);
+ evutil_closesocket(fd);
+ fd = EVUTIL_INVALID_SOCKET;
+
+ evhttp_free(http);
+
+ tt_int_op(test_ok, ==, 2);
+ end:
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static void
+http_sent_cb(struct evhttp_request *req, void *arg)
+{
+ ev_uintptr_t val = (ev_uintptr_t)arg;
+ struct evbuffer *b;
+
+ if (val != 0xDEADBEEF) {
+ fprintf(stdout, "FAILED on_complete_cb argument\n");
+ exit(1);
+ }
+
+ b = evhttp_request_get_output_buffer(req);
+ if (evbuffer_get_length(b) != 0) {
+ fprintf(stdout, "FAILED on_complete_cb output buffer not written\n");
+ exit(1);
+ }
+
+ TT_BLATHER(("%s: called\n", __func__));
+
+ ++test_ok;
+}
+
+static void
+http_on_complete_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb = evbuffer_new();
+
+ evhttp_request_set_on_complete_cb(req, http_sent_cb, (void *)0xDEADBEEF);
+
+ TT_BLATHER(("%s: called\n", __func__));
+ evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+ /* allow sending of an empty reply */
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+ evbuffer_free(evb);
+
+ ++test_ok;
+}
+
+static void
+http_on_complete_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ http_request =
+ "GET /oncomplete HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev);
+
+ evhttp_free(http);
+
+ tt_int_op(test_ok, ==, 4);
+ end:
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static void
+http_allowed_methods_eventcb(struct bufferevent *bev, short what, void *arg)
+{
+ char **output = arg;
+ if ((what & (BEV_EVENT_ERROR|BEV_EVENT_EOF))) {
+ char buf[4096];
+ int n;
+ n = evbuffer_remove(bufferevent_get_input(bev), buf,
+ sizeof(buf)-1);
+ if (n >= 0) {
+ buf[n]='\0';
+ if (*output)
+ free(*output);
+ *output = strdup(buf);
+ }
+ event_base_loopexit(exit_base, NULL);
+ }
+}
+
+static void
+http_allowed_methods_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev1, *bev2, *bev3;
+ evutil_socket_t fd1=-1, fd2=-1, fd3=-1;
+ const char *http_request;
+ char *result1=NULL, *result2=NULL, *result3=NULL;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ fd1 = http_connect("127.0.0.1", port);
+ tt_assert(fd1 != EVUTIL_INVALID_SOCKET);
+
+ /* GET is out; PATCH is in. */
+ evhttp_set_allowed_methods(http, EVHTTP_REQ_PATCH);
+
+ /* Stupid thing to send a request */
+ bev1 = bufferevent_socket_new(data->base, fd1, 0);
+ bufferevent_enable(bev1, EV_READ|EV_WRITE);
+ bufferevent_setcb(bev1, NULL, NULL,
+ http_allowed_methods_eventcb, &result1);
+
+ http_request =
+ "GET /index.html HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev1, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ fd2 = http_connect("127.0.0.1", port);
+ tt_assert(fd2 != EVUTIL_INVALID_SOCKET);
+
+ bev2 = bufferevent_socket_new(data->base, fd2, 0);
+ bufferevent_enable(bev2, EV_READ|EV_WRITE);
+ bufferevent_setcb(bev2, NULL, NULL,
+ http_allowed_methods_eventcb, &result2);
+
+ http_request =
+ "PATCH /test HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev2, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ fd3 = http_connect("127.0.0.1", port);
+ tt_assert(fd3 != EVUTIL_INVALID_SOCKET);
+
+ bev3 = bufferevent_socket_new(data->base, fd3, 0);
+ bufferevent_enable(bev3, EV_READ|EV_WRITE);
+ bufferevent_setcb(bev3, NULL, NULL,
+ http_allowed_methods_eventcb, &result3);
+
+ http_request =
+ "FLOOP /test HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev3, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev1);
+ bufferevent_free(bev2);
+ bufferevent_free(bev3);
+
+ evhttp_free(http);
+
+ /* Method known but disallowed */
+ tt_assert(result1);
+ tt_assert(!strncmp(result1, "HTTP/1.1 501 ", strlen("HTTP/1.1 501 ")));
+
+ /* Method known and allowed */
+ tt_assert(result2);
+ tt_assert(!strncmp(result2, "HTTP/1.1 200 ", strlen("HTTP/1.1 200 ")));
+
+ /* Method unknown */
+ tt_assert(result3);
+ tt_assert(!strncmp(result3, "HTTP/1.1 501 ", strlen("HTTP/1.1 501 ")));
+
+ end:
+ if (result1)
+ free(result1);
+ if (result2)
+ free(result2);
+ if (result3)
+ free(result3);
+ if (fd1 >= 0)
+ evutil_closesocket(fd1);
+ if (fd2 >= 0)
+ evutil_closesocket(fd2);
+ if (fd3 >= 0)
+ evutil_closesocket(fd3);
+}
+
+static void http_request_no_action_done(struct evhttp_request *, void *);
+static void http_request_done(struct evhttp_request *, void *);
+static void http_request_empty_done(struct evhttp_request *, void *);
+
+static void
+http_connection_test_(struct basic_test_data *data, int persistent,
+ const char *address, struct evdns_base *dnsbase, int ipv6, int family,
+ int ssl)
+{
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http;
+
+ int mask = 0;
+ if (ipv6)
+ mask |= HTTP_BIND_IPV6;
+ if (ssl)
+ mask |= HTTP_BIND_SSL;
+
+ http = http_setup(&port, data->base, mask);
+
+ test_ok = 0;
+ if (!http && ipv6) {
+ tt_skip();
+ }
+ tt_assert(http);
+
+ if (ssl) {
+#ifdef EVENT__HAVE_OPENSSL
+ SSL *ssl = SSL_new(get_ssl_ctx());
+ struct bufferevent *bev = bufferevent_openssl_socket_new(
+ data->base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING, BEV_OPT_DEFER_CALLBACKS);
+ bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);
+
+ evcon = evhttp_connection_base_bufferevent_new(data->base, dnsbase, bev, address, port);
+#else
+ tt_skip();
+#endif
+ } else {
+ evcon = evhttp_connection_base_new(data->base, dnsbase, address, port);
+ }
+ tt_assert(evcon);
+ evhttp_connection_set_family(evcon, family);
+
+ tt_assert(evhttp_connection_get_base(evcon) == data->base);
+
+ exit_base = data->base;
+
+ tt_assert(evhttp_connection_get_server(evcon) == NULL);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok);
+
+ /* try to make another request over the same connection */
+ test_ok = 0;
+
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /*
+ * if our connections are not supposed to be persistent; request
+ * a close from the server.
+ */
+ if (!persistent)
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Connection", "close");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ /* make another request: request empty reply */
+ test_ok = 0;
+
+ req = evhttp_request_new(http_request_empty_done, data->base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_connection_test(void *arg)
+{
+ http_connection_test_(arg, 0, "127.0.0.1", NULL, 0, AF_UNSPEC, 0);
+}
+static void
+http_persist_connection_test(void *arg)
+{
+ http_connection_test_(arg, 1, "127.0.0.1", NULL, 0, AF_UNSPEC, 0);
+}
+
+static struct regress_dns_server_table search_table[] = {
+ { "localhost", "A", "127.0.0.1", 0, 0 },
+ { NULL, NULL, NULL, 0, 0 }
+};
+
+static void
+http_connection_async_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evdns_base *dns_base = NULL;
+ ev_uint16_t portnum = 0;
+ char address[64];
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+ tt_assert(regress_dnsserver(data->base, &portnum, search_table));
+
+ dns_base = evdns_base_new(data->base, 0/* init name servers */);
+ tt_assert(dns_base);
+
+ /* Add ourself as the only nameserver, and make sure we really are
+ * the only nameserver. */
+ evutil_snprintf(address, sizeof(address), "127.0.0.1:%d", portnum);
+ evdns_base_nameserver_ip_add(dns_base, address);
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, dns_base, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok);
+
+ /* try to make another request over the same connection */
+ test_ok = 0;
+
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /*
+ * if our connections are not supposed to be persistent; request
+ * a close from the server.
+ */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Connection", "close");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ /* make another request: request empty reply */
+ test_ok = 0;
+
+ req = evhttp_request_new(http_request_empty_done, data->base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+ regress_clean_dnsserver();
+}
+
+static void
+http_autofree_connection_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req[2] = { NULL };
+ struct evhttp *http = http_setup(&port, data->base, 0);
+ size_t i;
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule two request to the HTTP
+ * server using our make request method.
+ */
+ req[0] = evhttp_request_new(http_request_empty_done, data->base);
+ req[1] = evhttp_request_new(http_request_empty_done, data->base);
+
+ /* Add the information that we care about */
+ for (i = 0; i < ARRAY_SIZE(req); ++i) {
+ evhttp_add_header(evhttp_request_get_output_headers(req[i]), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req[i]), "Connection", "close");
+ evhttp_add_header(evhttp_request_get_output_headers(req[i]), "Empty", "itis");
+
+ if (evhttp_make_request(evcon, req[i], EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("couldn't make request");
+ }
+ }
+
+ /*
+ * Tell libevent to free the connection when the request completes
+ * We then set the evcon pointer to NULL since we don't want to free it
+ * when this function ends.
+ */
+ evhttp_connection_free_on_completion(evcon);
+ evcon = NULL;
+
+ for (i = 0; i < ARRAY_SIZE(req); ++i)
+ event_base_dispatch(data->base);
+
+ /* at this point, the http server should have no connection */
+ tt_assert(TAILQ_FIRST(&http->connections) == NULL);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_request_never_call(struct evhttp_request *req, void *arg)
+{
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+}
+static void
+http_failed_request_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(!req);
+end:
+ event_base_loopexit(arg, NULL);
+}
+#ifndef _WIN32
+static void
+http_timed_out_request_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(req);
+ tt_int_op(evhttp_request_get_response_code(req), !=, HTTP_OK);
+end:
+ event_base_loopexit(arg, NULL);
+}
+#endif
+
+static void
+http_request_error_cb_with_cancel(enum evhttp_request_error error, void *arg)
+{
+ if (error != EVREQ_HTTP_REQUEST_CANCEL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+ test_ok = 1;
+
+ {
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_sec = 0;
+ tv.tv_usec = 500 * 1000;
+ event_base_loopexit(exit_base, &tv);
+ }
+}
+static void
+http_do_cancel(evutil_socket_t fd, short what, void *arg)
+{
+ struct evhttp_request *req = arg;
+ evhttp_cancel_request(req);
+ ++test_ok;
+}
+static void
+http_no_write(struct evbuffer *buffer, const struct evbuffer_cb_info *info, void *arg)
+{
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+}
+static void
+http_free_evcons(struct evhttp_connection **evcons)
+{
+ struct evhttp_connection *evcon, **orig = evcons;
+
+ if (!evcons)
+ return;
+
+ while ((evcon = *evcons++)) {
+ evhttp_connection_free(evcon);
+ }
+ free(orig);
+}
+/** fill the backlog to force server drop packages for timeouts */
+static struct evhttp_connection **
+http_fill_backlog(struct event_base *base, int port)
+{
+#define BACKLOG_SIZE 256
+ struct evhttp_connection **evcon = malloc(sizeof(*evcon) * (BACKLOG_SIZE + 1));
+ int i;
+
+ for (i = 0; i < BACKLOG_SIZE; ++i) {
+ struct evhttp_request *req;
+
+ evcon[i] = evhttp_connection_base_new(base, NULL, "127.0.0.1", port);
+ tt_assert(evcon[i]);
+ evhttp_connection_set_timeout(evcon[i], 5);
+
+ req = evhttp_request_new(http_request_never_call, NULL);
+ tt_assert(req);
+ tt_int_op(evhttp_make_request(evcon[i], req, EVHTTP_REQ_GET, "/delay"), !=, -1);
+ }
+ evcon[i] = NULL;
+
+ return evcon;
+ end:
+ fprintf(stderr, "Couldn't fill the backlog");
+ return NULL;
+}
+
+enum http_cancel_test_type {
+ BASIC = 1,
+ BY_HOST = 2,
+ NO_NS = 4,
+ INACTIVE_SERVER = 8,
+ SERVER_TIMEOUT = 16,
+ NS_TIMEOUT = 32,
+};
+static struct evhttp_request *
+http_cancel_test_bad_request_new(enum http_cancel_test_type type,
+ struct event_base *base)
+{
+#ifndef _WIN32
+ if (!(type & NO_NS) && (type & SERVER_TIMEOUT))
+ return evhttp_request_new(http_timed_out_request_done, base);
+ else
+#endif
+ if ((type & INACTIVE_SERVER) || (type & NO_NS))
+ return evhttp_request_new(http_failed_request_done, base);
+ else
+ return NULL;
+}
+static void
+http_cancel_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct bufferevent *bufev = NULL;
+ struct timeval tv;
+ struct evdns_base *dns_base = NULL;
+ ev_uint16_t portnum = 0;
+ char address[64];
+ struct evhttp *inactive_http = NULL;
+ struct event_base *inactive_base = NULL;
+ struct evhttp_connection **evcons = NULL;
+ struct event_base *base_to_fill = data->base;
+
+ enum http_cancel_test_type type =
+ (enum http_cancel_test_type)data->setup_data;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ if (type & BY_HOST) {
+ const char *timeout = (type & NS_TIMEOUT) ? "6" : "3";
+
+ tt_assert(regress_dnsserver(data->base, &portnum, search_table));
+
+ dns_base = evdns_base_new(data->base, 0/* init name servers */);
+ tt_assert(dns_base);
+
+ /** XXX: Hack the port to make timeout after resolving */
+ if (type & NO_NS)
+ ++portnum;
+
+ evutil_snprintf(address, sizeof(address), "127.0.0.1:%d", portnum);
+ evdns_base_nameserver_ip_add(dns_base, address);
+
+ evdns_base_set_option(dns_base, "timeout:", timeout);
+ evdns_base_set_option(dns_base, "initial-probe-timeout:", timeout);
+ evdns_base_set_option(dns_base, "attempts:", "1");
+ }
+
+ exit_base = data->base;
+
+ test_ok = 0;
+
+ if (type & INACTIVE_SERVER) {
+ port = 0;
+ inactive_base = event_base_new();
+ inactive_http = http_setup(&port, inactive_base, 0);
+
+ base_to_fill = inactive_base;
+ }
+
+ if (type & SERVER_TIMEOUT)
+ evcons = http_fill_backlog(base_to_fill, port);
+
+ evcon = evhttp_connection_base_new(
+ data->base, dns_base,
+ type & BY_HOST ? "localhost" : "127.0.0.1",
+ port);
+ if (type & INACTIVE_SERVER)
+ evhttp_connection_set_timeout(evcon, 5);
+ tt_assert(evcon);
+
+ bufev = evhttp_connection_get_bufferevent(evcon);
+ /* Guarantee that we stack in connect() not after waiting EV_READ after
+ * write() */
+ if (type & SERVER_TIMEOUT)
+ evbuffer_add_cb(bufferevent_get_output(bufev), http_no_write, NULL);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_request_never_call, NULL);
+ evhttp_request_set_error_cb(req, http_request_error_cb_with_cancel);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/delay"),
+ !=, -1);
+
+ evutil_timerclear(&tv);
+ tv.tv_sec = 0;
+ tv.tv_usec = 100 * 1000;
+
+ event_base_once(data->base, -1, EV_TIMEOUT, http_do_cancel, req, &tv);
+
+ event_base_dispatch(data->base);
+
+ if (type & NO_NS || type & INACTIVE_SERVER)
+ tt_int_op(test_ok, ==, 2); /** no servers responses */
+ else
+ tt_int_op(test_ok, ==, 3);
+
+ /* try to make another request over the same connection */
+ test_ok = 0;
+
+ http_free_evcons(evcons);
+ if (type & SERVER_TIMEOUT)
+ evcons = http_fill_backlog(base_to_fill, port);
+
+ req = http_cancel_test_bad_request_new(type, data->base);
+ if (!req)
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test"),
+ !=, -1);
+
+ event_base_dispatch(data->base);
+
+ /* make another request: request empty reply */
+ test_ok = 0;
+
+ http_free_evcons(evcons);
+ if (type & SERVER_TIMEOUT)
+ evcons = http_fill_backlog(base_to_fill, port);
+
+ req = http_cancel_test_bad_request_new(type, data->base);
+ if (!req)
+ req = evhttp_request_new(http_request_empty_done, data->base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Empty", "itis");
+
+ /* We give ownership of the request to the connection */
+ tt_int_op(evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test"),
+ !=, -1);
+
+ event_base_dispatch(data->base);
+
+ end:
+ http_free_evcons(evcons);
+ if (bufev)
+ evbuffer_remove_cb(bufferevent_get_output(bufev), http_no_write, NULL);
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+ regress_clean_dnsserver();
+ if (inactive_http)
+ evhttp_free(inactive_http);
+ if (inactive_base)
+ event_base_free(inactive_base);
+}
+
+static void
+http_request_no_action_done(struct evhttp_request *req, void *arg)
+{
+ EVUTIL_ASSERT(exit_base);
+ event_base_loopexit(exit_base, NULL);
+}
+
+static void
+http_request_done(struct evhttp_request *req, void *arg)
+{
+ const char *what = arg;
+
+ if (!req) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ EVUTIL_ASSERT(exit_base);
+ event_base_loopexit(exit_base, NULL);
+}
+
+static void
+http_request_expect_error(struct evhttp_request *req, void *arg)
+{
+ if (evhttp_request_get_response_code(req) == HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ EVUTIL_ASSERT(arg);
+ event_base_loopexit(arg, NULL);
+}
+
+/* test virtual hosts */
+static void
+http_virtual_host_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *second = NULL, *third = NULL;
+ evutil_socket_t fd;
+ struct bufferevent *bev;
+ const char *http_request;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+
+ /* virtual host */
+ second = evhttp_new(NULL);
+ evhttp_set_cb(second, "/funnybunny", http_basic_cb, http);
+ third = evhttp_new(NULL);
+ evhttp_set_cb(third, "/blackcoffee", http_basic_cb, http);
+
+ if (evhttp_add_virtual_host(http, "foo.com", second) == -1) {
+ tt_abort_msg("Couldn't add vhost");
+ }
+
+ if (evhttp_add_virtual_host(http, "bar.*.foo.com", third) == -1) {
+ tt_abort_msg("Couldn't add wildcarded vhost");
+ }
+
+ /* add some aliases to the vhosts */
+ tt_assert(evhttp_add_server_alias(second, "manolito.info") == 0);
+ tt_assert(evhttp_add_server_alias(third, "bonkers.org") == 0);
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /* make a request with a different host and expect an error */
+ req = evhttp_request_new(http_request_expect_error, data->base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/funnybunny") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1);
+
+ test_ok = 0;
+
+ /* make a request with the right host and expect a response */
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "foo.com");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/funnybunny") == -1) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1);
+
+ test_ok = 0;
+
+ /* make a request with the right host and expect a response */
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "bar.magic.foo.com");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/blackcoffee") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1)
+
+ test_ok = 0;
+
+ /* make a request with the right host and expect a response */
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "manolito.info");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/funnybunny") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1)
+
+ test_ok = 0;
+
+ /* make a request with the right host and expect a response */
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+
+ /* Add the Host header. This time with the optional port. */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "bonkers.org:8000");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/blackcoffee") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1)
+
+ test_ok = 0;
+
+ /* Now make a raw request with an absolute URI. */
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, NULL);
+
+ /* The host in the URI should override the Host: header */
+ http_request =
+ "GET http://manolito.info/funnybunny HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 2);
+
+ bufferevent_free(bev);
+ evutil_closesocket(fd);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+
+/* test date header and content length */
+
+static void
+http_request_empty_done(struct evhttp_request *req, void *arg)
+{
+ if (!req) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Date") == NULL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Length") == NULL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (strcmp(evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Length"),
+ "0")) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 0) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ EVUTIL_ASSERT(arg);
+ event_base_loopexit(arg, NULL);
+}
+
+/*
+ * HTTP DISPATCHER test
+ */
+
+void
+http_dispatcher_cb(struct evhttp_request *req, void *arg)
+{
+
+ struct evbuffer *evb = evbuffer_new();
+ TT_BLATHER(("%s: called\n", __func__));
+ evbuffer_add_printf(evb, "DISPATCHER_TEST");
+
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+ evbuffer_free(evb);
+}
+
+static void
+http_dispatcher_test_done(struct evhttp_request *req, void *arg)
+{
+ struct event_base *base = arg;
+ const char *what = "DISPATCHER_TEST";
+
+ if (!req) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+ fprintf(stderr, "FAILED (content type)\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+ fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+ (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+ exit(1);
+ }
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+ fprintf(stderr, "FAILED (data)\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_base_loopexit(base, NULL);
+}
+
+static void
+http_dispatcher_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /* also bind to local host */
+ evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+ /*
+ * At this point, we want to schedule an HTTP GET request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_dispatcher_test_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/?arg=val") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+/*
+ * HTTP POST test.
+ */
+
+void http_postrequest_done(struct evhttp_request *, void *);
+
+#define POST_DATA "Okay. Not really printf"
+
+static void
+http_post_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule an HTTP POST request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_postrequest_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), POST_DATA);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/postit") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 1);
+
+ test_ok = 0;
+
+ req = evhttp_request_new(http_postrequest_done, data->base);
+ tt_assert(req);
+
+ /* Now try with 100-continue. */
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "100-continue");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), POST_DATA);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/postit") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 1);
+
+ evhttp_connection_free(evcon);
+ evhttp_free(http);
+
+ end:
+ ;
+}
+
+void
+http_post_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb;
+ TT_BLATHER(("%s: called\n", __func__));
+
+ /* Yes, we are expecting a post request */
+ if (evhttp_request_get_command(req) != EVHTTP_REQ_POST) {
+ fprintf(stdout, "FAILED (post type)\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(POST_DATA)) {
+ fprintf(stdout, "FAILED (length: %lu vs %lu)\n",
+ (unsigned long) evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long) strlen(POST_DATA));
+ exit(1);
+ }
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), POST_DATA) != 0) {
+ fprintf(stdout, "FAILED (data)\n");
+ fprintf(stdout, "Got :%s\n", evbuffer_pullup(evhttp_request_get_input_buffer(req),-1));
+ fprintf(stdout, "Want:%s\n", POST_DATA);
+ exit(1);
+ }
+
+ evb = evbuffer_new();
+ evbuffer_add_printf(evb, BASIC_REQUEST_BODY);
+
+ evhttp_send_reply(req, HTTP_OK, "Everything is fine", evb);
+
+ evbuffer_free(evb);
+}
+
+void
+http_postrequest_done(struct evhttp_request *req, void *arg)
+{
+ const char *what = BASIC_REQUEST_BODY;
+ struct event_base *base = arg;
+
+ if (req == NULL) {
+ fprintf(stderr, "FAILED (timeout)\n");
+ exit(1);
+ }
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+
+ fprintf(stderr, "FAILED (response code)\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+ fprintf(stderr, "FAILED (content type)\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+ fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+ (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+ exit(1);
+ }
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+ fprintf(stderr, "FAILED (data)\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_base_loopexit(base, NULL);
+}
+
+/*
+ * HTTP PUT test, basically just like POST, but ...
+ */
+
+void http_putrequest_done(struct evhttp_request *, void *);
+
+#define PUT_DATA "Hi, I'm some PUT data"
+
+static void
+http_put_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * Schedule the HTTP PUT request
+ */
+
+ req = evhttp_request_new(http_putrequest_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "someotherhost");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), PUT_DATA);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_PUT, "/putit") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ evhttp_connection_free(evcon);
+ evhttp_free(http);
+
+ tt_int_op(test_ok, ==, 1);
+ end:
+ ;
+}
+
+void
+http_put_cb(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *evb;
+ TT_BLATHER(("%s: called\n", __func__));
+
+ /* Expecting a PUT request */
+ if (evhttp_request_get_command(req) != EVHTTP_REQ_PUT) {
+ fprintf(stdout, "FAILED (put type)\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(PUT_DATA)) {
+ fprintf(stdout, "FAILED (length: %lu vs %lu)\n",
+ (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(PUT_DATA));
+ exit(1);
+ }
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), PUT_DATA) != 0) {
+ fprintf(stdout, "FAILED (data)\n");
+ fprintf(stdout, "Got :%s\n", evbuffer_pullup(evhttp_request_get_input_buffer(req),-1));
+ fprintf(stdout, "Want:%s\n", PUT_DATA);
+ exit(1);
+ }
+
+ evb = evbuffer_new();
+ evbuffer_add_printf(evb, "That ain't funny");
+
+ evhttp_send_reply(req, HTTP_OK, "Everything is great", evb);
+
+ evbuffer_free(evb);
+}
+
+void
+http_putrequest_done(struct evhttp_request *req, void *arg)
+{
+ struct event_base *base = arg;
+ const char *what = "That ain't funny";
+
+ if (req == NULL) {
+ fprintf(stderr, "FAILED (timeout)\n");
+ exit(1);
+ }
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+
+ fprintf(stderr, "FAILED (response code)\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") == NULL) {
+ fprintf(stderr, "FAILED (content type)\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != strlen(what)) {
+ fprintf(stderr, "FAILED (length %lu vs %lu)\n",
+ (unsigned long)evbuffer_get_length(evhttp_request_get_input_buffer(req)), (unsigned long)strlen(what));
+ exit(1);
+ }
+
+
+ if (evbuffer_datacmp(evhttp_request_get_input_buffer(req), what) != 0) {
+ fprintf(stderr, "FAILED (data)\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_base_loopexit(base, NULL);
+}
+
+static void
+http_failure_readcb(struct bufferevent *bev, void *arg)
+{
+ const char *what = "400 Bad Request";
+ if (evbuffer_contains(bufferevent_get_input(bev), what)) {
+ test_ok = 2;
+ bufferevent_disable(bev, EV_READ);
+ event_base_loopexit(arg, NULL);
+ }
+}
+
+/*
+ * Testing that the HTTP server can deal with a malformed request.
+ */
+static void
+http_failure_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, http_failure_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ http_request = "illegal request\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev);
+
+ evhttp_free(http);
+
+ tt_int_op(test_ok, ==, 2);
+ end:
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static void
+close_detect_done(struct evhttp_request *req, void *arg)
+{
+ struct timeval tv;
+ tt_assert(req);
+ tt_assert(evhttp_request_get_response_code(req) == HTTP_OK);
+
+ test_ok = 1;
+
+ end:
+ evutil_timerclear(&tv);
+ tv.tv_usec = 150000;
+ event_base_loopexit(arg, &tv);
+}
+
+static void
+close_detect_launch(evutil_socket_t fd, short what, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ struct event_base *base = evhttp_connection_get_base(evcon);
+ struct evhttp_request *req;
+
+ req = evhttp_request_new(close_detect_done, base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_fail_msg("Couldn't make request");
+ }
+}
+
+static void
+close_detect_cb(struct evhttp_request *req, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ struct event_base *base = evhttp_connection_get_base(evcon);
+ struct timeval tv;
+
+ if (req != NULL && evhttp_request_get_response_code(req) != HTTP_OK) {
+ tt_abort_msg("Failed");
+ }
+
+ evutil_timerclear(&tv);
+ tv.tv_sec = 0; /* longer than the http time out */
+ tv.tv_usec = 600000; /* longer than the http time out */
+
+ /* launch a new request on the persistent connection in .3 seconds */
+ event_base_once(base, -1, EV_TIMEOUT, close_detect_launch, evcon, &tv);
+ end:
+ ;
+}
+
+
+static void
+http_close_detection_(struct basic_test_data *data, int with_delay)
+{
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ const struct timeval sec_tenth = { 0, 100000 };
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ /* .1 second timeout */
+ evhttp_set_timeout_tv(http, &sec_tenth);
+
+ evcon = evhttp_connection_base_new(data->base, NULL,
+ "127.0.0.1", port);
+ tt_assert(evcon);
+ evhttp_connection_set_timeout_tv(evcon, &sec_tenth);
+
+
+ tt_assert(evcon);
+ delayed_client = evcon;
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(close_detect_cb, evcon);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon,
+ req, EVHTTP_REQ_GET, with_delay ? "/largedelay" : "/test") == -1) {
+ tt_abort_msg("couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ /* at this point, the http server should have no connection */
+ tt_assert(TAILQ_FIRST(&http->connections) == NULL);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+static void
+http_close_detection_test(void *arg)
+{
+ http_close_detection_(arg, 0);
+}
+static void
+http_close_detection_delay_test(void *arg)
+{
+ http_close_detection_(arg, 1);
+}
+
+static void
+http_highport_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ int i = -1;
+ struct evhttp *myhttp = NULL;
+
+ /* Try a few different ports */
+ for (i = 0; i < 50; ++i) {
+ myhttp = evhttp_new(data->base);
+ if (evhttp_bind_socket(myhttp, "127.0.0.1", 65535 - i) == 0) {
+ test_ok = 1;
+ evhttp_free(myhttp);
+ return;
+ }
+ evhttp_free(myhttp);
+ }
+
+ tt_fail_msg("Couldn't get a high port");
+}
+
+static void
+http_bad_header_test(void *ptr)
+{
+ struct evkeyvalq headers;
+
+ TAILQ_INIT(&headers);
+
+ tt_want(evhttp_add_header(&headers, "One", "Two") == 0);
+ tt_want(evhttp_add_header(&headers, "One", "Two\r\n Three") == 0);
+ tt_want(evhttp_add_header(&headers, "One\r", "Two") == -1);
+ tt_want(evhttp_add_header(&headers, "One\n", "Two") == -1);
+ tt_want(evhttp_add_header(&headers, "One", "Two\r") == -1);
+ tt_want(evhttp_add_header(&headers, "One", "Two\n") == -1);
+
+ evhttp_clear_headers(&headers);
+}
+
+static int validate_header(
+ const struct evkeyvalq* headers,
+ const char *key, const char *value)
+{
+ const char *real_val = evhttp_find_header(headers, key);
+ tt_assert(real_val != NULL);
+ tt_want(strcmp(real_val, value) == 0);
+end:
+ return (0);
+}
+
+static void
+http_parse_query_test(void *ptr)
+{
+ struct evkeyvalq headers;
+ int r;
+
+ TAILQ_INIT(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test", &headers);
+ tt_want(validate_header(&headers, "q", "test") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test&foo=bar", &headers);
+ tt_want(validate_header(&headers, "q", "test") == 0);
+ tt_want(validate_header(&headers, "foo", "bar") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test+foo", &headers);
+ tt_want(validate_header(&headers, "q", "test foo") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test%0Afoo", &headers);
+ tt_want(validate_header(&headers, "q", "test\nfoo") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test%0Dfoo", &headers);
+ tt_want(validate_header(&headers, "q", "test\rfoo") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test&&q2", &headers);
+ tt_int_op(r, ==, -1);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test+this", &headers);
+ tt_want(validate_header(&headers, "q", "test this") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=test&q2=foo", &headers);
+ tt_int_op(r, ==, 0);
+ tt_want(validate_header(&headers, "q", "test") == 0);
+ tt_want(validate_header(&headers, "q2", "foo") == 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q&q2=foo", &headers);
+ tt_int_op(r, ==, -1);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=foo&q2", &headers);
+ tt_int_op(r, ==, -1);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=foo&q2&q3=x", &headers);
+ tt_int_op(r, ==, -1);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query("http://www.test.com/?q=&q2=&q3=", &headers);
+ tt_int_op(r, ==, 0);
+ tt_want(validate_header(&headers, "q", "") == 0);
+ tt_want(validate_header(&headers, "q2", "") == 0);
+ tt_want(validate_header(&headers, "q3", "") == 0);
+ evhttp_clear_headers(&headers);
+
+end:
+ evhttp_clear_headers(&headers);
+}
+static void
+http_parse_query_str_test(void *ptr)
+{
+ struct evkeyvalq headers;
+ int r;
+
+ TAILQ_INIT(&headers);
+
+ r = evhttp_parse_query_str("http://www.test.com/?q=test", &headers);
+ tt_assert(evhttp_find_header(&headers, "q") == NULL);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+ r = evhttp_parse_query_str("q=test", &headers);
+ tt_want(validate_header(&headers, "q", "test") == 0);
+ tt_int_op(r, ==, 0);
+ evhttp_clear_headers(&headers);
+
+end:
+ evhttp_clear_headers(&headers);
+}
+
+static void
+http_parse_uri_test(void *ptr)
+{
+ const int nonconform = (ptr != NULL);
+ const unsigned parse_flags =
+ nonconform ? EVHTTP_URI_NONCONFORMANT : 0;
+ struct evhttp_uri *uri = NULL;
+ char url_tmp[4096];
+#define URI_PARSE(uri) \
+ evhttp_uri_parse_with_flags((uri), parse_flags)
+
+#define TT_URI(want) do { \
+ char *ret = evhttp_uri_join(uri, url_tmp, sizeof(url_tmp)); \
+ tt_want(ret != NULL); \
+ tt_want(ret == url_tmp); \
+ if (strcmp(ret,want) != 0) \
+ TT_FAIL(("\"%s\" != \"%s\"",ret,want)); \
+ } while(0)
+
+ tt_want(evhttp_uri_join(NULL, 0, 0) == NULL);
+ tt_want(evhttp_uri_join(NULL, url_tmp, 0) == NULL);
+ tt_want(evhttp_uri_join(NULL, url_tmp, sizeof(url_tmp)) == NULL);
+
+ /* bad URIs: parsing */
+#define BAD(s) do { \
+ if (URI_PARSE(s) != NULL) \
+ TT_FAIL(("Expected error parsing \"%s\"",s)); \
+ } while(0)
+ /* Nonconformant URIs we can parse: parsing */
+#define NCF(s) do { \
+ uri = URI_PARSE(s); \
+ if (uri != NULL && !nonconform) { \
+ TT_FAIL(("Expected error parsing \"%s\"",s)); \
+ } else if (uri == NULL && nonconform) { \
+ TT_FAIL(("Couldn't parse nonconformant URI \"%s\"", \
+ s)); \
+ } \
+ if (uri) { \
+ tt_want(evhttp_uri_join(uri, url_tmp, \
+ sizeof(url_tmp))); \
+ evhttp_uri_free(uri); \
+ } \
+ } while(0)
+
+ NCF("http://www.test.com/ why hello");
+ NCF("http://www.test.com/why-hello\x01");
+ NCF("http://www.test.com/why-hello?\x01");
+ NCF("http://www.test.com/why-hello#\x01");
+ BAD("http://www.\x01.test.com/why-hello");
+ BAD("http://www.%7test.com/why-hello");
+ NCF("http://www.test.com/why-hell%7o");
+ BAD("h%3ttp://www.test.com/why-hello");
+ NCF("http://www.test.com/why-hello%7");
+ NCF("http://www.test.com/why-hell%7o");
+ NCF("http://www.test.com/foo?ba%r");
+ NCF("http://www.test.com/foo#ba%r");
+ BAD("99:99/foo");
+ BAD("http://www.test.com:999x/");
+ BAD("http://www.test.com:x/");
+ BAD("http://[hello-there]/");
+ BAD("http://[::1]]/");
+ BAD("http://[::1/");
+ BAD("http://[foob/");
+ BAD("http://[/");
+ BAD("http://[ffff:ffff:ffff:ffff:Ffff:ffff:ffff:"
+ "ffff:ffff:ffff:ffff:ffff:ffff:ffff]/");
+ BAD("http://[vX.foo]/");
+ BAD("http://[vX.foo]/");
+ BAD("http://[v.foo]/");
+ BAD("http://[v5.fo%o]/");
+ BAD("http://[v5X]/");
+ BAD("http://[v5]/");
+ BAD("http://[]/");
+ BAD("http://f\x01red@www.example.com/");
+ BAD("http://f%0red@www.example.com/");
+ BAD("http://www.example.com:9999999999999999999999999999999999999/");
+ BAD("http://www.example.com:hihi/");
+ BAD("://www.example.com/");
+
+ /* bad URIs: joining */
+ uri = evhttp_uri_new();
+ tt_want(0==evhttp_uri_set_host(uri, "www.example.com"));
+ tt_want(evhttp_uri_join(uri, url_tmp, sizeof(url_tmp)) != NULL);
+ /* not enough space: */
+ tt_want(evhttp_uri_join(uri, url_tmp, 3) == NULL);
+ /* host is set, but path doesn't start with "/": */
+ tt_want(0==evhttp_uri_set_path(uri, "hi_mom"));
+ tt_want(evhttp_uri_join(uri, url_tmp, sizeof(url_tmp)) == NULL);
+ tt_want(evhttp_uri_join(uri, NULL, sizeof(url_tmp))==NULL);
+ tt_want(evhttp_uri_join(uri, url_tmp, 0)==NULL);
+ evhttp_uri_free(uri);
+ uri = URI_PARSE("mailto:foo@bar");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_host(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(!strcmp(evhttp_uri_get_scheme(uri), "mailto"));
+ tt_want(!strcmp(evhttp_uri_get_path(uri), "foo@bar"));
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("mailto:foo@bar");
+ evhttp_uri_free(uri);
+
+ uri = evhttp_uri_new();
+ /* Bad URI usage: setting invalid values */
+ tt_want(-1 == evhttp_uri_set_scheme(uri,""));
+ tt_want(-1 == evhttp_uri_set_scheme(uri,"33"));
+ tt_want(-1 == evhttp_uri_set_scheme(uri,"hi!"));
+ tt_want(-1 == evhttp_uri_set_userinfo(uri,"hello@"));
+ tt_want(-1 == evhttp_uri_set_host(uri,"[1.2.3.4]"));
+ tt_want(-1 == evhttp_uri_set_host(uri,"["));
+ tt_want(-1 == evhttp_uri_set_host(uri,"www.[foo].com"));
+ tt_want(-1 == evhttp_uri_set_port(uri,-3));
+ tt_want(-1 == evhttp_uri_set_path(uri,"hello?world"));
+ tt_want(-1 == evhttp_uri_set_query(uri,"hello#world"));
+ tt_want(-1 == evhttp_uri_set_fragment(uri,"hello#world"));
+ /* Valid URI usage: setting valid values */
+ tt_want(0 == evhttp_uri_set_scheme(uri,"http"));
+ tt_want(0 == evhttp_uri_set_scheme(uri,NULL));
+ tt_want(0 == evhttp_uri_set_userinfo(uri,"username:pass"));
+ tt_want(0 == evhttp_uri_set_userinfo(uri,NULL));
+ tt_want(0 == evhttp_uri_set_host(uri,"www.example.com"));
+ tt_want(0 == evhttp_uri_set_host(uri,"1.2.3.4"));
+ tt_want(0 == evhttp_uri_set_host(uri,"[1:2:3:4::]"));
+ tt_want(0 == evhttp_uri_set_host(uri,"[v7.wobblewobble]"));
+ tt_want(0 == evhttp_uri_set_host(uri,NULL));
+ tt_want(0 == evhttp_uri_set_host(uri,""));
+ tt_want(0 == evhttp_uri_set_port(uri, -1));
+ tt_want(0 == evhttp_uri_set_port(uri, 80));
+ tt_want(0 == evhttp_uri_set_port(uri, 65535));
+ tt_want(0 == evhttp_uri_set_path(uri, ""));
+ tt_want(0 == evhttp_uri_set_path(uri, "/documents/public/index.html"));
+ tt_want(0 == evhttp_uri_set_path(uri, NULL));
+ tt_want(0 == evhttp_uri_set_query(uri, "key=val&key2=val2"));
+ tt_want(0 == evhttp_uri_set_query(uri, "keyvalblarg"));
+ tt_want(0 == evhttp_uri_set_query(uri, ""));
+ tt_want(0 == evhttp_uri_set_query(uri, NULL));
+ tt_want(0 == evhttp_uri_set_fragment(uri, ""));
+ tt_want(0 == evhttp_uri_set_fragment(uri, "here?i?am"));
+ tt_want(0 == evhttp_uri_set_fragment(uri, NULL));
+ evhttp_uri_free(uri);
+
+ /* Valid parsing */
+ uri = URI_PARSE("http://www.test.com/?q=t%33est");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=t%33est") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://www.test.com/?q=t%33est");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://%77ww.test.com");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "%77ww.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://%77ww.test.com");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://www.test.com?q=test");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://www.test.com?q=test");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://www.test.com#fragment");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want_str_op(evhttp_uri_get_fragment(uri), ==, "fragment");
+ TT_URI("http://www.test.com#fragment");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://8000/");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "8000") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://8000/");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://:8000/");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == 8000);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://:8000/");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://www.test.com:/"); /* empty port */
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want_str_op(evhttp_uri_get_path(uri), ==, "/");
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://www.test.com/");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("http://www.test.com:"); /* empty port 2 */
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "http") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("http://www.test.com");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("ftp://www.test.com/?q=test");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "www.test.com") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("ftp://www.test.com/?q=test");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("ftp://[::1]:999/?q=test");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "[::1]") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == 999);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("ftp://[::1]:999/?q=test");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("ftp://[ff00::127.0.0.1]/?q=test");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "[ff00::127.0.0.1]") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("ftp://[ff00::127.0.0.1]/?q=test");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("ftp://[v99.not_(any:time)_soon]/?q=test");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "ftp") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "[v99.not_(any:time)_soon]") == 0);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("ftp://[v99.not_(any:time)_soon]/?q=test");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("scheme://user:pass@foo.com:42/?q=test&s=some+thing#fragment");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+ tt_want(strcmp(evhttp_uri_get_userinfo(uri), "user:pass") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+ tt_want(evhttp_uri_get_port(uri) == 42);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=test&s=some+thing") == 0);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "fragment") == 0);
+ TT_URI("scheme://user:pass@foo.com:42/?q=test&s=some+thing#fragment");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("scheme://user@foo.com/#fragment");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+ tt_want(strcmp(evhttp_uri_get_userinfo(uri), "user") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "fragment") == 0);
+ TT_URI("scheme://user@foo.com/#fragment");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("scheme://%75ser@foo.com/#frag@ment");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "scheme") == 0);
+ tt_want(strcmp(evhttp_uri_get_userinfo(uri), "%75ser") == 0);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "foo.com") == 0);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "frag@ment") == 0);
+ TT_URI("scheme://%75ser@foo.com/#frag@ment");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("file:///some/path/to/the/file");
+ tt_want(strcmp(evhttp_uri_get_scheme(uri), "file") == 0);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/some/path/to/the/file") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("file:///some/path/to/the/file");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("///some/path/to/the-file");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_scheme(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(strcmp(evhttp_uri_get_host(uri), "") == 0);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/some/path/to/the-file") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("///some/path/to/the-file");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("/s:ome/path/to/the-file?q=99#fred");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_scheme(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_host(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "/s:ome/path/to/the-file") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=99") == 0);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "fred") == 0);
+ TT_URI("/s:ome/path/to/the-file?q=99#fred");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("relative/path/with/co:lon");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_scheme(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_host(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "relative/path/with/co:lon") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(evhttp_uri_get_fragment(uri) == NULL);
+ TT_URI("relative/path/with/co:lon");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("bob?q=99&q2=q?33#fr?ed");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_scheme(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_host(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "bob") == 0);
+ tt_want(strcmp(evhttp_uri_get_query(uri), "q=99&q2=q?33") == 0);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "fr?ed") == 0);
+ TT_URI("bob?q=99&q2=q?33#fr?ed");
+ evhttp_uri_free(uri);
+
+ uri = URI_PARSE("#fr?ed");
+ tt_want(uri != NULL);
+ tt_want(evhttp_uri_get_scheme(uri) == NULL);
+ tt_want(evhttp_uri_get_userinfo(uri) == NULL);
+ tt_want(evhttp_uri_get_host(uri) == NULL);
+ tt_want(evhttp_uri_get_port(uri) == -1);
+ tt_want(strcmp(evhttp_uri_get_path(uri), "") == 0);
+ tt_want(evhttp_uri_get_query(uri) == NULL);
+ tt_want(strcmp(evhttp_uri_get_fragment(uri), "fr?ed") == 0);
+ TT_URI("#fr?ed");
+ evhttp_uri_free(uri);
+#undef URI_PARSE
+#undef TT_URI
+#undef BAD
+}
+
+static void
+http_uriencode_test(void *ptr)
+{
+ char *s=NULL, *s2=NULL;
+ size_t sz;
+ int bytes_decoded;
+
+#define ENC(from,want,plus) do { \
+ s = evhttp_uriencode((from), -1, (plus)); \
+ tt_assert(s); \
+ tt_str_op(s,==,(want)); \
+ sz = -1; \
+ s2 = evhttp_uridecode((s), (plus), &sz); \
+ tt_assert(s2); \
+ tt_str_op(s2,==,(from)); \
+ tt_int_op(sz,==,strlen(from)); \
+ free(s); \
+ free(s2); \
+ s = s2 = NULL; \
+ } while (0)
+
+#define DEC(from,want,dp) do { \
+ s = evhttp_uridecode((from),(dp),&sz); \
+ tt_assert(s); \
+ tt_str_op(s,==,(want)); \
+ tt_int_op(sz,==,strlen(want)); \
+ free(s); \
+ s = NULL; \
+ } while (0)
+
+#define OLD_DEC(from,want) do { \
+ s = evhttp_decode_uri((from)); \
+ tt_assert(s); \
+ tt_str_op(s,==,(want)); \
+ free(s); \
+ s = NULL; \
+ } while (0)
+
+
+ ENC("Hello", "Hello",0);
+ ENC("99", "99",0);
+ ENC("", "",0);
+ ENC(
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789-.~_",
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789-.~_",0);
+ ENC(" ", "%20",0);
+ ENC(" ", "+",1);
+ ENC("\xff\xf0\xe0", "%FF%F0%E0",0);
+ ENC("\x01\x19", "%01%19",1);
+ ENC("http://www.ietf.org/rfc/rfc3986.txt",
+ "http%3A%2F%2Fwww.ietf.org%2Frfc%2Frfc3986.txt",1);
+
+ ENC("1+2=3", "1%2B2%3D3",1);
+ ENC("1+2=3", "1%2B2%3D3",0);
+
+ /* Now try encoding with internal NULs. */
+ s = evhttp_uriencode("hello\0world", 11, 0);
+ tt_assert(s);
+ tt_str_op(s,==,"hello%00world");
+ free(s);
+ s = NULL;
+
+ /* Now try decoding just part of string. */
+ s = malloc(6 + 1 /* NUL byte */);
+ bytes_decoded = evhttp_decode_uri_internal("hello%20%20", 6, s, 0);
+ tt_assert(s);
+ tt_int_op(bytes_decoded,==,6);
+ tt_str_op(s,==,"hello%");
+ free(s);
+ s = NULL;
+
+ /* Now try out some decoding cases that we don't generate with
+ * encode_uri: Make sure that malformed stuff doesn't crash... */
+ DEC("%%xhello th+ere \xff",
+ "%%xhello th+ere \xff", 0);
+ /* Make sure plus decoding works */
+ DEC("plus+should%20work+", "plus should work ",1);
+ /* Try some lowercase hex */
+ DEC("%f0%a0%b0", "\xf0\xa0\xb0",1);
+
+ /* Try an internal NUL. */
+ sz = 0;
+ s = evhttp_uridecode("%00%00x%00%00", 1, &sz);
+ tt_int_op(sz,==,5);
+ tt_assert(!memcmp(s, "\0\0x\0\0", 5));
+ free(s);
+ s = NULL;
+
+ /* Try with size == NULL */
+ sz = 0;
+ s = evhttp_uridecode("%00%00x%00%00", 1, NULL);
+ tt_assert(!memcmp(s, "\0\0x\0\0", 5));
+ free(s);
+ s = NULL;
+
+ /* Test out the crazy old behavior of the deprecated
+ * evhttp_decode_uri */
+ OLD_DEC("http://example.com/normal+path/?key=val+with+spaces",
+ "http://example.com/normal+path/?key=val with spaces");
+
+end:
+ if (s)
+ free(s);
+ if (s2)
+ free(s2);
+#undef ENC
+#undef DEC
+#undef OLD_DEC
+}
+
+static void
+http_base_test(void *ptr)
+{
+ struct event_base *base = NULL;
+ struct bufferevent *bev;
+ evutil_socket_t fd;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct evhttp *http;
+
+ test_ok = 0;
+ base = event_base_new();
+ tt_assert(base);
+ http = http_setup(&port, base, 0);
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(base, fd, 0);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, base);
+ bufferevent_base_set(base, bev);
+
+ http_request =
+ "GET /test HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ event_base_dispatch(base);
+
+ bufferevent_free(bev);
+ evutil_closesocket(fd);
+
+ evhttp_free(http);
+
+ tt_int_op(test_ok, ==, 2);
+
+end:
+ if (base)
+ event_base_free(base);
+}
+
+/*
+ * the server is just going to close the connection if it times out during
+ * reading the headers.
+ */
+
+static void
+http_incomplete_readcb(struct bufferevent *bev, void *arg)
+{
+ test_ok = -1;
+ event_base_loopexit(exit_base,NULL);
+}
+
+static void
+http_incomplete_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ /** For ssl */
+ if (what & BEV_EVENT_CONNECTED)
+ return;
+
+ if (what == (BEV_EVENT_READING|BEV_EVENT_EOF))
+ test_ok++;
+ else
+ test_ok = -2;
+ event_base_loopexit(exit_base,NULL);
+}
+
+static void
+http_incomplete_writecb(struct bufferevent *bev, void *arg)
+{
+ if (arg != NULL) {
+ evutil_socket_t fd = *(evutil_socket_t *)arg;
+ /* terminate the write side to simulate EOF */
+ shutdown(fd, EVUTIL_SHUT_WR);
+ }
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ /* enable reading of the reply */
+ bufferevent_enable(bev, EV_READ);
+ test_ok++;
+ }
+}
+
+static void
+http_incomplete_test_(struct basic_test_data *data, int use_timeout, int ssl)
+{
+ struct bufferevent *bev;
+ evutil_socket_t fd;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct timeval tv_start, tv_end;
+ struct evhttp *http = http_setup(&port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ evhttp_set_timeout(http, 1);
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(data->base, fd, ssl, 0);
+ bufferevent_setcb(bev,
+ http_incomplete_readcb, http_incomplete_writecb,
+ http_incomplete_errorcb, use_timeout ? NULL : &fd);
+
+ http_request =
+ "GET /test HTTP/1.1\r\n"
+ "Host: somehost\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ evutil_gettimeofday(&tv_start, NULL);
+
+ event_base_dispatch(data->base);
+
+ evutil_gettimeofday(&tv_end, NULL);
+ evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+ bufferevent_free(bev);
+ if (use_timeout) {
+ evutil_closesocket(fd);
+ fd = EVUTIL_INVALID_SOCKET;
+ }
+
+ evhttp_free(http);
+
+ if (use_timeout && tv_end.tv_sec >= 3) {
+ tt_abort_msg("time");
+ } else if (!use_timeout && tv_end.tv_sec >= 1) {
+ /* we should be done immediately */
+ tt_abort_msg("time");
+ }
+
+ tt_int_op(test_ok, ==, 2);
+ end:
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+static void http_incomplete_test(void *arg)
+{ http_incomplete_test_(arg, 0, 0); }
+static void http_incomplete_timeout_test(void *arg)
+{ http_incomplete_test_(arg, 1, 0); }
+
+
+/*
+ * the server is going to reply with chunked data.
+ */
+
+static void
+http_chunked_readcb(struct bufferevent *bev, void *arg)
+{
+ /* nothing here */
+}
+
+static void
+http_chunked_errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ struct evhttp_request *req = NULL;
+
+ /** SSL */
+ if (what & BEV_EVENT_CONNECTED)
+ return;
+
+ if (!test_ok)
+ goto out;
+
+ test_ok = -1;
+
+ if ((what & BEV_EVENT_EOF) != 0) {
+ const char *header;
+ enum message_read_status done;
+ req = evhttp_request_new(NULL, NULL);
+
+ /* req->kind = EVHTTP_RESPONSE; */
+ done = evhttp_parse_firstline_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ done = evhttp_parse_headers_(req, bufferevent_get_input(bev));
+ if (done != ALL_DATA_READ)
+ goto out;
+
+ header = evhttp_find_header(evhttp_request_get_input_headers(req), "Transfer-Encoding");
+ if (header == NULL || strcmp(header, "chunked"))
+ goto out;
+
+ header = evhttp_find_header(evhttp_request_get_input_headers(req), "Connection");
+ if (header == NULL || strcmp(header, "close"))
+ goto out;
+
+ header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+ if (header == NULL)
+ goto out;
+ /* 13 chars */
+ if (strcmp(header, "d")) {
+ free((void*)header);
+ goto out;
+ }
+ free((void*)header);
+
+ if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 13),
+ "This is funny", 13))
+ goto out;
+
+ evbuffer_drain(bufferevent_get_input(bev), 13 + 2);
+
+ header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+ if (header == NULL)
+ goto out;
+ /* 18 chars */
+ if (strcmp(header, "12"))
+ goto out;
+ free((char *)header);
+
+ if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 18),
+ "but not hilarious.", 18))
+ goto out;
+
+ evbuffer_drain(bufferevent_get_input(bev), 18 + 2);
+
+ header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+ if (header == NULL)
+ goto out;
+ /* 8 chars */
+ if (strcmp(header, "8")) {
+ free((void*)header);
+ goto out;
+ }
+ free((char *)header);
+
+ if (strncmp((char *)evbuffer_pullup(bufferevent_get_input(bev), 8),
+ "bwv 1052.", 8))
+ goto out;
+
+ evbuffer_drain(bufferevent_get_input(bev), 8 + 2);
+
+ header = evbuffer_readln(bufferevent_get_input(bev), NULL, EVBUFFER_EOL_CRLF);
+ if (header == NULL)
+ goto out;
+ /* 0 chars */
+ if (strcmp(header, "0")) {
+ free((void*)header);
+ goto out;
+ }
+ free((void *)header);
+
+ test_ok = 2;
+ }
+
+out:
+ if (req)
+ evhttp_request_free(req);
+
+ event_base_loopexit(arg, NULL);
+}
+
+static void
+http_chunked_writecb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ /* enable reading of the reply */
+ bufferevent_enable(bev, EV_READ);
+ test_ok++;
+ }
+}
+
+static void
+http_chunked_request_done(struct evhttp_request *req, void *arg)
+{
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evhttp_find_header(evhttp_request_get_input_headers(req),
+ "Transfer-Encoding") == NULL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 13 + 18 + 8) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ if (strncmp((char *)evbuffer_pullup(evhttp_request_get_input_buffer(req), 13 + 18 + 8),
+ "This is funnybut not hilarious.bwv 1052",
+ 13 + 18 + 8)) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_base_loopexit(arg, NULL);
+}
+
+static void
+http_chunk_out_test_impl(void *arg, int ssl)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev = NULL;
+ evutil_socket_t fd;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ struct timeval tv_start, tv_end;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ int i;
+ struct evhttp *http = http_setup(&port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(data->base, fd, ssl, BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev,
+ http_chunked_readcb, http_chunked_writecb,
+ http_chunked_errorcb, data->base);
+
+ http_request =
+ "GET /chunked HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+
+ evutil_gettimeofday(&tv_start, NULL);
+
+ event_base_dispatch(data->base);
+
+ bufferevent_free(bev);
+ bev = NULL;
+
+ evutil_gettimeofday(&tv_end, NULL);
+ evutil_timersub(&tv_end, &tv_start, &tv_end);
+
+ tt_int_op(tv_end.tv_sec, <, 1);
+
+ tt_int_op(test_ok, ==, 2);
+
+ /* now try again with the regular connection object */
+ bev = create_bev(data->base, -1, ssl, BEV_OPT_CLOSE_ON_FREE);
+ evcon = evhttp_connection_base_bufferevent_new(
+ data->base, NULL, bev, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /* make two requests to check the keepalive behavior */
+ for (i = 0; i < 2; i++) {
+ test_ok = 0;
+ req = evhttp_request_new(http_chunked_request_done, data->base);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/chunked") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_ok == 1);
+ }
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+static void http_chunk_out_test(void *arg)
+{ http_chunk_out_test_impl(arg, 0); }
+
+static void
+http_stream_out_test_impl(void *arg, int ssl)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct bufferevent *bev;
+ struct evhttp *http = http_setup(&port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ test_ok = 0;
+ exit_base = data->base;
+
+ bev = create_bev(data->base, -1, ssl, 0);
+ evcon = evhttp_connection_base_bufferevent_new(
+ data->base, NULL, bev, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_request_done,
+ (void *)"This is funnybut not hilarious.bwv 1052");
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/streamed")
+ == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+static void http_stream_out_test(void *arg)
+{ http_stream_out_test_impl(arg, 0); }
+
+static void
+http_stream_in_chunk(struct evhttp_request *req, void *arg)
+{
+ struct evbuffer *reply = arg;
+
+ if (evhttp_request_get_response_code(req) != HTTP_OK) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ evbuffer_add_buffer(reply, evhttp_request_get_input_buffer(req));
+}
+
+static void
+http_stream_in_done(struct evhttp_request *req, void *arg)
+{
+ if (evbuffer_get_length(evhttp_request_get_input_buffer(req)) != 0) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ event_base_loopexit(exit_base, NULL);
+}
+
+/**
+ * Makes a request and reads the response in chunks.
+ */
+static void
+http_stream_in_test_(struct basic_test_data *data, char const *url,
+ size_t expected_len, char const *expected)
+{
+ struct evhttp_connection *evcon;
+ struct evbuffer *reply = evbuffer_new();
+ struct evhttp_request *req = NULL;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+
+ evcon = evhttp_connection_base_new(data->base, NULL,"127.0.0.1", port);
+ tt_assert(evcon);
+
+ req = evhttp_request_new(http_stream_in_done, reply);
+ evhttp_request_set_chunked_cb(req, http_stream_in_chunk);
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, url) == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ if (evbuffer_get_length(reply) != expected_len) {
+ TT_DIE(("reply length %lu; expected %lu; FAILED (%s)\n",
+ (unsigned long)evbuffer_get_length(reply),
+ (unsigned long)expected_len,
+ (char*)evbuffer_pullup(reply, -1)));
+ }
+
+ if (memcmp(evbuffer_pullup(reply, -1), expected, expected_len) != 0) {
+ tt_abort_msg("Memory mismatch");
+ }
+
+ test_ok = 1;
+ end:
+ if (reply)
+ evbuffer_free(reply);
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_stream_in_test(void *arg)
+{
+ http_stream_in_test_(arg, "/chunked", 13 + 18 + 8,
+ "This is funnybut not hilarious.bwv 1052");
+
+ http_stream_in_test_(arg, "/test", strlen(BASIC_REQUEST_BODY),
+ BASIC_REQUEST_BODY);
+}
+
+static void
+http_stream_in_cancel_chunk(struct evhttp_request *req, void *arg)
+{
+ tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_OK);
+
+ end:
+ evhttp_cancel_request(req);
+ event_base_loopexit(arg, NULL);
+}
+
+static void
+http_stream_in_cancel_done(struct evhttp_request *req, void *arg)
+{
+ /* should never be called */
+ tt_fail_msg("In cancel done");
+}
+
+static void
+http_stream_in_cancel_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct evhttp_connection *evcon;
+ struct evhttp_request *req = NULL;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ req = evhttp_request_new(http_stream_in_cancel_done, data->base);
+ evhttp_request_set_chunked_cb(req, http_stream_in_cancel_chunk);
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/chunked") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ test_ok = 1;
+ end:
+ evhttp_connection_free(evcon);
+ evhttp_free(http);
+
+}
+
+static void
+http_connection_fail_done(struct evhttp_request *req, void *arg)
+{
+ struct evhttp_connection *evcon = arg;
+ struct event_base *base = evhttp_connection_get_base(evcon);
+
+ /* An ENETUNREACH error results in an unrecoverable
+ * evhttp_connection error (see evhttp_connection_fail_()). The
+ * connection will be reset, and the user will be notified with a NULL
+ * req parameter. */
+ tt_assert(!req);
+
+ evhttp_connection_free(evcon);
+
+ test_ok = 1;
+
+ end:
+ event_base_loopexit(base, NULL);
+}
+
+/* Test unrecoverable evhttp_connection errors by generating an ENETUNREACH
+ * error on connection. */
+static void
+http_connection_fail_test_impl(void *arg, int ssl)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct bufferevent *bev;
+ struct evhttp *http = http_setup(&port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ /* auto detect a port */
+ evhttp_free(http);
+
+ bev = create_bev(data->base, -1, ssl, 0);
+ /* Pick an unroutable address. This administratively scoped multicast
+ * address should do when working with TCP. */
+ evcon = evhttp_connection_base_bufferevent_new(
+ data->base, NULL, bev, "239.10.20.30", 80);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule an HTTP GET request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_connection_fail_done, evcon);
+ tt_assert(req);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(test_ok, ==, 1);
+
+ end:
+ ;
+}
+static void http_connection_fail_test(void *arg)
+{ http_connection_fail_test_impl(arg, 0); }
+
+static void
+http_connection_retry_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(req);
+ tt_int_op(evhttp_request_get_response_code(req), !=, HTTP_OK);
+ if (evhttp_find_header(evhttp_request_get_input_headers(req), "Content-Type") != NULL) {
+ tt_abort_msg("(content type)\n");
+ }
+
+ tt_uint_op(evbuffer_get_length(evhttp_request_get_input_buffer(req)), ==, 0);
+
+ test_ok = 1;
+ end:
+ event_base_loopexit(arg,NULL);
+}
+
+struct http_server
+{
+ ev_uint16_t port;
+ int ssl;
+ struct evhttp *http;
+};
+static struct event_base *http_make_web_server_base=NULL;
+static void
+http_make_web_server(evutil_socket_t fd, short what, void *arg)
+{
+ struct http_server *hs = (struct http_server *)arg;
+ hs->http = http_setup(&hs->port, http_make_web_server_base, hs->ssl ? HTTP_BIND_SSL : 0);
+}
+
+static void
+http_simple_test_impl(void *arg, int ssl, int dirty, const char *uri)
+{
+ struct basic_test_data *data = arg;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct bufferevent *bev;
+ struct http_server hs = { 0, ssl, NULL, };
+ struct evhttp *http = http_setup(&hs.port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ bev = create_bev(data->base, -1, ssl, 0);
+#ifdef EVENT__HAVE_OPENSSL
+ bufferevent_openssl_set_allow_dirty_shutdown(bev, dirty);
+#endif
+
+ evcon = evhttp_connection_base_bufferevent_new(
+ data->base, NULL, bev, "127.0.0.1", hs.port);
+ tt_assert(evcon);
+ evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+ req = evhttp_request_new(http_request_done, (void*) BASIC_REQUEST_BODY);
+ tt_assert(req);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, uri) == -1)
+ tt_abort_msg("Couldn't make request");
+
+ event_base_dispatch(data->base);
+ tt_int_op(test_ok, ==, 1);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+static void http_simple_test(void *arg)
+{ http_simple_test_impl(arg, 0, 0, "/test"); }
+static void http_simple_nonconformant_test(void *arg)
+{ http_simple_test_impl(arg, 0, 0, "/test nonconformant"); }
+
+static void
+http_connection_retry_test_basic(void *arg, const char *addr, struct evdns_base *dns_base, int ssl)
+{
+ struct basic_test_data *data = arg;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct timeval tv, tv_start, tv_end;
+ struct bufferevent *bev;
+ struct http_server hs = { 0, ssl, NULL, };
+ struct evhttp *http = http_setup(&hs.port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ /* auto detect a port */
+ evhttp_free(http);
+
+ bev = create_bev(data->base, -1, ssl, 0);
+ evcon = evhttp_connection_base_bufferevent_new(data->base, dns_base, bev, addr, hs.port);
+ tt_assert(evcon);
+ if (dns_base)
+ tt_assert(!evhttp_connection_set_flags(evcon, EVHTTP_CON_REUSE_CONNECTED_ADDR));
+
+ evhttp_connection_set_timeout(evcon, 1);
+ /* also bind to local host */
+ evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+ /*
+ * At this point, we want to schedule an HTTP GET request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_connection_retry_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/?arg=val") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_base_dispatch(data->base);
+ evutil_gettimeofday(&tv_end, NULL);
+ evutil_timersub(&tv_end, &tv_start, &tv_end);
+ tt_int_op(tv_end.tv_sec, <, 1);
+
+ tt_int_op(test_ok, ==, 1);
+
+ /*
+ * now test the same but with retries
+ */
+ test_ok = 0;
+ /** Shutdown dns server, to test conn_address reusing */
+ if (dns_base)
+ regress_clean_dnsserver();
+
+ {
+ const struct timeval tv_timeout = { 0, 500000 };
+ const struct timeval tv_retry = { 0, 500000 };
+ evhttp_connection_set_timeout_tv(evcon, &tv_timeout);
+ evhttp_connection_set_initial_retry_tv(evcon, &tv_retry);
+ }
+ evhttp_connection_set_retries(evcon, 1);
+
+ req = evhttp_request_new(http_connection_retry_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/?arg=val") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_base_dispatch(data->base);
+ evutil_gettimeofday(&tv_end, NULL);
+
+ /* fails fast, .5 sec to wait to retry, fails fast again. */
+ test_timeval_diff_leq(&tv_start, &tv_end, 500, 200);
+
+ tt_assert(test_ok == 1);
+
+ /*
+ * now test the same but with retries and give it a web server
+ * at the end
+ */
+ test_ok = 0;
+
+ evhttp_connection_set_timeout(evcon, 1);
+ evhttp_connection_set_retries(evcon, 3);
+
+ req = evhttp_request_new(http_dispatcher_test_done, data->base);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET,
+ "/?arg=val") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ /* start up a web server .2 seconds after the connection tried
+ * to send a request
+ */
+ evutil_timerclear(&tv);
+ tv.tv_usec = 200000;
+ http_make_web_server_base = data->base;
+ event_base_once(data->base, -1, EV_TIMEOUT, http_make_web_server, &hs, &tv);
+
+ evutil_gettimeofday(&tv_start, NULL);
+ event_base_dispatch(data->base);
+ evutil_gettimeofday(&tv_end, NULL);
+ /* We'll wait twice as long as we did last time. */
+ test_timeval_diff_leq(&tv_start, &tv_end, 1000, 400);
+
+ tt_int_op(test_ok, ==, 1);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(hs.http);
+}
+
+static void
+http_connection_retry_conn_address_test_impl(void *arg, int ssl)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t portnum = 0;
+ struct evdns_base *dns_base = NULL;
+ char address[64];
+
+ tt_assert(regress_dnsserver(data->base, &portnum, search_table));
+ dns_base = evdns_base_new(data->base, 0/* init name servers */);
+ tt_assert(dns_base);
+
+ /* Add ourself as the only nameserver, and make sure we really are
+ * the only nameserver. */
+ evutil_snprintf(address, sizeof(address), "127.0.0.1:%d", portnum);
+ evdns_base_nameserver_ip_add(dns_base, address);
+
+ http_connection_retry_test_basic(arg, "localhost", dns_base, ssl);
+
+ end:
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+ /** dnsserver will be cleaned in http_connection_retry_test_basic() */
+}
+static void http_connection_retry_conn_address_test(void *arg)
+{ http_connection_retry_conn_address_test_impl(arg, 0); }
+
+static void
+http_connection_retry_test_impl(void *arg, int ssl)
+{
+ http_connection_retry_test_basic(arg, "127.0.0.1", NULL, ssl);
+}
+static void
+http_connection_retry_test(void *arg)
+{ http_connection_retry_test_impl(arg, 0); }
+
+static void
+http_primitives(void *ptr)
+{
+ char *escaped = NULL;
+ struct evhttp *http = NULL;
+
+ escaped = evhttp_htmlescape("<script>");
+ tt_assert(escaped);
+ tt_str_op(escaped, ==, "&lt;script&gt;");
+ free(escaped);
+
+ escaped = evhttp_htmlescape("\"\'&");
+ tt_assert(escaped);
+ tt_str_op(escaped, ==, "&quot;&#039;&amp;");
+
+ http = evhttp_new(NULL);
+ tt_assert(http);
+ tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, http), ==, 0);
+ tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, http), ==, -1);
+ tt_int_op(evhttp_del_cb(http, "/test"), ==, 0);
+ tt_int_op(evhttp_del_cb(http, "/test"), ==, -1);
+ tt_int_op(evhttp_set_cb(http, "/test", http_basic_cb, http), ==, 0);
+
+ end:
+ if (escaped)
+ free(escaped);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_multi_line_header_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev= NULL;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ const char *http_start_request;
+ ev_uint16_t port = 0;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ tt_ptr_op(http, !=, NULL);
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ tt_ptr_op(bev, !=, NULL);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ http_start_request =
+ "GET /test HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "X-Multi-Extra-WS: libevent \r\n"
+ "\t\t\t2.1 \r\n"
+ "X-Multi: aaaaaaaa\r\n"
+ " a\r\n"
+ "\tEND\r\n"
+ "X-Last: last\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_start_request, strlen(http_start_request));
+ found_multi = found_multi2 = 0;
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(found_multi, ==, 1);
+ tt_int_op(found_multi2, ==, 1);
+ tt_int_op(test_ok, ==, 4);
+ end:
+ if (bev)
+ bufferevent_free(bev);
+ if (fd >= 0)
+ evutil_closesocket(fd);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_request_bad(struct evhttp_request *req, void *arg)
+{
+ if (req != NULL) {
+ fprintf(stderr, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_base_loopexit(arg, NULL);
+}
+
+static void
+http_negative_content_length_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_request_bad, data->base);
+
+ /* Cause the response to have a negative content-length */
+ evhttp_add_header(evhttp_request_get_output_headers(req), "X-Negative", "makeitso");
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+
+static void
+http_data_length_constraints_test_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(req);
+ tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_BADREQUEST);
+end:
+ event_base_loopexit(arg, NULL);
+}
+static void
+http_large_entity_test_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(req);
+ tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_ENTITYTOOLARGE);
+end:
+ event_base_loopexit(arg, NULL);
+}
+static void
+http_expectation_failed_done(struct evhttp_request *req, void *arg)
+{
+ tt_assert(req);
+ tt_int_op(evhttp_request_get_response_code(req), ==, HTTP_EXPECTATIONFAILED);
+end:
+ event_base_loopexit(arg, NULL);
+}
+
+static void
+http_data_length_constraints_test_impl(void *arg, int read_on_write_error)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ char *long_str = NULL;
+ const size_t continue_size = 1<<20;
+ const size_t size = (1<<20) * 3;
+ void (*cb)(struct evhttp_request *, void *);
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+ cb = http_failed_request_done;
+ if (read_on_write_error)
+ cb = http_data_length_constraints_test_done;
+
+ tt_assert(continue_size < size);
+
+ long_str = malloc(size);
+ memset(long_str, 'a', size);
+ long_str[size - 1] = '\0';
+
+ TT_BLATHER(("Creating connection to :%i", port));
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ if (read_on_write_error)
+ tt_assert(!evhttp_connection_set_flags(evcon, EVHTTP_CON_READ_ON_WRITE_ERROR));
+
+ evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+ evhttp_set_max_headers_size(http, size - 1);
+ TT_BLATHER(("Set max header size %zu", size - 1));
+
+ req = evhttp_request_new(http_data_length_constraints_test_done, data->base);
+ tt_assert(req);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Longheader", long_str);
+ TT_BLATHER(("GET /?arg=val"));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/?arg=val") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ req = evhttp_request_new(http_data_length_constraints_test_done, data->base);
+ tt_assert(req);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ /* GET /?arg=verylongvalue HTTP/1.1 */
+ TT_BLATHER(("GET %s", long_str));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, long_str) == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ evhttp_set_max_body_size(http, size - 2);
+ TT_BLATHER(("Set body header size %zu", size - 2));
+
+ if (read_on_write_error)
+ cb = http_large_entity_test_done;
+ req = evhttp_request_new(cb, data->base);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+ TT_BLATHER(("POST /"));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ req = evhttp_request_new(http_large_entity_test_done, data->base);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "100-continue");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+ TT_BLATHER(("POST / (Expect: 100-continue, http_large_entity_test_done)"));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ long_str[continue_size] = '\0';
+
+ req = evhttp_request_new(http_dispatcher_test_done, data->base);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "100-continue");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+ TT_BLATHER(("POST / (Expect: 100-continue, http_dispatcher_test_done)"));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ if (read_on_write_error)
+ cb = http_expectation_failed_done;
+ req = evhttp_request_new(cb, data->base);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Expect", "101-continue");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+ TT_BLATHER(("POST / (Expect: 101-continue)"));
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ test_ok = 1;
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+ if (long_str)
+ free(long_str);
+}
+static void http_data_length_constraints_test(void *arg)
+{ http_data_length_constraints_test_impl(arg, 0); }
+static void http_read_on_write_error_test(void *arg)
+{ http_data_length_constraints_test_impl(arg, 1); }
+
+static void
+http_lingering_close_test_impl(void *arg, int lingering)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ char *long_str = NULL;
+ size_t size = (1<<20) * 3;
+ void (*cb)(struct evhttp_request *, void *);
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ if (lingering)
+ tt_assert(!evhttp_set_flags(http, EVHTTP_SERVER_LINGERING_CLOSE));
+ evhttp_set_max_body_size(http, size / 2);
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+ evhttp_connection_set_local_address(evcon, "127.0.0.1");
+
+ /*
+ * At this point, we want to schedule an HTTP GET request
+ * server using our make request method.
+ */
+
+ long_str = malloc(size);
+ memset(long_str, 'a', size);
+ long_str[size - 1] = '\0';
+
+ if (lingering)
+ cb = http_large_entity_test_done;
+ else
+ cb = http_failed_request_done;
+ req = evhttp_request_new(cb, data->base);
+ tt_assert(req);
+ evhttp_add_header(evhttp_request_get_output_headers(req), "Host", "somehost");
+ evbuffer_add_printf(evhttp_request_get_output_buffer(req), "%s", long_str);
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_POST, "/") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ event_base_dispatch(data->base);
+
+ test_ok = 1;
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+ if (long_str)
+ free(long_str);
+}
+static void http_non_lingering_close_test(void *arg)
+{ http_lingering_close_test_impl(arg, 0); }
+static void http_lingering_close_test(void *arg)
+{ http_lingering_close_test_impl(arg, 1); }
+
+/*
+ * Testing client reset of server chunked connections
+ */
+
+struct terminate_state {
+ struct event_base *base;
+ struct evhttp_request *req;
+ struct bufferevent *bev;
+ evutil_socket_t fd;
+ int gotclosecb: 1;
+ int oneshot: 1;
+};
+
+static void
+terminate_chunked_trickle_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct terminate_state *state = arg;
+ struct evbuffer *evb;
+
+ if (!state->req) {
+ return;
+ }
+
+ if (evhttp_request_get_connection(state->req) == NULL) {
+ test_ok = 1;
+ evhttp_request_free(state->req);
+ event_base_loopexit(state->base,NULL);
+ return;
+ }
+
+ evb = evbuffer_new();
+ evbuffer_add_printf(evb, "%p", evb);
+ evhttp_send_reply_chunk(state->req, evb);
+ evbuffer_free(evb);
+
+ if (!state->oneshot) {
+ struct timeval tv;
+ tv.tv_sec = 0;
+ tv.tv_usec = 3000;
+ EVUTIL_ASSERT(state);
+ EVUTIL_ASSERT(state->base);
+ event_base_once(state->base, -1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
+ }
+}
+
+static void
+terminate_chunked_close_cb(struct evhttp_connection *evcon, void *arg)
+{
+ struct terminate_state *state = arg;
+ state->gotclosecb = 1;
+
+ /** TODO: though we can do this unconditionally */
+ if (state->oneshot) {
+ evhttp_request_free(state->req);
+ state->req = NULL;
+ event_base_loopexit(state->base,NULL);
+ }
+}
+
+static void
+terminate_chunked_cb(struct evhttp_request *req, void *arg)
+{
+ struct terminate_state *state = arg;
+ struct timeval tv;
+
+ /* we want to know if this connection closes on us */
+ evhttp_connection_set_closecb(
+ evhttp_request_get_connection(req),
+ terminate_chunked_close_cb, arg);
+
+ state->req = req;
+
+ evhttp_send_reply_start(req, HTTP_OK, "OK");
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 3000;
+ event_base_once(state->base, -1, EV_TIMEOUT, terminate_chunked_trickle_cb, arg, &tv);
+}
+
+static void
+terminate_chunked_client(evutil_socket_t fd, short event, void *arg)
+{
+ struct terminate_state *state = arg;
+ bufferevent_free(state->bev);
+ evutil_closesocket(state->fd);
+}
+
+static void
+terminate_readcb(struct bufferevent *bev, void *arg)
+{
+ /* just drop the data */
+ evbuffer_drain(bufferevent_get_input(bev), -1);
+}
+
+
+static void
+http_terminate_chunked_test_impl(void *arg, int oneshot)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev = NULL;
+ struct timeval tv;
+ const char *http_request;
+ ev_uint16_t port = 0;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+ struct terminate_state terminate_state;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+
+ evhttp_del_cb(http, "/test");
+ tt_assert(evhttp_set_cb(http, "/test",
+ terminate_chunked_cb, &terminate_state) == 0);
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = bufferevent_socket_new(data->base, fd, 0);
+ bufferevent_setcb(bev, terminate_readcb, http_writecb,
+ http_errorcb, data->base);
+
+ memset(&terminate_state, 0, sizeof(terminate_state));
+ terminate_state.base = data->base;
+ terminate_state.fd = fd;
+ terminate_state.bev = bev;
+ terminate_state.gotclosecb = 0;
+ terminate_state.oneshot = oneshot;
+
+ /* first half of the http request */
+ http_request =
+ "GET /test HTTP/1.1\r\n"
+ "Host: some\r\n\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+ evutil_timerclear(&tv);
+ tv.tv_usec = 10000;
+ event_base_once(data->base, -1, EV_TIMEOUT, terminate_chunked_client, &terminate_state,
+ &tv);
+
+ event_base_dispatch(data->base);
+
+ if (terminate_state.gotclosecb == 0)
+ test_ok = 0;
+
+ end:
+ if (fd >= 0)
+ evutil_closesocket(fd);
+ if (http)
+ evhttp_free(http);
+}
+static void
+http_terminate_chunked_test(void *arg)
+{
+ http_terminate_chunked_test_impl(arg, 0);
+}
+static void
+http_terminate_chunked_oneshot_test(void *arg)
+{
+ http_terminate_chunked_test_impl(arg, 1);
+}
+
+static struct regress_dns_server_table ipv6_search_table[] = {
+ { "localhost", "AAAA", "::1", 0, 0 },
+ { NULL, NULL, NULL, 0, 0 }
+};
+
+static void
+http_ipv6_for_domain_test_impl(void *arg, int family)
+{
+ struct basic_test_data *data = arg;
+ struct evdns_base *dns_base = NULL;
+ ev_uint16_t portnum = 0;
+ char address[64];
+
+ tt_assert(regress_dnsserver(data->base, &portnum, ipv6_search_table));
+
+ dns_base = evdns_base_new(data->base, 0/* init name servers */);
+ tt_assert(dns_base);
+
+ /* Add ourself as the only nameserver, and make sure we really are
+ * the only nameserver. */
+ evutil_snprintf(address, sizeof(address), "127.0.0.1:%d", portnum);
+ evdns_base_nameserver_ip_add(dns_base, address);
+
+ http_connection_test_(arg, 0 /* not persistent */, "localhost", dns_base,
+ 1 /* ipv6 */, family, 0);
+
+ end:
+ if (dns_base)
+ evdns_base_free(dns_base, 0);
+ regress_clean_dnsserver();
+}
+static void
+http_ipv6_for_domain_test(void *arg)
+{
+ http_ipv6_for_domain_test_impl(arg, AF_UNSPEC);
+}
+
+static void
+http_request_get_addr_on_close(struct evhttp_connection *evcon, void *arg)
+{
+ const struct sockaddr *storage;
+ char addrbuf[128];
+ char local[] = "127.0.0.1:";
+
+ test_ok = 0;
+ tt_assert(evcon);
+
+ storage = evhttp_connection_get_addr(evcon);
+ tt_assert(storage);
+
+ evutil_format_sockaddr_port_((struct sockaddr *)storage, addrbuf, sizeof(addrbuf));
+ tt_assert(!strncmp(addrbuf, local, sizeof(local) - 1));
+
+ test_ok = 1;
+ return;
+
+end:
+ test_ok = 0;
+}
+
+static void
+http_get_addr_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+ exit_base = data->base;
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+ evhttp_connection_set_closecb(evcon, http_request_get_addr_on_close, arg);
+
+ /*
+ * At this point, we want to schedule a request to the HTTP
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(http_request_done, (void *)BASIC_REQUEST_BODY);
+
+ /* We give ownership of the request to the connection */
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+
+ event_base_dispatch(data->base);
+
+ http_request_get_addr_on_close(evcon, NULL);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+http_set_family_test(void *arg)
+{
+ http_connection_test_(arg, 0, "127.0.0.1", NULL, 0, AF_UNSPEC, 0);
+}
+static void
+http_set_family_ipv4_test(void *arg)
+{
+ http_connection_test_(arg, 0, "127.0.0.1", NULL, 0, AF_INET, 0);
+}
+static void
+http_set_family_ipv6_test(void *arg)
+{
+ http_ipv6_for_domain_test_impl(arg, AF_INET6);
+}
+
+static void
+http_write_during_read(evutil_socket_t fd, short what, void *arg)
+{
+ struct bufferevent *bev = arg;
+ struct timeval tv;
+
+ bufferevent_write(bev, "foobar", strlen("foobar"));
+
+ evutil_timerclear(&tv);
+ tv.tv_sec = 1;
+ event_base_loopexit(exit_base, &tv);
+}
+static void
+http_write_during_read_test_impl(void *arg, int ssl)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct bufferevent *bev = NULL;
+ struct timeval tv;
+ evutil_socket_t fd;
+ const char *http_request;
+ struct evhttp *http = http_setup(&port, data->base, ssl ? HTTP_BIND_SSL : 0);
+
+ test_ok = 0;
+ exit_base = data->base;
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+ bev = create_bev(data->base, fd, 0, 0);
+ bufferevent_setcb(bev, NULL, NULL, NULL, data->base);
+ bufferevent_disable(bev, EV_READ);
+
+ http_request =
+ "GET /large HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "\r\n";
+
+ bufferevent_write(bev, http_request, strlen(http_request));
+ evutil_timerclear(&tv);
+ tv.tv_usec = 10000;
+ event_base_once(data->base, -1, EV_TIMEOUT, http_write_during_read, bev, &tv);
+
+ event_base_dispatch(data->base);
+
+end:
+ if (bev)
+ bufferevent_free(bev);
+ if (http)
+ evhttp_free(http);
+}
+static void http_write_during_read_test(void *arg)
+{ http_write_during_read_test_impl(arg, 0); }
+
+static void
+http_request_own_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ ev_uint16_t port = 0;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct evhttp *http = http_setup(&port, data->base, 0);
+
+ test_ok = 0;
+ exit_base = data->base;
+
+ evhttp_free(http);
+
+ evcon = evhttp_connection_base_new(data->base, NULL, "127.0.0.1", port);
+ tt_assert(evcon);
+
+ req = evhttp_request_new(http_request_no_action_done, NULL);
+
+ if (evhttp_make_request(evcon, req, EVHTTP_REQ_GET, "/test") == -1) {
+ tt_abort_msg("Couldn't make request");
+ }
+ evhttp_request_own(req);
+
+ event_base_dispatch(data->base);
+
+ end:
+ if (evcon)
+ evhttp_connection_free(evcon);
+ if (req)
+ evhttp_request_free(req);
+
+ test_ok = 1;
+}
+
+static void http_run_bev_request(struct event_base *base, int port,
+ const char *fmt, ...)
+{
+ struct bufferevent *bev = NULL;
+ va_list ap;
+ evutil_socket_t fd;
+ struct evbuffer *out;
+
+ fd = http_connect("127.0.0.1", port);
+ tt_assert(fd != EVUTIL_INVALID_SOCKET);
+
+ /* Stupid thing to send a request */
+ bev = create_bev(base, fd, 0, 0);
+ bufferevent_setcb(bev, http_readcb, http_writecb,
+ http_errorcb, base);
+ out = bufferevent_get_output(bev);
+
+ va_start(ap, fmt);
+ evbuffer_add_vprintf(out, fmt, ap);
+ va_end(ap);
+
+ event_base_dispatch(base);
+
+end:
+ if (bev)
+ bufferevent_free(bev);
+}
+static void
+http_request_extra_body_test(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev = NULL;
+ ev_uint16_t port = 0;
+ int i;
+ struct evhttp *http =
+ http_setup_gencb(&port, data->base, 0, http_timeout_cb, NULL);
+ struct evbuffer *body = NULL;
+
+ exit_base = data->base;
+ test_ok = 0;
+
+ body = evbuffer_new();
+ for (i = 0; i < 10000; ++i)
+ evbuffer_add_printf(body, "this is the body that HEAD should not have");
+
+ http_run_bev_request(data->base, port,
+ "HEAD /timeout HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "Content-Length: %i\r\n"
+ "\r\n%s",
+ (int)evbuffer_get_length(body),
+ evbuffer_pullup(body, -1)
+ );
+ tt_assert(test_ok == -2);
+
+ http_run_bev_request(data->base, port,
+ "HEAD /__gencb__ HTTP/1.1\r\n"
+ "Host: somehost\r\n"
+ "Connection: close\r\n"
+ "Content-Length: %i\r\n"
+ "\r\n%s",
+ (int)evbuffer_get_length(body),
+ evbuffer_pullup(body, -1)
+ );
+ tt_assert(test_ok == -2);
+
+ end:
+ evhttp_free(http);
+ if (bev)
+ bufferevent_free(bev);
+ if (body)
+ evbuffer_free(body);
+}
+
+#define HTTP_LEGACY(name) \
+ { #name, run_legacy_test_fn, TT_ISOLATED|TT_LEGACY, &legacy_setup, \
+ http_##name##_test }
+
+#define HTTP_CAST_ARG(a) ((void *)(a))
+#define HTTP_OFF_N(title, name, arg) \
+ { #title, http_##name##_test, TT_ISOLATED|TT_OFF_BY_DEFAULT, &basic_setup, HTTP_CAST_ARG(arg) }
+#define HTTP_RET_N(title, name, test_opts, arg) \
+ { #title, http_##name##_test, TT_ISOLATED|TT_RETRIABLE|test_opts, &basic_setup, HTTP_CAST_ARG(arg) }
+#define HTTP_N(title, name, test_opts, arg) \
+ { #title, http_##name##_test, TT_ISOLATED|test_opts, &basic_setup, HTTP_CAST_ARG(arg) }
+#define HTTP(name) HTTP_N(name, name, 0, NULL)
+#define HTTPS(name) \
+ { "https_" #name, https_##name##_test, TT_ISOLATED, &basic_setup, NULL }
+
+#ifdef EVENT__HAVE_OPENSSL
+static void https_basic_test(void *arg)
+{ http_basic_test_impl(arg, 1, "GET /test HTTP/1.1"); }
+static void https_filter_basic_test(void *arg)
+{ http_basic_test_impl(arg, 1 | HTTP_SSL_FILTER, "GET /test HTTP/1.1"); }
+static void https_incomplete_test(void *arg)
+{ http_incomplete_test_(arg, 0, 1); }
+static void https_incomplete_timeout_test(void *arg)
+{ http_incomplete_test_(arg, 1, 1); }
+static void https_simple_test(void *arg)
+{ http_simple_test_impl(arg, 1, 0, "/test"); }
+static void https_simple_dirty_test(void *arg)
+{ http_simple_test_impl(arg, 1, 1, "/test"); }
+static void https_connection_retry_conn_address_test(void *arg)
+{ http_connection_retry_conn_address_test_impl(arg, 1); }
+static void https_connection_retry_test(void *arg)
+{ http_connection_retry_test_impl(arg, 1); }
+static void https_chunk_out_test(void *arg)
+{ http_chunk_out_test_impl(arg, 1); }
+static void https_filter_chunk_out_test(void *arg)
+{ http_chunk_out_test_impl(arg, 1 | HTTP_SSL_FILTER); }
+static void https_stream_out_test(void *arg)
+{ http_stream_out_test_impl(arg, 1); }
+static void https_connection_fail_test(void *arg)
+{ http_connection_fail_test_impl(arg, 1); }
+static void https_write_during_read_test(void *arg)
+{ http_write_during_read_test_impl(arg, 1); }
+static void https_connection_test(void *arg)
+{ http_connection_test_(arg, 0, "127.0.0.1", NULL, 0, AF_UNSPEC, 1); }
+static void https_persist_connection_test(void *arg)
+{ http_connection_test_(arg, 1, "127.0.0.1", NULL, 0, AF_UNSPEC, 1); }
+#endif
+
+struct testcase_t http_testcases[] = {
+ { "primitives", http_primitives, 0, NULL, NULL },
+ { "base", http_base_test, TT_FORK, NULL, NULL },
+ { "bad_headers", http_bad_header_test, 0, NULL, NULL },
+ { "parse_query", http_parse_query_test, 0, NULL, NULL },
+ { "parse_query_str", http_parse_query_str_test, 0, NULL, NULL },
+ { "parse_uri", http_parse_uri_test, 0, NULL, NULL },
+ { "parse_uri_nc", http_parse_uri_test, 0, &basic_setup, (void*)"nc" },
+ { "uriencode", http_uriencode_test, 0, NULL, NULL },
+ HTTP(basic),
+ HTTP(basic_trailing_space),
+ HTTP(simple),
+ HTTP(simple_nonconformant),
+
+ HTTP_N(cancel, cancel, 0, BASIC),
+ HTTP_RET_N(cancel_by_host, cancel, 0, BY_HOST),
+ HTTP_RET_N(cancel_by_host_inactive_server, cancel, TT_NO_LOGS, BY_HOST | INACTIVE_SERVER),
+ HTTP_RET_N(cancel_by_host_no_ns, cancel, TT_NO_LOGS, BY_HOST | NO_NS),
+ HTTP_N(cancel_inactive_server, cancel, 0, INACTIVE_SERVER),
+ HTTP_N(cancel_by_host_no_ns_inactive_server, cancel, TT_NO_LOGS, BY_HOST | NO_NS | INACTIVE_SERVER),
+ HTTP_OFF_N(cancel_by_host_server_timeout, cancel, BY_HOST | INACTIVE_SERVER | SERVER_TIMEOUT),
+ HTTP_OFF_N(cancel_server_timeout, cancel, INACTIVE_SERVER | SERVER_TIMEOUT),
+ HTTP_OFF_N(cancel_by_host_no_ns_server_timeout, cancel, BY_HOST | NO_NS | INACTIVE_SERVER | SERVER_TIMEOUT),
+ HTTP_OFF_N(cancel_by_host_ns_timeout_server_timeout, cancel, BY_HOST | NO_NS | NS_TIMEOUT | INACTIVE_SERVER | SERVER_TIMEOUT),
+ HTTP_RET_N(cancel_by_host_ns_timeout, cancel, TT_NO_LOGS, BY_HOST | NO_NS | NS_TIMEOUT),
+ HTTP_RET_N(cancel_by_host_ns_timeout_inactive_server, cancel, TT_NO_LOGS, BY_HOST | NO_NS | NS_TIMEOUT | INACTIVE_SERVER),
+
+ HTTP(virtual_host),
+ HTTP(post),
+ HTTP(put),
+ HTTP(delete),
+ HTTP(allowed_methods),
+ HTTP(failure),
+ HTTP(connection),
+ HTTP(persist_connection),
+ HTTP(autofree_connection),
+ HTTP(connection_async),
+ HTTP(close_detection),
+ HTTP(close_detection_delay),
+ HTTP(bad_request),
+ HTTP(incomplete),
+ HTTP(incomplete_timeout),
+ HTTP(terminate_chunked),
+ HTTP(terminate_chunked_oneshot),
+ HTTP(on_complete),
+
+ HTTP(highport),
+ HTTP(dispatcher),
+ HTTP(multi_line_header),
+ HTTP(negative_content_length),
+ HTTP(chunk_out),
+ HTTP(stream_out),
+
+ HTTP(stream_in),
+ HTTP(stream_in_cancel),
+
+ HTTP(connection_fail),
+ { "connection_retry", http_connection_retry_test, TT_ISOLATED|TT_OFF_BY_DEFAULT, &basic_setup, NULL },
+ { "connection_retry_conn_address", http_connection_retry_conn_address_test,
+ TT_ISOLATED|TT_OFF_BY_DEFAULT, &basic_setup, NULL },
+
+ HTTP(data_length_constraints),
+ HTTP(read_on_write_error),
+ HTTP(non_lingering_close),
+ HTTP(lingering_close),
+
+ HTTP(ipv6_for_domain),
+ HTTP(get_addr),
+
+ HTTP(set_family),
+ HTTP(set_family_ipv4),
+ HTTP(set_family_ipv6),
+
+ HTTP(write_during_read),
+ HTTP(request_own),
+
+ HTTP(request_extra_body),
+
+#ifdef EVENT__HAVE_OPENSSL
+ HTTPS(basic),
+ HTTPS(filter_basic),
+ HTTPS(simple),
+ HTTPS(simple_dirty),
+ HTTPS(incomplete),
+ HTTPS(incomplete_timeout),
+ { "https_connection_retry", https_connection_retry_test, TT_ISOLATED|TT_OFF_BY_DEFAULT, &basic_setup, NULL },
+ { "https_connection_retry_conn_address", https_connection_retry_conn_address_test,
+ TT_ISOLATED|TT_OFF_BY_DEFAULT, &basic_setup, NULL },
+ HTTPS(chunk_out),
+ HTTPS(filter_chunk_out),
+ HTTPS(stream_out),
+ HTTPS(connection_fail),
+ HTTPS(write_during_read),
+ HTTPS(connection),
+ HTTPS(persist_connection),
+#endif
+
+ END_OF_TESTCASES
+};
+
+struct testcase_t http_iocp_testcases[] = {
+ { "simple", http_simple_test, TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup, NULL },
+#ifdef EVENT__HAVE_OPENSSL
+ { "https_simple", https_simple_test, TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP, &basic_setup, NULL },
+#endif
+ END_OF_TESTCASES
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_iocp.c b/ipc/chromium/src/third_party/libevent/test/regress_iocp.c
new file mode 100644
index 0000000000..17b385241f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_iocp.c
@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include "event2/event.h"
+#include "event2/thread.h"
+#include "event2/buffer.h"
+#include "event2/buffer_compat.h"
+#include "event2/bufferevent.h"
+
+#include <winsock2.h>
+#include <ws2tcpip.h>
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#include <winsock2.h>
+#undef WIN32_LEAN_AND_MEAN
+
+#include "iocp-internal.h"
+#include "evbuffer-internal.h"
+#include "evthread-internal.h"
+
+/* FIXME remove these ones */
+#include <sys/queue.h>
+#include "event2/event_struct.h"
+#include "event-internal.h"
+
+#define MAX_CALLS 16
+
+static void *count_lock = NULL, *count_cond = NULL;
+static int count = 0;
+
+static void
+count_init(void)
+{
+ EVTHREAD_ALLOC_LOCK(count_lock, 0);
+ EVTHREAD_ALLOC_COND(count_cond);
+
+ tt_assert(count_lock);
+ tt_assert(count_cond);
+
+end:
+ ;
+}
+
+static void
+count_free(void)
+{
+ EVTHREAD_FREE_LOCK(count_lock, 0);
+ EVTHREAD_FREE_COND(count_cond);
+}
+
+static void
+count_incr(void)
+{
+ EVLOCK_LOCK(count_lock, 0);
+ count++;
+ EVTHREAD_COND_BROADCAST(count_cond);
+ EVLOCK_UNLOCK(count_lock, 0);
+}
+
+static int
+count_wait_for(int i, int ms)
+{
+ struct timeval tv;
+ DWORD elapsed;
+ int rv = -1;
+
+ EVLOCK_LOCK(count_lock, 0);
+ while (ms > 0 && count != i) {
+ tv.tv_sec = 0;
+ tv.tv_usec = ms * 1000;
+ elapsed = GetTickCount();
+ EVTHREAD_COND_WAIT_TIMED(count_cond, count_lock, &tv);
+ elapsed = GetTickCount() - elapsed;
+ ms -= elapsed;
+ }
+ if (count == i)
+ rv = 0;
+ EVLOCK_UNLOCK(count_lock, 0);
+
+ return rv;
+}
+
+struct dummy_overlapped {
+ struct event_overlapped eo;
+ void *lock;
+ int call_count;
+ uintptr_t keys[MAX_CALLS];
+ ev_ssize_t sizes[MAX_CALLS];
+};
+
+static void
+dummy_cb(struct event_overlapped *o, uintptr_t key, ev_ssize_t n, int ok)
+{
+ struct dummy_overlapped *d_o =
+ EVUTIL_UPCAST(o, struct dummy_overlapped, eo);
+
+ EVLOCK_LOCK(d_o->lock, 0);
+ if (d_o->call_count < MAX_CALLS) {
+ d_o->keys[d_o->call_count] = key;
+ d_o->sizes[d_o->call_count] = n;
+ }
+ d_o->call_count++;
+ EVLOCK_UNLOCK(d_o->lock, 0);
+
+ count_incr();
+}
+
+static int
+pair_is_in(struct dummy_overlapped *o, uintptr_t key, ev_ssize_t n)
+{
+ int i;
+ int result = 0;
+ EVLOCK_LOCK(o->lock, 0);
+ for (i=0; i < o->call_count; ++i) {
+ if (o->keys[i] == key && o->sizes[i] == n) {
+ result = 1;
+ break;
+ }
+ }
+ EVLOCK_UNLOCK(o->lock, 0);
+ return result;
+}
+
+static void
+test_iocp_port(void *ptr)
+{
+ struct event_iocp_port *port = NULL;
+ struct dummy_overlapped o1, o2;
+
+ memset(&o1, 0, sizeof(o1));
+ memset(&o2, 0, sizeof(o2));
+
+ count_init();
+ EVTHREAD_ALLOC_LOCK(o1.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ EVTHREAD_ALLOC_LOCK(o2.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+
+ tt_assert(o1.lock);
+ tt_assert(o2.lock);
+
+ event_overlapped_init_(&o1.eo, dummy_cb);
+ event_overlapped_init_(&o2.eo, dummy_cb);
+
+ port = event_iocp_port_launch_(0);
+ tt_assert(port);
+
+ tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 10, 100));
+ tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 20, 200));
+
+ tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 11, 101));
+ tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 21, 201));
+
+ tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 12, 102));
+ tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 22, 202));
+
+ tt_assert(!event_iocp_activate_overlapped_(port, &o1.eo, 13, 103));
+ tt_assert(!event_iocp_activate_overlapped_(port, &o2.eo, 23, 203));
+
+ tt_int_op(count_wait_for(8, 2000), ==, 0);
+
+ tt_want(!event_iocp_shutdown_(port, 2000));
+
+ tt_int_op(o1.call_count, ==, 4);
+ tt_int_op(o2.call_count, ==, 4);
+
+ tt_want(pair_is_in(&o1, 10, 100));
+ tt_want(pair_is_in(&o1, 11, 101));
+ tt_want(pair_is_in(&o1, 12, 102));
+ tt_want(pair_is_in(&o1, 13, 103));
+
+ tt_want(pair_is_in(&o2, 20, 200));
+ tt_want(pair_is_in(&o2, 21, 201));
+ tt_want(pair_is_in(&o2, 22, 202));
+ tt_want(pair_is_in(&o2, 23, 203));
+
+end:
+ EVTHREAD_FREE_LOCK(o1.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ EVTHREAD_FREE_LOCK(o2.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ count_free();
+}
+
+static struct evbuffer *rbuf = NULL, *wbuf = NULL;
+
+static void
+read_complete(struct event_overlapped *eo, uintptr_t key,
+ ev_ssize_t nbytes, int ok)
+{
+ tt_assert(ok);
+ evbuffer_commit_read_(rbuf, nbytes);
+ count_incr();
+end:
+ ;
+}
+
+static void
+write_complete(struct event_overlapped *eo, uintptr_t key,
+ ev_ssize_t nbytes, int ok)
+{
+ tt_assert(ok);
+ evbuffer_commit_write_(wbuf, nbytes);
+ count_incr();
+end:
+ ;
+}
+
+static void
+test_iocp_evbuffer(void *ptr)
+{
+ struct event_overlapped rol, wol;
+ struct basic_test_data *data = ptr;
+ struct event_iocp_port *port = NULL;
+ struct evbuffer *buf=NULL;
+ struct evbuffer_chain *chain;
+ char junk[1024];
+ int i;
+
+ count_init();
+ event_overlapped_init_(&rol, read_complete);
+ event_overlapped_init_(&wol, write_complete);
+
+ for (i = 0; i < (int)sizeof(junk); ++i)
+ junk[i] = (char)(i);
+
+ rbuf = evbuffer_overlapped_new_(data->pair[0]);
+ wbuf = evbuffer_overlapped_new_(data->pair[1]);
+ evbuffer_enable_locking(rbuf, NULL);
+ evbuffer_enable_locking(wbuf, NULL);
+
+ port = event_iocp_port_launch_(0);
+ tt_assert(port);
+ tt_assert(rbuf);
+ tt_assert(wbuf);
+
+ tt_assert(!event_iocp_port_associate_(port, data->pair[0], 100));
+ tt_assert(!event_iocp_port_associate_(port, data->pair[1], 100));
+
+ for (i=0;i<10;++i)
+ evbuffer_add(wbuf, junk, sizeof(junk));
+
+ buf = evbuffer_new();
+ tt_assert(buf != NULL);
+ evbuffer_add(rbuf, junk, sizeof(junk));
+ tt_assert(!evbuffer_launch_read_(rbuf, 2048, &rol));
+ evbuffer_add_buffer(buf, rbuf);
+ tt_int_op(evbuffer_get_length(buf), ==, sizeof(junk));
+ for (chain = buf->first; chain; chain = chain->next)
+ tt_int_op(chain->flags & EVBUFFER_MEM_PINNED_ANY, ==, 0);
+ tt_assert(!evbuffer_get_length(rbuf));
+ tt_assert(!evbuffer_launch_write_(wbuf, 512, &wol));
+
+ tt_int_op(count_wait_for(2, 2000), ==, 0);
+
+ tt_int_op(evbuffer_get_length(rbuf),==,512);
+
+ /* FIXME Actually test some stuff here. */
+
+ tt_want(!event_iocp_shutdown_(port, 2000));
+end:
+ count_free();
+ evbuffer_free(rbuf);
+ evbuffer_free(wbuf);
+ if (buf) evbuffer_free(buf);
+}
+
+static int got_readcb = 0;
+
+static void
+async_readcb(struct bufferevent *bev, void *arg)
+{
+ /* Disabling read should cause the loop to quit */
+ bufferevent_disable(bev, EV_READ);
+ got_readcb++;
+}
+
+static void
+test_iocp_bufferevent_async(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ struct event_iocp_port *port = NULL;
+ struct bufferevent *bea1=NULL, *bea2=NULL;
+ char buf[128];
+ size_t n;
+
+ event_base_start_iocp_(data->base, 0);
+ port = event_base_get_iocp_(data->base);
+ tt_assert(port);
+
+ bea1 = bufferevent_async_new_(data->base, data->pair[0],
+ BEV_OPT_DEFER_CALLBACKS);
+ bea2 = bufferevent_async_new_(data->base, data->pair[1],
+ BEV_OPT_DEFER_CALLBACKS);
+ tt_assert(bea1);
+ tt_assert(bea2);
+
+ bufferevent_setcb(bea2, async_readcb, NULL, NULL, NULL);
+ bufferevent_enable(bea1, EV_WRITE);
+ bufferevent_enable(bea2, EV_READ);
+
+ bufferevent_write(bea1, "Hello world", strlen("Hello world")+1);
+
+ event_base_dispatch(data->base);
+
+ tt_int_op(got_readcb, ==, 1);
+ n = bufferevent_read(bea2, buf, sizeof(buf)-1);
+ buf[n]='\0';
+ tt_str_op(buf, ==, "Hello world");
+
+end:
+ bufferevent_free(bea1);
+ bufferevent_free(bea2);
+}
+
+
+struct testcase_t iocp_testcases[] = {
+ { "port", test_iocp_port, TT_FORK|TT_NEED_THREADS, &basic_setup, NULL },
+ { "evbuffer", test_iocp_evbuffer,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_THREADS,
+ &basic_setup, NULL },
+ { "bufferevent_async", test_iocp_bufferevent_async,
+ TT_FORK|TT_NEED_SOCKETPAIR|TT_NEED_THREADS|TT_NEED_BASE,
+ &basic_setup, NULL },
+ END_OF_TESTCASES
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_listener.c b/ipc/chromium/src/third_party/libevent/test/regress_listener.c
new file mode 100644
index 0000000000..871da4c62c
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_listener.c
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include <sys/types.h>
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+# include <arpa/inet.h>
+# endif
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+
+#include <string.h>
+
+#include "event2/listener.h"
+#include "event2/event.h"
+#include "event2/util.h"
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+static void
+acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *addr, int socklen, void *arg)
+{
+ int *ptr = arg;
+ --*ptr;
+ TT_BLATHER(("Got one for %p", ptr));
+ evutil_closesocket(fd);
+
+ if (! *ptr)
+ evconnlistener_disable(listener);
+}
+
+static void
+regress_pick_a_port(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evconnlistener *listener1 = NULL, *listener2 = NULL;
+ struct sockaddr_in sin;
+ int count1 = 2, count2 = 1;
+ struct sockaddr_storage ss1, ss2;
+ struct sockaddr_in *sin1, *sin2;
+ ev_socklen_t slen1 = sizeof(ss1), slen2 = sizeof(ss2);
+ unsigned int flags =
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC;
+ evutil_socket_t fd1, fd2, fd3;
+
+ fd1 = fd2 = fd3 = EVUTIL_INVALID_SOCKET;
+
+ if (data->setup_data && strstr((char*)data->setup_data, "ts")) {
+ flags |= LEV_OPT_THREADSAFE;
+ }
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+ sin.sin_port = 0; /* "You pick!" */
+
+ listener1 = evconnlistener_new_bind(base, acceptcb, &count1,
+ flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+ tt_assert(listener1);
+ listener2 = evconnlistener_new_bind(base, acceptcb, &count2,
+ flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+ tt_assert(listener2);
+
+ tt_assert(evconnlistener_get_fd(listener1) != EVUTIL_INVALID_SOCKET);
+ tt_assert(evconnlistener_get_fd(listener2) != EVUTIL_INVALID_SOCKET);
+ tt_assert(getsockname(evconnlistener_get_fd(listener1),
+ (struct sockaddr*)&ss1, &slen1) == 0);
+ tt_assert(getsockname(evconnlistener_get_fd(listener2),
+ (struct sockaddr*)&ss2, &slen2) == 0);
+ tt_int_op(ss1.ss_family, ==, AF_INET);
+ tt_int_op(ss2.ss_family, ==, AF_INET);
+
+ sin1 = (struct sockaddr_in*)&ss1;
+ sin2 = (struct sockaddr_in*)&ss2;
+ tt_int_op(ntohl(sin1->sin_addr.s_addr), ==, 0x7f000001);
+ tt_int_op(ntohl(sin2->sin_addr.s_addr), ==, 0x7f000001);
+ tt_int_op(sin1->sin_port, !=, sin2->sin_port);
+
+ tt_ptr_op(evconnlistener_get_base(listener1), ==, base);
+ tt_ptr_op(evconnlistener_get_base(listener2), ==, base);
+
+ fd1 = fd2 = fd3 = EVUTIL_INVALID_SOCKET;
+ evutil_socket_connect_(&fd1, (struct sockaddr*)&ss1, slen1);
+ evutil_socket_connect_(&fd2, (struct sockaddr*)&ss1, slen1);
+ evutil_socket_connect_(&fd3, (struct sockaddr*)&ss2, slen2);
+
+#ifdef _WIN32
+ Sleep(100); /* XXXX this is a stupid stopgap. */
+#endif
+ event_base_dispatch(base);
+
+ tt_int_op(count1, ==, 0);
+ tt_int_op(count2, ==, 0);
+
+end:
+ if (fd1>=0)
+ EVUTIL_CLOSESOCKET(fd1);
+ if (fd2>=0)
+ EVUTIL_CLOSESOCKET(fd2);
+ if (fd3>=0)
+ EVUTIL_CLOSESOCKET(fd3);
+ if (listener1)
+ evconnlistener_free(listener1);
+ if (listener2)
+ evconnlistener_free(listener2);
+}
+
+static void
+errorcb(struct evconnlistener *lis, void *data_)
+{
+ int *data = data_;
+ *data = 1000;
+ evconnlistener_disable(lis);
+}
+
+static void
+regress_listener_error(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evconnlistener *listener = NULL;
+ int count = 1;
+ unsigned int flags = LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE;
+
+ if (data->setup_data && strstr((char*)data->setup_data, "ts")) {
+ flags |= LEV_OPT_THREADSAFE;
+ }
+
+ /* send, so that pair[0] will look 'readable'*/
+ tt_int_op(send(data->pair[1], "hello", 5, 0), >, 0);
+
+ /* Start a listener with a bogus socket. */
+ listener = evconnlistener_new(base, acceptcb, &count,
+ flags, 0,
+ data->pair[0]);
+ tt_assert(listener);
+
+ evconnlistener_set_error_cb(listener, errorcb);
+
+ tt_assert(listener);
+
+ event_base_dispatch(base);
+ tt_int_op(count,==,1000); /* set by error cb */
+
+end:
+ if (listener)
+ evconnlistener_free(listener);
+}
+
+static void
+acceptcb_free(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *addr, int socklen, void *arg)
+{
+ int *ptr = arg;
+ --*ptr;
+ TT_BLATHER(("Got one for %p", ptr));
+ evutil_closesocket(fd);
+
+ if (! *ptr)
+ evconnlistener_free(listener);
+}
+static void
+regress_listener_close_accepted_fd(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evconnlistener *listener = NULL;
+ struct sockaddr_in sin;
+ struct sockaddr_storage ss;
+ ev_socklen_t slen = sizeof(ss);
+ int count = 1;
+ unsigned int flags = LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE;
+ evutil_socket_t fd = EVUTIL_INVALID_SOCKET;
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+ sin.sin_port = 0; /* "You pick!" */
+
+ /* Start a listener with a bogus socket. */
+ listener = evconnlistener_new_bind(base, acceptcb_free, &count,
+ flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+ tt_assert(listener);
+
+ tt_assert(getsockname(evconnlistener_get_fd(listener),
+ (struct sockaddr*)&ss, &slen) == 0);
+ evutil_socket_connect_(&fd, (struct sockaddr*)&ss, slen);
+
+ event_base_dispatch(base);
+
+end:
+ ;
+}
+
+static void
+regress_listener_immediate_close(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evconnlistener *listener = NULL;
+ struct sockaddr_in sin;
+ struct sockaddr_storage ss;
+ ev_socklen_t slen = sizeof(ss);
+ int count = 1;
+ unsigned int flags = LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE;
+ evutil_socket_t fd1 = EVUTIL_INVALID_SOCKET, fd2 = EVUTIL_INVALID_SOCKET;
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+ sin.sin_port = 0; /* "You pick!" */
+
+ /* Start a listener with a bogus socket. */
+ listener = evconnlistener_new_bind(base, acceptcb, &count,
+ flags, -1, (struct sockaddr *)&sin, sizeof(sin));
+ tt_assert(listener);
+
+ tt_assert(getsockname(evconnlistener_get_fd(listener),
+ (struct sockaddr*)&ss, &slen) == 0);
+
+ evutil_socket_connect_(&fd1, (struct sockaddr*)&ss, slen);
+ evutil_socket_connect_(&fd2, (struct sockaddr*)&ss, slen);
+
+ event_base_dispatch(base);
+
+ tt_int_op(count, ==, 0);
+
+end:
+ if (listener)
+ evconnlistener_free(listener);
+}
+
+#ifdef EVENT__HAVE_SETRLIMIT
+static void
+regress_listener_error_unlock(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ struct evconnlistener *listener = NULL;
+ unsigned int flags =
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE|LEV_OPT_THREADSAFE;
+
+ tt_int_op(send(data->pair[1], "hello", 5, 0), >, 0);
+
+ /* Start a listener with a bogus socket. */
+ listener = evconnlistener_new(base, acceptcb, NULL, flags, 0, data->pair[0]);
+ tt_assert(listener);
+
+ /** accept() must errored out with EMFILE */
+ {
+ struct rlimit rl;
+ rl.rlim_cur = rl.rlim_max = data->pair[1];
+ if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+ TT_DIE(("Can't change RLIMIT_NOFILE"));
+ }
+ }
+
+ event_base_loop(base, EVLOOP_ONCE);
+
+ /** with lock debugging, can fail on lock->count assertion */
+
+end:
+ if (listener)
+ evconnlistener_free(listener);
+}
+#endif
+
+struct testcase_t listener_testcases[] = {
+
+ { "randport", regress_pick_a_port, TT_FORK|TT_NEED_BASE,
+ &basic_setup, NULL},
+
+ { "randport_ts", regress_pick_a_port, TT_FORK|TT_NEED_BASE,
+ &basic_setup, (char*)"ts"},
+
+#ifdef EVENT__HAVE_SETRLIMIT
+ { "error_unlock", regress_listener_error_unlock,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR|TT_NO_LOGS,
+ &basic_setup, NULL},
+#endif
+
+ { "error", regress_listener_error,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR,
+ &basic_setup, NULL},
+
+ { "error_ts", regress_listener_error,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR,
+ &basic_setup, (char*)"ts"},
+
+ { "close_accepted_fd", regress_listener_close_accepted_fd,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL, },
+
+ { "immediate_close", regress_listener_immediate_close,
+ TT_FORK|TT_NEED_BASE, &basic_setup, NULL, },
+
+ END_OF_TESTCASES,
+};
+
+struct testcase_t listener_iocp_testcases[] = {
+ { "randport", regress_pick_a_port,
+ TT_FORK|TT_NEED_BASE|TT_ENABLE_IOCP,
+ &basic_setup, NULL},
+
+ { "error", regress_listener_error,
+ TT_FORK|TT_NEED_BASE|TT_NEED_SOCKETPAIR|TT_ENABLE_IOCP,
+ &basic_setup, NULL},
+
+ END_OF_TESTCASES,
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_main.c b/ipc/chromium/src/third_party/libevent/test/regress_main.c
new file mode 100644
index 0000000000..266561214b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_main.c
@@ -0,0 +1,528 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <io.h>
+#include <fcntl.h>
+#endif
+
+/* move_pthread_to_realtime_scheduling_class() */
+#ifdef EVENT__HAVE_MACH_MACH_H
+#include <mach/mach.h>
+#endif
+#ifdef EVENT__HAVE_MACH_MACH_TIME_H
+#include <mach/mach_time.h>
+#endif
+
+#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
+#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
+ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
+#define FORK_BREAKS_GCOV
+#include <vproc.h>
+#endif
+#endif
+
+#include "event2/event-config.h"
+
+#if 0
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#include <signal.h>
+#include <errno.h>
+#endif
+
+#include <sys/types.h>
+#ifdef EVENT__HAVE_SYS_STAT_H
+#include <sys/stat.h>
+#endif
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/dns.h"
+#include "event2/dns_compat.h"
+#include "event2/thread.h"
+
+#include "event2/event-config.h"
+#include "regress.h"
+#include "regress_thread.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include "../iocp-internal.h"
+#include "../event-internal.h"
+#include "../evthread-internal.h"
+
+struct evutil_weakrand_state test_weakrand_state;
+
+long
+timeval_msec_diff(const struct timeval *start, const struct timeval *end)
+{
+ long ms = end->tv_sec - start->tv_sec;
+ ms *= 1000;
+ ms += ((end->tv_usec - start->tv_usec)+500) / 1000;
+ return ms;
+}
+
+/* ============================================================ */
+/* Code to wrap up old legacy test cases that used setup() and cleanup().
+ *
+ * Not all of the tests designated "legacy" are ones that used setup() and
+ * cleanup(), of course. A test is legacy it it uses setup()/cleanup(), OR
+ * if it wants to find its event base/socketpair in global variables (ugh),
+ * OR if it wants to communicate success/failure through test_ok.
+ */
+
+/* This is set to true if we're inside a legacy test wrapper. It lets the
+ setup() and cleanup() functions in regress.c know they're not needed.
+ */
+int in_legacy_test_wrapper = 0;
+
+static void dnslogcb(int w, const char *m)
+{
+ TT_BLATHER(("%s", m));
+}
+
+/* creates a temporary file with the data in it. If *filename_out gets set,
+ * the caller should try to unlink it. */
+int
+regress_make_tmpfile(const void *data, size_t datalen, char **filename_out)
+{
+#ifndef _WIN32
+ char tmpfilename[32];
+ int fd;
+ *filename_out = NULL;
+ strcpy(tmpfilename, "/tmp/eventtmp.XXXXXX");
+#ifdef EVENT__HAVE_UMASK
+ umask(0077);
+#endif
+ fd = mkstemp(tmpfilename);
+ if (fd == -1)
+ return (-1);
+ if (write(fd, data, datalen) != (int)datalen) {
+ close(fd);
+ return (-1);
+ }
+ lseek(fd, 0, SEEK_SET);
+ /* remove it from the file system */
+ unlink(tmpfilename);
+ return (fd);
+#else
+ /* XXXX actually delete the file later */
+ char tmpfilepath[MAX_PATH];
+ char tmpfilename[MAX_PATH];
+ DWORD r, written;
+ int tries = 16;
+ HANDLE h;
+ r = GetTempPathA(MAX_PATH, tmpfilepath);
+ if (r > MAX_PATH || r == 0)
+ return (-1);
+ for (; tries > 0; --tries) {
+ r = GetTempFileNameA(tmpfilepath, "LIBEVENT", 0, tmpfilename);
+ if (r == 0)
+ return (-1);
+ h = CreateFileA(tmpfilename, GENERIC_READ|GENERIC_WRITE,
+ 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
+ if (h != INVALID_HANDLE_VALUE)
+ break;
+ }
+ if (tries == 0)
+ return (-1);
+ written = 0;
+ *filename_out = strdup(tmpfilename);
+ WriteFile(h, data, (DWORD)datalen, &written, NULL);
+ /* Closing the fd returned by this function will indeed close h. */
+ return _open_osfhandle((intptr_t)h,_O_RDONLY);
+#endif
+}
+
+#ifndef _WIN32
+pid_t
+regress_fork(void)
+{
+ pid_t pid = fork();
+#ifdef FORK_BREAKS_GCOV
+ vproc_transaction_begin(0);
+#endif
+ return pid;
+}
+#endif
+
+static void
+ignore_log_cb(int s, const char *msg)
+{
+}
+
+/**
+ * Put into the real time scheduling class for better timers latency.
+ * https://developer.apple.com/library/archive/technotes/tn2169/_index.html#//apple_ref/doc/uid/DTS40013172-CH1-TNTAG6000
+ */
+#if defined(__APPLE__)
+static void move_pthread_to_realtime_scheduling_class(pthread_t pthread)
+{
+ mach_timebase_info_data_t info;
+ mach_timebase_info(&info);
+
+ const uint64_t NANOS_PER_MSEC = 1000000ULL;
+ double clock2abs =
+ ((double)info.denom / (double)info.numer) * NANOS_PER_MSEC;
+
+ thread_time_constraint_policy_data_t policy;
+ policy.period = 0;
+ policy.computation = (uint32_t)(5 * clock2abs); // 5 ms of work
+ policy.constraint = (uint32_t)(10 * clock2abs);
+ policy.preemptible = FALSE;
+
+ int kr = thread_policy_set(pthread_mach_thread_np(pthread),
+ THREAD_TIME_CONSTRAINT_POLICY,
+ (thread_policy_t)&policy,
+ THREAD_TIME_CONSTRAINT_POLICY_COUNT);
+ if (kr != KERN_SUCCESS) {
+ mach_error("thread_policy_set:", kr);
+ exit(1);
+ }
+}
+
+void thread_setup(THREAD_T pthread)
+{
+ move_pthread_to_realtime_scheduling_class(pthread);
+}
+#else /** \__APPLE__ */
+void thread_setup(THREAD_T pthread) {}
+#endif /** \!__APPLE__ */
+
+
+void *
+basic_test_setup(const struct testcase_t *testcase)
+{
+ struct event_base *base = NULL;
+ evutil_socket_t spair[2] = { -1, -1 };
+ struct basic_test_data *data = NULL;
+
+ thread_setup(THREAD_SELF());
+
+#ifndef _WIN32
+ if (testcase->flags & TT_ENABLE_IOCP_FLAG)
+ return (void*)TT_SKIP;
+#endif
+
+ if (testcase->flags & TT_ENABLE_DEBUG_MODE &&
+ !libevent_tests_running_in_debug_mode) {
+ event_enable_debug_mode();
+ libevent_tests_running_in_debug_mode = 1;
+ }
+
+ if (testcase->flags & TT_NEED_THREADS) {
+ if (!(testcase->flags & TT_FORK))
+ return NULL;
+#if defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
+ if (evthread_use_pthreads())
+ exit(1);
+#elif defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
+ if (evthread_use_windows_threads())
+ exit(1);
+#else
+ return (void*)TT_SKIP;
+#endif
+ }
+
+ if (testcase->flags & TT_NEED_SOCKETPAIR) {
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, spair) == -1) {
+ fprintf(stderr, "%s: socketpair\n", __func__);
+ exit(1);
+ }
+
+ if (evutil_make_socket_nonblocking(spair[0]) == -1) {
+ fprintf(stderr, "fcntl(O_NONBLOCK)");
+ exit(1);
+ }
+
+ if (evutil_make_socket_nonblocking(spair[1]) == -1) {
+ fprintf(stderr, "fcntl(O_NONBLOCK)");
+ exit(1);
+ }
+ }
+ if (testcase->flags & TT_NEED_BASE) {
+ if (testcase->flags & TT_LEGACY)
+ base = event_init();
+ else
+ base = event_base_new();
+ if (!base)
+ exit(1);
+ }
+ if (testcase->flags & TT_ENABLE_IOCP_FLAG) {
+ if (event_base_start_iocp_(base, 0)<0) {
+ event_base_free(base);
+ return (void*)TT_SKIP;
+ }
+ }
+
+ if (testcase->flags & TT_NEED_DNS) {
+ evdns_set_log_fn(dnslogcb);
+ if (evdns_init())
+ return NULL; /* fast failure */ /*XXX asserts. */
+ }
+
+ if (testcase->flags & TT_NO_LOGS)
+ event_set_log_callback(ignore_log_cb);
+
+ data = calloc(1, sizeof(*data));
+ if (!data)
+ exit(1);
+ data->base = base;
+ data->pair[0] = spair[0];
+ data->pair[1] = spair[1];
+ data->setup_data = testcase->setup_data;
+ return data;
+}
+
+int
+basic_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ struct basic_test_data *data = ptr;
+
+ if (testcase->flags & TT_NO_LOGS)
+ event_set_log_callback(NULL);
+
+ if (testcase->flags & TT_NEED_SOCKETPAIR) {
+ if (data->pair[0] != -1)
+ evutil_closesocket(data->pair[0]);
+ if (data->pair[1] != -1)
+ evutil_closesocket(data->pair[1]);
+ }
+
+ if (testcase->flags & TT_NEED_DNS) {
+ evdns_shutdown(0);
+ }
+
+ if (testcase->flags & TT_NEED_BASE) {
+ if (data->base) {
+ event_base_assert_ok_(data->base);
+ event_base_free(data->base);
+ }
+ }
+
+ if (testcase->flags & TT_FORK)
+ libevent_global_shutdown();
+
+ free(data);
+
+ return 1;
+}
+
+const struct testcase_setup_t basic_setup = {
+ basic_test_setup, basic_test_cleanup
+};
+
+/* The "data" for a legacy test is just a pointer to the void fn(void)
+ function implementing the test case. We need to set up some globals,
+ though, since that's where legacy tests expect to find a socketpair
+ (sometimes) and a global event_base (sometimes).
+ */
+static void *
+legacy_test_setup(const struct testcase_t *testcase)
+{
+ struct basic_test_data *data = basic_test_setup(testcase);
+ if (data == (void*)TT_SKIP || data == NULL)
+ return data;
+ global_base = data->base;
+ pair[0] = data->pair[0];
+ pair[1] = data->pair[1];
+ data->legacy_test_fn = testcase->setup_data;
+ return data;
+}
+
+/* This function is the implementation of every legacy test case. It
+ sets test_ok to 0, invokes the test function, and tells tinytest that
+ the test failed if the test didn't set test_ok to 1.
+ */
+void
+run_legacy_test_fn(void *ptr)
+{
+ struct basic_test_data *data = ptr;
+ test_ok = called = 0;
+
+ in_legacy_test_wrapper = 1;
+ data->legacy_test_fn(); /* This part actually calls the test */
+ in_legacy_test_wrapper = 0;
+
+ if (!test_ok)
+ tt_abort_msg("Legacy unit test failed");
+
+end:
+ test_ok = 0;
+}
+
+/* This function doesn't have to clean up ptr (which is just a pointer
+ to the test function), but it may need to close the socketpair or
+ free the event_base.
+ */
+static int
+legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ int r = basic_test_cleanup(testcase, ptr);
+ pair[0] = pair[1] = -1;
+ global_base = NULL;
+ return r;
+}
+
+const struct testcase_setup_t legacy_setup = {
+ legacy_test_setup, legacy_test_cleanup
+};
+
+/* ============================================================ */
+
+#if (!defined(EVENT__HAVE_PTHREADS) && !defined(_WIN32)) || defined(EVENT__DISABLE_THREAD_SUPPORT)
+struct testcase_t thread_testcases[] = {
+ { "basic", NULL, TT_SKIP, NULL, NULL },
+ END_OF_TESTCASES
+};
+#endif
+
+struct testgroup_t testgroups[] = {
+ { "main/", main_testcases },
+ { "heap/", minheap_testcases },
+ { "et/", edgetriggered_testcases },
+ { "finalize/", finalize_testcases },
+ { "evbuffer/", evbuffer_testcases },
+ { "signal/", signal_testcases },
+ { "util/", util_testcases },
+ { "bufferevent/", bufferevent_testcases },
+ { "http/", http_testcases },
+ { "dns/", dns_testcases },
+ { "evtag/", evtag_testcases },
+ { "rpc/", rpc_testcases },
+ { "thread/", thread_testcases },
+ { "listener/", listener_testcases },
+#ifdef _WIN32
+ { "iocp/", iocp_testcases },
+ { "iocp/bufferevent/", bufferevent_iocp_testcases },
+ { "iocp/listener/", listener_iocp_testcases },
+ { "iocp/http/", http_iocp_testcases },
+#endif
+#ifdef EVENT__HAVE_OPENSSL
+ { "ssl/", ssl_testcases },
+#endif
+ END_OF_GROUPS
+};
+
+const char *alltests[] = { "+..", NULL };
+const char *livenettests[] = {
+ "+util/getaddrinfo_live",
+ "+dns/gethostby..",
+ "+dns/resolve_reverse",
+ NULL
+};
+const char *finetimetests[] = {
+ "+util/monotonic_res_precise",
+ "+util/monotonic_res_fallback",
+ "+thread/deferred_cb_skew",
+ "+http/connection_retry",
+ "+http/https_connection_retry",
+ NULL
+};
+struct testlist_alias_t testaliases[] = {
+ { "all", alltests },
+ { "live_net", livenettests },
+ { "fine_timing", finetimetests },
+ END_OF_ALIASES
+};
+
+int libevent_tests_running_in_debug_mode = 0;
+
+int
+main(int argc, const char **argv)
+{
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifndef _WIN32
+ if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+ return 1;
+#endif
+
+#ifdef _WIN32
+ tinytest_skip(testgroups, "http/connection_retry");
+ tinytest_skip(testgroups, "http/https_connection_retry");
+ tinytest_skip(testgroups, "http/read_on_write_error");
+#endif
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ if (!getenv("EVENT_NO_DEBUG_LOCKS"))
+ evthread_enable_lock_debugging();
+#endif
+
+ if (getenv("EVENT_DEBUG_MODE")) {
+ event_enable_debug_mode();
+ libevent_tests_running_in_debug_mode = 1;
+ }
+ if (getenv("EVENT_DEBUG_LOGGING_ALL")) {
+ event_enable_debug_logging(EVENT_DBG_ALL);
+ }
+
+ tinytest_set_aliases(testaliases);
+
+ evutil_weakrand_seed_(&test_weakrand_state, 0);
+
+ if (getenv("EVENT_NO_FILE_BUFFERING")) {
+ setbuf(stdout, NULL);
+ setbuf(stderr, NULL);
+ }
+
+ if (tinytest_main(argc,argv,testgroups))
+ return 1;
+
+ libevent_global_shutdown();
+
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_minheap.c b/ipc/chromium/src/third_party/libevent/test/regress_minheap.c
new file mode 100644
index 0000000000..05db32e26f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_minheap.c
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../minheap-internal.h"
+
+#include <stdlib.h>
+#include "event2/event_struct.h"
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+#include "regress.h"
+
+static void
+set_random_timeout(struct event *ev)
+{
+ ev->ev_timeout.tv_sec = test_weakrand();
+ ev->ev_timeout.tv_usec = test_weakrand() & 0xfffff;
+ ev->ev_timeout_pos.min_heap_idx = -1;
+}
+
+static void
+check_heap(struct min_heap *heap)
+{
+ unsigned i;
+ for (i = 1; i < heap->n; ++i) {
+ unsigned parent_idx = (i-1)/2;
+ tt_want(evutil_timercmp(&heap->p[i]->ev_timeout,
+ &heap->p[parent_idx]->ev_timeout, >=));
+ }
+}
+
+static void
+test_heap_randomized(void *ptr)
+{
+ struct min_heap heap;
+ struct event *inserted[1024];
+ struct event *e, *last_e;
+ int i;
+
+ min_heap_ctor_(&heap);
+
+ for (i = 0; i < 1024; ++i) {
+ inserted[i] = malloc(sizeof(struct event));
+ set_random_timeout(inserted[i]);
+ min_heap_push_(&heap, inserted[i]);
+ }
+ check_heap(&heap);
+
+ tt_assert(min_heap_size_(&heap) == 1024);
+
+ for (i = 0; i < 512; ++i) {
+ min_heap_erase_(&heap, inserted[i]);
+ if (0 == (i % 32))
+ check_heap(&heap);
+ }
+ tt_assert(min_heap_size_(&heap) == 512);
+
+ last_e = min_heap_pop_(&heap);
+ while (1) {
+ e = min_heap_pop_(&heap);
+ if (!e)
+ break;
+ tt_want(evutil_timercmp(&last_e->ev_timeout,
+ &e->ev_timeout, <=));
+ }
+ tt_assert(min_heap_size_(&heap) == 0);
+end:
+ for (i = 0; i < 1024; ++i)
+ free(inserted[i]);
+
+ min_heap_dtor_(&heap);
+}
+
+struct testcase_t minheap_testcases[] = {
+ { "randomized", test_heap_randomized, 0, NULL, NULL },
+ END_OF_TESTCASES
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_rpc.c b/ipc/chromium/src/third_party/libevent/test/regress_rpc.c
new file mode 100644
index 0000000000..87a7efa12f
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_rpc.c
@@ -0,0 +1,952 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <assert.h>
+
+#include "event2/buffer.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/http.h"
+#include "event2/http_compat.h"
+#include "event2/http_struct.h"
+#include "event2/rpc.h"
+#include "event2/rpc_struct.h"
+#include "event2/tag.h"
+#include "log-internal.h"
+
+#include "regress.gen.h"
+
+#include "regress.h"
+#include "regress_testutils.h"
+
+#ifndef NO_PYTHON_EXISTS
+
+static struct evhttp *
+http_setup(ev_uint16_t *pport)
+{
+ struct evhttp *myhttp;
+ ev_uint16_t port;
+ struct evhttp_bound_socket *sock;
+
+ myhttp = evhttp_new(NULL);
+ if (!myhttp)
+ event_errx(1, "Could not start web server");
+
+ /* Try a few different ports */
+ sock = evhttp_bind_socket_with_handle(myhttp, "127.0.0.1", 0);
+ if (!sock)
+ event_errx(1, "Couldn't open web port");
+
+ port = regress_get_socket_port(evhttp_bound_socket_get_fd(sock));
+
+ *pport = port;
+ return (myhttp);
+}
+
+EVRPC_HEADER(Message, msg, kill)
+EVRPC_HEADER(NeverReply, msg, kill)
+
+EVRPC_GENERATE(Message, msg, kill)
+EVRPC_GENERATE(NeverReply, msg, kill)
+
+static int need_input_hook = 0;
+static int need_output_hook = 0;
+
+static void
+MessageCb(EVRPC_STRUCT(Message)* rpc, void *arg)
+{
+ struct kill* kill_reply = rpc->reply;
+
+ if (need_input_hook) {
+ struct evhttp_request* req = EVRPC_REQUEST_HTTP(rpc);
+ const char *header = evhttp_find_header(
+ req->input_headers, "X-Hook");
+ assert(header);
+ assert(strcmp(header, "input") == 0);
+ }
+
+ /* we just want to fill in some non-sense */
+ EVTAG_ASSIGN(kill_reply, weapon, "dagger");
+ EVTAG_ASSIGN(kill_reply, action, "wave around like an idiot");
+
+ /* no reply to the RPC */
+ EVRPC_REQUEST_DONE(rpc);
+}
+
+static EVRPC_STRUCT(NeverReply) *saved_rpc;
+
+static void
+NeverReplyCb(EVRPC_STRUCT(NeverReply)* rpc, void *arg)
+{
+ test_ok += 1;
+ saved_rpc = rpc;
+}
+
+static void
+rpc_setup(struct evhttp **phttp, ev_uint16_t *pport, struct evrpc_base **pbase)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+
+ http = http_setup(&port);
+ base = evrpc_init(http);
+
+ EVRPC_REGISTER(base, Message, msg, kill, MessageCb, NULL);
+ EVRPC_REGISTER(base, NeverReply, msg, kill, NeverReplyCb, NULL);
+
+ *phttp = http;
+ *pport = port;
+ *pbase = base;
+
+ need_input_hook = 0;
+ need_output_hook = 0;
+}
+
+static void
+rpc_teardown(struct evrpc_base *base)
+{
+ assert(EVRPC_UNREGISTER(base, Message) == 0);
+ assert(EVRPC_UNREGISTER(base, NeverReply) == 0);
+
+ evrpc_free(base);
+}
+
+static void
+rpc_postrequest_failure(struct evhttp_request *req, void *arg)
+{
+ if (req->response_code != HTTP_SERVUNAVAIL) {
+
+ fprintf(stderr, "FAILED (response code)\n");
+ exit(1);
+ }
+
+ test_ok = 1;
+ event_loopexit(NULL);
+}
+
+/*
+ * Test a malformed payload submitted as an RPC
+ */
+
+static void
+rpc_basic_test(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ evcon = evhttp_connection_new("127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule an HTTP POST request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(rpc_postrequest_failure, NULL);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(req->output_headers, "Host", "somehost");
+ evbuffer_add_printf(req->output_buffer, "Some Nonsense");
+
+ if (evhttp_make_request(evcon, req,
+ EVHTTP_REQ_POST,
+ "/.rpc.Message") == -1) {
+ tt_abort();
+ }
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ evhttp_connection_free(evcon);
+
+ rpc_teardown(base);
+
+ tt_assert(test_ok == 1);
+
+end:
+ evhttp_free(http);
+}
+
+static void
+rpc_postrequest_done(struct evhttp_request *req, void *arg)
+{
+ struct kill* kill_reply = NULL;
+
+ if (req->response_code != HTTP_OK) {
+ fprintf(stderr, "FAILED (response code)\n");
+ exit(1);
+ }
+
+ kill_reply = kill_new();
+
+ if ((kill_unmarshal(kill_reply, req->input_buffer)) == -1) {
+ fprintf(stderr, "FAILED (unmarshal)\n");
+ exit(1);
+ }
+
+ kill_free(kill_reply);
+
+ test_ok = 1;
+ event_loopexit(NULL);
+}
+
+static void
+rpc_basic_message(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+ struct msg *msg;
+
+ rpc_setup(&http, &port, &base);
+
+ evcon = evhttp_connection_new("127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule an HTTP POST request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(rpc_postrequest_done, NULL);
+ if (req == NULL) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ /* Add the information that we care about */
+ evhttp_add_header(req->output_headers, "Host", "somehost");
+
+ /* set up the basic message */
+ msg = msg_new();
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "tester");
+ msg_marshal(req->output_buffer, msg);
+ msg_free(msg);
+
+ if (evhttp_make_request(evcon, req,
+ EVHTTP_REQ_POST,
+ "/.rpc.Message") == -1) {
+ fprintf(stdout, "FAILED\n");
+ exit(1);
+ }
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ evhttp_connection_free(evcon);
+
+ rpc_teardown(base);
+
+end:
+ evhttp_free(http);
+}
+
+static struct evrpc_pool *
+rpc_pool_with_connection(ev_uint16_t port)
+{
+ struct evhttp_connection *evcon;
+ struct evrpc_pool *pool;
+
+ pool = evrpc_pool_new(NULL);
+ assert(pool != NULL);
+
+ evcon = evhttp_connection_new("127.0.0.1", port);
+ assert(evcon != NULL);
+
+ evrpc_pool_add_connection(pool, evcon);
+
+ return (pool);
+}
+
+static void
+GotKillCb(struct evrpc_status *status,
+ struct msg *msg, struct kill *kill, void *arg)
+{
+ char *weapon;
+ char *action;
+
+ if (need_output_hook) {
+ struct evhttp_request *req = status->http_req;
+ const char *header = evhttp_find_header(
+ req->input_headers, "X-Pool-Hook");
+ assert(header);
+ assert(strcmp(header, "ran") == 0);
+ }
+
+ if (status->error != EVRPC_STATUS_ERR_NONE)
+ goto done;
+
+ if (EVTAG_GET(kill, weapon, &weapon) == -1) {
+ fprintf(stderr, "get weapon\n");
+ goto done;
+ }
+ if (EVTAG_GET(kill, action, &action) == -1) {
+ fprintf(stderr, "get action\n");
+ goto done;
+ }
+
+ if (strcmp(weapon, "dagger"))
+ goto done;
+
+ if (strcmp(action, "wave around like an idiot"))
+ goto done;
+
+ test_ok += 1;
+
+done:
+ event_loopexit(NULL);
+}
+
+static void
+GotKillCbTwo(struct evrpc_status *status,
+ struct msg *msg, struct kill *kill, void *arg)
+{
+ char *weapon;
+ char *action;
+
+ if (status->error != EVRPC_STATUS_ERR_NONE)
+ goto done;
+
+ if (EVTAG_GET(kill, weapon, &weapon) == -1) {
+ fprintf(stderr, "get weapon\n");
+ goto done;
+ }
+ if (EVTAG_GET(kill, action, &action) == -1) {
+ fprintf(stderr, "get action\n");
+ goto done;
+ }
+
+ if (strcmp(weapon, "dagger"))
+ goto done;
+
+ if (strcmp(action, "wave around like an idiot"))
+ goto done;
+
+ test_ok += 1;
+
+done:
+ if (test_ok == 2)
+ event_loopexit(NULL);
+}
+
+static int
+rpc_hook_add_header(void *ctx, struct evhttp_request *req,
+ struct evbuffer *evbuf, void *arg)
+{
+ const char *hook_type = arg;
+ if (strcmp("input", hook_type) == 0)
+ evhttp_add_header(req->input_headers, "X-Hook", hook_type);
+ else
+ evhttp_add_header(req->output_headers, "X-Hook", hook_type);
+
+ assert(evrpc_hook_get_connection(ctx) != NULL);
+
+ return (EVRPC_CONTINUE);
+}
+
+static int
+rpc_hook_add_meta(void *ctx, struct evhttp_request *req,
+ struct evbuffer *evbuf, void *arg)
+{
+ evrpc_hook_add_meta(ctx, "meta", "test", 5);
+
+ assert(evrpc_hook_get_connection(ctx) != NULL);
+
+ return (EVRPC_CONTINUE);
+}
+
+static int
+rpc_hook_remove_header(void *ctx, struct evhttp_request *req,
+ struct evbuffer *evbuf, void *arg)
+{
+ const char *header = evhttp_find_header(req->input_headers, "X-Hook");
+ void *data = NULL;
+ size_t data_len = 0;
+
+ assert(header != NULL);
+ assert(strcmp(header, arg) == 0);
+
+ evhttp_remove_header(req->input_headers, "X-Hook");
+ evhttp_add_header(req->input_headers, "X-Pool-Hook", "ran");
+
+ assert(evrpc_hook_find_meta(ctx, "meta", &data, &data_len) == 0);
+ assert(data != NULL);
+ assert(data_len == 5);
+
+ assert(evrpc_hook_get_connection(ctx) != NULL);
+
+ return (EVRPC_CONTINUE);
+}
+
+static void
+rpc_basic_client(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evrpc_pool *pool = NULL;
+ struct msg *msg = NULL;
+ struct kill *kill = NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ need_input_hook = 1;
+ need_output_hook = 1;
+
+ assert(evrpc_add_hook(base, EVRPC_INPUT, rpc_hook_add_header, (void*)"input")
+ != NULL);
+ assert(evrpc_add_hook(base, EVRPC_OUTPUT, rpc_hook_add_header, (void*)"output")
+ != NULL);
+
+ pool = rpc_pool_with_connection(port);
+ tt_assert(pool);
+
+ assert(evrpc_add_hook(pool, EVRPC_OUTPUT, rpc_hook_add_meta, NULL));
+ assert(evrpc_add_hook(pool, EVRPC_INPUT, rpc_hook_remove_header, (void*)"output"));
+
+ /* set up the basic message */
+ msg = msg_new();
+ tt_assert(msg);
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "tester");
+
+ kill = kill_new();
+
+ EVRPC_MAKE_REQUEST(Message, pool, msg, kill, GotKillCb, NULL);
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ tt_assert(test_ok == 1);
+
+ /* we do it twice to make sure that reuse works correctly */
+ kill_clear(kill);
+
+ EVRPC_MAKE_REQUEST(Message, pool, msg, kill, GotKillCb, NULL);
+
+ event_dispatch();
+
+ tt_assert(test_ok == 2);
+
+ /* we do it trice to make sure other stuff works, too */
+ kill_clear(kill);
+
+ {
+ struct evrpc_request_wrapper *ctx =
+ EVRPC_MAKE_CTX(Message, msg, kill,
+ pool, msg, kill, GotKillCb, NULL);
+ evrpc_make_request(ctx);
+ }
+
+ event_dispatch();
+
+ rpc_teardown(base);
+
+ tt_assert(test_ok == 3);
+
+end:
+ if (msg)
+ msg_free(msg);
+ if (kill)
+ kill_free(kill);
+
+ if (pool)
+ evrpc_pool_free(pool);
+ if (http)
+ evhttp_free(http);
+
+ need_input_hook = 0;
+ need_output_hook = 0;
+}
+
+/*
+ * We are testing that the second requests gets send over the same
+ * connection after the first RPCs completes.
+ */
+static void
+rpc_basic_queued_client(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evrpc_pool *pool = NULL;
+ struct msg *msg=NULL;
+ struct kill *kill_one=NULL, *kill_two=NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ pool = rpc_pool_with_connection(port);
+ tt_assert(pool);
+
+ /* set up the basic message */
+ msg = msg_new();
+ tt_assert(msg);
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "tester");
+
+ kill_one = kill_new();
+ kill_two = kill_new();
+
+ EVRPC_MAKE_REQUEST(Message, pool, msg, kill_one, GotKillCbTwo, NULL);
+ EVRPC_MAKE_REQUEST(Message, pool, msg, kill_two, GotKillCb, NULL);
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ rpc_teardown(base);
+
+ tt_assert(test_ok == 2);
+
+end:
+ if (msg)
+ msg_free(msg);
+ if (kill_one)
+ kill_free(kill_one);
+ if (kill_two)
+ kill_free(kill_two);
+
+ if (pool)
+ evrpc_pool_free(pool);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+GotErrorCb(struct evrpc_status *status,
+ struct msg *msg, struct kill *kill, void *arg)
+{
+ if (status->error != EVRPC_STATUS_ERR_TIMEOUT)
+ goto done;
+
+ /* should never be complete but just to check */
+ if (kill_complete(kill) == 0)
+ goto done;
+
+ test_ok += 1;
+
+done:
+ event_loopexit(NULL);
+}
+
+/* we just pause the rpc and continue it in the next callback */
+
+struct rpc_hook_ctx_ {
+ void *vbase;
+ void *ctx;
+};
+
+static int hook_pause_cb_called=0;
+
+static void
+rpc_hook_pause_cb(evutil_socket_t fd, short what, void *arg)
+{
+ struct rpc_hook_ctx_ *ctx = arg;
+ ++hook_pause_cb_called;
+ evrpc_resume_request(ctx->vbase, ctx->ctx, EVRPC_CONTINUE);
+ free(arg);
+}
+
+static int
+rpc_hook_pause(void *ctx, struct evhttp_request *req, struct evbuffer *evbuf,
+ void *arg)
+{
+ struct rpc_hook_ctx_ *tmp = malloc(sizeof(*tmp));
+ struct timeval tv;
+
+ assert(tmp != NULL);
+ tmp->vbase = arg;
+ tmp->ctx = ctx;
+
+ memset(&tv, 0, sizeof(tv));
+ event_once(-1, EV_TIMEOUT, rpc_hook_pause_cb, tmp, &tv);
+ return EVRPC_PAUSE;
+}
+
+static void
+rpc_basic_client_with_pause(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evrpc_pool *pool = NULL;
+ struct msg *msg = NULL;
+ struct kill *kill= NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ assert(evrpc_add_hook(base, EVRPC_INPUT, rpc_hook_pause, base));
+ assert(evrpc_add_hook(base, EVRPC_OUTPUT, rpc_hook_pause, base));
+
+ pool = rpc_pool_with_connection(port);
+ tt_assert(pool);
+ assert(evrpc_add_hook(pool, EVRPC_INPUT, rpc_hook_pause, pool));
+ assert(evrpc_add_hook(pool, EVRPC_OUTPUT, rpc_hook_pause, pool));
+
+ /* set up the basic message */
+ msg = msg_new();
+ tt_assert(msg);
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "tester");
+
+ kill = kill_new();
+
+ EVRPC_MAKE_REQUEST(Message, pool, msg, kill, GotKillCb, NULL);
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ tt_int_op(test_ok, ==, 1);
+ tt_int_op(hook_pause_cb_called, ==, 4);
+
+end:
+ if (base)
+ rpc_teardown(base);
+
+ if (msg)
+ msg_free(msg);
+ if (kill)
+ kill_free(kill);
+
+ if (pool)
+ evrpc_pool_free(pool);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+rpc_client_timeout(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evrpc_pool *pool = NULL;
+ struct msg *msg = NULL;
+ struct kill *kill = NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ pool = rpc_pool_with_connection(port);
+ tt_assert(pool);
+
+ /* set the timeout to 1 second. */
+ evrpc_pool_set_timeout(pool, 1);
+
+ /* set up the basic message */
+ msg = msg_new();
+ tt_assert(msg);
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "tester");
+
+ kill = kill_new();
+
+ EVRPC_MAKE_REQUEST(NeverReply, pool, msg, kill, GotErrorCb, NULL);
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ /* free the saved RPC structure up */
+ EVRPC_REQUEST_DONE(saved_rpc);
+
+ rpc_teardown(base);
+
+ tt_assert(test_ok == 2);
+
+end:
+ if (msg)
+ msg_free(msg);
+ if (kill)
+ kill_free(kill);
+
+ if (pool)
+ evrpc_pool_free(pool);
+ if (http)
+ evhttp_free(http);
+}
+
+static void
+rpc_test(void)
+{
+ struct msg *msg = NULL, *msg2 = NULL;
+ struct kill *attack = NULL;
+ struct run *run = NULL;
+ struct evbuffer *tmp = evbuffer_new();
+ struct timeval tv_start, tv_end;
+ ev_uint32_t tag;
+ int i;
+
+ msg = msg_new();
+
+ tt_assert(msg);
+
+ EVTAG_ASSIGN(msg, from_name, "niels");
+ EVTAG_ASSIGN(msg, to_name, "phoenix");
+
+ if (EVTAG_GET(msg, attack, &attack) == -1) {
+ tt_abort_msg("Failed to set kill message.");
+ }
+
+ EVTAG_ASSIGN(attack, weapon, "feather");
+ EVTAG_ASSIGN(attack, action, "tickle");
+ for (i = 0; i < 3; ++i) {
+ if (EVTAG_ARRAY_ADD_VALUE(attack, how_often, i) == NULL) {
+ tt_abort_msg("Failed to add how_often.");
+ }
+ }
+
+ evutil_gettimeofday(&tv_start, NULL);
+ for (i = 0; i < 1000; ++i) {
+ run = EVTAG_ARRAY_ADD(msg, run);
+ if (run == NULL) {
+ tt_abort_msg("Failed to add run message.");
+ }
+ EVTAG_ASSIGN(run, how, "very fast but with some data in it");
+ EVTAG_ASSIGN(run, fixed_bytes,
+ (ev_uint8_t*)"012345678901234567890123");
+
+ if (EVTAG_ARRAY_ADD_VALUE(
+ run, notes, "this is my note") == NULL) {
+ tt_abort_msg("Failed to add note.");
+ }
+ if (EVTAG_ARRAY_ADD_VALUE(run, notes, "pps") == NULL) {
+ tt_abort_msg("Failed to add note");
+ }
+
+ EVTAG_ASSIGN(run, large_number, 0xdead0a0bcafebeefLL);
+ EVTAG_ARRAY_ADD_VALUE(run, other_numbers, 0xdead0a0b);
+ EVTAG_ARRAY_ADD_VALUE(run, other_numbers, 0xbeefcafe);
+ }
+
+ if (msg_complete(msg) == -1)
+ tt_abort_msg("Failed to make complete message.");
+
+ evtag_marshal_msg(tmp, 0xdeaf, msg);
+
+ if (evtag_peek(tmp, &tag) == -1)
+ tt_abort_msg("Failed to peak tag.");
+
+ if (tag != 0xdeaf)
+ TT_DIE(("Got incorrect tag: %0x.", (unsigned)tag));
+
+ msg2 = msg_new();
+ if (evtag_unmarshal_msg(tmp, 0xdeaf, msg2) == -1)
+ tt_abort_msg("Failed to unmarshal message.");
+
+ evutil_gettimeofday(&tv_end, NULL);
+ evutil_timersub(&tv_end, &tv_start, &tv_end);
+ TT_BLATHER(("(%.1f us/add) ",
+ (float)tv_end.tv_sec/(float)i * 1000000.0 +
+ tv_end.tv_usec / (float)i));
+
+ if (!EVTAG_HAS(msg2, from_name) ||
+ !EVTAG_HAS(msg2, to_name) ||
+ !EVTAG_HAS(msg2, attack)) {
+ tt_abort_msg("Missing data structures.");
+ }
+
+ if (EVTAG_GET(msg2, attack, &attack) == -1) {
+ tt_abort_msg("Could not get attack.");
+ }
+
+ if (EVTAG_ARRAY_LEN(msg2, run) != i) {
+ tt_abort_msg("Wrong number of run messages.");
+ }
+
+ /* get the very first run message */
+ if (EVTAG_ARRAY_GET(msg2, run, 0, &run) == -1) {
+ tt_abort_msg("Failed to get run msg.");
+ } else {
+ /* verify the notes */
+ char *note_one, *note_two;
+ ev_uint64_t large_number;
+ ev_uint32_t short_number;
+
+ if (EVTAG_ARRAY_LEN(run, notes) != 2) {
+ tt_abort_msg("Wrong number of note strings.");
+ }
+
+ if (EVTAG_ARRAY_GET(run, notes, 0, &note_one) == -1 ||
+ EVTAG_ARRAY_GET(run, notes, 1, &note_two) == -1) {
+ tt_abort_msg("Could not get note strings.");
+ }
+
+ if (strcmp(note_one, "this is my note") ||
+ strcmp(note_two, "pps")) {
+ tt_abort_msg("Incorrect note strings encoded.");
+ }
+
+ if (EVTAG_GET(run, large_number, &large_number) == -1 ||
+ large_number != 0xdead0a0bcafebeefLL) {
+ tt_abort_msg("Incorrrect large_number.");
+ }
+
+ if (EVTAG_ARRAY_LEN(run, other_numbers) != 2) {
+ tt_abort_msg("Wrong number of other_numbers.");
+ }
+
+ if (EVTAG_ARRAY_GET(
+ run, other_numbers, 0, &short_number) == -1) {
+ tt_abort_msg("Could not get short number.");
+ }
+ tt_uint_op(short_number, ==, 0xdead0a0b);
+
+ }
+ tt_int_op(EVTAG_ARRAY_LEN(attack, how_often), ==, 3);
+
+ for (i = 0; i < 3; ++i) {
+ ev_uint32_t res;
+ if (EVTAG_ARRAY_GET(attack, how_often, i, &res) == -1) {
+ TT_DIE(("Cannot get %dth how_often msg.", i));
+ }
+ if ((int)res != i) {
+ TT_DIE(("Wrong message encoded %d != %d", i, res));
+ }
+ }
+
+ test_ok = 1;
+end:
+ if (msg)
+ msg_free(msg);
+ if (msg2)
+ msg_free(msg2);
+ if (tmp)
+ evbuffer_free(tmp);
+}
+
+static void
+rpc_invalid_type(void)
+{
+ ev_uint16_t port;
+ struct evhttp *http = NULL;
+ struct evrpc_base *base = NULL;
+ struct evhttp_connection *evcon = NULL;
+ struct evhttp_request *req = NULL;
+
+ rpc_setup(&http, &port, &base);
+
+ evcon = evhttp_connection_new("127.0.0.1", port);
+ tt_assert(evcon);
+
+ /*
+ * At this point, we want to schedule an HTTP POST request
+ * server using our make request method.
+ */
+
+ req = evhttp_request_new(rpc_postrequest_failure, NULL);
+ tt_assert(req);
+
+ /* Add the information that we care about */
+ evhttp_add_header(req->output_headers, "Host", "somehost");
+ evbuffer_add_printf(req->output_buffer, "Some Nonsense");
+
+ if (evhttp_make_request(evcon, req,
+ EVHTTP_REQ_GET,
+ "/.rpc.Message") == -1) {
+ tt_abort();
+ }
+
+ test_ok = 0;
+
+ event_dispatch();
+
+ evhttp_connection_free(evcon);
+
+ rpc_teardown(base);
+
+ tt_assert(test_ok == 1);
+
+end:
+ evhttp_free(http);
+}
+
+
+#define RPC_LEGACY(name) \
+ { #name, run_legacy_test_fn, TT_FORK|TT_NEED_BASE|TT_LEGACY, \
+ &legacy_setup, \
+ rpc_##name }
+#else
+/* NO_PYTHON_EXISTS */
+
+#define RPC_LEGACY(name) \
+ { #name, NULL, TT_SKIP, NULL, NULL }
+
+#endif
+
+struct testcase_t rpc_testcases[] = {
+ RPC_LEGACY(basic_test),
+ RPC_LEGACY(basic_message),
+ RPC_LEGACY(basic_client),
+ RPC_LEGACY(basic_queued_client),
+ RPC_LEGACY(basic_client_with_pause),
+ RPC_LEGACY(invalid_type),
+ RPC_LEGACY(client_timeout),
+ RPC_LEGACY(test),
+
+ END_OF_TESTCASES,
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_ssl.c b/ipc/chromium/src/third_party/libevent/test/regress_ssl.c
new file mode 100644
index 0000000000..37dc334dca
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_ssl.c
@@ -0,0 +1,1078 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// Get rid of OSX 10.7 and greater deprecation warnings.
+#if defined(__APPLE__) && defined(__clang__)
+#pragma clang diagnostic ignored "-Wdeprecated-declarations"
+#endif
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "util-internal.h"
+
+#ifndef _WIN32
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+#endif
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/bufferevent_ssl.h"
+#include "event2/bufferevent_struct.h"
+#include "event2/buffer.h"
+#include "event2/listener.h"
+
+#include "regress.h"
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#include <openssl/err.h>
+#include <openssl/pem.h>
+#include "openssl-compat.h"
+
+#include <string.h>
+#ifdef _WIN32
+#include <io.h>
+#define read _read
+#define write _write
+#else
+#include <unistd.h>
+#endif
+
+/* A pre-generated key, to save the cost of doing an RSA key generation step
+ * during the unit tests. It is published in this file, so you would have to
+ * be very foolish to consider using it in your own code. */
+static const char KEY[] =
+ "-----BEGIN RSA PRIVATE KEY-----\n"
+ "MIIEogIBAAKCAQEAtK07Ili0dkJb79m/sFmHoVJTWyLoveXex2yX/BtUzzcvZEOu\n"
+ "QLon/++5YOA48kzZm5K9mIwZkZhui1ZgJ5Bjq0LGAWTZGIn+NXjLFshPYvTKpOCW\n"
+ "uzL0Ir0LXMsBLYJQ5A4FomLNxs4I3H/dhDSGy/rSiJB1B4w2xNiwPK08/VL3zZqk\n"
+ "V+GsSvGIIkzhTMbqPJy9K8pqyjwOU2pgORS794yXciTGxWYjTDzJPgQ35YMDATaG\n"
+ "jr4HHo1zxU/Lj0pndSUK5rKLYxYQ3Uc8B3AVYDl9CP/GbOoQ4LBzS68JjcAUyp6i\n"
+ "6NfXlc2D9S9XgqVqwI+JqgJs0eW/+zPY2UEDWwIDAQABAoIBAD2HzV66FOM9YDAD\n"
+ "2RtGskEHV2nvLpIVadRCsFPkPvK+2X3s6rgSbbLkwh4y3lHuSCGKTNVZyQ9jeSos\n"
+ "xVxT+Q2HFQW+gYyw2gj91TQyDY8mzKhv8AVaqff2p5r3a7RC8CdqexK9UVUGL9Bg\n"
+ "H2F5vfpTtkVZ5PEoGDLblNFlMiMW/t1SobUeBVx+Msco/xqk9lFv1A9nnepGy0Gi\n"
+ "D+i6YNGTBsX22YhoCZl/ICxCL8lgqPei4FvBr9dBVh/jQgjuUBm2jz55p2r7+7Aw\n"
+ "khmXHReejoVokQ2+htgSgZNKlKuDy710ZpBqnDi8ynQi82Y2qCpyg/p/xcER54B6\n"
+ "hSftaiECgYEA2RkSoxU+nWk+BClQEUZRi88QK5W/M8oo1DvUs36hvPFkw3Jk/gz0\n"
+ "fgd5bnA+MXj0Fc0QHvbddPjIkyoI/evq9GPV+JYIuH5zabrlI3Jvya8q9QpAcEDO\n"
+ "KkL/O09qXVEW52S6l05nh4PLejyI7aTyTIN5nbVLac/+M8MY/qOjZksCgYEA1Q1o\n"
+ "L8kjSavU2xhQmSgZb9W62Do60sa3e73ljrDPoiyvbExldpSdziFYxHBD/Rep0ePf\n"
+ "eVSGS3VSwevt9/jSGo2Oa83TYYns9agBm03oR/Go/DukESdI792NsEM+PRFypVNy\n"
+ "AohWRLj0UU6DV+zLKp0VBavtx0ATeLFX0eN17TECgYBI2O/3Bz7uhQ0JSm+SjFz6\n"
+ "o+2SInp5P2G57aWu4VQWWY3tQ2p+EQzNaWam10UXRrXoxtmc+ktPX9e2AgnoYoyB\n"
+ "myqGcpnUhqHlnZAb999o9r1cYidDQ4uqhLauSTSwwXAFDzjJYsa8o03Y440y6QFh\n"
+ "CVD6yYXXqLJs3g96CqDexwKBgAHxq1+0QCQt8zVElYewO/svQhMzBNJjic0RQIT6\n"
+ "zAo4yij80XgxhvcYiszQEW6/xobpw2JCCS+rFGQ8mOFIXfJsFD6blDAxp/3d2JXo\n"
+ "MhRl+hrDGI4ng5zcsqxHEMxR2m/zwPiQ8eiSn3gWdVBaEsiCwmxY00ScKxFQ3PJH\n"
+ "Vw4hAoGAdZLd8KfjjG6lg7hfpVqavstqVi9LOgkHeCfdjn7JP+76kYrgLk/XdkrP\n"
+ "N/BHhtFVFjOi/mTQfQ5YfZImkm/1ePBy7437DT8BDkOxspa50kK4HPggHnU64h1w\n"
+ "lhdEOj7mAgHwGwwVZWOgs9Lq6vfztnSuhqjha1daESY6kDscPIQ=\n"
+ "-----END RSA PRIVATE KEY-----\n";
+
+EVP_PKEY *
+ssl_getkey(void)
+{
+ EVP_PKEY *key;
+ BIO *bio;
+
+ /* new read-only BIO backed by KEY. */
+ bio = BIO_new_mem_buf((char*)KEY, -1);
+ tt_assert(bio);
+
+ key = PEM_read_bio_PrivateKey(bio,NULL,NULL,NULL);
+ BIO_free(bio);
+ tt_assert(key);
+
+ return key;
+end:
+ return NULL;
+}
+
+X509 *
+ssl_getcert(EVP_PKEY *key)
+{
+ /* Dummy code to make a quick-and-dirty valid certificate with
+ OpenSSL. Don't copy this code into your own program! It does a
+ number of things in a stupid and insecure way. */
+ X509 *x509 = NULL;
+ X509_NAME *name = NULL;
+ int nid;
+ time_t now = time(NULL);
+
+ tt_assert(key);
+
+ x509 = X509_new();
+ tt_assert(x509);
+ tt_assert(0 != X509_set_version(x509, 2));
+ tt_assert(0 != ASN1_INTEGER_set(X509_get_serialNumber(x509),
+ (long)now));
+
+ name = X509_NAME_new();
+ tt_assert(name);
+ nid = OBJ_txt2nid("commonName");
+ tt_assert(NID_undef != nid);
+ tt_assert(0 != X509_NAME_add_entry_by_NID(
+ name, nid, MBSTRING_ASC, (unsigned char*)"example.com",
+ -1, -1, 0));
+
+ X509_set_subject_name(x509, name);
+ X509_set_issuer_name(x509, name);
+ X509_NAME_free(name);
+
+ X509_time_adj(X509_getm_notBefore(x509), 0, &now);
+ now += 3600;
+ X509_time_adj(X509_getm_notAfter(x509), 0, &now);
+ X509_set_pubkey(x509, key);
+ tt_assert(0 != X509_sign(x509, key, EVP_sha1()));
+
+ return x509;
+end:
+ X509_free(x509);
+ X509_NAME_free(name);
+ return NULL;
+}
+
+static int disable_tls_11_and_12 = 0;
+static SSL_CTX *the_ssl_ctx = NULL;
+
+SSL_CTX *
+get_ssl_ctx(void)
+{
+ if (the_ssl_ctx)
+ return the_ssl_ctx;
+ the_ssl_ctx = SSL_CTX_new(SSLv23_method());
+ if (!the_ssl_ctx)
+ return NULL;
+ if (disable_tls_11_and_12) {
+#ifdef SSL_OP_NO_TLSv1_2
+ SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_2);
+#endif
+#ifdef SSL_OP_NO_TLSv1_1
+ SSL_CTX_set_options(the_ssl_ctx, SSL_OP_NO_TLSv1_1);
+#endif
+ }
+ return the_ssl_ctx;
+}
+
+static int test_is_done;
+static int n_connected;
+static int got_close;
+static int got_error;
+static int got_timeout;
+static int renegotiate_at = -1;
+static int stop_when_connected;
+static int pending_connect_events;
+static struct event_base *exit_base;
+static X509 *the_cert;
+EVP_PKEY *the_key;
+
+void
+init_ssl(void)
+{
+#if (OPENSSL_VERSION_NUMBER < 0x10100000L) || \
+ (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x20700000L)
+ SSL_library_init();
+ ERR_load_crypto_strings();
+ SSL_load_error_strings();
+ OpenSSL_add_all_algorithms();
+ if (SSLeay() != OPENSSL_VERSION_NUMBER) {
+ TT_DECLARE("WARN",
+ ("Version mismatch for openssl: compiled with %lx but running with %lx",
+ (unsigned long)OPENSSL_VERSION_NUMBER, (unsigned long)SSLeay()));
+ }
+#endif
+}
+
+static void *
+ssl_test_setup(const struct testcase_t *testcase)
+{
+ init_ssl();
+
+ the_key = ssl_getkey();
+ EVUTIL_ASSERT(the_key);
+
+ the_cert = ssl_getcert(the_key);
+ EVUTIL_ASSERT(the_cert);
+
+ disable_tls_11_and_12 = 0;
+
+ return basic_test_setup(testcase);
+}
+static int
+ssl_test_cleanup(const struct testcase_t *testcase, void *ptr)
+{
+ int ret = basic_test_cleanup(testcase, ptr);
+ if (!ret) {
+ return ret;
+ }
+
+ test_is_done = 0;
+ n_connected = 0;
+ got_close = 0;
+ got_error = 0;
+ got_timeout = 0;
+ renegotiate_at = -1;
+ stop_when_connected = 0;
+ pending_connect_events = 0;
+ exit_base = NULL;
+
+ X509_free(the_cert);
+ EVP_PKEY_free(the_key);
+
+ SSL_CTX_free(the_ssl_ctx);
+ the_ssl_ctx = NULL;
+
+ return 1;
+}
+const struct testcase_setup_t ssl_setup = {
+ ssl_test_setup, ssl_test_cleanup
+};
+
+
+/* ====================
+ Here's a simple test: we read a number from the input, increment it, and
+ reply, until we get to 1001.
+*/
+
+enum regress_openssl_type
+{
+ REGRESS_OPENSSL_SOCKETPAIR = 1,
+ REGRESS_OPENSSL_FILTER = 2,
+ REGRESS_OPENSSL_RENEGOTIATE = 4,
+ REGRESS_OPENSSL_OPEN = 8,
+ REGRESS_OPENSSL_DIRTY_SHUTDOWN = 16,
+ REGRESS_OPENSSL_FD = 32,
+
+ REGRESS_OPENSSL_CLIENT = 64,
+ REGRESS_OPENSSL_SERVER = 128,
+
+ REGRESS_OPENSSL_FREED = 256,
+ REGRESS_OPENSSL_TIMEOUT = 512,
+ REGRESS_OPENSSL_SLEEP = 1024,
+
+ REGRESS_OPENSSL_CLIENT_WRITE = 2048,
+
+ REGRESS_DEFERRED_CALLBACKS = 4096,
+};
+
+static void
+bufferevent_openssl_check_fd(struct bufferevent *bev, int filter)
+{
+ tt_fd_op(bufferevent_getfd(bev), !=, EVUTIL_INVALID_SOCKET);
+ tt_fd_op(bufferevent_setfd(bev, EVUTIL_INVALID_SOCKET), ==, 0);
+ if (filter) {
+ tt_fd_op(bufferevent_getfd(bev), !=, EVUTIL_INVALID_SOCKET);
+ } else {
+ tt_fd_op(bufferevent_getfd(bev), ==, EVUTIL_INVALID_SOCKET);
+ }
+
+end:
+ ;
+}
+static void
+bufferevent_openssl_check_freed(struct bufferevent *bev)
+{
+ tt_int_op(event_pending(&bev->ev_read, EVLIST_ALL, NULL), ==, 0);
+ tt_int_op(event_pending(&bev->ev_write, EVLIST_ALL, NULL), ==, 0);
+
+end:
+ ;
+}
+
+static void
+free_on_cb(struct bufferevent *bev, void *ctx)
+{
+ TT_BLATHER(("free_on_cb: %p", bev));
+ bufferevent_free(bev);
+}
+
+static void
+respond_to_number(struct bufferevent *bev, void *ctx)
+{
+ struct evbuffer *b = bufferevent_get_input(bev);
+ char *line;
+ int n;
+
+ enum regress_openssl_type type;
+ type = (enum regress_openssl_type)ctx;
+
+ line = evbuffer_readln(b, NULL, EVBUFFER_EOL_LF);
+ if (! line)
+ return;
+ n = atoi(line);
+ if (n <= 0)
+ TT_FAIL(("Bad number: %s", line));
+ free(line);
+ TT_BLATHER(("The number was %d", n));
+ if (n == 1001) {
+ ++test_is_done;
+ bufferevent_free(bev); /* Should trigger close on other side. */
+ return;
+ }
+ if ((type & REGRESS_OPENSSL_CLIENT) && n == renegotiate_at) {
+ SSL_renegotiate(bufferevent_openssl_get_ssl(bev));
+ }
+ ++n;
+ evbuffer_add_printf(bufferevent_get_output(bev),
+ "%d\n", n);
+ TT_BLATHER(("Done reading; now writing."));
+ bufferevent_enable(bev, EV_WRITE);
+ bufferevent_disable(bev, EV_READ);
+}
+
+static void
+done_writing_cb(struct bufferevent *bev, void *ctx)
+{
+ struct evbuffer *b = bufferevent_get_output(bev);
+ if (evbuffer_get_length(b))
+ return;
+ TT_BLATHER(("Done writing."));
+ bufferevent_disable(bev, EV_WRITE);
+ bufferevent_enable(bev, EV_READ);
+}
+
+static void
+eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ X509 *peer_cert = NULL;
+ enum regress_openssl_type type;
+
+ type = (enum regress_openssl_type)ctx;
+
+ TT_BLATHER(("Got event %d", (int)what));
+ if (what & BEV_EVENT_CONNECTED) {
+ SSL *ssl;
+ ++n_connected;
+ ssl = bufferevent_openssl_get_ssl(bev);
+ tt_assert(ssl);
+ peer_cert = SSL_get_peer_certificate(ssl);
+ if (type & REGRESS_OPENSSL_SERVER) {
+ tt_assert(peer_cert == NULL);
+ } else {
+ tt_assert(peer_cert != NULL);
+ }
+ if (stop_when_connected) {
+ if (--pending_connect_events == 0)
+ event_base_loopexit(exit_base, NULL);
+ }
+
+ if ((type & REGRESS_OPENSSL_CLIENT_WRITE) && (type & REGRESS_OPENSSL_CLIENT))
+ evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
+ } else if (what & BEV_EVENT_EOF) {
+ TT_BLATHER(("Got a good EOF"));
+ ++got_close;
+ if (type & REGRESS_OPENSSL_FD) {
+ bufferevent_openssl_check_fd(bev, type & REGRESS_OPENSSL_FILTER);
+ }
+ if (type & REGRESS_OPENSSL_FREED) {
+ bufferevent_openssl_check_freed(bev);
+ }
+ bufferevent_free(bev);
+ } else if (what & BEV_EVENT_ERROR) {
+ TT_BLATHER(("Got an error."));
+ ++got_error;
+ if (type & REGRESS_OPENSSL_FD) {
+ bufferevent_openssl_check_fd(bev, type & REGRESS_OPENSSL_FILTER);
+ }
+ if (type & REGRESS_OPENSSL_FREED) {
+ bufferevent_openssl_check_freed(bev);
+ }
+ bufferevent_free(bev);
+ } else if (what & BEV_EVENT_TIMEOUT) {
+ TT_BLATHER(("Got timeout."));
+ ++got_timeout;
+ if (type & REGRESS_OPENSSL_FD) {
+ bufferevent_openssl_check_fd(bev, type & REGRESS_OPENSSL_FILTER);
+ }
+ if (type & REGRESS_OPENSSL_FREED) {
+ bufferevent_openssl_check_freed(bev);
+ }
+ bufferevent_free(bev);
+ }
+
+end:
+ if (peer_cert)
+ X509_free(peer_cert);
+}
+
+static void
+open_ssl_bufevs(struct bufferevent **bev1_out, struct bufferevent **bev2_out,
+ struct event_base *base, int is_open, int flags, SSL *ssl1, SSL *ssl2,
+ evutil_socket_t *fd_pair, struct bufferevent **underlying_pair,
+ enum regress_openssl_type type)
+{
+ int state1 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_CONNECTING;
+ int state2 = is_open ? BUFFEREVENT_SSL_OPEN :BUFFEREVENT_SSL_ACCEPTING;
+ int dirty_shutdown = type & REGRESS_OPENSSL_DIRTY_SHUTDOWN;
+ if (fd_pair) {
+ *bev1_out = bufferevent_openssl_socket_new(
+ base, fd_pair[0], ssl1, state1, flags);
+ *bev2_out = bufferevent_openssl_socket_new(
+ base, fd_pair[1], ssl2, state2, flags);
+ } else {
+ *bev1_out = bufferevent_openssl_filter_new(
+ base, underlying_pair[0], ssl1, state1, flags);
+ *bev2_out = bufferevent_openssl_filter_new(
+ base, underlying_pair[1], ssl2, state2, flags);
+
+ }
+ bufferevent_setcb(*bev1_out, respond_to_number, done_writing_cb,
+ eventcb, (void*)(REGRESS_OPENSSL_CLIENT | (long)type));
+ bufferevent_setcb(*bev2_out, respond_to_number, done_writing_cb,
+ eventcb, (void*)(REGRESS_OPENSSL_SERVER | (long)type));
+
+ bufferevent_openssl_set_allow_dirty_shutdown(*bev1_out, dirty_shutdown);
+ bufferevent_openssl_set_allow_dirty_shutdown(*bev2_out, dirty_shutdown);
+}
+
+static void
+regress_bufferevent_openssl(void *arg)
+{
+ struct basic_test_data *data = arg;
+
+ struct bufferevent *bev1, *bev2;
+ SSL *ssl1, *ssl2;
+ int flags = BEV_OPT_DEFER_CALLBACKS;
+ struct bufferevent *bev_ll[2] = { NULL, NULL };
+ evutil_socket_t *fd_pair = NULL;
+
+ enum regress_openssl_type type;
+ type = (enum regress_openssl_type)data->setup_data;
+
+ if (type & REGRESS_OPENSSL_RENEGOTIATE) {
+ if (OPENSSL_VERSION_NUMBER >= 0x10001000 &&
+ OPENSSL_VERSION_NUMBER < 0x1000104f) {
+ /* 1.0.1 up to 1.0.1c has a bug where TLS1.1 and 1.2
+ * can't renegotiate with themselves. Disable. */
+ disable_tls_11_and_12 = 1;
+ }
+ renegotiate_at = 600;
+ }
+
+ ssl1 = SSL_new(get_ssl_ctx());
+ ssl2 = SSL_new(get_ssl_ctx());
+
+ SSL_use_certificate(ssl2, the_cert);
+ SSL_use_PrivateKey(ssl2, the_key);
+
+ if (!(type & REGRESS_OPENSSL_OPEN))
+ flags |= BEV_OPT_CLOSE_ON_FREE;
+
+ if (!(type & REGRESS_OPENSSL_FILTER)) {
+ tt_assert(type & REGRESS_OPENSSL_SOCKETPAIR);
+ fd_pair = data->pair;
+ } else {
+ bev_ll[0] = bufferevent_socket_new(data->base, data->pair[0],
+ BEV_OPT_CLOSE_ON_FREE);
+ bev_ll[1] = bufferevent_socket_new(data->base, data->pair[1],
+ BEV_OPT_CLOSE_ON_FREE);
+ }
+
+ open_ssl_bufevs(&bev1, &bev2, data->base, 0, flags, ssl1, ssl2,
+ fd_pair, bev_ll, type);
+
+ if (!(type & REGRESS_OPENSSL_FILTER)) {
+ tt_fd_op(bufferevent_getfd(bev1), ==, data->pair[0]);
+ } else {
+ tt_ptr_op(bufferevent_get_underlying(bev1), ==, bev_ll[0]);
+ }
+
+ if (type & REGRESS_OPENSSL_OPEN) {
+ pending_connect_events = 2;
+ stop_when_connected = 1;
+ exit_base = data->base;
+ event_base_dispatch(data->base);
+ /* Okay, now the renegotiation is done. Make new
+ * bufferevents to test opening in BUFFEREVENT_SSL_OPEN */
+ flags |= BEV_OPT_CLOSE_ON_FREE;
+ bufferevent_free(bev1);
+ bufferevent_free(bev2);
+ bev1 = bev2 = NULL;
+ open_ssl_bufevs(&bev1, &bev2, data->base, 1, flags, ssl1, ssl2,
+ fd_pair, bev_ll, type);
+ }
+
+ if (!(type & REGRESS_OPENSSL_TIMEOUT)) {
+ bufferevent_enable(bev1, EV_READ|EV_WRITE);
+ bufferevent_enable(bev2, EV_READ|EV_WRITE);
+
+ if (!(type & REGRESS_OPENSSL_CLIENT_WRITE))
+ evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_is_done == 1);
+ tt_assert(n_connected == 2);
+
+ /* We don't handle shutdown properly yet */
+ if (type & REGRESS_OPENSSL_DIRTY_SHUTDOWN) {
+ tt_int_op(got_close, ==, 1);
+ tt_int_op(got_error, ==, 0);
+ } else {
+ tt_int_op(got_error, ==, 1);
+ }
+ tt_int_op(got_timeout, ==, 0);
+ } else {
+ struct timeval t = { 2, 0 };
+
+ bufferevent_enable(bev1, EV_READ|EV_WRITE);
+ bufferevent_disable(bev2, EV_READ|EV_WRITE);
+
+ bufferevent_set_timeouts(bev1, &t, &t);
+
+ if (!(type & REGRESS_OPENSSL_CLIENT_WRITE))
+ evbuffer_add_printf(bufferevent_get_output(bev1), "1\n");
+
+ event_base_dispatch(data->base);
+
+ tt_assert(test_is_done == 0);
+ tt_assert(n_connected == 0);
+
+ tt_int_op(got_close, ==, 0);
+ tt_int_op(got_error, ==, 0);
+ tt_int_op(got_timeout, ==, 1);
+
+ bufferevent_free(bev2);
+ }
+
+end:
+ return;
+}
+
+static void
+acceptcb_deferred(evutil_socket_t fd, short events, void *arg)
+{
+ struct bufferevent *bev = arg;
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+}
+static void
+acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *addr, int socklen, void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct bufferevent *bev;
+ enum regress_openssl_type type;
+ SSL *ssl = SSL_new(get_ssl_ctx());
+
+ type = (enum regress_openssl_type)data->setup_data;
+
+ SSL_use_certificate(ssl, the_cert);
+ SSL_use_PrivateKey(ssl, the_key);
+
+ bev = bufferevent_openssl_socket_new(
+ data->base, fd, ssl, BUFFEREVENT_SSL_ACCEPTING,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ tt_assert(bev);
+
+ bufferevent_setcb(bev, respond_to_number, NULL, eventcb,
+ (void*)(REGRESS_OPENSSL_SERVER));
+
+ if (type & REGRESS_OPENSSL_SLEEP) {
+ struct timeval when = { 1, 0 };
+ event_base_once(data->base, -1, EV_TIMEOUT,
+ acceptcb_deferred, bev, &when);
+ bufferevent_disable(bev, EV_READ|EV_WRITE);
+ } else {
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+ }
+
+ /* Only accept once, then disable ourself. */
+ evconnlistener_disable(listener);
+
+end:
+ ;
+}
+
+struct rwcount
+{
+ evutil_socket_t fd;
+ size_t read;
+ size_t write;
+};
+static int
+bio_rwcount_new(BIO *b)
+{
+ BIO_set_init(b, 0);
+ BIO_set_data(b, NULL);
+ return 1;
+}
+static int
+bio_rwcount_free(BIO *b)
+{
+ TT_BLATHER(("bio_rwcount_free: %p", b));
+ if (!b)
+ return 0;
+ if (BIO_get_shutdown(b)) {
+ BIO_set_init(b, 0);
+ BIO_set_data(b, NULL);
+ }
+ return 1;
+}
+static int
+bio_rwcount_read(BIO *b, char *out, int outlen)
+{
+ struct rwcount *rw = BIO_get_data(b);
+ ev_ssize_t ret = recv(rw->fd, out, outlen, 0);
+ ++rw->read;
+ if (ret == -1 && EVUTIL_ERR_RW_RETRIABLE(EVUTIL_SOCKET_ERROR())) {
+ BIO_set_retry_read(b);
+ }
+ return ret;
+}
+static int
+bio_rwcount_write(BIO *b, const char *in, int inlen)
+{
+ struct rwcount *rw = BIO_get_data(b);
+ ev_ssize_t ret = send(rw->fd, in, inlen, 0);
+ ++rw->write;
+ if (ret == -1 && EVUTIL_ERR_RW_RETRIABLE(EVUTIL_SOCKET_ERROR())) {
+ BIO_set_retry_write(b);
+ }
+ return ret;
+}
+static long
+bio_rwcount_ctrl(BIO *b, int cmd, long num, void *ptr)
+{
+ struct rwcount *rw = BIO_get_data(b);
+ long ret = 0;
+ switch (cmd) {
+ case BIO_C_GET_FD:
+ ret = rw->fd;
+ break;
+ case BIO_CTRL_GET_CLOSE:
+ ret = BIO_get_shutdown(b);
+ break;
+ case BIO_CTRL_SET_CLOSE:
+ BIO_set_shutdown(b, (int)num);
+ break;
+ case BIO_CTRL_PENDING:
+ ret = 0;
+ break;
+ case BIO_CTRL_WPENDING:
+ ret = 0;
+ break;
+ case BIO_CTRL_DUP:
+ case BIO_CTRL_FLUSH:
+ ret = 1;
+ break;
+ }
+ return ret;
+}
+static int
+bio_rwcount_puts(BIO *b, const char *s)
+{
+ return bio_rwcount_write(b, s, strlen(s));
+}
+#define BIO_TYPE_LIBEVENT_RWCOUNT 0xff1
+static BIO_METHOD *methods_rwcount;
+
+static BIO_METHOD *
+BIO_s_rwcount(void)
+{
+ if (methods_rwcount == NULL) {
+ methods_rwcount = BIO_meth_new(BIO_TYPE_LIBEVENT_RWCOUNT, "rwcount");
+ if (methods_rwcount == NULL)
+ return NULL;
+ BIO_meth_set_write(methods_rwcount, bio_rwcount_write);
+ BIO_meth_set_read(methods_rwcount, bio_rwcount_read);
+ BIO_meth_set_puts(methods_rwcount, bio_rwcount_puts);
+ BIO_meth_set_ctrl(methods_rwcount, bio_rwcount_ctrl);
+ BIO_meth_set_create(methods_rwcount, bio_rwcount_new);
+ BIO_meth_set_destroy(methods_rwcount, bio_rwcount_free);
+ }
+ return methods_rwcount;
+}
+static BIO *
+BIO_new_rwcount(int close_flag)
+{
+ BIO *result;
+ if (!(result = BIO_new(BIO_s_rwcount())))
+ return NULL;
+ BIO_set_init(result, 1);
+ BIO_set_data(result, NULL);
+ BIO_set_shutdown(result, !!close_flag);
+ return result;
+}
+
+static void
+regress_bufferevent_openssl_connect(void *arg)
+{
+ struct basic_test_data *data = arg;
+
+ struct event_base *base = data->base;
+
+ struct evconnlistener *listener;
+ struct bufferevent *bev;
+ struct sockaddr_in sin;
+ struct sockaddr_storage ss;
+ ev_socklen_t slen;
+ SSL *ssl;
+ struct rwcount rw = { -1, 0, 0 };
+ enum regress_openssl_type type;
+
+ type = (enum regress_openssl_type)data->setup_data;
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001);
+
+ memset(&ss, 0, sizeof(ss));
+ slen = sizeof(ss);
+
+ listener = evconnlistener_new_bind(base, acceptcb, data,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+ -1, (struct sockaddr *)&sin, sizeof(sin));
+
+ tt_assert(listener);
+ tt_assert(evconnlistener_get_fd(listener) >= 0);
+
+ ssl = SSL_new(get_ssl_ctx());
+ tt_assert(ssl);
+
+ bev = bufferevent_openssl_socket_new(
+ data->base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
+ tt_assert(bev);
+
+ bufferevent_setcb(bev, respond_to_number, free_on_cb, eventcb,
+ (void*)(REGRESS_OPENSSL_CLIENT));
+
+ tt_assert(getsockname(evconnlistener_get_fd(listener),
+ (struct sockaddr*)&ss, &slen) == 0);
+ tt_assert(slen == sizeof(struct sockaddr_in));
+ tt_int_op(((struct sockaddr*)&ss)->sa_family, ==, AF_INET);
+
+ tt_assert(0 ==
+ bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
+ /* Possible only when we have fd, since be_openssl can and will overwrite
+ * bio otherwise before */
+ if (type & REGRESS_OPENSSL_SLEEP) {
+ BIO *bio;
+
+ rw.fd = bufferevent_getfd(bev);
+ bio = BIO_new_rwcount(0);
+ tt_assert(bio);
+ BIO_set_data(bio, &rw);
+ SSL_set_bio(ssl, bio, bio);
+ }
+ evbuffer_add_printf(bufferevent_get_output(bev), "1\n");
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+
+ event_base_dispatch(base);
+
+ tt_int_op(rw.read, <=, 100);
+ tt_int_op(rw.write, <=, 100);
+end:
+ evconnlistener_free(listener);
+}
+
+struct wm_context
+{
+ int server;
+ int flags;
+ struct evbuffer *data;
+ size_t to_read;
+ size_t wm_high;
+ size_t limit;
+ size_t get;
+ struct bufferevent *bev;
+ struct wm_context *neighbour;
+};
+static void
+wm_transfer(struct bufferevent *bev, void *arg)
+{
+ struct wm_context *ctx = arg;
+ struct evbuffer *in = bufferevent_get_input(bev);
+ struct evbuffer *out = bufferevent_get_output(bev);
+ size_t len = evbuffer_get_length(in);
+ size_t drain = len < ctx->to_read ? len : ctx->to_read;
+
+ if (ctx->get >= ctx->limit) {
+ TT_BLATHER(("wm_transfer-%s(%p): break",
+ ctx->server ? "server" : "client", bev));
+ bufferevent_setcb(bev, NULL, NULL, NULL, NULL);
+ bufferevent_disable(bev, EV_READ);
+ if (ctx->neighbour->get >= ctx->neighbour->limit) {
+ event_base_loopbreak(bufferevent_get_base(bev));
+ }
+ } else {
+ ctx->get += drain;
+ evbuffer_drain(in, drain);
+ }
+
+ TT_BLATHER(("wm_transfer-%s(%p): "
+ "in: " EV_SIZE_FMT ", "
+ "out: " EV_SIZE_FMT ", "
+ "got: " EV_SIZE_FMT "",
+ ctx->server ? "server" : "client", bev,
+ evbuffer_get_length(in),
+ evbuffer_get_length(out),
+ ctx->get));
+
+ evbuffer_add_buffer_reference(out, ctx->data);
+}
+static void
+wm_eventcb(struct bufferevent *bev, short what, void *arg)
+{
+ struct wm_context *ctx = arg;
+ TT_BLATHER(("wm_eventcb-%s(%p): %i",
+ ctx->server ? "server" : "client", bev, what));
+ if (what & BEV_EVENT_CONNECTED) {
+ } else {
+ ctx->get = 0;
+ }
+}
+static void
+wm_acceptcb(struct evconnlistener *listener, evutil_socket_t fd,
+ struct sockaddr *addr, int socklen, void *arg)
+{
+ struct wm_context *ctx = arg;
+ struct bufferevent *bev;
+ struct event_base *base = evconnlistener_get_base(listener);
+ SSL *ssl = SSL_new(get_ssl_ctx());
+
+ SSL_use_certificate(ssl, the_cert);
+ SSL_use_PrivateKey(ssl, the_key);
+
+ bev = bufferevent_openssl_socket_new(
+ base, fd, ssl, BUFFEREVENT_SSL_ACCEPTING, ctx->flags);
+
+ TT_BLATHER(("wm_transfer-%s(%p): accept",
+ ctx->server ? "server" : "client", bev));
+
+ bufferevent_setwatermark(bev, EV_READ, 0, ctx->wm_high);
+ bufferevent_setcb(bev, wm_transfer, NULL, wm_eventcb, ctx);
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+ ctx->bev = bev;
+
+ /* Only accept once, then disable ourself. */
+ evconnlistener_disable(listener);
+}
+static void
+regress_bufferevent_openssl_wm(void *arg)
+{
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+
+ struct evconnlistener *listener;
+ struct bufferevent *bev;
+ struct sockaddr_in sin;
+ struct sockaddr_storage ss;
+ enum regress_openssl_type type =
+ (enum regress_openssl_type)data->setup_data;
+ int bev_flags = BEV_OPT_CLOSE_ON_FREE;
+ ev_socklen_t slen;
+ SSL *ssl;
+ struct wm_context client, server;
+ char *payload;
+ size_t payload_len = 1<<10;
+ size_t wm_high = 5<<10;
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001);
+
+ memset(&ss, 0, sizeof(ss));
+ slen = sizeof(ss);
+
+ if (type & REGRESS_DEFERRED_CALLBACKS)
+ bev_flags |= BEV_OPT_DEFER_CALLBACKS;
+
+ memset(&client, 0, sizeof(client));
+ memset(&server, 0, sizeof(server));
+ client.server = 0;
+ server.server = 1;
+ client.flags = server.flags = bev_flags;
+ client.data = evbuffer_new();
+ server.data = evbuffer_new();
+ payload = calloc(1, payload_len);
+ memset(payload, 'A', payload_len);
+ evbuffer_add(server.data, payload, payload_len);
+ evbuffer_add(client.data, payload, payload_len);
+ client.wm_high = server.wm_high = wm_high;
+ client.limit = server.limit = wm_high<<3;
+ client.to_read = server.to_read = payload_len>>1;
+
+ TT_BLATHER(("openssl_wm: "
+ "payload_len = " EV_SIZE_FMT ", "
+ "wm_high = " EV_SIZE_FMT ", "
+ "limit = " EV_SIZE_FMT ", "
+ "to_read: " EV_SIZE_FMT "",
+ payload_len,
+ wm_high,
+ server.limit,
+ server.to_read));
+
+ listener = evconnlistener_new_bind(base, wm_acceptcb, &server,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+ -1, (struct sockaddr *)&sin, sizeof(sin));
+
+ tt_assert(listener);
+ tt_assert(evconnlistener_get_fd(listener) >= 0);
+
+ ssl = SSL_new(get_ssl_ctx());
+ tt_assert(ssl);
+
+ if (type & REGRESS_OPENSSL_FILTER) {
+ bev = bufferevent_socket_new(data->base, -1, client.flags);
+ tt_assert(bev);
+ bev = bufferevent_openssl_filter_new(
+ base, bev, ssl, BUFFEREVENT_SSL_CONNECTING, client.flags);
+ } else {
+ bev = bufferevent_openssl_socket_new(
+ data->base, -1, ssl,
+ BUFFEREVENT_SSL_CONNECTING,
+ client.flags);
+ }
+ tt_assert(bev);
+ client.bev = bev;
+
+ server.neighbour = &client;
+ client.neighbour = &server;
+
+ bufferevent_setwatermark(bev, EV_READ, 0, client.wm_high);
+ bufferevent_setcb(bev, wm_transfer, NULL, wm_eventcb, &client);
+
+ tt_assert(getsockname(evconnlistener_get_fd(listener),
+ (struct sockaddr*)&ss, &slen) == 0);
+
+ tt_assert(!bufferevent_socket_connect(bev, (struct sockaddr*)&ss, slen));
+ tt_assert(!evbuffer_add_buffer_reference(bufferevent_get_output(bev), client.data));
+ tt_assert(!bufferevent_enable(bev, EV_READ|EV_WRITE));
+
+ event_base_dispatch(base);
+
+ tt_int_op(client.get, ==, client.limit);
+ tt_int_op(server.get, ==, server.limit);
+
+end:
+ free(payload);
+ evbuffer_free(client.data);
+ evbuffer_free(server.data);
+ evconnlistener_free(listener);
+ bufferevent_free(client.bev);
+ bufferevent_free(server.bev);
+
+ /* XXX: by some reason otherise there is a leak */
+ if (!(type & REGRESS_OPENSSL_FILTER))
+ event_base_loop(base, EVLOOP_ONCE);
+}
+
+struct testcase_t ssl_testcases[] = {
+#define T(a) ((void *)(a))
+ { "bufferevent_socketpair", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup, T(REGRESS_OPENSSL_SOCKETPAIR) },
+ { "bufferevent_socketpair_write_after_connect", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR|REGRESS_OPENSSL_CLIENT_WRITE) },
+ { "bufferevent_filter", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup, T(REGRESS_OPENSSL_FILTER) },
+ { "bufferevent_filter_write_after_connect", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER|REGRESS_OPENSSL_CLIENT_WRITE) },
+ { "bufferevent_renegotiate_socketpair", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_RENEGOTIATE) },
+ { "bufferevent_renegotiate_filter", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_RENEGOTIATE) },
+ { "bufferevent_socketpair_startopen", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_OPEN) },
+ { "bufferevent_filter_startopen", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_OPEN) },
+
+ { "bufferevent_socketpair_dirty_shutdown", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+ { "bufferevent_filter_dirty_shutdown", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+ { "bufferevent_renegotiate_socketpair_dirty_shutdown",
+ regress_bufferevent_openssl,
+ TT_ISOLATED,
+ &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_RENEGOTIATE | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+ { "bufferevent_renegotiate_filter_dirty_shutdown",
+ regress_bufferevent_openssl,
+ TT_ISOLATED,
+ &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_RENEGOTIATE | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+ { "bufferevent_socketpair_startopen_dirty_shutdown",
+ regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_OPEN | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+ { "bufferevent_filter_startopen_dirty_shutdown",
+ regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_OPEN | REGRESS_OPENSSL_DIRTY_SHUTDOWN) },
+
+ { "bufferevent_socketpair_fd", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_FD) },
+ { "bufferevent_socketpair_freed", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_FREED) },
+ { "bufferevent_socketpair_freed_fd", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_FREED | REGRESS_OPENSSL_FD) },
+ { "bufferevent_filter_freed_fd", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_FILTER | REGRESS_OPENSSL_FREED | REGRESS_OPENSSL_FD) },
+
+ { "bufferevent_socketpair_timeout", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_TIMEOUT) },
+ { "bufferevent_socketpair_timeout_freed_fd", regress_bufferevent_openssl,
+ TT_ISOLATED, &ssl_setup,
+ T(REGRESS_OPENSSL_SOCKETPAIR | REGRESS_OPENSSL_TIMEOUT | REGRESS_OPENSSL_FREED | REGRESS_OPENSSL_FD) },
+
+ { "bufferevent_connect", regress_bufferevent_openssl_connect,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, NULL },
+ { "bufferevent_connect_sleep", regress_bufferevent_openssl_connect,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, T(REGRESS_OPENSSL_SLEEP) },
+
+ { "bufferevent_wm", regress_bufferevent_openssl_wm,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, NULL },
+ { "bufferevent_wm_filter", regress_bufferevent_openssl_wm,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, T(REGRESS_OPENSSL_FILTER) },
+ { "bufferevent_wm_defer", regress_bufferevent_openssl_wm,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, T(REGRESS_DEFERRED_CALLBACKS) },
+ { "bufferevent_wm_filter_defer", regress_bufferevent_openssl_wm,
+ TT_FORK|TT_NEED_BASE, &ssl_setup, T(REGRESS_OPENSSL_FILTER|REGRESS_DEFERRED_CALLBACKS) },
+
+#undef T
+
+ END_OF_TESTCASES,
+};
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_testutils.c b/ipc/chromium/src/third_party/libevent/test/regress_testutils.c
new file mode 100644
index 0000000000..b0ce7dbba2
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_testutils.c
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#include <sys/queue.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <signal.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/dns.h"
+#include "event2/dns_struct.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/bufferevent.h"
+#include "log-internal.h"
+#include "regress.h"
+#include "regress_testutils.h"
+
+/* globals */
+static struct evdns_server_port *dns_port;
+evutil_socket_t dns_sock = -1;
+
+/* Helper: return the port that a socket is bound on, in host order. */
+int
+regress_get_socket_port(evutil_socket_t fd)
+{
+ struct sockaddr_storage ss;
+ ev_socklen_t socklen = sizeof(ss);
+ if (getsockname(fd, (struct sockaddr*)&ss, &socklen) != 0)
+ return -1;
+ if (ss.ss_family == AF_INET)
+ return ntohs( ((struct sockaddr_in*)&ss)->sin_port);
+ else if (ss.ss_family == AF_INET6)
+ return ntohs( ((struct sockaddr_in6*)&ss)->sin6_port);
+ else
+ return -1;
+}
+
+struct evdns_server_port *
+regress_get_dnsserver(struct event_base *base,
+ ev_uint16_t *portnum,
+ evutil_socket_t *psock,
+ evdns_request_callback_fn_type cb,
+ void *arg)
+{
+ struct evdns_server_port *port = NULL;
+ evutil_socket_t sock;
+ struct sockaddr_in my_addr;
+
+ sock = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sock < 0) {
+ tt_abort_perror("socket");
+ }
+
+ evutil_make_socket_nonblocking(sock);
+
+ memset(&my_addr, 0, sizeof(my_addr));
+ my_addr.sin_family = AF_INET;
+ my_addr.sin_port = htons(*portnum);
+ my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
+ if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
+ evutil_closesocket(sock);
+ tt_abort_perror("bind");
+ }
+ port = evdns_add_server_port_with_base(base, sock, 0, cb, arg);
+ if (!*portnum)
+ *portnum = regress_get_socket_port(sock);
+ if (psock)
+ *psock = sock;
+
+ return port;
+end:
+ return NULL;
+}
+
+void
+regress_clean_dnsserver(void)
+{
+ if (dns_port) {
+ evdns_close_server_port(dns_port);
+ dns_port = NULL;
+ }
+ if (dns_sock >= 0) {
+ evutil_closesocket(dns_sock);
+ dns_sock = -1;
+ }
+}
+
+static void strtolower(char *s)
+{
+ while (*s) {
+ *s = EVUTIL_TOLOWER_(*s);
+ ++s;
+ }
+}
+void
+regress_dns_server_cb(struct evdns_server_request *req, void *data)
+{
+ struct regress_dns_server_table *tab = data;
+ char *question;
+
+ if (req->nquestions != 1)
+ TT_DIE(("Only handling one question at a time; got %d",
+ req->nquestions));
+
+ question = req->questions[0]->name;
+
+ while (tab->q && evutil_ascii_strcasecmp(question, tab->q) &&
+ strcmp("*", tab->q))
+ ++tab;
+ if (tab->q == NULL)
+ TT_DIE(("Unexpected question: '%s'", question));
+
+ ++tab->seen;
+
+ if (tab->lower)
+ strtolower(question);
+
+ if (!strcmp(tab->anstype, "err")) {
+ int err = atoi(tab->ans);
+ tt_assert(! evdns_server_request_respond(req, err));
+ return;
+ } else if (!strcmp(tab->anstype, "errsoa")) {
+ int err = atoi(tab->ans);
+ char soa_record[] =
+ "\x04" "dns1" "\x05" "icann" "\x03" "org" "\0"
+ "\x0a" "hostmaster" "\x05" "icann" "\x03" "org" "\0"
+ "\x77\xde\x5e\xba" /* serial */
+ "\x00\x00\x1c\x20" /* refreshtime = 2h */
+ "\x00\x00\x0e\x10" /* retry = 1h */
+ "\x00\x12\x75\x00" /* expiration = 14d */
+ "\x00\x00\x0e\x10" /* min.ttl = 1h */
+ ;
+ evdns_server_request_add_reply(
+ req, EVDNS_AUTHORITY_SECTION,
+ "example.com", EVDNS_TYPE_SOA, EVDNS_CLASS_INET,
+ 42, sizeof(soa_record) - 1, 0, soa_record);
+ tt_assert(! evdns_server_request_respond(req, err));
+ return;
+ } else if (!strcmp(tab->anstype, "A")) {
+ struct in_addr in;
+ if (!evutil_inet_pton(AF_INET, tab->ans, &in)) {
+ TT_DIE(("Bad A value %s in table", tab->ans));
+ }
+ evdns_server_request_add_a_reply(req, question, 1, &in.s_addr,
+ 100);
+ } else if (!strcmp(tab->anstype, "AAAA")) {
+ struct in6_addr in6;
+ if (!evutil_inet_pton(AF_INET6, tab->ans, &in6)) {
+ TT_DIE(("Bad AAAA value %s in table", tab->ans));
+ }
+ evdns_server_request_add_aaaa_reply(req,
+ question, 1, &in6.s6_addr, 100);
+ } else {
+ TT_DIE(("Weird table entry with type '%s'", tab->anstype));
+ }
+ tt_assert(! evdns_server_request_respond(req, 0))
+ return;
+end:
+ tt_want(! evdns_server_request_drop(req));
+}
+
+int
+regress_dnsserver(struct event_base *base, ev_uint16_t *port,
+ struct regress_dns_server_table *search_table)
+{
+ dns_port = regress_get_dnsserver(base, port, &dns_sock,
+ regress_dns_server_cb, search_table);
+ return dns_port != NULL;
+}
+
+int
+regress_get_listener_addr(struct evconnlistener *lev,
+ struct sockaddr *sa, ev_socklen_t *socklen)
+{
+ evutil_socket_t s = evconnlistener_get_fd(lev);
+ if (s <= 0)
+ return -1;
+ return getsockname(s, sa, socklen);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_testutils.h b/ipc/chromium/src/third_party/libevent/test/regress_testutils.h
new file mode 100644
index 0000000000..040516a585
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_testutils.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef REGRESS_TESTUTILS_H_INCLUDED_
+#define REGRESS_TESTUTILS_H_INCLUDED_
+
+#include "event2/dns.h"
+
+struct regress_dns_server_table {
+ const char *q;
+ const char *anstype;
+ const char *ans;
+ int seen;
+ int lower;
+};
+
+struct evdns_server_port *
+regress_get_dnsserver(struct event_base *base,
+ ev_uint16_t *portnum,
+ evutil_socket_t *psock,
+ evdns_request_callback_fn_type cb,
+ void *arg);
+
+/* Helper: return the port that a socket is bound on, in host order. */
+int regress_get_socket_port(evutil_socket_t fd);
+
+/* used to look up pre-canned responses in a search table */
+void regress_dns_server_cb(
+ struct evdns_server_request *req, void *data);
+
+/* globally allocates a dns server that serves from a search table */
+int regress_dnsserver(struct event_base *base, ev_uint16_t *port,
+ struct regress_dns_server_table *seach_table);
+
+/* clean up the global dns server resources */
+void regress_clean_dnsserver(void);
+
+struct evconnlistener;
+struct sockaddr;
+int regress_get_listener_addr(struct evconnlistener *lev,
+ struct sockaddr *sa, ev_socklen_t *socklen);
+
+#endif /* REGRESS_TESTUTILS_H_INCLUDED_ */
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_thread.c b/ipc/chromium/src/third_party/libevent/test/regress_thread.c
new file mode 100644
index 0000000000..1e0ce41ff9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_thread.c
@@ -0,0 +1,590 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+
+#ifdef EVENT__HAVE_PTHREADS
+#include <pthread.h>
+#elif defined(_WIN32)
+#include <process.h>
+#endif
+#include <assert.h>
+#ifdef EVENT__HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#include <time.h>
+
+#include "sys/queue.h"
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/thread.h"
+#include "event2/util.h"
+#include "evthread-internal.h"
+#include "event-internal.h"
+#include "defer-internal.h"
+#include "regress.h"
+#include "tinytest_macros.h"
+#include "time-internal.h"
+#include "regress_thread.h"
+
+struct cond_wait {
+ void *lock;
+ void *cond;
+};
+
+static void
+wake_all_timeout(evutil_socket_t fd, short what, void *arg)
+{
+ struct cond_wait *cw = arg;
+ EVLOCK_LOCK(cw->lock, 0);
+ EVTHREAD_COND_BROADCAST(cw->cond);
+ EVLOCK_UNLOCK(cw->lock, 0);
+
+}
+
+static void
+wake_one_timeout(evutil_socket_t fd, short what, void *arg)
+{
+ struct cond_wait *cw = arg;
+ EVLOCK_LOCK(cw->lock, 0);
+ EVTHREAD_COND_SIGNAL(cw->cond);
+ EVLOCK_UNLOCK(cw->lock, 0);
+}
+
+#define NUM_THREADS 100
+#define NUM_ITERATIONS 100
+void *count_lock;
+static int count;
+
+static THREAD_FN
+basic_thread(void *arg)
+{
+ struct cond_wait cw;
+ struct event_base *base = arg;
+ struct event ev;
+ int i = 0;
+
+ EVTHREAD_ALLOC_LOCK(cw.lock, 0);
+ EVTHREAD_ALLOC_COND(cw.cond);
+ assert(cw.lock);
+ assert(cw.cond);
+
+ evtimer_assign(&ev, base, wake_all_timeout, &cw);
+ for (i = 0; i < NUM_ITERATIONS; i++) {
+ struct timeval tv;
+ evutil_timerclear(&tv);
+ tv.tv_sec = 0;
+ tv.tv_usec = 3000;
+
+ EVLOCK_LOCK(cw.lock, 0);
+ /* we need to make sure that event does not happen before
+ * we get to wait on the conditional variable */
+ assert(evtimer_add(&ev, &tv) == 0);
+
+ assert(EVTHREAD_COND_WAIT(cw.cond, cw.lock) == 0);
+ EVLOCK_UNLOCK(cw.lock, 0);
+
+ EVLOCK_LOCK(count_lock, 0);
+ ++count;
+ EVLOCK_UNLOCK(count_lock, 0);
+ }
+
+ /* exit the loop only if all threads fired all timeouts */
+ EVLOCK_LOCK(count_lock, 0);
+ if (count >= NUM_THREADS * NUM_ITERATIONS)
+ event_base_loopexit(base, NULL);
+ EVLOCK_UNLOCK(count_lock, 0);
+
+ EVTHREAD_FREE_LOCK(cw.lock, 0);
+ EVTHREAD_FREE_COND(cw.cond);
+
+ THREAD_RETURN();
+}
+
+static int notification_fd_used = 0;
+#ifndef _WIN32
+static int got_sigchld = 0;
+static void
+sigchld_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct timeval tv;
+ struct event_base *base = arg;
+
+ got_sigchld++;
+ tv.tv_usec = 100000;
+ tv.tv_sec = 0;
+ event_base_loopexit(base, &tv);
+}
+
+
+static void
+notify_fd_cb(evutil_socket_t fd, short event, void *arg)
+{
+ ++notification_fd_used;
+}
+#endif
+
+static void
+thread_basic(void *arg)
+{
+ THREAD_T threads[NUM_THREADS];
+ struct event ev;
+ struct timeval tv;
+ int i;
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+
+ struct event *notification_event = NULL;
+ struct event *sigchld_event = NULL;
+
+ EVTHREAD_ALLOC_LOCK(count_lock, 0);
+ tt_assert(count_lock);
+
+ tt_assert(base);
+ if (evthread_make_base_notifiable(base)<0) {
+ tt_abort_msg("Couldn't make base notifiable!");
+ }
+
+#ifndef _WIN32
+ if (data->setup_data && !strcmp(data->setup_data, "forking")) {
+ pid_t pid;
+ int status;
+ sigchld_event = evsignal_new(base, SIGCHLD, sigchld_cb, base);
+ /* This piggybacks on the th_notify_fd weirdly, and looks
+ * inside libevent internals. Not a good idea in non-testing
+ * code! */
+ notification_event = event_new(base,
+ base->th_notify_fd[0], EV_READ|EV_PERSIST, notify_fd_cb,
+ NULL);
+ event_add(sigchld_event, NULL);
+ event_add(notification_event, NULL);
+
+ if ((pid = fork()) == 0) {
+ event_del(notification_event);
+ if (event_reinit(base) < 0) {
+ TT_FAIL(("reinit"));
+ exit(1);
+ }
+ event_assign(notification_event, base,
+ base->th_notify_fd[0], EV_READ|EV_PERSIST,
+ notify_fd_cb, NULL);
+ event_add(notification_event, NULL);
+ goto child;
+ }
+
+ event_base_dispatch(base);
+
+ if (waitpid(pid, &status, 0) == -1)
+ tt_abort_perror("waitpid");
+ TT_BLATHER(("Waitpid okay\n"));
+
+ tt_assert(got_sigchld);
+ tt_int_op(notification_fd_used, ==, 0);
+
+ goto end;
+ }
+
+child:
+#endif
+ for (i = 0; i < NUM_THREADS; ++i)
+ THREAD_START(threads[i], basic_thread, base);
+
+ evtimer_assign(&ev, base, NULL, NULL);
+ evutil_timerclear(&tv);
+ tv.tv_sec = 1000;
+ event_add(&ev, &tv);
+
+ event_base_dispatch(base);
+
+ for (i = 0; i < NUM_THREADS; ++i)
+ THREAD_JOIN(threads[i]);
+
+ event_del(&ev);
+
+ tt_int_op(count, ==, NUM_THREADS * NUM_ITERATIONS);
+
+ EVTHREAD_FREE_LOCK(count_lock, 0);
+
+ TT_BLATHER(("notifiations==%d", notification_fd_used));
+
+end:
+
+ if (notification_event)
+ event_free(notification_event);
+ if (sigchld_event)
+ event_free(sigchld_event);
+}
+
+#undef NUM_THREADS
+#define NUM_THREADS 10
+
+struct alerted_record {
+ struct cond_wait *cond;
+ struct timeval delay;
+ struct timeval alerted_at;
+ int timed_out;
+};
+
+static THREAD_FN
+wait_for_condition(void *arg)
+{
+ struct alerted_record *rec = arg;
+ int r;
+
+ EVLOCK_LOCK(rec->cond->lock, 0);
+ if (rec->delay.tv_sec || rec->delay.tv_usec) {
+ r = EVTHREAD_COND_WAIT_TIMED(rec->cond->cond, rec->cond->lock,
+ &rec->delay);
+ } else {
+ r = EVTHREAD_COND_WAIT(rec->cond->cond, rec->cond->lock);
+ }
+ EVLOCK_UNLOCK(rec->cond->lock, 0);
+
+ evutil_gettimeofday(&rec->alerted_at, NULL);
+ if (r == 1)
+ rec->timed_out = 1;
+
+ THREAD_RETURN();
+}
+
+static void
+thread_conditions_simple(void *arg)
+{
+ struct timeval tv_signal, tv_timeout, tv_broadcast;
+ struct alerted_record alerted[NUM_THREADS];
+ THREAD_T threads[NUM_THREADS];
+ struct cond_wait cond;
+ int i;
+ struct timeval launched_at;
+ struct event wake_one;
+ struct event wake_all;
+ struct basic_test_data *data = arg;
+ struct event_base *base = data->base;
+ int n_timed_out=0, n_signal=0, n_broadcast=0;
+
+ tv_signal.tv_sec = tv_timeout.tv_sec = tv_broadcast.tv_sec = 0;
+ tv_signal.tv_usec = 30*1000;
+ tv_timeout.tv_usec = 150*1000;
+ tv_broadcast.tv_usec = 500*1000;
+
+ EVTHREAD_ALLOC_LOCK(cond.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ EVTHREAD_ALLOC_COND(cond.cond);
+ tt_assert(cond.lock);
+ tt_assert(cond.cond);
+ for (i = 0; i < NUM_THREADS; ++i) {
+ memset(&alerted[i], 0, sizeof(struct alerted_record));
+ alerted[i].cond = &cond;
+ }
+
+ /* Threads 5 and 6 will be allowed to time out */
+ memcpy(&alerted[5].delay, &tv_timeout, sizeof(tv_timeout));
+ memcpy(&alerted[6].delay, &tv_timeout, sizeof(tv_timeout));
+
+ evtimer_assign(&wake_one, base, wake_one_timeout, &cond);
+ evtimer_assign(&wake_all, base, wake_all_timeout, &cond);
+
+ evutil_gettimeofday(&launched_at, NULL);
+
+ /* Launch the threads... */
+ for (i = 0; i < NUM_THREADS; ++i) {
+ THREAD_START(threads[i], wait_for_condition, &alerted[i]);
+ }
+
+ /* Start the timers... */
+ tt_int_op(event_add(&wake_one, &tv_signal), ==, 0);
+ tt_int_op(event_add(&wake_all, &tv_broadcast), ==, 0);
+
+ /* And run for a bit... */
+ event_base_dispatch(base);
+
+ /* And wait till the threads are done. */
+ for (i = 0; i < NUM_THREADS; ++i)
+ THREAD_JOIN(threads[i]);
+
+ /* Now, let's see what happened. At least one of 5 or 6 should
+ * have timed out. */
+ n_timed_out = alerted[5].timed_out + alerted[6].timed_out;
+ tt_int_op(n_timed_out, >=, 1);
+ tt_int_op(n_timed_out, <=, 2);
+
+ for (i = 0; i < NUM_THREADS; ++i) {
+ const struct timeval *target_delay;
+ struct timeval target_time, actual_delay;
+ if (alerted[i].timed_out) {
+ TT_BLATHER(("%d looks like a timeout\n", i));
+ target_delay = &tv_timeout;
+ tt_assert(i == 5 || i == 6);
+ } else if (evutil_timerisset(&alerted[i].alerted_at)) {
+ long diff1,diff2;
+ evutil_timersub(&alerted[i].alerted_at,
+ &launched_at, &actual_delay);
+ diff1 = timeval_msec_diff(&actual_delay,
+ &tv_signal);
+ diff2 = timeval_msec_diff(&actual_delay,
+ &tv_broadcast);
+ if (labs(diff1) < labs(diff2)) {
+ TT_BLATHER(("%d looks like a signal\n", i));
+ target_delay = &tv_signal;
+ ++n_signal;
+ } else {
+ TT_BLATHER(("%d looks like a broadcast\n", i));
+ target_delay = &tv_broadcast;
+ ++n_broadcast;
+ }
+ } else {
+ TT_FAIL(("Thread %d never got woken", i));
+ continue;
+ }
+ evutil_timeradd(target_delay, &launched_at, &target_time);
+ test_timeval_diff_leq(&target_time, &alerted[i].alerted_at,
+ 0, 200);
+ }
+ tt_int_op(n_broadcast + n_signal + n_timed_out, ==, NUM_THREADS);
+ tt_int_op(n_signal, ==, 1);
+
+end:
+ EVTHREAD_FREE_LOCK(cond.lock, EVTHREAD_LOCKTYPE_RECURSIVE);
+ EVTHREAD_FREE_COND(cond.cond);
+}
+
+#define CB_COUNT 128
+#define QUEUE_THREAD_COUNT 8
+
+static void
+SLEEP_MS(int ms)
+{
+ struct timeval tv;
+ tv.tv_sec = ms/1000;
+ tv.tv_usec = (ms%1000)*1000;
+ evutil_usleep_(&tv);
+}
+
+struct deferred_test_data {
+ struct event_callback cbs[CB_COUNT];
+ struct event_base *queue;
+};
+
+static struct timeval timer_start = {0,0};
+static struct timeval timer_end = {0,0};
+static unsigned callback_count = 0;
+static THREAD_T load_threads[QUEUE_THREAD_COUNT];
+static struct deferred_test_data deferred_data[QUEUE_THREAD_COUNT];
+
+static void
+deferred_callback(struct event_callback *cb, void *arg)
+{
+ SLEEP_MS(1);
+ callback_count += 1;
+}
+
+static THREAD_FN
+load_deferred_queue(void *arg)
+{
+ struct deferred_test_data *data = arg;
+ size_t i;
+
+ for (i = 0; i < CB_COUNT; ++i) {
+ event_deferred_cb_init_(&data->cbs[i], 0, deferred_callback,
+ NULL);
+ event_deferred_cb_schedule_(data->queue, &data->cbs[i]);
+ SLEEP_MS(1);
+ }
+
+ THREAD_RETURN();
+}
+
+static void
+timer_callback(evutil_socket_t fd, short what, void *arg)
+{
+ evutil_gettimeofday(&timer_end, NULL);
+}
+
+static void
+start_threads_callback(evutil_socket_t fd, short what, void *arg)
+{
+ int i;
+
+ for (i = 0; i < QUEUE_THREAD_COUNT; ++i) {
+ THREAD_START(load_threads[i], load_deferred_queue,
+ &deferred_data[i]);
+ }
+}
+
+static void
+thread_deferred_cb_skew(void *arg)
+{
+ struct timeval tv_timer = {1, 0};
+ struct event_base *base = NULL;
+ struct event_config *cfg = NULL;
+ struct timeval elapsed;
+ int elapsed_usec;
+ int i;
+
+ cfg = event_config_new();
+ tt_assert(cfg);
+ event_config_set_max_dispatch_interval(cfg, NULL, 16, 0);
+
+ base = event_base_new_with_config(cfg);
+ tt_assert(base);
+
+ for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
+ deferred_data[i].queue = base;
+
+ evutil_gettimeofday(&timer_start, NULL);
+ event_base_once(base, -1, EV_TIMEOUT, timer_callback, NULL,
+ &tv_timer);
+ event_base_once(base, -1, EV_TIMEOUT, start_threads_callback,
+ NULL, NULL);
+ event_base_dispatch(base);
+
+ evutil_timersub(&timer_end, &timer_start, &elapsed);
+ TT_BLATHER(("callback count, %u", callback_count));
+ elapsed_usec =
+ (unsigned)(elapsed.tv_sec*1000000 + elapsed.tv_usec);
+ TT_BLATHER(("elapsed time, %u usec", elapsed_usec));
+
+ /* XXX be more intelligent here. just make sure skew is
+ * within .4 seconds for now. */
+ tt_assert(elapsed_usec >= 600000 && elapsed_usec <= 1400000);
+
+end:
+ for (i = 0; i < QUEUE_THREAD_COUNT; ++i)
+ THREAD_JOIN(load_threads[i]);
+ if (base)
+ event_base_free(base);
+ if (cfg)
+ event_config_free(cfg);
+}
+
+static struct event time_events[5];
+static struct timeval times[5];
+static struct event_base *exit_base = NULL;
+static void
+note_time_cb(evutil_socket_t fd, short what, void *arg)
+{
+ evutil_gettimeofday(arg, NULL);
+ if (arg == &times[4]) {
+ event_base_loopbreak(exit_base);
+ }
+}
+static THREAD_FN
+register_events_subthread(void *arg)
+{
+ struct timeval tv = {0,0};
+ SLEEP_MS(100);
+ event_active(&time_events[0], EV_TIMEOUT, 1);
+ SLEEP_MS(100);
+ event_active(&time_events[1], EV_TIMEOUT, 1);
+ SLEEP_MS(100);
+ tv.tv_usec = 100*1000;
+ event_add(&time_events[2], &tv);
+ tv.tv_usec = 150*1000;
+ event_add(&time_events[3], &tv);
+ SLEEP_MS(200);
+ event_active(&time_events[4], EV_TIMEOUT, 1);
+
+ THREAD_RETURN();
+}
+
+static void
+thread_no_events(void *arg)
+{
+ THREAD_T thread;
+ struct basic_test_data *data = arg;
+ struct timeval starttime, endtime;
+ int i;
+ exit_base = data->base;
+
+ memset(times,0,sizeof(times));
+ for (i=0;i<5;++i) {
+ event_assign(&time_events[i], data->base,
+ -1, 0, note_time_cb, &times[i]);
+ }
+
+ evutil_gettimeofday(&starttime, NULL);
+ THREAD_START(thread, register_events_subthread, data->base);
+ event_base_loop(data->base, EVLOOP_NO_EXIT_ON_EMPTY);
+ evutil_gettimeofday(&endtime, NULL);
+ tt_assert(event_base_got_break(data->base));
+ THREAD_JOIN(thread);
+ for (i=0; i<5; ++i) {
+ struct timeval diff;
+ double sec;
+ evutil_timersub(&times[i], &starttime, &diff);
+ sec = diff.tv_sec + diff.tv_usec/1.0e6;
+ TT_BLATHER(("event %d at %.4f seconds", i, sec));
+ }
+ test_timeval_diff_eq(&starttime, &times[0], 100);
+ test_timeval_diff_eq(&starttime, &times[1], 200);
+ test_timeval_diff_eq(&starttime, &times[2], 400);
+ test_timeval_diff_eq(&starttime, &times[3], 450);
+ test_timeval_diff_eq(&starttime, &times[4], 500);
+ test_timeval_diff_eq(&starttime, &endtime, 500);
+
+end:
+ ;
+}
+
+#define TEST(name, f) \
+ { #name, thread_##name, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE|(f), \
+ &basic_setup, NULL }
+
+struct testcase_t thread_testcases[] = {
+ { "basic", thread_basic, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,
+ &basic_setup, NULL },
+#ifndef _WIN32
+ { "forking", thread_basic, TT_FORK|TT_NEED_THREADS|TT_NEED_BASE,
+ &basic_setup, (char*)"forking" },
+#endif
+ TEST(conditions_simple, TT_RETRIABLE),
+ { "deferred_cb_skew", thread_deferred_cb_skew,
+ TT_FORK|TT_NEED_THREADS|TT_OFF_BY_DEFAULT,
+ &basic_setup, NULL },
+#ifndef _WIN32
+ /****** XXX TODO FIXME windows seems to be having some timing trouble,
+ * looking into it now. / ellzey
+ ******/
+ TEST(no_events, TT_RETRIABLE),
+#endif
+ END_OF_TESTCASES
+};
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_thread.h b/ipc/chromium/src/third_party/libevent/test/regress_thread.h
new file mode 100644
index 0000000000..a954fefa56
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_thread.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef REGRESS_THREAD_H_INCLUDED_
+#define REGRESS_THREAD_H_INCLUDED_
+
+#if defined(_WIN32) /** _WIN32 */
+#define THREAD_T void * /* HANDLE */
+#define THREAD_FN unsigned __stdcall
+#define THREAD_RETURN() return (0)
+#define THREAD_SELF() GetCurrentThreadId()
+#define THREAD_START(threadvar, fn, arg) do { \
+ uintptr_t threadhandle = _beginthreadex(NULL,0,fn,(arg),0,NULL); \
+ (threadvar) = (THREAD_T)threadhandle; \
+ thread_setup(threadvar); \
+} while (0)
+#define THREAD_JOIN(th) WaitForSingleObject(th, INFINITE)
+#else /* !_WIN32 */
+#include <pthread.h>
+#define THREAD_T pthread_t
+#define THREAD_FN void *
+#define THREAD_RETURN() return (NULL)
+#define THREAD_SELF() pthread_self()
+#define THREAD_START(threadvar, fn, arg) do { \
+ if (!pthread_create(&(threadvar), NULL, fn, arg)) \
+ thread_setup(threadvar); \
+} while (0)
+#define THREAD_JOIN(th) pthread_join(th, NULL)
+#endif /* \!_WIN32 */
+
+void thread_setup(THREAD_T pthread);
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_util.c b/ipc/chromium/src/third_party/libevent/test/regress_util.c
new file mode 100644
index 0000000000..45caa2700a
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_util.c
@@ -0,0 +1,1681 @@
+/*
+ * Copyright (c) 2009-2012 Nick Mathewson and Niels Provos
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/** For event_debug() usage/coverage */
+#define EVENT_VISIBILITY_WANT_DLLIMPORT
+
+#include "../util-internal.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN6_H
+#include <netinet/in6.h>
+#endif
+#ifdef EVENT__HAVE_SYS_WAIT_H
+#include <sys/wait.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include "../ipv6-internal.h"
+#include "../log-internal.h"
+#include "../strlcpy-internal.h"
+#include "../mm-internal.h"
+#include "../time-internal.h"
+
+#include "regress.h"
+
+enum entry_status { NORMAL, CANONICAL, BAD };
+
+/* This is a big table of results we expect from generating and parsing */
+static struct ipv4_entry {
+ const char *addr;
+ ev_uint32_t res;
+ enum entry_status status;
+} ipv4_entries[] = {
+ { "1.2.3.4", 0x01020304u, CANONICAL },
+ { "255.255.255.255", 0xffffffffu, CANONICAL },
+ { "256.0.0.0", 0, BAD },
+ { "ABC", 0, BAD },
+ { "1.2.3.4.5", 0, BAD },
+ { "176.192.208.244", 0xb0c0d0f4, CANONICAL },
+ { NULL, 0, BAD },
+};
+
+static struct ipv6_entry {
+ const char *addr;
+ ev_uint32_t res[4];
+ enum entry_status status;
+} ipv6_entries[] = {
+ { "::", { 0, 0, 0, 0, }, CANONICAL },
+ { "0:0:0:0:0:0:0:0", { 0, 0, 0, 0, }, NORMAL },
+ { "::1", { 0, 0, 0, 1, }, CANONICAL },
+ { "::1.2.3.4", { 0, 0, 0, 0x01020304, }, CANONICAL },
+ { "ffff:1::", { 0xffff0001u, 0, 0, 0, }, CANONICAL },
+ { "ffff:0000::", { 0xffff0000u, 0, 0, 0, }, NORMAL },
+ { "ffff::1234", { 0xffff0000u, 0, 0, 0x1234, }, CANONICAL },
+ { "0102::1.2.3.4", {0x01020000u, 0, 0, 0x01020304u }, NORMAL },
+ { "::9:c0a8:1:1", { 0, 0, 0x0009c0a8u, 0x00010001u }, CANONICAL },
+ { "::ffff:1.2.3.4", { 0, 0, 0x000ffffu, 0x01020304u }, CANONICAL },
+ { "FFFF::", { 0xffff0000u, 0, 0, 0 }, NORMAL },
+ { "foobar.", { 0, 0, 0, 0 }, BAD },
+ { "foobar", { 0, 0, 0, 0 }, BAD },
+ { "fo:obar", { 0, 0, 0, 0 }, BAD },
+ { "ffff", { 0, 0, 0, 0 }, BAD },
+ { "fffff::", { 0, 0, 0, 0 }, BAD },
+ { "fffff::", { 0, 0, 0, 0 }, BAD },
+ { "::1.0.1.1000", { 0, 0, 0, 0 }, BAD },
+ { "1:2:33333:4::", { 0, 0, 0, 0 }, BAD },
+ { "1:2:3:4:5:6:7:8:9", { 0, 0, 0, 0 }, BAD },
+ { "1::2::3", { 0, 0, 0, 0 }, BAD },
+ { ":::1", { 0, 0, 0, 0 }, BAD },
+ { NULL, { 0, 0, 0, 0, }, BAD },
+};
+
+static void
+regress_ipv4_parse(void *ptr)
+{
+ int i;
+ for (i = 0; ipv4_entries[i].addr; ++i) {
+ char written[128];
+ struct ipv4_entry *ent = &ipv4_entries[i];
+ struct in_addr in;
+ int r;
+ r = evutil_inet_pton(AF_INET, ent->addr, &in);
+ if (r == 0) {
+ if (ent->status != BAD) {
+ TT_FAIL(("%s did not parse, but it's a good address!",
+ ent->addr));
+ }
+ continue;
+ }
+ if (ent->status == BAD) {
+ TT_FAIL(("%s parsed, but we expected an error", ent->addr));
+ continue;
+ }
+ if (ntohl(in.s_addr) != ent->res) {
+ TT_FAIL(("%s parsed to %lx, but we expected %lx", ent->addr,
+ (unsigned long)ntohl(in.s_addr),
+ (unsigned long)ent->res));
+ continue;
+ }
+ if (ent->status == CANONICAL) {
+ const char *w = evutil_inet_ntop(AF_INET, &in, written,
+ sizeof(written));
+ if (!w) {
+ TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
+ continue;
+ }
+ if (strcmp(written, ent->addr)) {
+ TT_FAIL(("Tried to write out %s; got %s",
+ ent->addr, written));
+ continue;
+ }
+ }
+
+ }
+
+}
+
+static void
+regress_ipv6_parse(void *ptr)
+{
+#ifdef AF_INET6
+ int i, j;
+
+ for (i = 0; ipv6_entries[i].addr; ++i) {
+ char written[128];
+ struct ipv6_entry *ent = &ipv6_entries[i];
+ struct in6_addr in6;
+ int r;
+ r = evutil_inet_pton(AF_INET6, ent->addr, &in6);
+ if (r == 0) {
+ if (ent->status != BAD)
+ TT_FAIL(("%s did not parse, but it's a good address!",
+ ent->addr));
+ continue;
+ }
+ if (ent->status == BAD) {
+ TT_FAIL(("%s parsed, but we expected an error", ent->addr));
+ continue;
+ }
+ for (j = 0; j < 4; ++j) {
+ /* Can't use s6_addr32 here; some don't have it. */
+ ev_uint32_t u =
+ ((ev_uint32_t)in6.s6_addr[j*4 ] << 24) |
+ ((ev_uint32_t)in6.s6_addr[j*4+1] << 16) |
+ ((ev_uint32_t)in6.s6_addr[j*4+2] << 8) |
+ ((ev_uint32_t)in6.s6_addr[j*4+3]);
+ if (u != ent->res[j]) {
+ TT_FAIL(("%s did not parse as expected.", ent->addr));
+ continue;
+ }
+ }
+ if (ent->status == CANONICAL) {
+ const char *w = evutil_inet_ntop(AF_INET6, &in6, written,
+ sizeof(written));
+ if (!w) {
+ TT_FAIL(("Tried to write out %s; got NULL.", ent->addr));
+ continue;
+ }
+ if (strcmp(written, ent->addr)) {
+ TT_FAIL(("Tried to write out %s; got %s", ent->addr, written));
+ continue;
+ }
+ }
+
+ }
+#else
+ TT_BLATHER(("Skipping IPv6 address parsing."));
+#endif
+}
+
+static struct ipv6_entry_scope {
+ const char *addr;
+ ev_uint32_t res[4];
+ unsigned scope;
+ enum entry_status status;
+} ipv6_entries_scope[] = {
+ { "2001:DB8::", { 0x20010db8, 0, 0 }, 0, NORMAL },
+ { "2001:DB8::%0", { 0x20010db8, 0, 0, 0 }, 0, NORMAL },
+ { "2001:DB8::%1", { 0x20010db8, 0, 0, 0 }, 1, NORMAL },
+ { "foobar.", { 0, 0, 0, 0 }, 0, BAD },
+ { "2001:DB8::%does-not-exist", { 0, 0, 0, 0 }, 0, BAD },
+ { NULL, { 0, 0, 0, 0, }, 0, BAD },
+};
+static void
+regress_ipv6_parse_scope(void *ptr)
+{
+#ifdef AF_INET6
+ int i, j;
+ unsigned if_scope;
+
+ for (i = 0; ipv6_entries_scope[i].addr; ++i) {
+ struct ipv6_entry_scope *ent = &ipv6_entries_scope[i];
+ struct in6_addr in6;
+ int r;
+ r = evutil_inet_pton_scope(AF_INET6, ent->addr, &in6,
+ &if_scope);
+ if (r == 0) {
+ if (ent->status != BAD)
+ TT_FAIL(("%s did not parse, but it's a good address!",
+ ent->addr));
+ continue;
+ }
+ if (ent->status == BAD) {
+ TT_FAIL(("%s parsed, but we expected an error", ent->addr));
+ continue;
+ }
+ for (j = 0; j < 4; ++j) {
+ /* Can't use s6_addr32 here; some don't have it. */
+ ev_uint32_t u =
+ ((ev_uint32_t)in6.s6_addr[j*4 ] << 24) |
+ ((ev_uint32_t)in6.s6_addr[j*4+1] << 16) |
+ ((ev_uint32_t)in6.s6_addr[j*4+2] << 8) |
+ ((ev_uint32_t)in6.s6_addr[j*4+3]);
+ if (u != ent->res[j]) {
+ TT_FAIL(("%s did not parse as expected.", ent->addr));
+ continue;
+ }
+ }
+ if (if_scope != ent->scope) {
+ TT_FAIL(("%s did not parse as expected.", ent->addr));
+ continue;
+ }
+ }
+#else
+ TT_BLATHER(("Skipping IPv6 address parsing."));
+#endif
+}
+
+
+static struct sa_port_ent {
+ const char *parse;
+ int safamily;
+ const char *addr;
+ int port;
+} sa_port_ents[] = {
+ { "[ffff::1]:1000", AF_INET6, "ffff::1", 1000 },
+ { "[ffff::1]", AF_INET6, "ffff::1", 0 },
+ { "[ffff::1", 0, NULL, 0 },
+ { "[ffff::1]:65599", 0, NULL, 0 },
+ { "[ffff::1]:0", 0, NULL, 0 },
+ { "[ffff::1]:-1", 0, NULL, 0 },
+ { "::1", AF_INET6, "::1", 0 },
+ { "1:2::1", AF_INET6, "1:2::1", 0 },
+ { "192.168.0.1:50", AF_INET, "192.168.0.1", 50 },
+ { "1.2.3.4", AF_INET, "1.2.3.4", 0 },
+ { NULL, 0, NULL, 0 },
+};
+
+static void
+regress_sockaddr_port_parse(void *ptr)
+{
+ struct sockaddr_storage ss;
+ int i, r;
+
+ for (i = 0; sa_port_ents[i].parse; ++i) {
+ struct sa_port_ent *ent = &sa_port_ents[i];
+ int len = sizeof(ss);
+ memset(&ss, 0, sizeof(ss));
+ r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
+ if (r < 0) {
+ if (ent->safamily)
+ TT_FAIL(("Couldn't parse %s!", ent->parse));
+ continue;
+ } else if (! ent->safamily) {
+ TT_FAIL(("Shouldn't have been able to parse %s!", ent->parse));
+ continue;
+ }
+ if (ent->safamily == AF_INET) {
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
+ sin.sin_len = sizeof(sin);
+#endif
+ sin.sin_family = AF_INET;
+ sin.sin_port = htons(ent->port);
+ r = evutil_inet_pton(AF_INET, ent->addr, &sin.sin_addr);
+ if (1 != r) {
+ TT_FAIL(("Couldn't parse ipv4 target %s.", ent->addr));
+ } else if (memcmp(&sin, &ss, sizeof(sin))) {
+ TT_FAIL(("Parse for %s was not as expected.", ent->parse));
+ } else if (len != sizeof(sin)) {
+ TT_FAIL(("Length for %s not as expected.",ent->parse));
+ }
+ } else {
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+#ifdef EVENT__HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
+ sin6.sin6_len = sizeof(sin6);
+#endif
+ sin6.sin6_family = AF_INET6;
+ sin6.sin6_port = htons(ent->port);
+ r = evutil_inet_pton(AF_INET6, ent->addr, &sin6.sin6_addr);
+ if (1 != r) {
+ TT_FAIL(("Couldn't parse ipv6 target %s.", ent->addr));
+ } else if (memcmp(&sin6, &ss, sizeof(sin6))) {
+ TT_FAIL(("Parse for %s was not as expected.", ent->parse));
+ } else if (len != sizeof(sin6)) {
+ TT_FAIL(("Length for %s not as expected.",ent->parse));
+ }
+ }
+ }
+}
+
+
+static void
+regress_sockaddr_port_format(void *ptr)
+{
+ struct sockaddr_storage ss;
+ int len;
+ const char *cp;
+ char cbuf[128];
+ int r;
+
+ len = sizeof(ss);
+ r = evutil_parse_sockaddr_port("192.168.1.1:80",
+ (struct sockaddr*)&ss, &len);
+ tt_int_op(r,==,0);
+ cp = evutil_format_sockaddr_port_(
+ (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+ tt_ptr_op(cp,==,cbuf);
+ tt_str_op(cp,==,"192.168.1.1:80");
+
+ len = sizeof(ss);
+ r = evutil_parse_sockaddr_port("[ff00::8010]:999",
+ (struct sockaddr*)&ss, &len);
+ tt_int_op(r,==,0);
+ cp = evutil_format_sockaddr_port_(
+ (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+ tt_ptr_op(cp,==,cbuf);
+ tt_str_op(cp,==,"[ff00::8010]:999");
+
+ ss.ss_family=99;
+ cp = evutil_format_sockaddr_port_(
+ (struct sockaddr*)&ss, cbuf, sizeof(cbuf));
+ tt_ptr_op(cp,==,cbuf);
+ tt_str_op(cp,==,"<addr with socktype 99>");
+end:
+ ;
+}
+
+static struct sa_pred_ent {
+ const char *parse;
+
+ int is_loopback;
+} sa_pred_entries[] = {
+ { "127.0.0.1", 1 },
+ { "127.0.3.2", 1 },
+ { "128.1.2.3", 0 },
+ { "18.0.0.1", 0 },
+ { "129.168.1.1", 0 },
+
+ { "::1", 1 },
+ { "::0", 0 },
+ { "f::1", 0 },
+ { "::501", 0 },
+ { NULL, 0 },
+
+};
+
+static void
+test_evutil_sockaddr_predicates(void *ptr)
+{
+ struct sockaddr_storage ss;
+ int r, i;
+
+ for (i=0; sa_pred_entries[i].parse; ++i) {
+ struct sa_pred_ent *ent = &sa_pred_entries[i];
+ int len = sizeof(ss);
+
+ r = evutil_parse_sockaddr_port(ent->parse, (struct sockaddr*)&ss, &len);
+
+ if (r<0) {
+ TT_FAIL(("Couldn't parse %s!", ent->parse));
+ continue;
+ }
+
+ /* sockaddr_is_loopback */
+ if (ent->is_loopback != evutil_sockaddr_is_loopback_((struct sockaddr*)&ss)) {
+ TT_FAIL(("evutil_sockaddr_loopback(%s) not as expected",
+ ent->parse));
+ }
+ }
+}
+
+static void
+test_evutil_strtoll(void *ptr)
+{
+ const char *s;
+ char *endptr;
+
+ tt_want(evutil_strtoll("5000000000", NULL, 10) ==
+ ((ev_int64_t)5000000)*1000);
+ tt_want(evutil_strtoll("-5000000000", NULL, 10) ==
+ ((ev_int64_t)5000000)*-1000);
+ s = " 99999stuff";
+ tt_want(evutil_strtoll(s, &endptr, 10) == (ev_int64_t)99999);
+ tt_want(endptr == s+6);
+ tt_want(evutil_strtoll("foo", NULL, 10) == 0);
+ }
+
+static void
+test_evutil_snprintf(void *ptr)
+{
+ char buf[16];
+ int r;
+ ev_uint64_t u64 = ((ev_uint64_t)1000000000)*200;
+ ev_int64_t i64 = -1 * (ev_int64_t) u64;
+ size_t size = 8000;
+ ev_ssize_t ssize = -9000;
+
+ r = evutil_snprintf(buf, sizeof(buf), "%d %d", 50, 100);
+ tt_str_op(buf, ==, "50 100");
+ tt_int_op(r, ==, 6);
+
+ r = evutil_snprintf(buf, sizeof(buf), "longish %d", 1234567890);
+ tt_str_op(buf, ==, "longish 1234567");
+ tt_int_op(r, ==, 18);
+
+ r = evutil_snprintf(buf, sizeof(buf), EV_U64_FMT, EV_U64_ARG(u64));
+ tt_str_op(buf, ==, "200000000000");
+ tt_int_op(r, ==, 12);
+
+ r = evutil_snprintf(buf, sizeof(buf), EV_I64_FMT, EV_I64_ARG(i64));
+ tt_str_op(buf, ==, "-200000000000");
+ tt_int_op(r, ==, 13);
+
+ r = evutil_snprintf(buf, sizeof(buf), EV_SIZE_FMT" "EV_SSIZE_FMT,
+ EV_SIZE_ARG(size), EV_SSIZE_ARG(ssize));
+ tt_str_op(buf, ==, "8000 -9000");
+ tt_int_op(r, ==, 10);
+
+ end:
+ ;
+}
+
+static void
+test_evutil_casecmp(void *ptr)
+{
+ tt_int_op(evutil_ascii_strcasecmp("ABC", "ABC"), ==, 0);
+ tt_int_op(evutil_ascii_strcasecmp("ABC", "abc"), ==, 0);
+ tt_int_op(evutil_ascii_strcasecmp("ABC", "abcd"), <, 0);
+ tt_int_op(evutil_ascii_strcasecmp("ABC", "abb"), >, 0);
+ tt_int_op(evutil_ascii_strcasecmp("ABCd", "abc"), >, 0);
+
+ tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 100), ==, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEvEnT", 4), ==, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibEXXXX", 4), ==, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Libevent", "LibE", 4), ==, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Libe", "LibEvEnT", 4), ==, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Lib", "LibEvEnT", 4), <, 0);
+ tt_int_op(evutil_ascii_strncasecmp("abc", "def", 99), <, 0);
+ tt_int_op(evutil_ascii_strncasecmp("Z", "qrst", 1), >, 0);
+end:
+ ;
+}
+
+static void
+test_evutil_rtrim(void *ptr)
+{
+#define TEST_TRIM(s, result) \
+ do { \
+ if (cp) mm_free(cp); \
+ cp = mm_strdup(s); \
+ tt_assert(cp); \
+ evutil_rtrim_lws_(cp); \
+ tt_str_op(cp, ==, result); \
+ } while(0)
+
+ char *cp = NULL;
+ (void) ptr;
+
+ TEST_TRIM("", "");
+ TEST_TRIM("a", "a");
+ TEST_TRIM("abcdef ghi", "abcdef ghi");
+
+ TEST_TRIM(" ", "");
+ TEST_TRIM(" ", "");
+ TEST_TRIM("a ", "a");
+ TEST_TRIM("abcdef gH ", "abcdef gH");
+
+ TEST_TRIM("\t\t", "");
+ TEST_TRIM(" \t", "");
+ TEST_TRIM("\t", "");
+ TEST_TRIM("a \t", "a");
+ TEST_TRIM("a\t ", "a");
+ TEST_TRIM("a\t", "a");
+ TEST_TRIM("abcdef gH \t ", "abcdef gH");
+
+end:
+ if (cp)
+ mm_free(cp);
+}
+
+static int logsev = 0;
+static char *logmsg = NULL;
+
+static void
+logfn(int severity, const char *msg)
+{
+ logsev = severity;
+ tt_want(msg);
+ if (msg) {
+ if (logmsg)
+ free(logmsg);
+ logmsg = strdup(msg);
+ }
+}
+
+static int fatal_want_severity = 0;
+static const char *fatal_want_message = NULL;
+static void
+fatalfn(int exitcode)
+{
+ if (logsev != fatal_want_severity ||
+ !logmsg ||
+ strcmp(logmsg, fatal_want_message))
+ exit(0);
+ else
+ exit(exitcode);
+}
+
+#ifndef _WIN32
+#define CAN_CHECK_ERR
+static void
+check_error_logging(void (*fn)(void), int wantexitcode,
+ int wantseverity, const char *wantmsg)
+{
+ pid_t pid;
+ int status = 0, exitcode;
+ fatal_want_severity = wantseverity;
+ fatal_want_message = wantmsg;
+ if ((pid = regress_fork()) == 0) {
+ /* child process */
+ fn();
+ exit(0); /* should be unreachable. */
+ } else {
+ wait(&status);
+ exitcode = WEXITSTATUS(status);
+ tt_int_op(wantexitcode, ==, exitcode);
+ }
+end:
+ ;
+}
+
+static void
+errx_fn(void)
+{
+ event_errx(2, "Fatal error; too many kumquats (%d)", 5);
+}
+
+static void
+err_fn(void)
+{
+ errno = ENOENT;
+ event_err(5,"Couldn't open %s", "/very/bad/file");
+}
+
+static void
+sock_err_fn(void)
+{
+ evutil_socket_t fd = socket(AF_INET, SOCK_STREAM, 0);
+#ifdef _WIN32
+ EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
+#else
+ errno = EAGAIN;
+#endif
+ event_sock_err(20, fd, "Unhappy socket");
+}
+#endif
+
+static void
+test_evutil_log(void *ptr)
+{
+ evutil_socket_t fd = -1;
+ char buf[128];
+
+ event_set_log_callback(logfn);
+ event_set_fatal_callback(fatalfn);
+#define RESET() do { \
+ logsev = 0; \
+ if (logmsg) free(logmsg); \
+ logmsg = NULL; \
+ } while (0)
+#define LOGEQ(sev,msg) do { \
+ tt_int_op(logsev,==,sev); \
+ tt_assert(logmsg != NULL); \
+ tt_str_op(logmsg,==,msg); \
+ } while (0)
+
+#ifdef CAN_CHECK_ERR
+ /* We need to disable these tests for now. Previously, the logging
+ * module didn't enforce the requirement that a fatal callback
+ * actually exit. Now, it exits no matter what, so if we wan to
+ * reinstate these tests, we'll need to fork for each one. */
+ check_error_logging(errx_fn, 2, EVENT_LOG_ERR,
+ "Fatal error; too many kumquats (5)");
+ RESET();
+#endif
+
+ event_warnx("Far too many %s (%d)", "wombats", 99);
+ LOGEQ(EVENT_LOG_WARN, "Far too many wombats (99)");
+ RESET();
+
+ event_msgx("Connecting lime to coconut");
+ LOGEQ(EVENT_LOG_MSG, "Connecting lime to coconut");
+ RESET();
+
+ event_debug(("A millisecond passed! We should log that!"));
+#ifdef USE_DEBUG
+ LOGEQ(EVENT_LOG_DEBUG, "A millisecond passed! We should log that!");
+#else
+ tt_int_op(logsev,==,0);
+ tt_ptr_op(logmsg,==,NULL);
+#endif
+ RESET();
+
+ /* Try with an errno. */
+ errno = ENOENT;
+ event_warn("Couldn't open %s", "/bad/file");
+ evutil_snprintf(buf, sizeof(buf),
+ "Couldn't open /bad/file: %s",strerror(ENOENT));
+ LOGEQ(EVENT_LOG_WARN,buf);
+ RESET();
+
+#ifdef CAN_CHECK_ERR
+ evutil_snprintf(buf, sizeof(buf),
+ "Couldn't open /very/bad/file: %s",strerror(ENOENT));
+ check_error_logging(err_fn, 5, EVENT_LOG_ERR, buf);
+ RESET();
+#endif
+
+ /* Try with a socket errno. */
+ fd = socket(AF_INET, SOCK_STREAM, 0);
+#ifdef _WIN32
+ evutil_snprintf(buf, sizeof(buf),
+ "Unhappy socket: %s",
+ evutil_socket_error_to_string(WSAEWOULDBLOCK));
+ EVUTIL_SET_SOCKET_ERROR(WSAEWOULDBLOCK);
+#else
+ evutil_snprintf(buf, sizeof(buf),
+ "Unhappy socket: %s", strerror(EAGAIN));
+ errno = EAGAIN;
+#endif
+ event_sock_warn(fd, "Unhappy socket");
+ LOGEQ(EVENT_LOG_WARN, buf);
+ RESET();
+
+#ifdef CAN_CHECK_ERR
+ check_error_logging(sock_err_fn, 20, EVENT_LOG_ERR, buf);
+ RESET();
+#endif
+
+#undef RESET
+#undef LOGEQ
+end:
+ if (logmsg)
+ free(logmsg);
+ if (fd >= 0)
+ evutil_closesocket(fd);
+}
+
+static void
+test_evutil_strlcpy(void *arg)
+{
+ char buf[8];
+
+ /* Successful case. */
+ tt_int_op(5, ==, strlcpy(buf, "Hello", sizeof(buf)));
+ tt_str_op(buf, ==, "Hello");
+
+ /* Overflow by a lot. */
+ tt_int_op(13, ==, strlcpy(buf, "pentasyllabic", sizeof(buf)));
+ tt_str_op(buf, ==, "pentasy");
+
+ /* Overflow by exactly one. */
+ tt_int_op(8, ==, strlcpy(buf, "overlong", sizeof(buf)));
+ tt_str_op(buf, ==, "overlon");
+end:
+ ;
+}
+
+struct example_struct {
+ const char *a;
+ const char *b;
+ long c;
+};
+
+static void
+test_evutil_upcast(void *arg)
+{
+ struct example_struct es1;
+ const char **cp;
+ es1.a = "World";
+ es1.b = "Hello";
+ es1.c = -99;
+
+ tt_int_op(evutil_offsetof(struct example_struct, b), ==, sizeof(char*));
+
+ cp = &es1.b;
+ tt_ptr_op(EVUTIL_UPCAST(cp, struct example_struct, b), ==, &es1);
+
+end:
+ ;
+}
+
+static void
+test_evutil_integers(void *arg)
+{
+ ev_int64_t i64;
+ ev_uint64_t u64;
+ ev_int32_t i32;
+ ev_uint32_t u32;
+ ev_int16_t i16;
+ ev_uint16_t u16;
+ ev_int8_t i8;
+ ev_uint8_t u8;
+
+ void *ptr;
+ ev_intptr_t iptr;
+ ev_uintptr_t uptr;
+
+ ev_ssize_t ssize;
+
+ tt_int_op(sizeof(u64), ==, 8);
+ tt_int_op(sizeof(i64), ==, 8);
+ tt_int_op(sizeof(u32), ==, 4);
+ tt_int_op(sizeof(i32), ==, 4);
+ tt_int_op(sizeof(u16), ==, 2);
+ tt_int_op(sizeof(i16), ==, 2);
+ tt_int_op(sizeof(u8), ==, 1);
+ tt_int_op(sizeof(i8), ==, 1);
+
+ tt_int_op(sizeof(ev_ssize_t), ==, sizeof(size_t));
+ tt_int_op(sizeof(ev_intptr_t), >=, sizeof(void *));
+ tt_int_op(sizeof(ev_uintptr_t), ==, sizeof(intptr_t));
+
+ u64 = 1000000000;
+ u64 *= 1000000000;
+ tt_assert(u64 / 1000000000 == 1000000000);
+ i64 = -1000000000;
+ i64 *= 1000000000;
+ tt_assert(i64 / 1000000000 == -1000000000);
+
+ u64 = EV_UINT64_MAX;
+ i64 = EV_INT64_MAX;
+ tt_assert(u64 > 0);
+ tt_assert(i64 > 0);
+ u64++;
+/* i64++; */
+ tt_assert(u64 == 0);
+/* tt_assert(i64 == EV_INT64_MIN); */
+/* tt_assert(i64 < 0); */
+
+ u32 = EV_UINT32_MAX;
+ i32 = EV_INT32_MAX;
+ tt_assert(u32 > 0);
+ tt_assert(i32 > 0);
+ u32++;
+/* i32++; */
+ tt_assert(u32 == 0);
+/* tt_assert(i32 == EV_INT32_MIN); */
+/* tt_assert(i32 < 0); */
+
+ u16 = EV_UINT16_MAX;
+ i16 = EV_INT16_MAX;
+ tt_assert(u16 > 0);
+ tt_assert(i16 > 0);
+ u16++;
+/* i16++; */
+ tt_assert(u16 == 0);
+/* tt_assert(i16 == EV_INT16_MIN); */
+/* tt_assert(i16 < 0); */
+
+ u8 = EV_UINT8_MAX;
+ i8 = EV_INT8_MAX;
+ tt_assert(u8 > 0);
+ tt_assert(i8 > 0);
+ u8++;
+/* i8++;*/
+ tt_assert(u8 == 0);
+/* tt_assert(i8 == EV_INT8_MIN); */
+/* tt_assert(i8 < 0); */
+
+/*
+ ssize = EV_SSIZE_MAX;
+ tt_assert(ssize > 0);
+ ssize++;
+ tt_assert(ssize < 0);
+ tt_assert(ssize == EV_SSIZE_MIN);
+*/
+
+ ptr = &ssize;
+ iptr = (ev_intptr_t)ptr;
+ uptr = (ev_uintptr_t)ptr;
+ ptr = (void *)iptr;
+ tt_assert(ptr == &ssize);
+ ptr = (void *)uptr;
+ tt_assert(ptr == &ssize);
+
+ iptr = -1;
+ tt_assert(iptr < 0);
+end:
+ ;
+}
+
+struct evutil_addrinfo *
+ai_find_by_family(struct evutil_addrinfo *ai, int family)
+{
+ while (ai) {
+ if (ai->ai_family == family)
+ return ai;
+ ai = ai->ai_next;
+ }
+ return NULL;
+}
+
+struct evutil_addrinfo *
+ai_find_by_protocol(struct evutil_addrinfo *ai, int protocol)
+{
+ while (ai) {
+ if (ai->ai_protocol == protocol)
+ return ai;
+ ai = ai->ai_next;
+ }
+ return NULL;
+}
+
+
+int
+test_ai_eq_(const struct evutil_addrinfo *ai, const char *sockaddr_port,
+ int socktype, int protocol, int line)
+{
+ struct sockaddr_storage ss;
+ int slen = sizeof(ss);
+ int gotport;
+ char buf[128];
+ memset(&ss, 0, sizeof(ss));
+ if (socktype > 0)
+ tt_int_op(ai->ai_socktype, ==, socktype);
+ if (protocol > 0)
+ tt_int_op(ai->ai_protocol, ==, protocol);
+
+ if (evutil_parse_sockaddr_port(
+ sockaddr_port, (struct sockaddr*)&ss, &slen)<0) {
+ TT_FAIL(("Couldn't parse expected address %s on line %d",
+ sockaddr_port, line));
+ return -1;
+ }
+ if (ai->ai_family != ss.ss_family) {
+ TT_FAIL(("Address family %d did not match %d on line %d",
+ ai->ai_family, ss.ss_family, line));
+ return -1;
+ }
+ if (ai->ai_addr->sa_family == AF_INET) {
+ struct sockaddr_in *sin = (struct sockaddr_in*)ai->ai_addr;
+ evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
+ gotport = ntohs(sin->sin_port);
+ if (ai->ai_addrlen != sizeof(struct sockaddr_in)) {
+ TT_FAIL(("Addr size mismatch on line %d", line));
+ return -1;
+ }
+ } else {
+ struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)ai->ai_addr;
+ evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf, sizeof(buf));
+ gotport = ntohs(sin6->sin6_port);
+ if (ai->ai_addrlen != sizeof(struct sockaddr_in6)) {
+ TT_FAIL(("Addr size mismatch on line %d", line));
+ return -1;
+ }
+ }
+ if (evutil_sockaddr_cmp(ai->ai_addr, (struct sockaddr*)&ss, 1)) {
+ TT_FAIL(("Wanted %s, got %s:%d on line %d", sockaddr_port,
+ buf, gotport, line));
+ return -1;
+ } else {
+ TT_BLATHER(("Wanted %s, got %s:%d on line %d", sockaddr_port,
+ buf, gotport, line));
+ }
+ return 0;
+end:
+ TT_FAIL(("Test failed on line %d", line));
+ return -1;
+}
+
+static void
+test_evutil_rand(void *arg)
+{
+ char buf1[32];
+ char buf2[32];
+ int counts[256];
+ int i, j, k, n=0;
+ struct evutil_weakrand_state seed = { 12346789U };
+
+ memset(buf2, 0, sizeof(buf2));
+ memset(counts, 0, sizeof(counts));
+
+ for (k=0;k<32;++k) {
+ /* Try a few different start and end points; try to catch
+ * the various misaligned cases of arc4random_buf */
+ int startpoint = evutil_weakrand_(&seed) % 4;
+ int endpoint = 32 - (evutil_weakrand_(&seed) % 4);
+
+ memset(buf2, 0, sizeof(buf2));
+
+ /* Do 6 runs over buf1, or-ing the result into buf2 each
+ * time, to make sure we're setting each byte that we mean
+ * to set. */
+ for (i=0;i<8;++i) {
+ memset(buf1, 0, sizeof(buf1));
+ evutil_secure_rng_get_bytes(buf1 + startpoint,
+ endpoint-startpoint);
+ n += endpoint - startpoint;
+ for (j=0; j<32; ++j) {
+ if (j >= startpoint && j < endpoint) {
+ buf2[j] |= buf1[j];
+ ++counts[(unsigned char)buf1[j]];
+ } else {
+ tt_assert(buf1[j] == 0);
+ tt_int_op(buf1[j], ==, 0);
+
+ }
+ }
+ }
+
+ /* This will give a false positive with P=(256**8)==(2**64)
+ * for each character. */
+ for (j=startpoint;j<endpoint;++j) {
+ tt_int_op(buf2[j], !=, 0);
+ }
+ }
+
+ evutil_weakrand_seed_(&seed, 0);
+ for (i = 0; i < 10000; ++i) {
+ ev_int32_t r = evutil_weakrand_range_(&seed, 9999);
+ tt_int_op(0, <=, r);
+ tt_int_op(r, <, 9999);
+ }
+
+ /* for (i=0;i<256;++i) { printf("%3d %2d\n", i, counts[i]); } */
+end:
+ ;
+}
+
+static void
+test_EVUTIL_IS_(void *arg)
+{
+ tt_int_op(EVUTIL_ISDIGIT_('0'), ==, 1);
+ tt_int_op(EVUTIL_ISDIGIT_('a'), ==, 0);
+ tt_int_op(EVUTIL_ISDIGIT_('\xff'), ==, 0);
+end:
+ ;
+}
+
+static void
+test_evutil_getaddrinfo(void *arg)
+{
+ struct evutil_addrinfo *ai = NULL, *a;
+ struct evutil_addrinfo hints;
+ int r;
+
+ /* Try using it as a pton. */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evutil_getaddrinfo("1.2.3.4", "8080", &hints, &ai);
+ tt_int_op(r, ==, 0);
+ tt_assert(ai);
+ tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
+ test_ai_eq(ai, "1.2.3.4:8080", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_protocol = IPPROTO_UDP;
+ r = evutil_getaddrinfo("1001:b0b::f00f", "4321", &hints, &ai);
+ tt_int_op(r, ==, 0);
+ tt_assert(ai);
+ tt_ptr_op(ai->ai_next, ==, NULL); /* no ambiguity */
+ test_ai_eq(ai, "[1001:b0b::f00f]:4321", SOCK_DGRAM, IPPROTO_UDP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ /* Try out the behavior of nodename=NULL */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_INET;
+ hints.ai_protocol = IPPROTO_TCP;
+ hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind */
+ r = evutil_getaddrinfo(NULL, "9999", &hints, &ai);
+ tt_int_op(r,==,0);
+ tt_assert(ai);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ test_ai_eq(ai, "0.0.0.0:9999", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+ hints.ai_flags = 0; /* as if for connect */
+ r = evutil_getaddrinfo(NULL, "9998", &hints, &ai);
+ tt_assert(ai);
+ tt_int_op(r,==,0);
+ test_ai_eq(ai, "127.0.0.1:9998", SOCK_STREAM, IPPROTO_TCP);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ hints.ai_flags = 0; /* as if for connect */
+ hints.ai_family = PF_INET6;
+ r = evutil_getaddrinfo(NULL, "9997", &hints, &ai);
+ tt_assert(ai);
+ tt_int_op(r,==,0);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ test_ai_eq(ai, "[::1]:9997", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ hints.ai_flags = EVUTIL_AI_PASSIVE; /* as if for bind. */
+ hints.ai_family = PF_INET6;
+ r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
+ tt_assert(ai);
+ tt_int_op(r,==,0);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ test_ai_eq(ai, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ /* Now try an unspec one. We should get a v6 and a v4. */
+ hints.ai_family = PF_UNSPEC;
+ r = evutil_getaddrinfo(NULL, "9996", &hints, &ai);
+ tt_assert(ai);
+ tt_int_op(r,==,0);
+ a = ai_find_by_family(ai, PF_INET6);
+ tt_assert(a);
+ test_ai_eq(a, "[::]:9996", SOCK_STREAM, IPPROTO_TCP);
+ a = ai_find_by_family(ai, PF_INET);
+ tt_assert(a);
+ test_ai_eq(a, "0.0.0.0:9996", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ /* Try out AI_NUMERICHOST: successful case. Also try
+ * multiprotocol. */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+ r = evutil_getaddrinfo("1.2.3.4", NULL, &hints, &ai);
+ tt_int_op(r, ==, 0);
+ a = ai_find_by_protocol(ai, IPPROTO_TCP);
+ tt_assert(a);
+ test_ai_eq(a, "1.2.3.4", SOCK_STREAM, IPPROTO_TCP);
+ a = ai_find_by_protocol(ai, IPPROTO_UDP);
+ tt_assert(a);
+ test_ai_eq(a, "1.2.3.4", SOCK_DGRAM, IPPROTO_UDP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ /* Try the failing case of AI_NUMERICHOST */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_flags = EVUTIL_AI_NUMERICHOST;
+ r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
+ tt_int_op(r, ==, EVUTIL_EAI_NONAME);
+ tt_ptr_op(ai, ==, NULL);
+
+ /* Try symbolic service names wit AI_NUMERICSERV */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = EVUTIL_AI_NUMERICSERV;
+ r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
+ tt_int_op(r,==,EVUTIL_EAI_NONAME);
+
+ /* Try symbolic service names */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evutil_getaddrinfo("1.2.3.4", "http", &hints, &ai);
+ if (r!=0) {
+ TT_DECLARE("SKIP", ("Symbolic service names seem broken."));
+ } else {
+ tt_assert(ai);
+ test_ai_eq(ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+ }
+
+end:
+ if (ai)
+ evutil_freeaddrinfo(ai);
+}
+
+static void
+test_evutil_getaddrinfo_live(void *arg)
+{
+ struct evutil_addrinfo *ai = NULL;
+ struct evutil_addrinfo hints;
+
+ struct sockaddr_in6 *sin6;
+ struct sockaddr_in *sin;
+ char buf[128];
+ const char *cp;
+ int r;
+
+ /* Now do some actual lookups. */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_INET;
+ hints.ai_protocol = IPPROTO_TCP;
+ hints.ai_socktype = SOCK_STREAM;
+ r = evutil_getaddrinfo("www.google.com", "80", &hints, &ai);
+ if (r != 0) {
+ TT_DECLARE("SKIP", ("Couldn't resolve www.google.com"));
+ } else {
+ tt_assert(ai);
+ tt_int_op(ai->ai_family, ==, PF_INET);
+ tt_int_op(ai->ai_protocol, ==, IPPROTO_TCP);
+ tt_int_op(ai->ai_socktype, ==, SOCK_STREAM);
+ tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in));
+ sin = (struct sockaddr_in*)ai->ai_addr;
+ tt_int_op(sin->sin_family, ==, AF_INET);
+ tt_int_op(sin->sin_port, ==, htons(80));
+ tt_int_op(sin->sin_addr.s_addr, !=, 0xffffffff);
+
+ cp = evutil_inet_ntop(AF_INET, &sin->sin_addr, buf, sizeof(buf));
+ TT_BLATHER(("www.google.com resolved to %s",
+ cp?cp:"<unwriteable>"));
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+ }
+
+ hints.ai_family = PF_INET6;
+ r = evutil_getaddrinfo("ipv6.google.com", "80", &hints, &ai);
+ if (r != 0) {
+ TT_BLATHER(("Couldn't do an ipv6 lookup for ipv6.google.com"));
+ } else {
+ tt_assert(ai);
+ tt_int_op(ai->ai_family, ==, PF_INET6);
+ tt_int_op(ai->ai_addrlen, ==, sizeof(struct sockaddr_in6));
+ sin6 = (struct sockaddr_in6*)ai->ai_addr;
+ tt_int_op(sin6->sin6_port, ==, htons(80));
+
+ cp = evutil_inet_ntop(AF_INET6, &sin6->sin6_addr, buf,
+ sizeof(buf));
+ TT_BLATHER(("ipv6.google.com resolved to %s",
+ cp?cp:"<unwriteable>"));
+ }
+
+end:
+ if (ai)
+ evutil_freeaddrinfo(ai);
+}
+
+static void
+test_evutil_getaddrinfo_AI_ADDRCONFIG(void *arg)
+{
+ struct evutil_addrinfo *ai = NULL;
+ struct evutil_addrinfo hints;
+ int r;
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = EVUTIL_AI_PASSIVE|EVUTIL_AI_ADDRCONFIG;
+
+ /* IPv4 */
+ r = evutil_getaddrinfo("127.0.0.1", "80", &hints, &ai);
+ tt_int_op(r, ==, 0);
+ tt_assert(ai);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ test_ai_eq(ai, "127.0.0.1:80", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+ /* IPv6 */
+ r = evutil_getaddrinfo("::1", "80", &hints, &ai);
+ tt_int_op(r, ==, 0);
+ tt_assert(ai);
+ tt_ptr_op(ai->ai_next, ==, NULL);
+ test_ai_eq(ai, "[::1]:80", SOCK_STREAM, IPPROTO_TCP);
+ evutil_freeaddrinfo(ai);
+ ai = NULL;
+
+end:
+ if (ai)
+ evutil_freeaddrinfo(ai);
+}
+
+#ifdef _WIN32
+static void
+test_evutil_loadsyslib(void *arg)
+{
+ HMODULE h=NULL;
+
+ h = evutil_load_windows_system_library_(TEXT("kernel32.dll"));
+ tt_assert(h);
+
+end:
+ if (h)
+ CloseHandle(h);
+
+}
+#endif
+
+/** Test mm_malloc(). */
+static void
+test_event_malloc(void *arg)
+{
+ void *p = NULL;
+ (void)arg;
+
+ /* mm_malloc(0) should simply return NULL. */
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+ errno = 0;
+ p = mm_malloc(0);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, 0);
+#endif
+
+ /* Trivial case. */
+ errno = 0;
+ p = mm_malloc(8);
+ tt_assert(p != NULL);
+ tt_int_op(errno, ==, 0);
+ mm_free(p);
+
+ end:
+ errno = 0;
+ return;
+}
+
+static void
+test_event_calloc(void *arg)
+{
+ void *p = NULL;
+ (void)arg;
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+ /* mm_calloc() should simply return NULL
+ * if either argument is zero. */
+ errno = 0;
+ p = mm_calloc(0, 0);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, 0);
+ errno = 0;
+ p = mm_calloc(0, 1);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, 0);
+ errno = 0;
+ p = mm_calloc(1, 0);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, 0);
+#endif
+
+ /* Trivial case. */
+ errno = 0;
+ p = mm_calloc(8, 8);
+ tt_assert(p != NULL);
+ tt_int_op(errno, ==, 0);
+ mm_free(p);
+ p = NULL;
+
+ /* mm_calloc() should set errno = ENOMEM and return NULL
+ * in case of potential overflow. */
+ errno = 0;
+ p = mm_calloc(EV_SIZE_MAX/2, EV_SIZE_MAX/2 + 8);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, ENOMEM);
+
+ end:
+ errno = 0;
+ if (p)
+ mm_free(p);
+
+ return;
+}
+
+static void
+test_event_strdup(void *arg)
+{
+ void *p = NULL;
+ (void)arg;
+
+#ifndef EVENT__DISABLE_MM_REPLACEMENT
+ /* mm_strdup(NULL) should set errno = EINVAL and return NULL. */
+ errno = 0;
+ p = mm_strdup(NULL);
+ tt_assert(p == NULL);
+ tt_int_op(errno, ==, EINVAL);
+#endif
+
+ /* Trivial cases. */
+
+ errno = 0;
+ p = mm_strdup("");
+ tt_assert(p != NULL);
+ tt_int_op(errno, ==, 0);
+ tt_str_op(p, ==, "");
+ mm_free(p);
+
+ errno = 0;
+ p = mm_strdup("foo");
+ tt_assert(p != NULL);
+ tt_int_op(errno, ==, 0);
+ tt_str_op(p, ==, "foo");
+ mm_free(p);
+
+ /* XXX
+ * mm_strdup(str) where str is a string of length EV_SIZE_MAX
+ * should set errno = ENOMEM and return NULL. */
+
+ end:
+ errno = 0;
+ return;
+}
+
+static void
+test_evutil_usleep(void *arg)
+{
+ struct timeval tv1, tv2, tv3, diff1, diff2;
+ const struct timeval quarter_sec = {0, 250*1000};
+ const struct timeval tenth_sec = {0, 100*1000};
+ long usec1, usec2;
+
+ evutil_gettimeofday(&tv1, NULL);
+ evutil_usleep_(&quarter_sec);
+ evutil_gettimeofday(&tv2, NULL);
+ evutil_usleep_(&tenth_sec);
+ evutil_gettimeofday(&tv3, NULL);
+
+ evutil_timersub(&tv2, &tv1, &diff1);
+ evutil_timersub(&tv3, &tv2, &diff2);
+ usec1 = diff1.tv_sec * 1000000 + diff1.tv_usec;
+ usec2 = diff2.tv_sec * 1000000 + diff2.tv_usec;
+
+ tt_int_op(usec1, >, 200000);
+ tt_int_op(usec1, <, 300000);
+ tt_int_op(usec2, >, 80000);
+ tt_int_op(usec2, <, 120000);
+
+end:
+ ;
+}
+
+static void
+test_evutil_monotonic_res(void *data_)
+{
+ /* Basic santity-test for monotonic timers. What we'd really like
+ * to do is make sure that they can't go backwards even when the
+ * system clock goes backwards. But we haven't got a good way to
+ * move the system clock backwards.
+ */
+ struct basic_test_data *data = data_;
+ struct evutil_monotonic_timer timer;
+ const int precise = strstr(data->setup_data, "precise") != NULL;
+ const int fallback = strstr(data->setup_data, "fallback") != NULL;
+ struct timeval tv[10], delay;
+ int total_diff = 0;
+
+ int flags = 0, wantres, acceptdiff, i;
+ if (precise)
+ flags |= EV_MONOT_PRECISE;
+ if (fallback)
+ flags |= EV_MONOT_FALLBACK;
+ if (precise || fallback) {
+#ifdef _WIN32
+ wantres = 10*1000;
+ acceptdiff = 1000;
+#else
+ wantres = 1000;
+ acceptdiff = 300;
+#endif
+ } else {
+ wantres = 40*1000;
+ acceptdiff = 20*1000;
+ }
+
+ TT_BLATHER(("Precise = %d", precise));
+ TT_BLATHER(("Fallback = %d", fallback));
+
+ /* First, make sure we match up with usleep. */
+
+ delay.tv_sec = 0;
+ delay.tv_usec = wantres;
+
+ tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
+
+ for (i = 0; i < 10; ++i) {
+ evutil_gettime_monotonic_(&timer, &tv[i]);
+ evutil_usleep_(&delay);
+ }
+
+ for (i = 0; i < 9; ++i) {
+ struct timeval diff;
+ tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
+ evutil_timersub(&tv[i+1], &tv[i], &diff);
+ tt_int_op(diff.tv_sec, ==, 0);
+ total_diff += diff.tv_usec;
+ TT_BLATHER(("Difference = %d", (int)diff.tv_usec));
+ }
+ tt_int_op(abs(total_diff/9 - wantres), <, acceptdiff);
+
+end:
+ ;
+}
+
+static void
+test_evutil_monotonic_prc(void *data_)
+{
+ struct basic_test_data *data = data_;
+ struct evutil_monotonic_timer timer;
+ const int precise = strstr(data->setup_data, "precise") != NULL;
+ const int fallback = strstr(data->setup_data, "fallback") != NULL;
+ struct timeval tv[10];
+ int total_diff = 0;
+ int i, maxstep = 25*1000,flags=0;
+ if (precise)
+ maxstep = 500;
+ if (precise)
+ flags |= EV_MONOT_PRECISE;
+ if (fallback)
+ flags |= EV_MONOT_FALLBACK;
+ tt_int_op(evutil_configure_monotonic_time_(&timer, flags), ==, 0);
+
+ /* find out what precision we actually see. */
+
+ evutil_gettime_monotonic_(&timer, &tv[0]);
+ for (i = 1; i < 10; ++i) {
+ do {
+ evutil_gettime_monotonic_(&timer, &tv[i]);
+ } while (evutil_timercmp(&tv[i-1], &tv[i], ==));
+ }
+
+ total_diff = 0;
+ for (i = 0; i < 9; ++i) {
+ struct timeval diff;
+ tt_assert(evutil_timercmp(&tv[i], &tv[i+1], <));
+ evutil_timersub(&tv[i+1], &tv[i], &diff);
+ tt_int_op(diff.tv_sec, ==, 0);
+ total_diff += diff.tv_usec;
+ TT_BLATHER(("Step difference = %d", (int)diff.tv_usec));
+ }
+ TT_BLATHER(("Average step difference = %d", total_diff / 9));
+ tt_int_op(total_diff/9, <, maxstep);
+
+end:
+ ;
+}
+
+static void
+create_tm_from_unix_epoch(struct tm *cur_p, const time_t t)
+{
+#ifdef _WIN32
+ struct tm *tmp = gmtime(&t);
+ if (!tmp) {
+ fprintf(stderr, "gmtime: %s (%i)", strerror(errno), (int)t);
+ exit(1);
+ }
+ *cur_p = *tmp;
+#else
+ gmtime_r(&t, cur_p);
+#endif
+}
+
+static struct date_rfc1123_case {
+ time_t t;
+ char date[30];
+} date_rfc1123_cases[] = {
+ { 0, "Thu, 01 Jan 1970 00:00:00 GMT"} /* UNIX time of zero */,
+ { 946684799, "Fri, 31 Dec 1999 23:59:59 GMT"} /* the last moment of the 20th century */,
+ { 946684800, "Sat, 01 Jan 2000 00:00:00 GMT"} /* the first moment of the 21st century */,
+ { 981072000, "Fri, 02 Feb 2001 00:00:00 GMT"},
+ { 1015113600, "Sun, 03 Mar 2002 00:00:00 GMT"},
+ { 1049414400, "Fri, 04 Apr 2003 00:00:00 GMT"},
+ { 1083715200, "Wed, 05 May 2004 00:00:00 GMT"},
+ { 1118016000, "Mon, 06 Jun 2005 00:00:00 GMT"},
+ { 1152230400, "Fri, 07 Jul 2006 00:00:00 GMT"},
+ { 1186531200, "Wed, 08 Aug 2007 00:00:00 GMT"},
+ { 1220918400, "Tue, 09 Sep 2008 00:00:00 GMT"},
+ { 1255132800, "Sat, 10 Oct 2009 00:00:00 GMT"},
+ { 1289433600, "Thu, 11 Nov 2010 00:00:00 GMT"},
+ { 1323648000, "Mon, 12 Dec 2011 00:00:00 GMT"},
+#ifndef _WIN32
+#if EVENT__SIZEOF_TIME_T > 4
+ /** In win32 case we have max "23:59:59 January 18, 2038, UTC" for time32 */
+ { 4294967296, "Sun, 07 Feb 2106 06:28:16 GMT"} /* 2^32 */,
+ /** In win32 case we have max "23:59:59, December 31, 3000, UTC" for time64 */
+ {253402300799, "Fri, 31 Dec 9999 23:59:59 GMT"} /* long long future no one can imagine */,
+#endif /* time_t != 32bit */
+ { 1456704000, "Mon, 29 Feb 2016 00:00:00 GMT"} /* leap year */,
+#endif
+ { 1435708800, "Wed, 01 Jul 2015 00:00:00 GMT"} /* leap second */,
+ { 1481866376, "Fri, 16 Dec 2016 05:32:56 GMT"} /* the time this test case is generated */,
+ {0, ""} /* end of test cases. */
+};
+
+static void
+test_evutil_date_rfc1123(void *arg)
+{
+ struct tm query;
+ char result[30];
+ size_t i = 0;
+
+ /* Checks if too small buffers are safely accepted. */
+ {
+ create_tm_from_unix_epoch(&query, 0);
+ evutil_date_rfc1123(result, 8, &query);
+ tt_str_op(result, ==, "Thu, 01");
+ }
+
+ /* Checks for testcases. */
+ for (i = 0; ; i++) {
+ struct date_rfc1123_case c = date_rfc1123_cases[i];
+
+ if (strlen(c.date) == 0)
+ break;
+
+ create_tm_from_unix_epoch(&query, c.t);
+ evutil_date_rfc1123(result, sizeof(result), &query);
+ tt_str_op(result, ==, c.date);
+ }
+
+end:
+ ;
+}
+
+static void
+test_evutil_v4addr_is_local(void *arg)
+{
+ struct sockaddr_in sin;
+ sin.sin_family = AF_INET;
+
+ /* we use evutil_inet_pton() here to fill in network-byte order */
+#define LOCAL(str, yes) do { \
+ tt_int_op(evutil_inet_pton(AF_INET, str, &sin.sin_addr), ==, 1); \
+ tt_int_op(evutil_v4addr_is_local_(&sin.sin_addr), ==, yes); \
+} while (0)
+
+ /** any */
+ sin.sin_addr.s_addr = INADDR_ANY;
+ tt_int_op(evutil_v4addr_is_local_(&sin.sin_addr), ==, 1);
+
+ /** loopback */
+ sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ tt_int_op(evutil_v4addr_is_local_(&sin.sin_addr), ==, 1);
+ LOCAL("127.0.0.1", 1);
+ LOCAL("127.255.255.255", 1);
+ LOCAL("121.0.0.1", 0);
+
+ /** link-local */
+ LOCAL("169.254.0.1", 1);
+ LOCAL("169.254.255.255", 1);
+ LOCAL("170.0.0.0", 0);
+
+ /** Multicast */
+ LOCAL("224.0.0.0", 1);
+ LOCAL("239.255.255.255", 1);
+ LOCAL("240.0.0.0", 0);
+end:
+ ;
+}
+
+static void
+test_evutil_v6addr_is_local(void *arg)
+{
+ struct sockaddr_in6 sin6;
+ struct in6_addr anyaddr = IN6ADDR_ANY_INIT;
+ struct in6_addr loopback = IN6ADDR_LOOPBACK_INIT;
+
+ sin6.sin6_family = AF_INET6;
+#define LOCAL6(str, yes) do { \
+ tt_int_op(evutil_inet_pton(AF_INET6, str, &sin6.sin6_addr), ==, 1);\
+ tt_int_op(evutil_v6addr_is_local_(&sin6.sin6_addr), ==, yes); \
+} while (0)
+
+ /** any */
+ tt_int_op(evutil_v6addr_is_local_(&anyaddr), ==, 1);
+ LOCAL6("::0", 1);
+
+ /** loopback */
+ tt_int_op(evutil_v6addr_is_local_(&loopback), ==, 1);
+ LOCAL6("::1", 1);
+
+ /** IPV4 mapped */
+ LOCAL6("::ffff:0:0", 1);
+ /** IPv4 translated */
+ LOCAL6("::ffff:0:0:0", 1);
+ /** IPv4/IPv6 translation */
+ LOCAL6("64:ff9b::", 0);
+ /** Link-local */
+ LOCAL6("fe80::", 1);
+ /** Multicast */
+ LOCAL6("ff00::", 1);
+ /** Unspecified */
+ LOCAL6("::", 1);
+
+ /** Global Internet */
+ LOCAL6("2001::", 0);
+ LOCAL6("2001:4860:4802:32::1b", 0);
+end:
+ ;
+}
+
+struct testcase_t util_testcases[] = {
+ { "ipv4_parse", regress_ipv4_parse, 0, NULL, NULL },
+ { "ipv6_parse", regress_ipv6_parse, 0, NULL, NULL },
+ { "ipv6_parse_scope", regress_ipv6_parse_scope, 0, NULL, NULL },
+ { "sockaddr_port_parse", regress_sockaddr_port_parse, 0, NULL, NULL },
+ { "sockaddr_port_format", regress_sockaddr_port_format, 0, NULL, NULL },
+ { "sockaddr_predicates", test_evutil_sockaddr_predicates, 0,NULL,NULL },
+ { "evutil_snprintf", test_evutil_snprintf, 0, NULL, NULL },
+ { "evutil_strtoll", test_evutil_strtoll, 0, NULL, NULL },
+ { "evutil_casecmp", test_evutil_casecmp, 0, NULL, NULL },
+ { "evutil_rtrim", test_evutil_rtrim, 0, NULL, NULL },
+ { "strlcpy", test_evutil_strlcpy, 0, NULL, NULL },
+ { "log", test_evutil_log, TT_FORK, NULL, NULL },
+ { "upcast", test_evutil_upcast, 0, NULL, NULL },
+ { "integers", test_evutil_integers, 0, NULL, NULL },
+ { "rand", test_evutil_rand, TT_FORK, NULL, NULL },
+ { "EVUTIL_IS_", test_EVUTIL_IS_, 0, NULL, NULL },
+ { "getaddrinfo", test_evutil_getaddrinfo, TT_FORK, NULL, NULL },
+ { "getaddrinfo_live", test_evutil_getaddrinfo_live, TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
+ { "getaddrinfo_AI_ADDRCONFIG", test_evutil_getaddrinfo_AI_ADDRCONFIG, TT_FORK|TT_OFF_BY_DEFAULT, NULL, NULL },
+#ifdef _WIN32
+ { "loadsyslib", test_evutil_loadsyslib, TT_FORK, NULL, NULL },
+#endif
+ { "mm_malloc", test_event_malloc, 0, NULL, NULL },
+ { "mm_calloc", test_event_calloc, 0, NULL, NULL },
+ { "mm_strdup", test_event_strdup, 0, NULL, NULL },
+ { "usleep", test_evutil_usleep, TT_RETRIABLE, NULL, NULL },
+ { "monotonic_res", test_evutil_monotonic_res, 0, &basic_setup, (void*)"" },
+ { "monotonic_res_precise", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"precise" },
+ { "monotonic_res_fallback", test_evutil_monotonic_res, TT_OFF_BY_DEFAULT, &basic_setup, (void*)"fallback" },
+ { "monotonic_prc", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"" },
+ { "monotonic_prc_precise", test_evutil_monotonic_prc, TT_RETRIABLE, &basic_setup, (void*)"precise" },
+ { "monotonic_prc_fallback", test_evutil_monotonic_prc, 0, &basic_setup, (void*)"fallback" },
+ { "date_rfc1123", test_evutil_date_rfc1123, 0, NULL, NULL },
+ { "evutil_v4addr_is_local", test_evutil_v4addr_is_local, 0, NULL, NULL },
+ { "evutil_v6addr_is_local", test_evutil_v6addr_is_local, 0, NULL, NULL },
+ END_OF_TESTCASES,
+};
+
diff --git a/ipc/chromium/src/third_party/libevent/test/regress_zlib.c b/ipc/chromium/src/third_party/libevent/test/regress_zlib.c
new file mode 100644
index 0000000000..5fe774913e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/regress_zlib.c
@@ -0,0 +1,348 @@
+/*
+ * Copyright (c) 2008-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* The old tests here need assertions to work. */
+#undef NDEBUG
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#endif
+
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#ifndef _WIN32
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#include <netdb.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <assert.h>
+#include <errno.h>
+
+#include "event2/util.h"
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/buffer.h"
+#include "event2/bufferevent.h"
+
+#include "regress.h"
+#include "mm-internal.h"
+
+/* zlib 1.2.4 and 1.2.5 do some "clever" things with macros. Instead of
+ saying "(defined(FOO) ? FOO : 0)" they like to say "FOO-0", on the theory
+ that nobody will care if the compile outputs a no-such-identifier warning.
+
+ Sorry, but we like -Werror over here, so I guess we need to define these.
+ I hope that zlib 1.2.6 doesn't break these too.
+*/
+#ifndef _LARGEFILE64_SOURCE
+#define _LARGEFILE64_SOURCE 0
+#endif
+#ifndef _LFS64_LARGEFILE
+#define _LFS64_LARGEFILE 0
+#endif
+#ifndef _FILE_OFFSET_BITS
+#define _FILE_OFFSET_BITS 0
+#endif
+#ifndef off64_t
+#define off64_t ev_int64_t
+#endif
+
+#include <zlib.h>
+
+static int infilter_calls;
+static int outfilter_calls;
+static int readcb_finished;
+static int writecb_finished;
+static int errorcb_invoked;
+
+/*
+ * Zlib filters
+ */
+
+static void
+zlib_deflate_free(void *ctx)
+{
+ z_streamp p = ctx;
+
+ assert(deflateEnd(p) == Z_OK);
+ mm_free(p);
+}
+
+static void
+zlib_inflate_free(void *ctx)
+{
+ z_streamp p = ctx;
+
+ assert(inflateEnd(p) == Z_OK);
+ mm_free(p);
+}
+
+static int
+getstate(enum bufferevent_flush_mode state)
+{
+ switch (state) {
+ case BEV_FINISHED:
+ return Z_FINISH;
+ case BEV_FLUSH:
+ return Z_SYNC_FLUSH;
+ case BEV_NORMAL:
+ default:
+ return Z_NO_FLUSH;
+ }
+}
+
+/*
+ * The input filter is triggered only on new input read from the network.
+ * That means all input data needs to be consumed or the filter needs to
+ * initiate its own triggering via a timeout.
+ */
+static enum bufferevent_filter_result
+zlib_input_filter(struct evbuffer *src, struct evbuffer *dst,
+ ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+ struct evbuffer_iovec v_in[1];
+ struct evbuffer_iovec v_out[1];
+ int nread, nwrite;
+ int res, n;
+
+ z_streamp p = ctx;
+
+ do {
+ /* let's do some decompression */
+ n = evbuffer_peek(src, -1, NULL, v_in, 1);
+ if (n) {
+ p->avail_in = v_in[0].iov_len;
+ p->next_in = (unsigned char *)v_in[0].iov_base;
+ } else {
+ p->avail_in = 0;
+ p->next_in = 0;
+ }
+
+ evbuffer_reserve_space(dst, 4096, v_out, 1);
+ p->next_out = (unsigned char *)v_out[0].iov_base;
+ p->avail_out = v_out[0].iov_len;
+
+ /* we need to flush zlib if we got a flush */
+ res = inflate(p, getstate(state));
+
+ /* let's figure out how much was compressed */
+ nread = v_in[0].iov_len - p->avail_in;
+ nwrite = v_out[0].iov_len - p->avail_out;
+
+ evbuffer_drain(src, nread);
+ v_out[0].iov_len = nwrite;
+ evbuffer_commit_space(dst, v_out, 1);
+
+ if (res==Z_BUF_ERROR) {
+ /* We're out of space, or out of decodeable input.
+ Only if nwrite == 0 assume the latter.
+ */
+ if (nwrite == 0)
+ return BEV_NEED_MORE;
+ } else {
+ assert(res == Z_OK || res == Z_STREAM_END);
+ }
+
+ } while (evbuffer_get_length(src) > 0);
+
+ ++infilter_calls;
+
+ return (BEV_OK);
+}
+
+static enum bufferevent_filter_result
+zlib_output_filter(struct evbuffer *src, struct evbuffer *dst,
+ ev_ssize_t lim, enum bufferevent_flush_mode state, void *ctx)
+{
+ struct evbuffer_iovec v_in[1];
+ struct evbuffer_iovec v_out[1];
+ int nread, nwrite;
+ int res, n;
+
+ z_streamp p = ctx;
+
+ do {
+ /* let's do some compression */
+ n = evbuffer_peek(src, -1, NULL, v_in, 1);
+ if (n) {
+ p->avail_in = v_in[0].iov_len;
+ p->next_in = (unsigned char *)v_in[0].iov_base;
+ } else {
+ p->avail_in = 0;
+ p->next_in = 0;
+ }
+
+ evbuffer_reserve_space(dst, 4096, v_out, 1);
+ p->next_out = (unsigned char *)v_out[0].iov_base;
+ p->avail_out = v_out[0].iov_len;
+
+ /* we need to flush zlib if we got a flush */
+ res = deflate(p, getstate(state));
+
+ /* let's figure out how much was decompressed */
+ nread = v_in[0].iov_len - p->avail_in;
+ nwrite = v_out[0].iov_len - p->avail_out;
+
+ evbuffer_drain(src, nread);
+ v_out[0].iov_len = nwrite;
+ evbuffer_commit_space(dst, v_out, 1);
+
+ if (res==Z_BUF_ERROR) {
+ /* We're out of space, or out of decodeable input.
+ Only if nwrite == 0 assume the latter.
+ */
+ if (nwrite == 0)
+ return BEV_NEED_MORE;
+ } else {
+ assert(res == Z_OK || res == Z_STREAM_END);
+ }
+
+ } while (evbuffer_get_length(src) > 0);
+
+ ++outfilter_calls;
+
+ return (BEV_OK);
+}
+
+/*
+ * simple bufferevent test (over transparent zlib treatment)
+ */
+
+static void
+readcb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bufferevent_get_input(bev)) == 8333) {
+ struct evbuffer *evbuf = evbuffer_new();
+ assert(evbuf != NULL);
+
+ /* gratuitous test of bufferevent_read_buffer */
+ bufferevent_read_buffer(bev, evbuf);
+
+ bufferevent_disable(bev, EV_READ);
+
+ if (evbuffer_get_length(evbuf) == 8333) {
+ ++readcb_finished;
+ }
+
+ evbuffer_free(evbuf);
+ }
+}
+
+static void
+writecb(struct bufferevent *bev, void *arg)
+{
+ if (evbuffer_get_length(bufferevent_get_output(bev)) == 0) {
+ ++writecb_finished;
+ }
+}
+
+static void
+errorcb(struct bufferevent *bev, short what, void *arg)
+{
+ errorcb_invoked = 1;
+}
+
+void
+test_bufferevent_zlib(void *arg)
+{
+ struct bufferevent *bev1=NULL, *bev2=NULL;
+ char buffer[8333];
+ z_stream *z_input, *z_output;
+ int i, r;
+ evutil_socket_t pair[2] = {-1, -1};
+ (void)arg;
+
+ infilter_calls = outfilter_calls = readcb_finished = writecb_finished
+ = errorcb_invoked = 0;
+
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1) {
+ tt_abort_perror("socketpair");
+ }
+
+ evutil_make_socket_nonblocking(pair[0]);
+ evutil_make_socket_nonblocking(pair[1]);
+
+ bev1 = bufferevent_socket_new(NULL, pair[0], 0);
+ bev2 = bufferevent_socket_new(NULL, pair[1], 0);
+
+ z_output = mm_calloc(sizeof(*z_output), 1);
+ r = deflateInit(z_output, Z_DEFAULT_COMPRESSION);
+ tt_int_op(r, ==, Z_OK);
+ z_input = mm_calloc(sizeof(*z_input), 1);
+ r = inflateInit(z_input);
+ tt_int_op(r, ==, Z_OK);
+
+ /* initialize filters */
+ bev1 = bufferevent_filter_new(bev1, NULL, zlib_output_filter,
+ BEV_OPT_CLOSE_ON_FREE, zlib_deflate_free, z_output);
+ bev2 = bufferevent_filter_new(bev2, zlib_input_filter,
+ NULL, BEV_OPT_CLOSE_ON_FREE, zlib_inflate_free, z_input);
+ bufferevent_setcb(bev1, readcb, writecb, errorcb, NULL);
+ bufferevent_setcb(bev2, readcb, writecb, errorcb, NULL);
+
+ bufferevent_disable(bev1, EV_READ);
+ bufferevent_enable(bev1, EV_WRITE);
+
+ bufferevent_enable(bev2, EV_READ);
+
+ for (i = 0; i < (int)sizeof(buffer); i++)
+ buffer[i] = i;
+
+ /* break it up into multiple buffer chains */
+ bufferevent_write(bev1, buffer, 1800);
+ bufferevent_write(bev1, buffer + 1800, sizeof(buffer) - 1800);
+
+ /* we are done writing - we need to flush everything */
+ bufferevent_flush(bev1, EV_WRITE, BEV_FINISHED);
+
+ event_dispatch();
+
+ tt_want(infilter_calls);
+ tt_want(outfilter_calls);
+ tt_want(readcb_finished);
+ tt_want(writecb_finished);
+ tt_want(!errorcb_invoked);
+
+ test_ok = 1;
+end:
+ if (bev1)
+ bufferevent_free(bev1);
+ if (bev2)
+ bufferevent_free(bev2);
+
+ if (pair[0] >= 0)
+ evutil_closesocket(pair[0]);
+ if (pair[1] >= 0)
+ evutil_closesocket(pair[1]);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/rpcgen_wrapper.sh b/ipc/chromium/src/third_party/libevent/test/rpcgen_wrapper.sh
new file mode 100755
index 0000000000..fe582d57bd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/rpcgen_wrapper.sh
@@ -0,0 +1,43 @@
+#!/bin/sh
+# libevent rpcgen_wrapper.sh
+# Transforms event_rpcgen.py failure into success for make, only if
+# regress.gen.c and regress.gen.h already exist in $srcdir. This
+# is needed for "make distcheck" to pass the read-only $srcdir build,
+# as with read-only sources fresh from tarball, regress.gen.[ch] will
+# be correct in $srcdir but unwritable. This previously triggered
+# Makefile.am to create stub regress.gen.c and regress.gen.h in the
+# distcheck _build directory, which were then detected as leftover
+# files in the build tree after distclean, breaking distcheck.
+# Note that regress.gen.[ch] are not in fresh git clones, making
+# working Python a requirement for make distcheck of a git tree.
+
+exit_updated() {
+# echo "Updated ${srcdir}/regress.gen.c and ${srcdir}/regress.gen.h"
+ exit 0
+}
+
+exit_reuse() {
+ echo "event_rpcgen.py failed, ${srcdir}/regress.gen.\[ch\] will be reused." >&2
+ exit 0
+}
+
+exit_failed() {
+ echo "Could not generate regress.gen.\[ch\] using event_rpcgen.sh" >&2
+ exit 1
+}
+srcdir=$1
+srcdir=${srcdir:-.}
+
+${srcdir}/../event_rpcgen.py --quiet ${srcdir}/regress.rpc \
+ test/regress.gen.h test/regress.gen.c
+
+case "$?" in
+ 0)
+ exit_updated
+ ;;
+ *)
+ test -r ${srcdir}/regress.gen.c -a -r ${srcdir}/regress.gen.h && \
+ exit_reuse
+ exit_failed
+ ;;
+esac
diff --git a/ipc/chromium/src/third_party/libevent/test/test-changelist.c b/ipc/chromium/src/third_party/libevent/test/test-changelist.c
new file mode 100644
index 0000000000..fd1a17f5bd
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-changelist.c
@@ -0,0 +1,224 @@
+/*
+ * Copyright (c) 2010-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/util.h"
+#include <time.h>
+
+struct cpu_usage_timer {
+#ifdef _WIN32
+ HANDLE thread;
+ FILETIME usertimeBegin;
+ FILETIME kerneltimeBegin;
+#else
+ clock_t ticksBegin;
+#endif
+ struct timeval timeBegin;
+};
+static void
+start_cpu_usage_timer(struct cpu_usage_timer *timer)
+{
+#ifdef _WIN32
+ int r;
+ FILETIME createtime, exittime;
+ timer->thread = GetCurrentThread();
+ r = GetThreadTimes(timer->thread, &createtime, &exittime,
+ &timer->usertimeBegin, &timer->kerneltimeBegin);
+ if (r==0) printf("GetThreadTimes failed.");
+#else
+ timer->ticksBegin = clock();
+#endif
+
+ evutil_gettimeofday(&timer->timeBegin, NULL);
+}
+#ifdef _WIN32
+static ev_int64_t
+filetime_to_100nsec(const FILETIME *ft)
+{
+ /* Number of 100-nanosecond units */
+ ev_int64_t n = ft->dwHighDateTime;
+ n <<= 32;
+ n += ft->dwLowDateTime;
+ return n;
+}
+static double
+filetime_diff(const FILETIME *ftStart, const FILETIME *ftEnd)
+{
+ ev_int64_t s, e, diff;
+ double r;
+ s = filetime_to_100nsec(ftStart);
+ e = filetime_to_100nsec(ftEnd);
+ diff = e - s;
+ r = (double) diff;
+ return r / 1.0e7;
+}
+#endif
+
+static void
+get_cpu_usage(struct cpu_usage_timer *timer, double *secElapsedOut,
+ double *secUsedOut, double *usageOut)
+{
+#ifdef _WIN32
+ double usertime_seconds, kerneltime_seconds;
+ FILETIME createtime, exittime, usertimeEnd, kerneltimeEnd;
+ int r;
+#else
+ clock_t ticksEnd;
+#endif
+ struct timeval timeEnd, timeDiff;
+ double secondsPassed, secondsUsed;
+
+#ifdef _WIN32
+ r = GetThreadTimes(timer->thread, &createtime, &exittime,
+ &usertimeEnd, &kerneltimeEnd);
+ if (r==0) printf("GetThreadTimes failed.");
+ usertime_seconds = filetime_diff(&timer->usertimeBegin, &usertimeEnd);
+ kerneltime_seconds = filetime_diff(&timer->kerneltimeBegin, &kerneltimeEnd);
+ secondsUsed = kerneltime_seconds + usertime_seconds;
+#else
+ ticksEnd = clock();
+ secondsUsed = (ticksEnd - timer->ticksBegin) / (double)CLOCKS_PER_SEC;
+#endif
+ evutil_gettimeofday(&timeEnd, NULL);
+ evutil_timersub(&timeEnd, &timer->timeBegin, &timeDiff);
+ secondsPassed = timeDiff.tv_sec + (timeDiff.tv_usec / 1.0e6);
+
+ *secElapsedOut = secondsPassed;
+ *secUsedOut = secondsUsed;
+ *usageOut = secondsUsed / secondsPassed;
+}
+
+static void
+write_cb(evutil_socket_t fd, short event, void *arg)
+{
+ printf("write callback. should only see this once\n");
+
+ /* got what we want remove the event */
+ event_del(*(struct event**)arg);
+
+ /* opps changed my mind add it back again */
+ event_add(*(struct event**)arg,NULL);
+
+ /* not a good day for decisiveness, I really didn't want it after all */
+ event_del(*(struct event**)arg);
+
+}
+
+static void
+timeout_cb(evutil_socket_t fd, short event, void *arg)
+{
+ printf("timeout fired, time to end test\n");
+ event_del(*(struct event**)arg);
+ return;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event* ev;
+ struct event* timeout;
+ struct event_base* base;
+
+ evutil_socket_t pair[2];
+ struct timeval tv;
+ struct cpu_usage_timer timer;
+
+ double usage, secPassed, secUsed;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+ return (1);
+
+ /* Initialize the event library */
+ if (!(base = event_base_new()))
+ return (1);
+
+ /* Initialize a timeout to terminate the test */
+ timeout = evtimer_new(base,timeout_cb,&timeout);
+ /* and watch for writability on one end of the pipe */
+ ev = event_new(base,pair[1],EV_WRITE | EV_PERSIST, write_cb, &ev);
+
+ tv.tv_sec = 1;
+ tv.tv_usec = 500*1000;
+
+ evtimer_add(timeout, &tv);
+
+ event_add(ev, NULL);
+
+ start_cpu_usage_timer(&timer);
+
+ event_base_dispatch(base);
+
+ event_free(ev);
+ event_free(timeout);
+ event_base_free(base);
+
+ get_cpu_usage(&timer, &secPassed, &secUsed, &usage);
+
+ /* attempt to calculate our cpu usage over the test should be
+ virtually nil */
+
+ printf("usec used=%d, usec passed=%d, cpu usage=%.2f%%\n",
+ (int)(secUsed*1e6),
+ (int)(secPassed*1e6),
+ usage*100);
+
+ if (usage > 50.0) /* way too high */
+ return 1;
+
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-closed.c b/ipc/chromium/src/third_party/libevent/test/test-closed.c
new file mode 100644
index 0000000000..9e6050408d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-closed.c
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2013 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+#include <evutil.h>
+
+struct timeval timeout = {3, 0};
+
+static void
+closed_cb(evutil_socket_t fd, short event, void *arg)
+{
+ if (EV_TIMEOUT & event) {
+ printf("%s: Timeout!\n", __func__);
+ exit(1);
+ }
+
+ if (EV_CLOSED & event) {
+ printf("%s: detected socket close with success\n", __func__);
+ return;
+ }
+
+ printf("%s: unable to detect socket close\n", __func__);
+ exit(1);
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event_base *base;
+ struct event_config *cfg;
+ struct event *ev;
+ const char *test = "test string";
+ evutil_socket_t pair[2];
+
+ /* Initialize the library and check if the backend
+ supports EV_FEATURE_EARLY_CLOSE
+ */
+ cfg = event_config_new();
+ event_config_require_features(cfg, EV_FEATURE_EARLY_CLOSE);
+ base = event_base_new_with_config(cfg);
+ event_config_free(cfg);
+ if (!base) {
+ /* Backend doesn't support EV_FEATURE_EARLY_CLOSE */
+ return 0;
+ }
+
+ /* Create a pair of sockets */
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+ return (1);
+
+ /* Send some data on socket 0 and immediately close it */
+ if (send(pair[0], test, (int)strlen(test)+1, 0) < 0)
+ return (1);
+ shutdown(pair[0], EVUTIL_SHUT_WR);
+
+ /* Dispatch */
+ ev = event_new(base, pair[1], EV_CLOSED | EV_TIMEOUT, closed_cb, event_self_cbarg());
+ event_add(ev, &timeout);
+ event_base_dispatch(base);
+
+ /* Finalize library */
+ event_free(ev);
+ event_base_free(base);
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-dumpevents.c b/ipc/chromium/src/third_party/libevent/test/test-dumpevents.c
new file mode 100644
index 0000000000..1c272d4c01
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-dumpevents.c
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+
+#include <stdio.h>
+#include <event2/event.h>
+#include <signal.h>
+
+static void
+sock_perror(const char *s)
+{
+#ifdef _WIN32
+ const char *err = evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR());
+ fprintf(stderr, "%s: %s\n", s, err);
+#else
+ perror(s);
+#endif
+}
+
+static void
+callback1(evutil_socket_t fd, short events, void *arg)
+{
+}
+static void
+callback2(evutil_socket_t fd, short events, void *arg)
+{
+}
+
+/* Testing code for event_base_dump_events().
+
+ Notes that just because we have code to exercise this function,
+ doesn't mean that *ANYTHING* about the output format is guaranteed to
+ remain in the future.
+ */
+int
+main(int argc, char **argv)
+{
+#define N_EVENTS 13
+ int i;
+ struct event *ev[N_EVENTS];
+ evutil_socket_t pair1[2];
+ evutil_socket_t pair2[2];
+ struct timeval tv_onesec = {1,0};
+ struct timeval tv_two5sec = {2,500*1000};
+ const struct timeval *tv_onesec_common;
+ const struct timeval *tv_two5sec_common;
+ struct event_base *base;
+ struct timeval now;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifdef _WIN32
+#define LOCAL_SOCKETPAIR_AF AF_INET
+#else
+#define LOCAL_SOCKETPAIR_AF AF_UNIX
+#endif
+
+ if (evutil_make_internal_pipe_(pair1) < 0 ||
+ evutil_make_internal_pipe_(pair2) < 0) {
+ sock_perror("evutil_make_internal_pipe_");
+ return 1;
+ }
+
+ if (!(base = event_base_new())) {
+ fprintf(stderr,"Couldn't make event_base\n");
+ return 2;
+ }
+
+ tv_onesec_common = event_base_init_common_timeout(base, &tv_onesec);
+ tv_two5sec_common = event_base_init_common_timeout(base, &tv_two5sec);
+
+ ev[0] = event_new(base, pair1[0], EV_WRITE, callback1, NULL);
+ ev[1] = event_new(base, pair1[1], EV_READ|EV_PERSIST, callback1, NULL);
+ ev[2] = event_new(base, pair2[0], EV_WRITE|EV_PERSIST, callback2, NULL);
+ ev[3] = event_new(base, pair2[1], EV_READ, callback2, NULL);
+
+ /* For timers */
+ ev[4] = evtimer_new(base, callback1, NULL);
+ ev[5] = evtimer_new(base, callback1, NULL);
+ ev[6] = evtimer_new(base, callback1, NULL);
+ ev[7] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+ ev[8] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+ ev[9] = event_new(base, -1, EV_PERSIST, callback2, NULL);
+
+ /* To activate */
+ ev[10] = event_new(base, -1, 0, callback1, NULL);
+ ev[11] = event_new(base, -1, 0, callback2, NULL);
+
+ /* Signals */
+ ev[12] = evsignal_new(base, SIGINT, callback2, NULL);
+
+ event_add(ev[0], NULL);
+ event_add(ev[1], &tv_onesec);
+ event_add(ev[2], tv_onesec_common);
+ event_add(ev[3], tv_two5sec_common);
+
+ event_add(ev[4], tv_onesec_common);
+ event_add(ev[5], tv_onesec_common);
+ event_add(ev[6], &tv_onesec);
+ event_add(ev[7], tv_two5sec_common);
+ event_add(ev[8], tv_onesec_common);
+ event_add(ev[9], &tv_two5sec);
+
+ event_active(ev[10], EV_READ, 1);
+ event_active(ev[11], EV_READ|EV_WRITE|EV_TIMEOUT, 1);
+ event_active(ev[1], EV_READ, 1);
+
+ event_add(ev[12], NULL);
+
+ evutil_gettimeofday(&now,NULL);
+ puts("=====expected");
+ printf("Now= %ld.%06d\n",(long)now.tv_sec,(int)now.tv_usec);
+ puts("Inserted:");
+ printf(" %p [fd %ld] Write\n",ev[0],(long)pair1[0]);
+ printf(" %p [fd %ld] Read Persist Timeout=T+1\n",ev[1],(long)pair1[1]);
+ printf(" %p [fd %ld] Write Persist Timeout=T+1\n",ev[2],(long)pair2[0]);
+ printf(" %p [fd %ld] Read Timeout=T+2.5\n",ev[3],(long)pair2[1]);
+ printf(" %p [fd -1] Timeout=T+1\n",ev[4]);
+ printf(" %p [fd -1] Timeout=T+1\n",ev[5]);
+ printf(" %p [fd -1] Timeout=T+1\n",ev[6]);
+ printf(" %p [fd -1] Persist Timeout=T+2.5\n",ev[7]);
+ printf(" %p [fd -1] Persist Timeout=T+1\n",ev[8]);
+ printf(" %p [fd -1] Persist Timeout=T+2.5\n",ev[9]);
+ printf(" %p [sig %d] Signal Persist\n", ev[12], (int)SIGINT);
+
+ puts("Active:");
+ printf(" %p [fd -1, priority=0] Read active\n", ev[10]);
+ printf(" %p [fd -1, priority=0] Read Write Timeout active\n", ev[11]);
+ printf(" %p [fd %ld, priority=0] Read active\n", ev[1], (long)pair1[1]);
+
+ puts("======received");
+ event_base_dump_events(base, stdout);
+
+ for (i = 0; i < N_EVENTS; ++i) {
+ event_free(ev[i]);
+ }
+ event_base_free(base);
+
+ return 0;
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-eof.c b/ipc/chromium/src/third_party/libevent/test/test-eof.c
new file mode 100644
index 0000000000..de2fd88b99
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-eof.c
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+
+#include <event.h>
+#include <evutil.h>
+
+int test_okay = 1;
+int called = 0;
+struct timeval timeout = {60, 0};
+
+static void
+read_cb(evutil_socket_t fd, short event, void *arg)
+{
+ char buf[256];
+ int len;
+
+ if (EV_TIMEOUT & event) {
+ printf("%s: Timeout!\n", __func__);
+ exit(1);
+ }
+
+ len = recv(fd, buf, sizeof(buf), 0);
+
+ printf("%s: read %d%s\n", __func__,
+ len, len ? "" : " - means EOF");
+
+ if (len) {
+ if (!called)
+ event_add(arg, &timeout);
+ } else if (called == 1)
+ test_okay = 0;
+
+ called++;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event ev;
+ const char *test = "test string";
+ evutil_socket_t pair[2];
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+ return (1);
+
+
+ if (send(pair[0], test, (int)strlen(test)+1, 0) < 0)
+ return (1);
+ shutdown(pair[0], EVUTIL_SHUT_WR);
+
+ /* Initialize the event library */
+ event_init();
+
+ /* Initialize one event */
+ event_set(&ev, pair[1], EV_READ | EV_TIMEOUT, read_cb, &ev);
+
+ event_add(&ev, &timeout);
+
+ event_dispatch();
+
+ return (test_okay);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-fdleak.c b/ipc/chromium/src/third_party/libevent/test/test-fdleak.c
new file mode 100644
index 0000000000..a1fb4ed13b
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-fdleak.c
@@ -0,0 +1,252 @@
+/*
+ * Copyright (c) 2012 Ross Lagerwall <rosslagerwall@gmail.com>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#include <windows.h>
+#endif
+#include <string.h>
+#include <stdlib.h>
+#include <errno.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_RESOURCE_H
+#include <sys/resource.h>
+#endif
+#ifdef EVENT__HAVE_NETINET_IN_H
+#include <netinet/in.h>
+#endif
+
+#include "event2/event.h"
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/listener.h"
+
+/* Number of requests to make. Setting this too high might result in the machine
+ running out of ephemeral ports */
+#ifdef _WIN32
+#define MAX_REQUESTS 1000
+#else
+#define MAX_REQUESTS 4000
+#endif
+
+/* Provide storage for the address, both for the server & the clients */
+static struct sockaddr_in saddr;
+
+/* Number of sucessful requests so far */
+static int num_requests;
+
+static void start_client(struct event_base *base);
+
+static void
+my_perror(const char *s)
+{
+ fprintf(stderr, "%s: %s",
+ s, evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR()));
+}
+
+/*
+===============================================
+Server functions
+===============================================
+*/
+
+/* Read a byte from the client and write it back */
+static void
+server_read_cb(struct bufferevent *bev, void *ctx)
+{
+ while (evbuffer_get_length(bufferevent_get_input(bev))) {
+ unsigned char tmp;
+ bufferevent_read(bev, &tmp, 1);
+ bufferevent_write(bev, &tmp, 1);
+ }
+}
+
+/* Wait for an EOF and then free the bufferevent */
+static void
+server_event_cb(struct bufferevent *bev, short events, void *ctx)
+{
+ if (events & BEV_EVENT_ERROR) {
+ my_perror("Error from bufferevent");
+ exit(1);
+ } else if (events & BEV_EVENT_EOF) {
+ bufferevent_free(bev);
+ if (num_requests == MAX_REQUESTS) {
+ event_base_loopbreak(bufferevent_get_base(bev));
+ }
+ }
+}
+
+/* Accept a client socket and set it up to for reading & writing */
+static void
+listener_accept_cb(struct evconnlistener *listener, evutil_socket_t sock,
+ struct sockaddr *addr, int len, void *ptr)
+{
+ struct event_base *base = evconnlistener_get_base(listener);
+ struct bufferevent *bev = bufferevent_socket_new(base, sock,
+ BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev, server_read_cb, NULL, server_event_cb, NULL);
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+}
+
+/* Start the server listening on a random port and start the first client. */
+static void
+start_loop(void)
+{
+ struct event_base *base;
+ struct evconnlistener *listener;
+ struct sockaddr_storage ss;
+ ev_socklen_t socklen = sizeof(ss);
+ evutil_socket_t fd;
+
+ base = event_base_new();
+ if (base == NULL) {
+ puts("Could not open event base!");
+ exit(1);
+ }
+
+ listener = evconnlistener_new_bind(base, listener_accept_cb, NULL,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE,
+ -1, (struct sockaddr *)&saddr, sizeof(saddr));
+ if (listener == NULL) {
+ my_perror("Could not create listener!");
+ exit(1);
+ }
+ fd = evconnlistener_get_fd(listener);
+ if (fd < 0) {
+ puts("Couldn't get fd from listener");
+ exit(1);
+ }
+ if (getsockname(fd, (struct sockaddr *)&ss, &socklen) < 0) {
+ my_perror("getsockname()");
+ exit(1);
+ }
+ memcpy(&saddr, &ss, sizeof(saddr));
+ if (saddr.sin_family != AF_INET) {
+ puts("AF mismatch from getsockname().");
+ exit(1);
+ }
+
+ start_client(base);
+
+ event_base_dispatch(base);
+
+ evconnlistener_free(listener);
+ event_base_free(base);
+}
+
+/*
+===============================================
+Client functions
+===============================================
+*/
+
+/* Check that the server sends back the same byte that the client sent.
+ If MAX_REQUESTS have been reached, exit. Otherwise, start another client. */
+static void
+client_read_cb(struct bufferevent *bev, void *ctx)
+{
+ unsigned char tmp;
+ struct event_base *base = bufferevent_get_base(bev);
+
+ bufferevent_read(bev, &tmp, 1);
+ if (tmp != 'A') {
+ puts("Incorrect data received!");
+ exit(2);
+ }
+ bufferevent_free(bev);
+
+ num_requests++;
+ if (++num_requests < MAX_REQUESTS) {
+ start_client(base);
+ }
+}
+
+/* Send a byte to the server. */
+static void
+client_event_cb(struct bufferevent *bev, short events, void *ctx)
+{
+ if (events & BEV_EVENT_CONNECTED) {
+ unsigned char tmp = 'A';
+ bufferevent_write(bev, &tmp, 1);
+ } else if (events & BEV_EVENT_ERROR) {
+ puts("Client socket got error!");
+ exit(2);
+ }
+
+ bufferevent_enable(bev, EV_READ);
+}
+
+/* Open a client socket to connect to localhost on sin */
+static void
+start_client(struct event_base *base)
+{
+ struct bufferevent *bev = bufferevent_socket_new(base, -1,
+ BEV_OPT_CLOSE_ON_FREE);
+ bufferevent_setcb(bev, client_read_cb, NULL, client_event_cb, NULL);
+
+ if (bufferevent_socket_connect(bev, (struct sockaddr *)&saddr,
+ sizeof(saddr)) < 0) {
+ my_perror("Could not connect!");
+ bufferevent_free(bev);
+ exit(2);
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+#ifdef EVENT__HAVE_SETRLIMIT
+ /* Set the fd limit to a low value so that any fd leak is caught without
+ making many requests. */
+ struct rlimit rl;
+ rl.rlim_cur = rl.rlim_max = 20;
+ if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
+ my_perror("setrlimit");
+ exit(3);
+ }
+#endif
+
+#ifdef _WIN32
+ WSADATA WSAData;
+ WSAStartup(0x101, &WSAData);
+#endif
+
+ /* Set up an address, used by both client & server. */
+ memset(&saddr, 0, sizeof(saddr));
+ saddr.sin_family = AF_INET;
+ saddr.sin_addr.s_addr = htonl(0x7f000001);
+ saddr.sin_port = 0; /* Tell the implementation to pick a port. */
+
+ start_loop();
+
+ return 0;
+}
+
+/* XXX why does this test cause so much latency sometimes (OSX 10.5)? */
diff --git a/ipc/chromium/src/third_party/libevent/test/test-init.c b/ipc/chromium/src/third_party/libevent/test/test-init.c
new file mode 100644
index 0000000000..aea49ee942
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-init.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef _WIN32
+#include <unistd.h>
+#endif
+#include <errno.h>
+
+#include <event.h>
+
+int
+main(int argc, char **argv)
+{
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ /* Initialize the event library */
+ event_init();
+
+ return (0);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-ratelim.c b/ipc/chromium/src/third_party/libevent/test/test-ratelim.c
new file mode 100644
index 0000000000..34112e39e1
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-ratelim.c
@@ -0,0 +1,688 @@
+/*
+ * Copyright (c) 2009-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+#include <math.h>
+
+#ifdef _WIN32
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#else
+#include <sys/socket.h>
+#include <netinet/in.h>
+# ifdef _XOPEN_SOURCE_EXTENDED
+# include <arpa/inet.h>
+# endif
+#endif
+#include <signal.h>
+
+#include "event2/bufferevent.h"
+#include "event2/buffer.h"
+#include "event2/event.h"
+#include "event2/util.h"
+#include "event2/listener.h"
+#include "event2/thread.h"
+
+#ifndef MIN
+#define MIN(a,b) (((a)<(b))?(a):(b))
+#endif
+
+static struct evutil_weakrand_state weakrand_state;
+
+static int cfg_verbose = 0;
+static int cfg_help = 0;
+
+static int cfg_n_connections = 30;
+static int cfg_duration = 5;
+static int cfg_connlimit = 0;
+static int cfg_grouplimit = 0;
+static int cfg_tick_msec = 1000;
+static int cfg_min_share = -1;
+static int cfg_group_drain = 0;
+
+static int cfg_connlimit_tolerance = -1;
+static int cfg_grouplimit_tolerance = -1;
+static int cfg_stddev_tolerance = -1;
+
+#ifdef _WIN32
+static int cfg_enable_iocp = 0;
+#endif
+
+static struct timeval cfg_tick = { 0, 500*1000 };
+
+static struct ev_token_bucket_cfg *conn_bucket_cfg = NULL;
+static struct ev_token_bucket_cfg *group_bucket_cfg = NULL;
+struct bufferevent_rate_limit_group *ratelim_group = NULL;
+static double seconds_per_tick = 0.0;
+
+struct client_state {
+ size_t queued;
+ ev_uint64_t received;
+
+};
+static const struct timeval *ms100_common=NULL;
+
+/* Timers bias for slow CPUs, affects:
+ * - cfg_connlimit_tolerance (--check-connlimit)
+ * - cfg_grouplimit_tolerance (--check-grouplimit)
+ * - cfg_stddev_tolerance (--check-stddev)
+ */
+static int timer_bias_events;
+static struct timeval timer_bias_start;
+double timer_bias_spend;
+/* Real cost is less (approximately ~5 usec),
+ * this macros adjusted to make the bias less */
+#define TIMER_MAX_COST_USEC 10
+
+/* info from check_bucket_levels_cb */
+static int total_n_bev_checks = 0;
+static ev_int64_t total_rbucket_level=0;
+static ev_int64_t total_wbucket_level=0;
+static ev_int64_t total_max_to_read=0;
+static ev_int64_t total_max_to_write=0;
+static ev_int64_t max_bucket_level=EV_INT64_MIN;
+static ev_int64_t min_bucket_level=EV_INT64_MAX;
+
+/* from check_group_bucket_levels_cb */
+static int total_n_group_bev_checks = 0;
+static ev_int64_t total_group_rbucket_level = 0;
+static ev_int64_t total_group_wbucket_level = 0;
+
+static int n_echo_conns_open = 0;
+
+/* Info on the open connections */
+struct bufferevent **bevs;
+struct client_state *states;
+struct bufferevent_rate_limit_group *group = NULL;
+
+static void check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg);
+
+static void
+loud_writecb(struct bufferevent *bev, void *ctx)
+{
+ struct client_state *cs = ctx;
+ struct evbuffer *output = bufferevent_get_output(bev);
+ char buf[1024];
+ int r = evutil_weakrand_(&weakrand_state);
+ memset(buf, r, sizeof(buf));
+ while (evbuffer_get_length(output) < 8192) {
+ evbuffer_add(output, buf, sizeof(buf));
+ cs->queued += sizeof(buf);
+ }
+}
+
+static void
+discard_readcb(struct bufferevent *bev, void *ctx)
+{
+ struct client_state *cs = ctx;
+ struct evbuffer *input = bufferevent_get_input(bev);
+ size_t len = evbuffer_get_length(input);
+ evbuffer_drain(input, len);
+ cs->received += len;
+}
+
+static void
+write_on_connectedcb(struct bufferevent *bev, short what, void *ctx)
+{
+ if (what & BEV_EVENT_CONNECTED) {
+ loud_writecb(bev, ctx);
+ /* XXXX this shouldn't be needed. */
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+ }
+}
+
+static void
+echo_readcb(struct bufferevent *bev, void *ctx)
+{
+ struct evbuffer *input = bufferevent_get_input(bev);
+ struct evbuffer *output = bufferevent_get_output(bev);
+
+ evbuffer_add_buffer(output, input);
+ if (evbuffer_get_length(output) > 1024000)
+ bufferevent_disable(bev, EV_READ);
+}
+
+static void
+echo_writecb(struct bufferevent *bev, void *ctx)
+{
+ struct evbuffer *output = bufferevent_get_output(bev);
+ if (evbuffer_get_length(output) < 512000)
+ bufferevent_enable(bev, EV_READ);
+}
+
+static void
+echo_eventcb(struct bufferevent *bev, short what, void *ctx)
+{
+ if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
+ --n_echo_conns_open;
+ bufferevent_free(bev);
+ }
+}
+
+static void
+echo_listenercb(struct evconnlistener *listener, evutil_socket_t newsock,
+ struct sockaddr *sourceaddr, int socklen, void *ctx)
+{
+ struct event_base *base = ctx;
+ int flags = BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE;
+ struct bufferevent *bev;
+
+ bev = bufferevent_socket_new(base, newsock, flags);
+ bufferevent_setcb(bev, echo_readcb, echo_writecb, echo_eventcb, NULL);
+ if (conn_bucket_cfg) {
+ struct event *check_event =
+ event_new(base, -1, EV_PERSIST, check_bucket_levels_cb, bev);
+ bufferevent_set_rate_limit(bev, conn_bucket_cfg);
+
+ assert(bufferevent_get_token_bucket_cfg(bev) != NULL);
+ event_add(check_event, ms100_common);
+ }
+ if (ratelim_group)
+ bufferevent_add_to_rate_limit_group(bev, ratelim_group);
+ ++n_echo_conns_open;
+ bufferevent_enable(bev, EV_READ|EV_WRITE);
+}
+
+/* Called periodically to check up on how full the buckets are */
+static void
+check_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct bufferevent *bev = arg;
+
+ ev_ssize_t r = bufferevent_get_read_limit(bev);
+ ev_ssize_t w = bufferevent_get_write_limit(bev);
+ ev_ssize_t rm = bufferevent_get_max_to_read(bev);
+ ev_ssize_t wm = bufferevent_get_max_to_write(bev);
+ /* XXXX check that no value is above the cofigured burst
+ * limit */
+ total_rbucket_level += r;
+ total_wbucket_level += w;
+ total_max_to_read += rm;
+ total_max_to_write += wm;
+#define B(x) \
+ if ((x) > max_bucket_level) \
+ max_bucket_level = (x); \
+ if ((x) < min_bucket_level) \
+ min_bucket_level = (x)
+ B(r);
+ B(w);
+#undef B
+
+ total_n_bev_checks++;
+ if (total_n_bev_checks >= .8 * ((double)cfg_duration / cfg_tick_msec) * cfg_n_connections) {
+ event_free(event_base_get_running_event(bufferevent_get_base(bev)));
+ }
+}
+
+static void
+check_group_bucket_levels_cb(evutil_socket_t fd, short events, void *arg)
+{
+ if (ratelim_group) {
+ ev_ssize_t r = bufferevent_rate_limit_group_get_read_limit(ratelim_group);
+ ev_ssize_t w = bufferevent_rate_limit_group_get_write_limit(ratelim_group);
+ total_group_rbucket_level += r;
+ total_group_wbucket_level += w;
+ }
+ ++total_n_group_bev_checks;
+}
+
+static void
+group_drain_cb(evutil_socket_t fd, short events, void *arg)
+{
+ bufferevent_rate_limit_group_decrement_read(ratelim_group, cfg_group_drain);
+ bufferevent_rate_limit_group_decrement_write(ratelim_group, cfg_group_drain);
+}
+
+static void
+timer_bias_cb(evutil_socket_t fd, short events, void *arg)
+{
+ struct event *event = arg;
+ struct timeval end;
+ struct timeval diff;
+
+ /** XXX: use rdtsc? (portability issues?) */
+ evutil_gettimeofday(&end, NULL);
+ evutil_timersub(&end, &timer_bias_start, &diff);
+ timer_bias_spend += diff.tv_sec + diff.tv_usec * 1e6;
+ timer_bias_start = end;
+
+ if (++timer_bias_events == 100)
+ event_del(event);
+}
+static double
+timer_bias_calculate(void)
+{
+ struct event_config *cfg = NULL;
+ struct event_base *base = NULL;
+ struct event *timer = NULL;
+ struct timeval tv = { 0, 1 };
+ int done = 0;
+
+ cfg = event_config_new();
+ if (!cfg)
+ goto err;
+ if (event_config_set_flag(cfg, EVENT_BASE_FLAG_PRECISE_TIMER))
+ goto err;
+ base = event_base_new_with_config(cfg);
+ if (!base)
+ goto err;
+
+ timer = event_new(base, -1, EV_PERSIST, timer_bias_cb, event_self_cbarg());
+ if (!timer || event_add(timer, &tv)) {
+ goto err;
+ }
+
+ evutil_gettimeofday(&timer_bias_start, NULL);
+ event_base_dispatch(base);
+ done = 1;
+
+err:
+ if (cfg)
+ event_config_free(cfg);
+ if (timer)
+ event_free(timer);
+ if (base)
+ event_base_free(base);
+
+ if (done)
+ return MIN(timer_bias_spend / 1e6 / timer_bias_events / TIMER_MAX_COST_USEC, 5);
+
+ fprintf(stderr, "Couldn't create event for CPU cycle counter bias\n");
+ return -1;
+}
+
+static int
+test_ratelimiting(void)
+{
+ struct event_base *base;
+ struct sockaddr_in sin;
+ struct evconnlistener *listener;
+
+ struct sockaddr_storage ss;
+ ev_socklen_t slen;
+
+ int i;
+
+ struct timeval tv;
+
+ ev_uint64_t total_received;
+ double total_sq_persec, total_persec;
+ double variance;
+ double expected_total_persec = -1.0, expected_avg_persec = -1.0;
+ int ok = 1;
+ struct event_config *base_cfg;
+ struct event *periodic_level_check;
+ struct event *group_drain_event=NULL;
+ double timer_bias;
+
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = AF_INET;
+ sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
+ sin.sin_port = 0; /* unspecified port */
+
+ if (0)
+ event_enable_debug_mode();
+
+ timer_bias = timer_bias_calculate();
+ if (timer_bias > 1) {
+ fprintf(stderr, "CPU is slow, timers bias is %f\n", timer_bias);
+ cfg_connlimit_tolerance *= timer_bias;
+ cfg_grouplimit_tolerance *= timer_bias;
+ cfg_stddev_tolerance *= timer_bias;
+ } else {
+ printf("CPU is fast enough, timers bias is %f\n", timer_bias);
+ }
+
+ base_cfg = event_config_new();
+
+#ifdef _WIN32
+ if (cfg_enable_iocp) {
+#ifdef EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED
+ evthread_use_windows_threads();
+#endif
+ event_config_set_flag(base_cfg, EVENT_BASE_FLAG_STARTUP_IOCP);
+ }
+#endif
+
+ base = event_base_new_with_config(base_cfg);
+ event_config_free(base_cfg);
+ if (! base) {
+ fprintf(stderr, "Couldn't create event_base");
+ return 1;
+ }
+
+ listener = evconnlistener_new_bind(base, echo_listenercb, base,
+ LEV_OPT_CLOSE_ON_FREE|LEV_OPT_REUSEABLE, -1,
+ (struct sockaddr *)&sin, sizeof(sin));
+ if (! listener) {
+ fprintf(stderr, "Couldn't create listener");
+ return 1;
+ }
+
+ slen = sizeof(ss);
+ if (getsockname(evconnlistener_get_fd(listener), (struct sockaddr *)&ss,
+ &slen) < 0) {
+ perror("getsockname");
+ return 1;
+ }
+
+ if (cfg_connlimit > 0) {
+ conn_bucket_cfg = ev_token_bucket_cfg_new(
+ cfg_connlimit, cfg_connlimit * 4,
+ cfg_connlimit, cfg_connlimit * 4,
+ &cfg_tick);
+ assert(conn_bucket_cfg);
+ }
+
+ if (cfg_grouplimit > 0) {
+ group_bucket_cfg = ev_token_bucket_cfg_new(
+ cfg_grouplimit, cfg_grouplimit * 4,
+ cfg_grouplimit, cfg_grouplimit * 4,
+ &cfg_tick);
+ group = ratelim_group = bufferevent_rate_limit_group_new(
+ base, group_bucket_cfg);
+ expected_total_persec = cfg_grouplimit - (cfg_group_drain / seconds_per_tick);
+ expected_avg_persec = cfg_grouplimit / cfg_n_connections;
+ if (cfg_connlimit > 0 && expected_avg_persec > cfg_connlimit)
+ expected_avg_persec = cfg_connlimit;
+ if (cfg_min_share >= 0)
+ bufferevent_rate_limit_group_set_min_share(
+ ratelim_group, cfg_min_share);
+ }
+
+ if (expected_avg_persec < 0 && cfg_connlimit > 0)
+ expected_avg_persec = cfg_connlimit;
+
+ if (expected_avg_persec > 0)
+ expected_avg_persec /= seconds_per_tick;
+ if (expected_total_persec > 0)
+ expected_total_persec /= seconds_per_tick;
+
+ bevs = calloc(cfg_n_connections, sizeof(struct bufferevent *));
+ states = calloc(cfg_n_connections, sizeof(struct client_state));
+
+ for (i = 0; i < cfg_n_connections; ++i) {
+ bevs[i] = bufferevent_socket_new(base, -1,
+ BEV_OPT_CLOSE_ON_FREE|BEV_OPT_THREADSAFE);
+ assert(bevs[i]);
+ bufferevent_setcb(bevs[i], discard_readcb, loud_writecb,
+ write_on_connectedcb, &states[i]);
+ bufferevent_enable(bevs[i], EV_READ|EV_WRITE);
+ bufferevent_socket_connect(bevs[i], (struct sockaddr *)&ss,
+ slen);
+ }
+
+ tv.tv_sec = cfg_duration - 1;
+ tv.tv_usec = 995000;
+
+ event_base_loopexit(base, &tv);
+
+ tv.tv_sec = 0;
+ tv.tv_usec = 100*1000;
+ ms100_common = event_base_init_common_timeout(base, &tv);
+
+ periodic_level_check = event_new(base, -1, EV_PERSIST, check_group_bucket_levels_cb, NULL);
+ event_add(periodic_level_check, ms100_common);
+
+ if (cfg_group_drain && ratelim_group) {
+ group_drain_event = event_new(base, -1, EV_PERSIST, group_drain_cb, NULL);
+ event_add(group_drain_event, &cfg_tick);
+ }
+
+ event_base_dispatch(base);
+
+ ratelim_group = NULL; /* So no more responders get added */
+ event_free(periodic_level_check);
+ if (group_drain_event)
+ event_free(group_drain_event);
+
+ for (i = 0; i < cfg_n_connections; ++i) {
+ bufferevent_free(bevs[i]);
+ }
+ evconnlistener_free(listener);
+
+ /* Make sure no new echo_conns get added to the group. */
+ ratelim_group = NULL;
+
+ /* This should get _everybody_ freed */
+ while (n_echo_conns_open) {
+ printf("waiting for %d conns\n", n_echo_conns_open);
+ tv.tv_sec = 0;
+ tv.tv_usec = 300000;
+ event_base_loopexit(base, &tv);
+ event_base_dispatch(base);
+ }
+
+ if (group)
+ bufferevent_rate_limit_group_free(group);
+
+ if (total_n_bev_checks) {
+ printf("Average read bucket level: %f\n",
+ (double)total_rbucket_level/total_n_bev_checks);
+ printf("Average write bucket level: %f\n",
+ (double)total_wbucket_level/total_n_bev_checks);
+ printf("Highest read bucket level: %f\n",
+ (double)max_bucket_level);
+ printf("Highest write bucket level: %f\n",
+ (double)min_bucket_level);
+ printf("Average max-to-read: %f\n",
+ ((double)total_max_to_read)/total_n_bev_checks);
+ printf("Average max-to-write: %f\n",
+ ((double)total_max_to_write)/total_n_bev_checks);
+ }
+ if (total_n_group_bev_checks) {
+ printf("Average group read bucket level: %f\n",
+ ((double)total_group_rbucket_level)/total_n_group_bev_checks);
+ printf("Average group write bucket level: %f\n",
+ ((double)total_group_wbucket_level)/total_n_group_bev_checks);
+ }
+
+ total_received = 0;
+ total_persec = 0.0;
+ total_sq_persec = 0.0;
+ for (i=0; i < cfg_n_connections; ++i) {
+ double persec = states[i].received;
+ persec /= cfg_duration;
+ total_received += states[i].received;
+ total_persec += persec;
+ total_sq_persec += persec*persec;
+ printf("%d: %f per second\n", i+1, persec);
+ }
+ printf(" total: %f per second\n",
+ ((double)total_received)/cfg_duration);
+ if (expected_total_persec > 0) {
+ double diff = expected_total_persec -
+ ((double)total_received/cfg_duration);
+ printf(" [Off by %lf]\n", diff);
+ if (cfg_grouplimit_tolerance > 0 &&
+ fabs(diff) > cfg_grouplimit_tolerance) {
+ fprintf(stderr, "Group bandwidth out of bounds\n");
+ ok = 0;
+ }
+ }
+
+ printf(" average: %f per second\n",
+ (((double)total_received)/cfg_duration)/cfg_n_connections);
+ if (expected_avg_persec > 0) {
+ double diff = expected_avg_persec - (((double)total_received)/cfg_duration)/cfg_n_connections;
+ printf(" [Off by %lf]\n", diff);
+ if (cfg_connlimit_tolerance > 0 &&
+ fabs(diff) > cfg_connlimit_tolerance) {
+ fprintf(stderr, "Connection bandwidth out of bounds\n");
+ ok = 0;
+ }
+ }
+
+ variance = total_sq_persec/cfg_n_connections - total_persec*total_persec/(cfg_n_connections*cfg_n_connections);
+
+ printf(" stddev: %f per second\n", sqrt(variance));
+ if (cfg_stddev_tolerance > 0 &&
+ sqrt(variance) > cfg_stddev_tolerance) {
+ fprintf(stderr, "Connection variance out of bounds\n");
+ ok = 0;
+ }
+
+ event_base_free(base);
+ free(bevs);
+ free(states);
+
+ return ok ? 0 : 1;
+}
+
+static struct option {
+ const char *name; int *ptr; int min; int isbool;
+} options[] = {
+ { "-v", &cfg_verbose, 0, 1 },
+ { "-h", &cfg_help, 0, 1 },
+ { "-n", &cfg_n_connections, 1, 0 },
+ { "-d", &cfg_duration, 1, 0 },
+ { "-c", &cfg_connlimit, 0, 0 },
+ { "-g", &cfg_grouplimit, 0, 0 },
+ { "-G", &cfg_group_drain, -100000, 0 },
+ { "-t", &cfg_tick_msec, 10, 0 },
+ { "--min-share", &cfg_min_share, 0, 0 },
+ { "--check-connlimit", &cfg_connlimit_tolerance, 0, 0 },
+ { "--check-grouplimit", &cfg_grouplimit_tolerance, 0, 0 },
+ { "--check-stddev", &cfg_stddev_tolerance, 0, 0 },
+#ifdef _WIN32
+ { "--iocp", &cfg_enable_iocp, 0, 1 },
+#endif
+ { NULL, NULL, -1, 0 },
+};
+
+static int
+handle_option(int argc, char **argv, int *i, const struct option *opt)
+{
+ long val;
+ char *endptr = NULL;
+ if (opt->isbool) {
+ *opt->ptr = 1;
+ return 0;
+ }
+ if (*i + 1 == argc) {
+ fprintf(stderr, "Too few arguments to '%s'\n",argv[*i]);
+ return -1;
+ }
+ val = strtol(argv[*i+1], &endptr, 10);
+ if (*argv[*i+1] == '\0' || !endptr || *endptr != '\0') {
+ fprintf(stderr, "Couldn't parse numeric value '%s'\n",
+ argv[*i+1]);
+ return -1;
+ }
+ if (val < opt->min || val > 0x7fffffff) {
+ fprintf(stderr, "Value '%s' is out-of-range'\n",
+ argv[*i+1]);
+ return -1;
+ }
+ *opt->ptr = (int)val;
+ ++*i;
+ return 0;
+}
+
+static void
+usage(void)
+{
+ fprintf(stderr,
+"test-ratelim [-v] [-n INT] [-d INT] [-c INT] [-g INT] [-t INT]\n\n"
+"Pushes bytes through a number of possibly rate-limited connections, and\n"
+"displays average throughput.\n\n"
+" -n INT: Number of connections to open (default: 30)\n"
+" -d INT: Duration of the test in seconds (default: 5 sec)\n");
+ fprintf(stderr,
+" -c INT: Connection-rate limit applied to each connection in bytes per second\n"
+" (default: None.)\n"
+" -g INT: Group-rate limit applied to sum of all usage in bytes per second\n"
+" (default: None.)\n"
+" -G INT: drain INT bytes from the group limit every tick. (default: 0)\n"
+" -t INT: Granularity of timing, in milliseconds (default: 1000 msec)\n");
+}
+
+int
+main(int argc, char **argv)
+{
+ int i,j;
+ double ratio;
+
+#ifdef _WIN32
+ WORD wVersionRequested = MAKEWORD(2,2);
+ WSADATA wsaData;
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ evutil_weakrand_seed_(&weakrand_state, 0);
+
+#ifndef _WIN32
+ if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+ return 1;
+#endif
+ for (i = 1; i < argc; ++i) {
+ for (j = 0; options[j].name; ++j) {
+ if (!strcmp(argv[i],options[j].name)) {
+ if (handle_option(argc,argv,&i,&options[j])<0)
+ return 1;
+ goto again;
+ }
+ }
+ fprintf(stderr, "Unknown option '%s'\n", argv[i]);
+ usage();
+ return 1;
+ again:
+ ;
+ }
+ if (cfg_help) {
+ usage();
+ return 0;
+ }
+
+ cfg_tick.tv_sec = cfg_tick_msec / 1000;
+ cfg_tick.tv_usec = (cfg_tick_msec % 1000)*1000;
+
+ seconds_per_tick = ratio = cfg_tick_msec / 1000.0;
+
+ cfg_connlimit *= ratio;
+ cfg_grouplimit *= ratio;
+
+ {
+ struct timeval tv;
+ evutil_gettimeofday(&tv, NULL);
+#ifdef _WIN32
+ srand(tv.tv_usec);
+#else
+ srandom(tv.tv_usec);
+#endif
+ }
+
+#ifndef EVENT__DISABLE_THREAD_SUPPORT
+ evthread_enable_lock_debugging();
+#endif
+
+ return test_ratelimiting();
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/test-ratelim.sh b/ipc/chromium/src/third_party/libevent/test/test-ratelim.sh
new file mode 100755
index 0000000000..b5e0ca62a9
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-ratelim.sh
@@ -0,0 +1,88 @@
+#!/bin/sh
+
+FAILED=no
+
+if test "x$TEST_OUTPUT_FILE" = "x"
+then
+ TEST_OUTPUT_FILE=/dev/null
+fi
+
+# /bin/echo is a little more likely to support -n than sh's builtin echo.
+if test -x /bin/echo
+then
+ ECHO=/bin/echo
+else
+ ECHO=echo
+fi
+
+if test "$TEST_OUTPUT_FILE" != "/dev/null"
+then
+ touch "$TEST_OUTPUT_FILE" || exit 1
+fi
+
+TEST_DIR=.
+
+T=`echo "$0" | sed -e 's/test-ratelim.sh$//'`
+if test -x "$T/test-ratelim"
+then
+ TEST_DIR="$T"
+fi
+
+announce () {
+ echo $@
+ echo $@ >>"$TEST_OUTPUT_FILE"
+}
+
+announce_n () {
+ $ECHO -n $@
+ echo $@ >>"$TEST_OUTPUT_FILE"
+}
+
+
+run_tests () {
+ announce_n " Group limits, no connection limit:"
+ if $TEST_DIR/test-ratelim -g 30000 -n 30 -t 100 --check-grouplimit 1000 --check-stddev 100 >>"$TEST_OUTPUT_FILE"
+ then
+ announce OKAY
+ else
+ announce FAILED
+ FAILED=yes
+ fi
+
+ announce_n " Connection limit, no group limit:"
+ if $TEST_DIR/test-ratelim -c 1000 -n 30 -t 100 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+
+ announce_n " Connection limit and group limit:"
+ if $TEST_DIR/test-ratelim -c 1000 -g 30000 -n 30 -t 100 --check-grouplimit 1000 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+
+ announce_n " Connection limit and group limit with independent drain:"
+ if $TEST_DIR/test-ratelim -c 1000 -g 35000 -n 30 -t 100 -G 500 --check-grouplimit 1000 --check-connlimit 50 --check-stddev 50 >>"$TEST_OUTPUT_FILE"
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+
+
+}
+
+announce "Running rate-limiting tests:"
+
+run_tests
+
+if test "$FAILED" = "yes"; then
+ exit 1
+fi
diff --git a/ipc/chromium/src/third_party/libevent/test/test-time.c b/ipc/chromium/src/third_party/libevent/test/test-time.c
new file mode 100644
index 0000000000..a8b3846263
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-time.c
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "util-internal.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#ifndef _WIN32
+#include <unistd.h>
+#include <sys/time.h>
+#endif
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_compat.h"
+#include "event2/event_struct.h"
+
+int called = 0;
+
+#define NEVENT 20000
+
+struct event *ev[NEVENT];
+
+struct evutil_weakrand_state weakrand_state;
+
+static int
+rand_int(int n)
+{
+ return evutil_weakrand_(&weakrand_state) % n;
+}
+
+static void
+time_cb(evutil_socket_t fd, short event, void *arg)
+{
+ struct timeval tv;
+ int i, j;
+
+ called++;
+
+ if (called < 10*NEVENT) {
+ for (i = 0; i < 10; i++) {
+ j = rand_int(NEVENT);
+ tv.tv_sec = 0;
+ tv.tv_usec = rand_int(50000);
+ if (tv.tv_usec % 2 || called < NEVENT)
+ evtimer_add(ev[j], &tv);
+ else
+ evtimer_del(ev[j]);
+ }
+ }
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event_base *base;
+ struct timeval tv;
+ int i;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+ evutil_weakrand_seed_(&weakrand_state, 0);
+
+ if (getenv("EVENT_DEBUG_LOGGING_ALL")) {
+ event_enable_debug_logging(EVENT_DBG_ALL);
+ }
+
+ base = event_base_new();
+
+ for (i = 0; i < NEVENT; i++) {
+ ev[i] = evtimer_new(base, time_cb, event_self_cbarg());
+ tv.tv_sec = 0;
+ tv.tv_usec = rand_int(50000);
+ evtimer_add(ev[i], &tv);
+ }
+
+ i = event_base_dispatch(base);
+
+ printf("event_base_dispatch=%d, called=%d, EVENT=%d\n",
+ i, called, NEVENT);
+
+ if (i == 1 && called >= NEVENT) {
+ return EXIT_SUCCESS;
+ } else {
+ return EXIT_FAILURE;
+ }
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test-weof.c b/ipc/chromium/src/third_party/libevent/test/test-weof.c
new file mode 100644
index 0000000000..68e7cd4579
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test-weof.c
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2002-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "../util-internal.h"
+#include "event2/event-config.h"
+
+#ifdef _WIN32
+#include <winsock2.h>
+#else
+#include <unistd.h>
+#endif
+#include <sys/types.h>
+#include <sys/stat.h>
+#ifdef EVENT__HAVE_SYS_TIME_H
+#include <sys/time.h>
+#endif
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#include <fcntl.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <signal.h>
+#include <errno.h>
+
+#include "event2/event.h"
+#include "event2/event_struct.h"
+#include "event2/event_compat.h"
+#include "event2/util.h"
+
+evutil_socket_t pair[2];
+int test_okay = 1;
+int called = 0;
+
+static void
+write_cb(evutil_socket_t fd, short event, void *arg)
+{
+ const char *test = "test string";
+ int len;
+
+ len = send(fd, test, (int)strlen(test) + 1, 0);
+
+ printf("%s: write %d%s\n", __func__,
+ len, len ? "" : " - means EOF");
+
+ if (len > 0) {
+ if (!called)
+ event_add(arg, NULL);
+ evutil_closesocket(pair[0]);
+ } else if (called == 1)
+ test_okay = 0;
+
+ called++;
+}
+
+int
+main(int argc, char **argv)
+{
+ struct event ev;
+
+#ifdef _WIN32
+ WORD wVersionRequested;
+ WSADATA wsaData;
+
+ wVersionRequested = MAKEWORD(2, 2);
+
+ (void) WSAStartup(wVersionRequested, &wsaData);
+#endif
+
+#ifndef _WIN32
+ if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
+ return (1);
+#endif
+
+ if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
+ return (1);
+
+ /* Initialize the event library */
+ event_init();
+
+ /* Initialize one event */
+ event_set(&ev, pair[1], EV_WRITE, write_cb, &ev);
+
+ event_add(&ev, NULL);
+
+ event_dispatch();
+
+ return (test_okay);
+}
+
diff --git a/ipc/chromium/src/third_party/libevent/test/test.sh b/ipc/chromium/src/third_party/libevent/test/test.sh
new file mode 100755
index 0000000000..f91a8b0445
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/test.sh
@@ -0,0 +1,188 @@
+#!/bin/sh
+
+BACKENDS="EVPORT KQUEUE EPOLL DEVPOLL POLL SELECT WIN32"
+TESTS="test-eof test-closed test-weof test-time test-changelist test-fdleak"
+FAILED=no
+TEST_OUTPUT_FILE=${TEST_OUTPUT_FILE:-/dev/null}
+REGRESS_ARGS=${REGRESS_ARGS:-}
+
+# /bin/echo is a little more likely to support -n than sh's builtin echo,
+# printf is even more likely
+if test "`printf %s hello 2>&1`" = "hello"
+then
+ ECHO_N="printf %s"
+else
+ if test -x /bin/echo
+ then
+ ECHO_N="/bin/echo -n"
+ else
+ ECHO_N="echo -n"
+ fi
+fi
+
+if test "$TEST_OUTPUT_FILE" != "/dev/null"
+then
+ touch "$TEST_OUTPUT_FILE" || exit 1
+fi
+
+TEST_DIR=.
+TEST_SRC_DIR=.
+
+T=`echo "$0" | sed -e 's/test.sh$//'`
+if test -x "$T/test-init"
+then
+ TEST_DIR="$T"
+elif test -x "./test/test-init"
+then
+ TEST_DIR="./test"
+fi
+if test -f "$T/check-dumpevents.py"
+then
+ TEST_SRC_DIR="$T"
+elif test -f "./test/check-dumpevents.py"
+then
+ TEST_SRC_DIR="./test"
+fi
+
+setup () {
+ for i in $BACKENDS; do
+ eval "EVENT_NO$i=yes; export EVENT_NO$i"
+ done
+ unset EVENT_EPOLL_USE_CHANGELIST
+ unset EVENT_PRECISE_TIMER
+}
+
+announce () {
+ echo "$@"
+ echo "$@" >>"$TEST_OUTPUT_FILE"
+}
+
+announce_n () {
+ $ECHO_N "$@"
+ echo "$@" >>"$TEST_OUTPUT_FILE"
+}
+
+
+run_tests () {
+ if $TEST_DIR/test-init 2>>"$TEST_OUTPUT_FILE" ;
+ then
+ true
+ else
+ announce Skipping test
+ return
+ fi
+ for i in $TESTS; do
+ announce_n " $i: "
+ if $TEST_DIR/$i >>"$TEST_OUTPUT_FILE" ;
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+ done
+ announce_n " test-dumpevents: "
+ if python -c 'import sys; assert(sys.version_info >= (2, 4))' 2>/dev/null && test -f $TEST_SRC_DIR/check-dumpevents.py; then
+ if $TEST_DIR/test-dumpevents | $TEST_SRC_DIR/check-dumpevents.py >> "$TEST_OUTPUT_FILE" ;
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ fi
+ else
+ # no python
+ if $TEST_DIR/test-dumpevents >/dev/null; then
+ announce "OKAY (output not checked)" ;
+ else
+ announce "FAILED (output not checked)" ;
+ fi
+ fi
+
+ test -x $TEST_DIR/regress || return
+ announce_n " regress: "
+ if test "$TEST_OUTPUT_FILE" = "/dev/null" ;
+ then
+ $TEST_DIR/regress --quiet $REGRESS_ARGS
+ else
+ $TEST_DIR/regress $REGRESS_ARGS >>"$TEST_OUTPUT_FILE"
+ fi
+ if test "$?" = "0" ;
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+
+ announce_n " regress_debug: "
+ if test "$TEST_OUTPUT_FILE" = "/dev/null" ;
+ then
+ EVENT_DEBUG_MODE=1 $TEST_DIR/regress --quiet $REGRESS_ARGS
+ else
+ EVENT_DEBUG_MODE=1 $TEST_DIR/regress $REGRESS_ARGS >>"$TEST_OUTPUT_FILE"
+ fi
+ if test "$?" = "0" ;
+ then
+ announce OKAY ;
+ else
+ announce FAILED ;
+ FAILED=yes
+ fi
+}
+
+do_test() {
+ setup
+ announce "$1 $2"
+ unset EVENT_NO$1
+ if test "$2" = "(changelist)" ; then
+ EVENT_EPOLL_USE_CHANGELIST=yes; export EVENT_EPOLL_USE_CHANGELIST
+ elif test "$2" = "(timerfd)" ; then
+ EVENT_PRECISE_TIMER=1; export EVENT_PRECISE_TIMER
+ elif test "$2" = "(timerfd+changelist)" ; then
+ EVENT_EPOLL_USE_CHANGELIST=yes; export EVENT_EPOLL_USE_CHANGELIST
+ EVENT_PRECISE_TIMER=1; export EVENT_PRECISE_TIMER
+ fi
+
+ run_tests
+}
+
+usage()
+{
+ cat <<EOL
+ -b - specify backends
+ -t - run timerfd test
+ -c - run changelist test
+ -T - run timerfd+changelist test
+EOL
+}
+main()
+{
+ backends=$BACKENDS
+ timerfd=0
+ changelist=0
+ timerfd_changelist=0
+
+ while getopts "b:tcT" c; do
+ case "$c" in
+ b) backends="$OPTARG";;
+ t) timerfd=1;;
+ c) changelist=1;;
+ T) timerfd_changelist=1;;
+ ?*) usage && exit 1;;
+ esac
+ done
+
+ announce "Running tests:"
+
+ [ $timerfd -eq 0 ] || do_test EPOLL "(timerfd)"
+ [ $changelist -eq 0 ] || do_test EPOLL "(changelist)"
+ [ $timerfd_changelist -eq 0 ] || do_test EPOLL "(timerfd+changelist)"
+ for i in $backends; do
+ do_test $i
+ done
+
+ if test "$FAILED" = "yes"; then
+ exit 1
+ fi
+}
+main "$@"
diff --git a/ipc/chromium/src/third_party/libevent/test/tinytest.c b/ipc/chromium/src/third_party/libevent/test/tinytest.c
new file mode 100644
index 0000000000..85dfe74a72
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/tinytest.c
@@ -0,0 +1,610 @@
+/* tinytest.c -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifdef TINYTEST_LOCAL
+#include "tinytest_local.h"
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <assert.h>
+
+#ifndef NO_FORKING
+
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <unistd.h>
+#endif
+
+#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
+#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
+ __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
+/* Workaround for a stupid bug in OSX 10.6 */
+#define FORK_BREAKS_GCOV
+#include <vproc.h>
+#endif
+#endif
+
+#endif /* !NO_FORKING */
+
+#ifndef __GNUC__
+#define __attribute__(x)
+#endif
+
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#define LONGEST_TEST_NAME 16384
+#define DEFAULT_TESTCASE_TIMEOUT 30U
+#define MAGIC_EXITCODE 42
+
+static int in_tinytest_main = 0; /**< true if we're in tinytest_main().*/
+static int n_ok = 0; /**< Number of tests that have passed */
+static int n_bad = 0; /**< Number of tests that have failed. */
+static int n_skipped = 0; /**< Number of tests that have been skipped. */
+
+static int opt_forked = 0; /**< True iff we're called from inside a win32 fork*/
+static int opt_nofork = 0; /**< Suppress calls to fork() for debugging. */
+static int opt_verbosity = 1; /**< -==quiet,0==terse,1==normal,2==verbose */
+static unsigned int opt_timeout = DEFAULT_TESTCASE_TIMEOUT; /**< Timeout for every test (using alarm()) */
+const char *verbosity_flag = "";
+
+const struct testlist_alias_t *cfg_aliases=NULL;
+
+enum outcome { SKIP=2, OK=1, FAIL=0 };
+static enum outcome cur_test_outcome = 0;
+const char *cur_test_prefix = NULL; /**< prefix of the current test group */
+/** Name of the current test, if we haven't logged is yet. Used for --quiet */
+const char *cur_test_name = NULL;
+
+static void usage(struct testgroup_t *groups, int list_groups)
+ __attribute__((noreturn));
+static int process_test_option(struct testgroup_t *groups, const char *test);
+
+#ifdef _WIN32
+/* Copy of argv[0] for win32. */
+static char commandname[MAX_PATH+1];
+
+struct timeout_thread_args {
+ const testcase_fn *fn;
+ void *env;
+};
+
+static DWORD WINAPI
+timeout_thread_proc_(LPVOID arg)
+{
+ struct timeout_thread_args *args = arg;
+ (*(args->fn))(args->env);
+ ExitThread(cur_test_outcome == FAIL ? 1 : 0);
+}
+
+static enum outcome
+testcase_run_in_thread_(const struct testcase_t *testcase, void *env)
+{
+ /* We will never run testcase in a new thread when the
+ timeout is set to zero */
+ assert(opt_timeout);
+ DWORD ret, tid;
+ HANDLE handle;
+ struct timeout_thread_args args = {
+ &(testcase->fn),
+ env
+ };
+
+ handle =CreateThread(NULL, 0, timeout_thread_proc_,
+ (LPVOID)&args, 0, &tid);
+ ret = WaitForSingleObject(handle, opt_timeout * 1000U);
+ if (ret == WAIT_OBJECT_0) {
+ ret = 0;
+ if (!GetExitCodeThread(handle, &ret)) {
+ printf("GetExitCodeThread failed\n");
+ ret = 1;
+ }
+ } else if (ret == WAIT_TIMEOUT) {
+ printf("timeout\n");
+ } else {
+ printf("Wait failed\n");
+ }
+ CloseHandle(handle);
+ if (ret == 0)
+ return OK;
+ else if (ret == MAGIC_EXITCODE)
+ return SKIP;
+ else
+ return FAIL;
+}
+#else
+static unsigned int testcase_set_timeout_(void)
+{
+ return alarm(opt_timeout);
+}
+
+static unsigned int testcase_reset_timeout_(void)
+{
+ return alarm(0);
+}
+#endif
+
+static enum outcome
+testcase_run_bare_(const struct testcase_t *testcase)
+{
+ void *env = NULL;
+ int outcome;
+ if (testcase->setup) {
+ env = testcase->setup->setup_fn(testcase);
+ if (!env)
+ return FAIL;
+ else if (env == (void*)TT_SKIP)
+ return SKIP;
+ }
+
+ cur_test_outcome = OK;
+ {
+ if (opt_timeout) {
+#ifdef _WIN32
+ cur_test_outcome = testcase_run_in_thread_(testcase, env);
+#else
+ testcase_set_timeout_();
+ testcase->fn(env);
+ testcase_reset_timeout_();
+#endif
+ } else {
+ testcase->fn(env);
+ }
+ }
+ outcome = cur_test_outcome;
+
+ if (testcase->setup) {
+ if (testcase->setup->cleanup_fn(testcase, env) == 0)
+ outcome = FAIL;
+ }
+
+ return outcome;
+}
+
+
+#ifndef NO_FORKING
+
+static enum outcome
+testcase_run_forked_(const struct testgroup_t *group,
+ const struct testcase_t *testcase)
+{
+#ifdef _WIN32
+ /* Fork? On Win32? How primitive! We'll do what the smart kids do:
+ we'll invoke our own exe (whose name we recall from the command
+ line) with a command line that tells it to run just the test we
+ want, and this time without forking.
+
+ (No, threads aren't an option. The whole point of forking is to
+ share no state between tests.)
+ */
+ int ok;
+ char buffer[LONGEST_TEST_NAME+256];
+ STARTUPINFOA si;
+ PROCESS_INFORMATION info;
+ DWORD ret;
+
+ if (!in_tinytest_main) {
+ printf("\nERROR. On Windows, testcase_run_forked_ must be"
+ " called from within tinytest_main.\n");
+ abort();
+ }
+ if (opt_verbosity>0)
+ printf("[forking] ");
+
+ snprintf(buffer, sizeof(buffer), "%s --RUNNING-FORKED %s --timeout 0 %s%s",
+ commandname, verbosity_flag, group->prefix, testcase->name);
+
+ memset(&si, 0, sizeof(si));
+ memset(&info, 0, sizeof(info));
+ si.cb = sizeof(si);
+
+ ok = CreateProcessA(commandname, buffer, NULL, NULL, 0,
+ 0, NULL, NULL, &si, &info);
+ if (!ok) {
+ printf("CreateProcess failed!\n");
+ return FAIL;
+ }
+ ret = WaitForSingleObject(info.hProcess,
+ (opt_timeout ? opt_timeout * 1000U : INFINITE));
+
+ if (ret == WAIT_OBJECT_0) {
+ GetExitCodeProcess(info.hProcess, &ret);
+ } else if (ret == WAIT_TIMEOUT) {
+ printf("timeout\n");
+ } else {
+ printf("Wait failed\n");
+ }
+ CloseHandle(info.hProcess);
+ CloseHandle(info.hThread);
+ if (ret == 0)
+ return OK;
+ else if (ret == MAGIC_EXITCODE)
+ return SKIP;
+ else
+ return FAIL;
+#else
+ int outcome_pipe[2];
+ pid_t pid;
+ (void)group;
+
+ if (pipe(outcome_pipe))
+ perror("opening pipe");
+
+ if (opt_verbosity>0)
+ printf("[forking] ");
+ pid = fork();
+#ifdef FORK_BREAKS_GCOV
+ vproc_transaction_begin(0);
+#endif
+ if (!pid) {
+ /* child. */
+ int test_r, write_r;
+ char b[1];
+ close(outcome_pipe[0]);
+ test_r = testcase_run_bare_(testcase);
+ assert(0<=(int)test_r && (int)test_r<=2);
+ b[0] = "NYS"[test_r];
+ write_r = (int)write(outcome_pipe[1], b, 1);
+ if (write_r != 1) {
+ perror("write outcome to pipe");
+ exit(1);
+ }
+ exit(0);
+ return FAIL; /* unreachable */
+ } else {
+ /* parent */
+ int status, r, exitcode;
+ char b[1];
+ /* Close this now, so that if the other side closes it,
+ * our read fails. */
+ close(outcome_pipe[1]);
+ r = (int)read(outcome_pipe[0], b, 1);
+ if (r == 0) {
+ printf("[Lost connection!] ");
+ return FAIL;
+ } else if (r != 1) {
+ perror("read outcome from pipe");
+ }
+ waitpid(pid, &status, 0);
+ exitcode = WEXITSTATUS(status);
+ close(outcome_pipe[0]);
+ if (opt_verbosity>1)
+ printf("%s%s: exited with %i (%i)\n", group->prefix, testcase->name, exitcode, status);
+ if (exitcode != 0)
+ {
+ printf("[atexit failure!] ");
+ return FAIL;
+ }
+ return b[0]=='Y' ? OK : (b[0]=='S' ? SKIP : FAIL);
+ }
+#endif
+}
+
+#endif /* !NO_FORKING */
+
+int
+testcase_run_one(const struct testgroup_t *group,
+ const struct testcase_t *testcase)
+{
+ enum outcome outcome;
+
+ if (testcase->flags & (TT_SKIP|TT_OFF_BY_DEFAULT)) {
+ if (opt_verbosity>0)
+ printf("%s%s: %s\n",
+ group->prefix, testcase->name,
+ (testcase->flags & TT_SKIP) ? "SKIPPED" : "DISABLED");
+ ++n_skipped;
+ return SKIP;
+ }
+
+ if (opt_verbosity>0 && !opt_forked) {
+ printf("%s%s: ", group->prefix, testcase->name);
+ } else {
+ if (opt_verbosity==0) printf(".");
+ cur_test_prefix = group->prefix;
+ cur_test_name = testcase->name;
+ }
+
+#ifndef NO_FORKING
+ if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) {
+ outcome = testcase_run_forked_(group, testcase);
+ } else {
+#else
+ {
+#endif
+ outcome = testcase_run_bare_(testcase);
+ }
+
+ if (outcome == OK) {
+ if (opt_verbosity>0 && !opt_forked)
+ puts(opt_verbosity==1?"OK":"");
+ } else if (outcome == SKIP) {
+ if (opt_verbosity>0 && !opt_forked)
+ puts("SKIPPED");
+ } else {
+ if (!opt_forked)
+ printf("\n [%s FAILED]\n", testcase->name);
+ }
+
+ if (opt_forked) {
+ exit(outcome==OK ? 0 : (outcome==SKIP?MAGIC_EXITCODE : 1));
+ return 1; /* unreachable */
+ } else {
+ return (int)outcome;
+ }
+}
+
+int
+tinytest_set_flag_(struct testgroup_t *groups, const char *arg, int set, unsigned long flag)
+{
+ int i, j;
+ size_t length = LONGEST_TEST_NAME;
+ char fullname[LONGEST_TEST_NAME];
+ int found=0;
+ if (strstr(arg, ".."))
+ length = strstr(arg,"..")-arg;
+ for (i=0; groups[i].prefix; ++i) {
+ for (j=0; groups[i].cases[j].name; ++j) {
+ struct testcase_t *testcase = &groups[i].cases[j];
+ snprintf(fullname, sizeof(fullname), "%s%s",
+ groups[i].prefix, testcase->name);
+ if (!flag) { /* Hack! */
+ printf(" %s", fullname);
+ if (testcase->flags & TT_OFF_BY_DEFAULT)
+ puts(" (Off by default)");
+ else if (testcase->flags & TT_SKIP)
+ puts(" (DISABLED)");
+ else
+ puts("");
+ }
+ if (!strncmp(fullname, arg, length)) {
+ if (set)
+ testcase->flags |= flag;
+ else
+ testcase->flags &= ~flag;
+ ++found;
+ }
+ }
+ }
+ return found;
+}
+
+static void
+usage(struct testgroup_t *groups, int list_groups)
+{
+ puts("Options are: [--verbose|--quiet|--terse] [--no-fork] [--timeout <sec>]");
+ puts(" Specify tests by name, or using a prefix ending with '..'");
+ puts(" To skip a test, prefix its name with a colon.");
+ puts(" To enable a disabled test, prefix its name with a plus.");
+ puts(" Use --list-tests for a list of tests.");
+ if (list_groups) {
+ puts("Known tests are:");
+ tinytest_set_flag_(groups, "..", 1, 0);
+ }
+ exit(0);
+}
+
+static int
+process_test_alias(struct testgroup_t *groups, const char *test)
+{
+ int i, j, n, r;
+ for (i=0; cfg_aliases && cfg_aliases[i].name; ++i) {
+ if (!strcmp(cfg_aliases[i].name, test)) {
+ n = 0;
+ for (j = 0; cfg_aliases[i].tests[j]; ++j) {
+ r = process_test_option(groups, cfg_aliases[i].tests[j]);
+ if (r<0)
+ return -1;
+ n += r;
+ }
+ return n;
+ }
+ }
+ printf("No such test alias as @%s!",test);
+ return -1;
+}
+
+static int
+process_test_option(struct testgroup_t *groups, const char *test)
+{
+ int flag = TT_ENABLED_;
+ int n = 0;
+ if (test[0] == '@') {
+ return process_test_alias(groups, test + 1);
+ } else if (test[0] == ':') {
+ ++test;
+ flag = TT_SKIP;
+ } else if (test[0] == '+') {
+ ++test;
+ ++n;
+ if (!tinytest_set_flag_(groups, test, 0, TT_OFF_BY_DEFAULT)) {
+ printf("No such test as %s!\n", test);
+ return -1;
+ }
+ } else {
+ ++n;
+ }
+ if (!tinytest_set_flag_(groups, test, 1, flag)) {
+ printf("No such test as %s!\n", test);
+ return -1;
+ }
+ return n;
+}
+
+void
+tinytest_set_aliases(const struct testlist_alias_t *aliases)
+{
+ cfg_aliases = aliases;
+}
+
+int
+tinytest_main(int c, const char **v, struct testgroup_t *groups)
+{
+ int i, j, n=0;
+
+#ifdef _WIN32
+ const char *sp = strrchr(v[0], '.');
+ const char *extension = "";
+ if (!sp || stricmp(sp, ".exe"))
+ extension = ".exe"; /* Add an exe so CreateProcess will work */
+ snprintf(commandname, sizeof(commandname), "%s%s", v[0], extension);
+ commandname[MAX_PATH]='\0';
+#endif
+ for (i=1; i<c; ++i) {
+ if (v[i][0] == '-') {
+ if (!strcmp(v[i], "--RUNNING-FORKED")) {
+ opt_forked = 1;
+ } else if (!strcmp(v[i], "--no-fork")) {
+ opt_nofork = 1;
+ } else if (!strcmp(v[i], "--quiet")) {
+ opt_verbosity = -1;
+ verbosity_flag = "--quiet";
+ } else if (!strcmp(v[i], "--verbose")) {
+ opt_verbosity = 2;
+ verbosity_flag = "--verbose";
+ } else if (!strcmp(v[i], "--terse")) {
+ opt_verbosity = 0;
+ verbosity_flag = "--terse";
+ } else if (!strcmp(v[i], "--help")) {
+ usage(groups, 0);
+ } else if (!strcmp(v[i], "--list-tests")) {
+ usage(groups, 1);
+ } else if (!strcmp(v[i], "--timeout")) {
+ ++i;
+ if (i >= c) {
+ fprintf(stderr, "--timeout requires argument\n");
+ return -1;
+ }
+ opt_timeout = (unsigned)atoi(v[i]);
+ } else {
+ fprintf(stderr, "Unknown option %s. Try --help\n", v[i]);
+ return -1;
+ }
+ } else {
+ int r = process_test_option(groups, v[i]);
+ if (r<0)
+ return -1;
+ n += r;
+ }
+ }
+ if (!n)
+ tinytest_set_flag_(groups, "..", 1, TT_ENABLED_);
+
+#ifdef _IONBF
+ setvbuf(stdout, NULL, _IONBF, 0);
+#endif
+
+ ++in_tinytest_main;
+ for (i = 0; groups[i].prefix; ++i) {
+ struct testgroup_t *group = &groups[i];
+ for (j = 0; group->cases[j].name; ++j) {
+ struct testcase_t *testcase = &group->cases[j];
+ int test_attempts = 3;
+ int test_ret_err;
+
+ if (!(testcase->flags & TT_ENABLED_))
+ continue;
+
+ for (;;) {
+ test_ret_err = testcase_run_one(group, testcase);
+
+ if (test_ret_err == OK)
+ break;
+ if (!(testcase->flags & TT_RETRIABLE))
+ break;
+ printf("\n [RETRYING %s (%i)]\n", testcase->name, test_attempts);
+ if (!test_attempts--)
+ break;
+ }
+
+ switch (test_ret_err) {
+ case OK: ++n_ok; break;
+ case SKIP: ++n_skipped; break;
+ default: ++n_bad; break;
+ }
+ }
+ }
+
+ --in_tinytest_main;
+
+ if (opt_verbosity==0)
+ puts("");
+
+ if (n_bad)
+ printf("%d/%d TESTS FAILED. (%d skipped)\n", n_bad,
+ n_bad+n_ok,n_skipped);
+ else if (opt_verbosity >= 1)
+ printf("%d tests ok. (%d skipped)\n", n_ok, n_skipped);
+
+ return (n_bad == 0) ? 0 : 1;
+}
+
+int
+tinytest_get_verbosity_(void)
+{
+ return opt_verbosity;
+}
+
+void
+tinytest_set_test_failed_(void)
+{
+ if (opt_verbosity <= 0 && cur_test_name) {
+ if (opt_verbosity==0) puts("");
+ printf("%s%s: ", cur_test_prefix, cur_test_name);
+ cur_test_name = NULL;
+ }
+ cur_test_outcome = FAIL;
+}
+
+void
+tinytest_set_test_skipped_(void)
+{
+ if (cur_test_outcome==OK)
+ cur_test_outcome = SKIP;
+}
+
+char *
+tinytest_format_hex_(const void *val_, unsigned long len)
+{
+ const unsigned char *val = val_;
+ char *result, *cp;
+ size_t i;
+
+ if (!val)
+ return strdup("null");
+ if (!(result = malloc(len*2+1)))
+ return strdup("<allocation failure>");
+ cp = result;
+ for (i=0;i<len;++i) {
+ *cp++ = "0123456789ABCDEF"[val[i] >> 4];
+ *cp++ = "0123456789ABCDEF"[val[i] & 0x0f];
+ }
+ *cp = 0;
+ return result;
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/tinytest.h b/ipc/chromium/src/third_party/libevent/test/tinytest.h
new file mode 100644
index 0000000000..d321dd4675
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/tinytest.h
@@ -0,0 +1,103 @@
+/* tinytest.h -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TINYTEST_H_INCLUDED_
+#define TINYTEST_H_INCLUDED_
+
+/** Flag for a test that needs to run in a subprocess. */
+#define TT_FORK (1<<0)
+/** Runtime flag for a test we've decided to skip. */
+#define TT_SKIP (1<<1)
+/** Internal runtime flag for a test we've decided to run. */
+#define TT_ENABLED_ (1<<2)
+/** Flag for a test that's off by default. */
+#define TT_OFF_BY_DEFAULT (1<<3)
+/** Flag for a test that should be runned again in case of failure (but not
+ * more then 3 times). */
+#define TT_RETRIABLE (1<<4)
+/** If you add your own flags, make them start at this point. */
+#define TT_FIRST_USER_FLAG (1<<5)
+
+typedef void (*testcase_fn)(void *);
+
+struct testcase_t;
+
+/** Functions to initialize/teardown a structure for a testcase. */
+struct testcase_setup_t {
+ /** Return a new structure for use by a given testcase. */
+ void *(*setup_fn)(const struct testcase_t *);
+ /** Clean/free a structure from setup_fn. Return 1 if ok, 0 on err. */
+ int (*cleanup_fn)(const struct testcase_t *, void *);
+};
+
+/** A single test-case that you can run. */
+struct testcase_t {
+ const char *name; /**< An identifier for this case. */
+ testcase_fn fn; /**< The function to run to implement this case. */
+ unsigned long flags; /**< Bitfield of TT_* flags. */
+ const struct testcase_setup_t *setup; /**< Optional setup/cleanup fns*/
+ void *setup_data; /**< Extra data usable by setup function */
+};
+#define END_OF_TESTCASES { NULL, NULL, 0, NULL, NULL }
+
+/** A group of tests that are selectable together. */
+struct testgroup_t {
+ const char *prefix; /**< Prefix to prepend to testnames. */
+ struct testcase_t *cases; /** Array, ending with END_OF_TESTCASES */
+};
+#define END_OF_GROUPS { NULL, NULL}
+
+struct testlist_alias_t {
+ const char *name;
+ const char **tests;
+};
+#define END_OF_ALIASES { NULL, NULL }
+
+/** Implementation: called from a test to indicate failure, before logging. */
+void tinytest_set_test_failed_(void);
+/** Implementation: called from a test to indicate that we're skipping. */
+void tinytest_set_test_skipped_(void);
+/** Implementation: return 0 for quiet, 1 for normal, 2 for loud. */
+int tinytest_get_verbosity_(void);
+/** Implementation: Set a flag on tests matching a name; returns number
+ * of tests that matched. */
+int tinytest_set_flag_(struct testgroup_t *, const char *, int set, unsigned long);
+/** Implementation: Put a chunk of memory into hex. */
+char *tinytest_format_hex_(const void *, unsigned long);
+
+/** Set all tests in 'groups' matching the name 'named' to be skipped. */
+#define tinytest_skip(groups, named) \
+ tinytest_set_flag_(groups, named, 1, TT_SKIP)
+
+/** Run a single testcase in a single group. */
+int testcase_run_one(const struct testgroup_t *,const struct testcase_t *);
+
+void tinytest_set_aliases(const struct testlist_alias_t *aliases);
+
+/** Run a set of testcases from an END_OF_GROUPS-terminated array of groups,
+ as selected from the command line. */
+int tinytest_main(int argc, const char **argv, struct testgroup_t *groups);
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/test/tinytest_demo.c b/ipc/chromium/src/third_party/libevent/test/tinytest_demo.c
new file mode 100644
index 0000000000..123855fff7
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/tinytest_demo.c
@@ -0,0 +1,292 @@
+/* tinytest_demo.c -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+/* Welcome to the example file for tinytest! I'll show you how to set up
+ * some simple and not-so-simple testcases. */
+
+/* Make sure you include these headers. */
+#include "tinytest.h"
+#include "tinytest_macros.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <time.h>
+#ifdef _WIN32
+#include <windows.h>
+#else
+#include <unistd.h>
+#endif
+
+/* ============================================================ */
+
+/* First, let's see if strcmp is working. (All your test cases should be
+ * functions declared to take a single void * as an argument.) */
+void
+test_strcmp(void *data)
+{
+ (void)data; /* This testcase takes no data. */
+
+ /* Let's make sure the empty string is equal to itself */
+ if (strcmp("","")) {
+ /* This macro tells tinytest to stop the current test
+ * and go straight to the "end" label. */
+ tt_abort_msg("The empty string was not equal to itself");
+ }
+
+ /* Pretty often, calling tt_abort_msg to indicate failure is more
+ heavy-weight than you want. Instead, just say: */
+ tt_assert(strcmp("testcase", "testcase") == 0);
+
+ /* Occasionally, you don't want to stop the current testcase just
+ because a single assertion has failed. In that case, use
+ tt_want: */
+ tt_want(strcmp("tinytest", "testcase") > 0);
+
+ /* You can use the tt_*_op family of macros to compare values and to
+ fail unless they have the relationship you want. They produce
+ more useful output than tt_assert, since they display the actual
+ values of the failing things.
+
+ Fail unless strcmp("abc, "abc") == 0 */
+ tt_int_op(strcmp("abc", "abc"), ==, 0);
+
+ /* Fail unless strcmp("abc, "abcd") is less than 0 */
+ tt_int_op(strcmp("abc", "abcd"), < , 0);
+
+ /* Incidentally, there's a test_str_op that uses strcmp internally. */
+ tt_str_op("abc", <, "abcd");
+
+
+ /* Every test-case function needs to finish with an "end:"
+ label and (optionally) code to clean up local variables. */
+ end:
+ ;
+}
+
+/* ============================================================ */
+
+/* Now let's mess with setup and teardown functions! These are handy if
+ you have a bunch of tests that all need a similar environment, and you
+ want to reconstruct that environment freshly for each one. */
+
+/* First you declare a type to hold the environment info, and functions to
+ set it up and tear it down. */
+struct data_buffer {
+ /* We're just going to have couple of character buffer. Using
+ setup/teardown functions is probably overkill for this case.
+
+ You could also do file descriptors, complicated handles, temporary
+ files, etc. */
+ char buffer1[512];
+ char buffer2[512];
+};
+/* The setup function needs to take a const struct testcase_t and return
+ void* */
+void *
+setup_data_buffer(const struct testcase_t *testcase)
+{
+ struct data_buffer *db = malloc(sizeof(struct data_buffer));
+
+ /* If you had a complicated set of setup rules, you might behave
+ differently here depending on testcase->flags or
+ testcase->setup_data or even or testcase->name. */
+
+ /* Returning a NULL here would mean that we couldn't set up for this
+ test, so we don't need to test db for null. */
+ return db;
+}
+/* The clean function deallocates storage carefully and returns true on
+ success. */
+int
+clean_data_buffer(const struct testcase_t *testcase, void *ptr)
+{
+ struct data_buffer *db = ptr;
+
+ if (db) {
+ free(db);
+ return 1;
+ }
+ return 0;
+}
+/* Finally, declare a testcase_setup_t with these functions. */
+struct testcase_setup_t data_buffer_setup = {
+ setup_data_buffer, clean_data_buffer
+};
+
+
+/* Now let's write our test. */
+void
+test_memcpy(void *ptr)
+{
+ /* This time, we use the argument. */
+ struct data_buffer *db = ptr;
+
+ /* We'll also introduce a local variable that might need cleaning up. */
+ char *mem = NULL;
+
+ /* Let's make sure that memcpy does what we'd like. */
+ strcpy(db->buffer1, "String 0");
+ memcpy(db->buffer2, db->buffer1, sizeof(db->buffer1));
+ tt_str_op(db->buffer1, ==, db->buffer2);
+
+ /* This one works if there's an internal NUL. */
+ tt_mem_op(db->buffer1, <, db->buffer2, sizeof(db->buffer1));
+
+ /* Now we've allocated memory that's referenced by a local variable.
+ The end block of the function will clean it up. */
+ mem = strdup("Hello world.");
+ tt_assert(mem);
+
+ /* Another rather trivial test. */
+ tt_str_op(db->buffer1, !=, mem);
+
+ end:
+ /* This time our end block has something to do. */
+ if (mem)
+ free(mem);
+}
+
+void
+test_timeout(void *ptr)
+{
+ time_t t1, t2;
+ (void)ptr;
+ t1 = time(NULL);
+#ifdef _WIN32
+ Sleep(5000);
+#else
+ sleep(5);
+#endif
+ t2 = time(NULL);
+
+ tt_int_op(t2-t1, >=, 4);
+
+ tt_int_op(t2-t1, <=, 6);
+
+ end:
+ ;
+}
+
+void
+test_timeout_retry(void *ptr)
+{
+ static int i = 0;
+
+ ++i;
+ tt_int_op(i, !=, 1);
+
+ time_t t1, t2;
+ (void)ptr;
+ t1 = time(NULL);
+#ifdef _WIN32
+ Sleep(5000);
+#else
+ sleep(5);
+#endif
+ t2 = time(NULL);
+
+ tt_int_op(t2-t1, >=, 4);
+
+ tt_int_op(t2-t1, <=, 6);
+
+ end:
+ ;
+}
+
+/* ============================================================ */
+
+/* Now we need to make sure that our tests get invoked. First, you take
+ a bunch of related tests and put them into an array of struct testcase_t.
+*/
+
+struct testcase_t demo_tests[] = {
+ /* Here's a really simple test: it has a name you can refer to it
+ with, and a function to invoke it. */
+ { "strcmp", test_strcmp, },
+
+ /* The second test has a flag, "TT_FORK", to make it run in a
+ subprocess, and a pointer to the testcase_setup_t that configures
+ its environment. */
+ { "memcpy", test_memcpy, TT_FORK, &data_buffer_setup },
+
+ /* This flag is off-by-default, since it takes a while to run. You
+ * can enable it manually by passing +demo/timeout at the command line.*/
+ { "timeout", test_timeout, TT_OFF_BY_DEFAULT },
+
+ /* This test will be retried. (and it will not pass from the first
+ * time) */
+ { "timeout_retry", test_timeout_retry, TT_RETRIABLE },
+
+ /* The array has to end with END_OF_TESTCASES. */
+ END_OF_TESTCASES
+};
+
+/* Next, we make an array of testgroups. This is mandatory. Unlike more
+ heavy-duty testing frameworks, groups can't nest. */
+struct testgroup_t groups[] = {
+
+ /* Every group has a 'prefix', and an array of tests. That's it. */
+ { "demo/", demo_tests },
+
+ END_OF_GROUPS
+};
+
+/* We can also define test aliases. These can be used for types of tests that
+ * cut across groups. */
+const char *alltests[] = { "+..", NULL };
+const char *slowtests[] = { "+demo/timeout", NULL };
+struct testlist_alias_t aliases[] = {
+
+ { "ALL", alltests },
+ { "SLOW", slowtests },
+
+ END_OF_ALIASES
+};
+
+
+int
+main(int c, const char **v)
+{
+ /* Finally, just call tinytest_main(). It lets you specify verbose
+ or quiet output with --verbose and --quiet. You can list
+ specific tests:
+
+ tinytest-demo demo/memcpy
+
+ or use a ..-wildcard to select multiple tests with a common
+ prefix:
+
+ tinytest-demo demo/..
+
+ If you list no tests, you get them all by default, so that
+ "tinytest-demo" and "tinytest-demo .." mean the same thing.
+
+ */
+ tinytest_set_aliases(aliases);
+ return tinytest_main(c, v, groups);
+}
diff --git a/ipc/chromium/src/third_party/libevent/test/tinytest_local.h b/ipc/chromium/src/third_party/libevent/test/tinytest_local.h
new file mode 100644
index 0000000000..87ec2fa67e
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/tinytest_local.h
@@ -0,0 +1,12 @@
+
+#include "util-internal.h"
+#ifdef _WIN32
+#include <winsock2.h>
+#endif
+
+#include "event2/util.h"
+
+#ifdef snprintf
+#undef snprintf
+#endif
+#define snprintf evutil_snprintf
diff --git a/ipc/chromium/src/third_party/libevent/test/tinytest_macros.h b/ipc/chromium/src/third_party/libevent/test/tinytest_macros.h
new file mode 100644
index 0000000000..e01f5d56cb
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/test/tinytest_macros.h
@@ -0,0 +1,213 @@
+/* tinytest_macros.h -- Copyright 2009-2012 Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TINYTEST_MACROS_H_INCLUDED_
+#define TINYTEST_MACROS_H_INCLUDED_
+
+/* Helpers for defining statement-like macros */
+#define TT_STMT_BEGIN do {
+#define TT_STMT_END } while (0)
+
+/* Redefine this if your test functions want to abort with something besides
+ * "goto end;" */
+#ifndef TT_EXIT_TEST_FUNCTION
+#define TT_EXIT_TEST_FUNCTION TT_STMT_BEGIN goto end; TT_STMT_END
+#endif
+
+/* Redefine this if you want to note success/failure in some different way. */
+#ifndef TT_DECLARE
+#define TT_DECLARE(prefix, args) \
+ TT_STMT_BEGIN \
+ printf("\n %s %s:%d: ",prefix,__FILE__,__LINE__); \
+ printf args ; \
+ TT_STMT_END
+#endif
+
+/* Announce a failure. Args are parenthesized printf args. */
+#define TT_GRIPE(args) TT_DECLARE("FAIL", args)
+
+/* Announce a non-failure if we're verbose. */
+#define TT_BLATHER(args) \
+ TT_STMT_BEGIN \
+ if (tinytest_get_verbosity_()>1) TT_DECLARE(" OK", args); \
+ TT_STMT_END
+
+#define TT_DIE(args) \
+ TT_STMT_BEGIN \
+ tinytest_set_test_failed_(); \
+ TT_GRIPE(args); \
+ TT_EXIT_TEST_FUNCTION; \
+ TT_STMT_END
+
+#define TT_FAIL(args) \
+ TT_STMT_BEGIN \
+ tinytest_set_test_failed_(); \
+ TT_GRIPE(args); \
+ TT_STMT_END
+
+/* Fail and abort the current test for the reason in msg */
+#define tt_abort_printf(msg) TT_DIE(msg)
+#define tt_abort_perror(op) TT_DIE(("%s: %s [%d]",(op),strerror(errno), errno))
+#define tt_abort_msg(msg) TT_DIE(("%s", msg))
+#define tt_abort() TT_DIE(("%s", "(Failed.)"))
+
+/* Fail but do not abort the current test for the reason in msg. */
+#define tt_failprint_f(msg) TT_FAIL(msg)
+#define tt_fail_perror(op) TT_FAIL(("%s: %s [%d]",(op),strerror(errno), errno))
+#define tt_fail_msg(msg) TT_FAIL(("%s", msg))
+#define tt_fail() TT_FAIL(("%s", "(Failed.)"))
+
+/* End the current test, and indicate we are skipping it. */
+#define tt_skip() \
+ TT_STMT_BEGIN \
+ tinytest_set_test_skipped_(); \
+ TT_EXIT_TEST_FUNCTION; \
+ TT_STMT_END
+
+#define tt_want_(b, msg, fail) \
+ TT_STMT_BEGIN \
+ if (!(b)) { \
+ tinytest_set_test_failed_(); \
+ TT_GRIPE(("%s",msg)); \
+ fail; \
+ } else { \
+ TT_BLATHER(("%s",msg)); \
+ } \
+ TT_STMT_END
+
+/* Assert b, but do not stop the test if b fails. Log msg on failure. */
+#define tt_want_msg(b, msg) \
+ tt_want_(b, msg, );
+
+/* Assert b and stop the test if b fails. Log msg on failure. */
+#define tt_assert_msg(b, msg) \
+ tt_want_(b, msg, TT_EXIT_TEST_FUNCTION);
+
+/* Assert b, but do not stop the test if b fails. */
+#define tt_want(b) tt_want_msg( (b), "want("#b")")
+/* Assert b, and stop the test if b fails. */
+#define tt_assert(b) tt_assert_msg((b), "assert("#b")")
+
+#define tt_assert_test_fmt_type(a,b,str_test,type,test,printf_type,printf_fmt, \
+ setup_block,cleanup_block,die_on_fail) \
+ TT_STMT_BEGIN \
+ type val1_ = (type)(a); \
+ type val2_ = (type)(b); \
+ int tt_status_ = (test); \
+ if (!tt_status_ || tinytest_get_verbosity_()>1) { \
+ printf_type print_; \
+ printf_type print1_; \
+ printf_type print2_; \
+ type value_ = val1_; \
+ setup_block; \
+ print1_ = print_; \
+ value_ = val2_; \
+ setup_block; \
+ print2_ = print_; \
+ TT_DECLARE(tt_status_?" OK":"FAIL", \
+ ("assert(%s): "printf_fmt" vs "printf_fmt, \
+ str_test, print1_, print2_)); \
+ print_ = print1_; \
+ cleanup_block; \
+ print_ = print2_; \
+ cleanup_block; \
+ if (!tt_status_) { \
+ tinytest_set_test_failed_(); \
+ die_on_fail ; \
+ } \
+ } \
+ TT_STMT_END
+
+#define tt_assert_test_type(a,b,str_test,type,test,fmt,die_on_fail) \
+ tt_assert_test_fmt_type(a,b,str_test,type,test,type,fmt, \
+ {print_=value_;},{},die_on_fail)
+
+#define tt_assert_test_type_opt(a,b,str_test,type,test,fmt,die_on_fail) \
+ tt_assert_test_fmt_type(a,b,str_test,type,test,type,fmt, \
+ {print_=value_?value_:"<NULL>";},{},die_on_fail)
+
+/* Helper: assert that a op b, when cast to type. Format the values with
+ * printf format fmt on failure. */
+#define tt_assert_op_type(a,op,b,type,fmt) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,type,(val1_ op val2_),fmt, \
+ TT_EXIT_TEST_FUNCTION)
+
+#define tt_int_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_), \
+ "%ld",TT_EXIT_TEST_FUNCTION)
+
+/** To compare SOCKET(windows)/fd */
+#define tt_fd_op(a,op,b) do { \
+ int _a = (int)(a); \
+ int _b = (int)(b); \
+ tt_assert_test_type(_a,_b,#a" "#op" "#b,long,(val1_ op val2_), \
+ "%ld",TT_EXIT_TEST_FUNCTION); \
+} while (0)
+
+#define tt_uint_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long, \
+ (val1_ op val2_),"%lu",TT_EXIT_TEST_FUNCTION)
+
+#define tt_ptr_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,const void*, \
+ (val1_ op val2_),"%p",TT_EXIT_TEST_FUNCTION)
+
+/** XXX: have some issues with printing this non-NUL terminated strings */
+#define tt_nstr_op(n,a,op,b) \
+ tt_assert_test_type_opt(a,b,#a" "#op" "#b,const char *, \
+ (val1_ && val2_ && strncmp(val1_,val2_,(n)) op 0),"<%s>", \
+ TT_EXIT_TEST_FUNCTION)
+
+#define tt_str_op(a,op,b) \
+ tt_assert_test_type_opt(a,b,#a" "#op" "#b,const char *, \
+ (val1_ && val2_ && strcmp(val1_,val2_) op 0),"<%s>", \
+ TT_EXIT_TEST_FUNCTION)
+
+#define tt_mem_op(expr1, op, expr2, len) \
+ tt_assert_test_fmt_type(expr1,expr2,#expr1" "#op" "#expr2, \
+ const void *, \
+ (val1_ && val2_ && memcmp(val1_, val2_, len) op 0), \
+ char *, "%s", \
+ { print_ = tinytest_format_hex_(value_, (len)); }, \
+ { if (print_) free(print_); }, \
+ TT_EXIT_TEST_FUNCTION \
+ );
+
+#define tt_want_int_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_),"%ld",(void)0)
+
+#define tt_want_uint_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long, \
+ (val1_ op val2_),"%lu",(void)0)
+
+#define tt_want_ptr_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,const void*, \
+ (val1_ op val2_),"%p",(void)0)
+
+#define tt_want_str_op(a,op,b) \
+ tt_assert_test_type(a,b,#a" "#op" "#b,const char *, \
+ (strcmp(val1_,val2_) op 0),"<%s>",(void)0)
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/time-internal.h b/ipc/chromium/src/third_party/libevent/time-internal.h
new file mode 100644
index 0000000000..e79e6a528d
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/time-internal.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef TIME_INTERNAL_H_INCLUDED_
+#define TIME_INTERNAL_H_INCLUDED_
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef EVENT__HAVE_MACH_MACH_TIME_H
+/* For mach_timebase_info */
+#include <mach/mach_time.h>
+#endif
+
+#include <time.h>
+
+#include "event2/util.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(EVENT__HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
+#define HAVE_POSIX_MONOTONIC
+#elif defined(EVENT__HAVE_MACH_ABSOLUTE_TIME)
+#define HAVE_MACH_MONOTONIC
+#elif defined(_WIN32)
+#define HAVE_WIN32_MONOTONIC
+#else
+#define HAVE_FALLBACK_MONOTONIC
+#endif
+
+long evutil_tv_to_msec_(const struct timeval *tv);
+EVENT2_EXPORT_SYMBOL
+void evutil_usleep_(const struct timeval *tv);
+
+#ifdef _WIN32
+typedef ULONGLONG (WINAPI *ev_GetTickCount_func)(void);
+#endif
+
+struct evutil_monotonic_timer {
+
+#ifdef HAVE_MACH_MONOTONIC
+ struct mach_timebase_info mach_timebase_units;
+#endif
+
+#ifdef HAVE_POSIX_MONOTONIC
+ int monotonic_clock;
+#endif
+
+#ifdef HAVE_WIN32_MONOTONIC
+ ev_GetTickCount_func GetTickCount64_fn;
+ ev_GetTickCount_func GetTickCount_fn;
+ ev_uint64_t last_tick_count;
+ ev_uint64_t adjust_tick_count;
+
+ ev_uint64_t first_tick;
+ ev_uint64_t first_counter;
+ double usec_per_count;
+ int use_performance_counter;
+#endif
+
+ struct timeval adjust_monotonic_clock;
+ struct timeval last_time;
+};
+
+EVENT2_EXPORT_SYMBOL
+int evutil_configure_monotonic_time_(struct evutil_monotonic_timer *mt,
+ int flags);
+EVENT2_EXPORT_SYMBOL
+int evutil_gettime_monotonic_(struct evutil_monotonic_timer *mt, struct timeval *tv);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_INTERNAL_H_INCLUDED_ */
diff --git a/ipc/chromium/src/third_party/libevent/util-internal.h b/ipc/chromium/src/third_party/libevent/util-internal.h
new file mode 100644
index 0000000000..39576c71ca
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/util-internal.h
@@ -0,0 +1,551 @@
+/*
+ * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef UTIL_INTERNAL_H_INCLUDED_
+#define UTIL_INTERNAL_H_INCLUDED_
+
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#include <errno.h>
+
+/* For EVUTIL_ASSERT */
+#include "log-internal.h"
+#include <stdio.h>
+#include <stdlib.h>
+#ifdef EVENT__HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+#ifdef EVENT__HAVE_SYS_EVENTFD_H
+#include <sys/eventfd.h>
+#endif
+#include "event2/util.h"
+
+#include "time-internal.h"
+#include "ipv6-internal.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* __has_attribute() wrapper */
+#ifdef __has_attribute
+# define EVUTIL_HAS_ATTRIBUTE __has_attribute
+#endif
+/** clang 3 __has_attribute misbehaves in some versions */
+#if defined(__clang__) && __clang__ == 1
+# if defined(__apple_build_version__)
+# if __clang_major__ <= 6
+# undef EVUTIL_HAS_ATTRIBUTE
+# endif
+# else /* !__apple_build_version__ */
+# if __clang_major__ == 3 && __clang_minor__ >= 2 && __clang_minor__ <= 5
+# undef EVUTIL_HAS_ATTRIBUTE
+# endif
+# endif /* __apple_build_version__ */
+#endif /*\ defined(__clang__) && __clang__ == 1 */
+#ifndef EVUTIL_HAS_ATTRIBUTE
+# define EVUTIL_HAS_ATTRIBUTE(x) 0
+#endif
+
+/* If we need magic to say "inline", get it for free internally. */
+#ifdef EVENT__inline
+#define inline EVENT__inline
+#endif
+
+/* Define to appropriate substitute if compiler doesnt have __func__ */
+#if defined(EVENT__HAVE___func__)
+# ifndef __func__
+# define __func__ __func__
+# endif
+#elif defined(EVENT__HAVE___FUNCTION__)
+# define __func__ __FUNCTION__
+#else
+# define __func__ __FILE__
+#endif
+
+/* A good no-op to use in macro definitions. */
+#define EVUTIL_NIL_STMT_ ((void)0)
+/* A no-op that tricks the compiler into thinking a condition is used while
+ * definitely not making any code for it. Used to compile out asserts while
+ * avoiding "unused variable" warnings. The "!" forces the compiler to
+ * do the sizeof() on an int, in case "condition" is a bitfield value.
+ */
+#define EVUTIL_NIL_CONDITION_(condition) do { \
+ (void)sizeof(!(condition)); \
+} while(0)
+
+/* Internal use only: macros to match patterns of error codes in a
+ cross-platform way. We need these macros because of two historical
+ reasons: first, nonblocking IO functions are generally written to give an
+ error on the "blocked now, try later" case, so sometimes an error from a
+ read, write, connect, or accept means "no error; just wait for more
+ data," and we need to look at the error code. Second, Windows defines
+ a different set of error codes for sockets. */
+
+#ifndef _WIN32
+
+#if EAGAIN == EWOULDBLOCK
+#define EVUTIL_ERR_IS_EAGAIN(e) \
+ ((e) == EAGAIN)
+#else
+#define EVUTIL_ERR_IS_EAGAIN(e) \
+ ((e) == EAGAIN || (e) == EWOULDBLOCK)
+#endif
+
+/* True iff e is an error that means a read/write operation can be retried. */
+#define EVUTIL_ERR_RW_RETRIABLE(e) \
+ ((e) == EINTR || EVUTIL_ERR_IS_EAGAIN(e))
+/* True iff e is an error that means an connect can be retried. */
+#define EVUTIL_ERR_CONNECT_RETRIABLE(e) \
+ ((e) == EINTR || (e) == EINPROGRESS)
+/* True iff e is an error that means a accept can be retried. */
+#define EVUTIL_ERR_ACCEPT_RETRIABLE(e) \
+ ((e) == EINTR || EVUTIL_ERR_IS_EAGAIN(e) || (e) == ECONNABORTED)
+
+/* True iff e is an error that means the connection was refused */
+#define EVUTIL_ERR_CONNECT_REFUSED(e) \
+ ((e) == ECONNREFUSED)
+
+#else
+/* Win32 */
+
+#define EVUTIL_ERR_IS_EAGAIN(e) \
+ ((e) == WSAEWOULDBLOCK || (e) == EAGAIN)
+
+#define EVUTIL_ERR_RW_RETRIABLE(e) \
+ ((e) == WSAEWOULDBLOCK || \
+ (e) == WSAEINTR)
+
+#define EVUTIL_ERR_CONNECT_RETRIABLE(e) \
+ ((e) == WSAEWOULDBLOCK || \
+ (e) == WSAEINTR || \
+ (e) == WSAEINPROGRESS || \
+ (e) == WSAEINVAL)
+
+#define EVUTIL_ERR_ACCEPT_RETRIABLE(e) \
+ EVUTIL_ERR_RW_RETRIABLE(e)
+
+#define EVUTIL_ERR_CONNECT_REFUSED(e) \
+ ((e) == WSAECONNREFUSED)
+
+#endif
+
+/* Arguments for shutdown() */
+#ifdef SHUT_RD
+#define EVUTIL_SHUT_RD SHUT_RD
+#else
+#define EVUTIL_SHUT_RD 0
+#endif
+#ifdef SHUT_WR
+#define EVUTIL_SHUT_WR SHUT_WR
+#else
+#define EVUTIL_SHUT_WR 1 /* SD_SEND */
+#endif
+#ifdef SHUT_BOTH
+#define EVUTIL_SHUT_BOTH SHUT_BOTH
+#else
+#define EVUTIL_SHUT_BOTH 2
+#endif
+
+/* Helper: Verify that all the elements in 'dlist' are internally consistent.
+ * Checks for circular lists and bad prev/next pointers.
+ *
+ * Example usage:
+ * EVUTIL_ASSERT_LIST_OK(eventlist, event, ev_next);
+ */
+#define EVUTIL_ASSERT_LIST_OK(dlist, type, field) do { \
+ struct type *elm1, *elm2, **nextp; \
+ if (LIST_EMPTY((dlist))) \
+ break; \
+ \
+ /* Check list for circularity using Floyd's */ \
+ /* 'Tortoise and Hare' algorithm */ \
+ elm1 = LIST_FIRST((dlist)); \
+ elm2 = LIST_NEXT(elm1, field); \
+ while (elm1 && elm2) { \
+ EVUTIL_ASSERT(elm1 != elm2); \
+ elm1 = LIST_NEXT(elm1, field); \
+ elm2 = LIST_NEXT(elm2, field); \
+ if (!elm2) \
+ break; \
+ EVUTIL_ASSERT(elm1 != elm2); \
+ elm2 = LIST_NEXT(elm2, field); \
+ } \
+ \
+ /* Now check next and prev pointers for consistency. */ \
+ nextp = &LIST_FIRST((dlist)); \
+ elm1 = LIST_FIRST((dlist)); \
+ while (elm1) { \
+ EVUTIL_ASSERT(*nextp == elm1); \
+ EVUTIL_ASSERT(nextp == elm1->field.le_prev); \
+ nextp = &LIST_NEXT(elm1, field); \
+ elm1 = *nextp; \
+ } \
+ } while (0)
+
+/* Helper: Verify that all the elements in a TAILQ are internally consistent.
+ * Checks for circular lists and bad prev/next pointers.
+ *
+ * Example usage:
+ * EVUTIL_ASSERT_TAILQ_OK(activelist, event, ev_active_next);
+ */
+#define EVUTIL_ASSERT_TAILQ_OK(tailq, type, field) do { \
+ struct type *elm1, *elm2, **nextp; \
+ if (TAILQ_EMPTY((tailq))) \
+ break; \
+ \
+ /* Check list for circularity using Floyd's */ \
+ /* 'Tortoise and Hare' algorithm */ \
+ elm1 = TAILQ_FIRST((tailq)); \
+ elm2 = TAILQ_NEXT(elm1, field); \
+ while (elm1 && elm2) { \
+ EVUTIL_ASSERT(elm1 != elm2); \
+ elm1 = TAILQ_NEXT(elm1, field); \
+ elm2 = TAILQ_NEXT(elm2, field); \
+ if (!elm2) \
+ break; \
+ EVUTIL_ASSERT(elm1 != elm2); \
+ elm2 = TAILQ_NEXT(elm2, field); \
+ } \
+ \
+ /* Now check next and prev pointers for consistency. */ \
+ nextp = &TAILQ_FIRST((tailq)); \
+ elm1 = TAILQ_FIRST((tailq)); \
+ while (elm1) { \
+ EVUTIL_ASSERT(*nextp == elm1); \
+ EVUTIL_ASSERT(nextp == elm1->field.tqe_prev); \
+ nextp = &TAILQ_NEXT(elm1, field); \
+ elm1 = *nextp; \
+ } \
+ EVUTIL_ASSERT(nextp == (tailq)->tqh_last); \
+ } while (0)
+
+/* Locale-independent replacements for some ctypes functions. Use these
+ * when you care about ASCII's notion of character types, because you are about
+ * to send those types onto the wire.
+ */
+EVENT2_EXPORT_SYMBOL
+int EVUTIL_ISALPHA_(char c);
+EVENT2_EXPORT_SYMBOL
+int EVUTIL_ISALNUM_(char c);
+int EVUTIL_ISSPACE_(char c);
+EVENT2_EXPORT_SYMBOL
+int EVUTIL_ISDIGIT_(char c);
+EVENT2_EXPORT_SYMBOL
+int EVUTIL_ISXDIGIT_(char c);
+int EVUTIL_ISPRINT_(char c);
+int EVUTIL_ISLOWER_(char c);
+int EVUTIL_ISUPPER_(char c);
+EVENT2_EXPORT_SYMBOL
+char EVUTIL_TOUPPER_(char c);
+EVENT2_EXPORT_SYMBOL
+char EVUTIL_TOLOWER_(char c);
+
+/** Remove all trailing horizontal whitespace (space or tab) from the end of a
+ * string */
+EVENT2_EXPORT_SYMBOL
+void evutil_rtrim_lws_(char *);
+
+
+/** Helper macro. If we know that a given pointer points to a field in a
+ structure, return a pointer to the structure itself. Used to implement
+ our half-baked C OO. Example:
+
+ struct subtype {
+ int x;
+ struct supertype common;
+ int y;
+ };
+ ...
+ void fn(struct supertype *super) {
+ struct subtype *sub = EVUTIL_UPCAST(super, struct subtype, common);
+ ...
+ }
+ */
+#define EVUTIL_UPCAST(ptr, type, field) \
+ ((type *)(((char*)(ptr)) - evutil_offsetof(type, field)))
+
+/* As open(pathname, flags, mode), except that the file is always opened with
+ * the close-on-exec flag set. (And the mode argument is mandatory.)
+ */
+int evutil_open_closeonexec_(const char *pathname, int flags, unsigned mode);
+
+EVENT2_EXPORT_SYMBOL
+int evutil_read_file_(const char *filename, char **content_out, size_t *len_out,
+ int is_binary);
+
+EVENT2_EXPORT_SYMBOL
+int evutil_socket_connect_(evutil_socket_t *fd_ptr, const struct sockaddr *sa, int socklen);
+
+int evutil_socket_finished_connecting_(evutil_socket_t fd);
+
+EVENT2_EXPORT_SYMBOL
+int evutil_ersatz_socketpair_(int, int , int, evutil_socket_t[]);
+
+int evutil_resolve_(int family, const char *hostname, struct sockaddr *sa,
+ ev_socklen_t *socklen, int port);
+
+const char *evutil_getenv_(const char *name);
+
+/* Structure to hold the state of our weak random number generator.
+ */
+struct evutil_weakrand_state {
+ ev_uint32_t seed;
+};
+
+#define EVUTIL_WEAKRAND_MAX EV_INT32_MAX
+
+/* Initialize the state of a week random number generator based on 'seed'. If
+ * the seed is 0, construct a new seed based on not-very-strong platform
+ * entropy, like the PID and the time of day.
+ *
+ * This function, and the other evutil_weakrand* functions, are meant for
+ * speed, not security or statistical strength. If you need a RNG which an
+ * attacker can't predict, or which passes strong statistical tests, use the
+ * evutil_secure_rng* functions instead.
+ */
+EVENT2_EXPORT_SYMBOL
+ev_uint32_t evutil_weakrand_seed_(struct evutil_weakrand_state *state, ev_uint32_t seed);
+/* Return a pseudorandom value between 0 and EVUTIL_WEAKRAND_MAX inclusive.
+ * Updates the state in 'seed' as needed -- this value must be protected by a
+ * lock.
+ */
+EVENT2_EXPORT_SYMBOL
+ev_int32_t evutil_weakrand_(struct evutil_weakrand_state *seed);
+/* Return a pseudorandom value x such that 0 <= x < top. top must be no more
+ * than EVUTIL_WEAKRAND_MAX. Updates the state in 'seed' as needed -- this
+ * value must be proteced by a lock */
+EVENT2_EXPORT_SYMBOL
+ev_int32_t evutil_weakrand_range_(struct evutil_weakrand_state *seed, ev_int32_t top);
+
+/* Evaluates to the same boolean value as 'p', and hints to the compiler that
+ * we expect this value to be false. */
+#if defined(__GNUC__) && __GNUC__ >= 3 /* gcc 3.0 or later */
+#define EVUTIL_UNLIKELY(p) __builtin_expect(!!(p),0)
+#else
+#define EVUTIL_UNLIKELY(p) (p)
+#endif
+
+#if EVUTIL_HAS_ATTRIBUTE(fallthrough)
+#define EVUTIL_FALLTHROUGH __attribute__((fallthrough))
+#else
+#define EVUTIL_FALLTHROUGH /* fallthrough */
+#endif
+
+/* Replacement for assert() that calls event_errx on failure. */
+#ifdef NDEBUG
+#define EVUTIL_ASSERT(cond) EVUTIL_NIL_CONDITION_(cond)
+#define EVUTIL_FAILURE_CHECK(cond) 0
+#else
+#define EVUTIL_ASSERT(cond) \
+ do { \
+ if (EVUTIL_UNLIKELY(!(cond))) { \
+ event_errx(EVENT_ERR_ABORT_, \
+ "%s:%d: Assertion %s failed in %s", \
+ __FILE__,__LINE__,#cond,__func__); \
+ /* In case a user-supplied handler tries to */ \
+ /* return control to us, log and abort here. */ \
+ (void)fprintf(stderr, \
+ "%s:%d: Assertion %s failed in %s", \
+ __FILE__,__LINE__,#cond,__func__); \
+ abort(); \
+ } \
+ } while (0)
+#define EVUTIL_FAILURE_CHECK(cond) EVUTIL_UNLIKELY(cond)
+#endif
+
+#ifndef EVENT__HAVE_STRUCT_SOCKADDR_STORAGE
+/* Replacement for sockaddr storage that we can use internally on platforms
+ * that lack it. It is not space-efficient, but neither is sockaddr_storage.
+ */
+struct sockaddr_storage {
+ union {
+ struct sockaddr ss_sa;
+ struct sockaddr_in ss_sin;
+ struct sockaddr_in6 ss_sin6;
+ char ss_padding[128];
+ } ss_union;
+};
+#define ss_family ss_union.ss_sa.sa_family
+#endif
+
+/* Internal addrinfo error code. This one is returned from only from
+ * evutil_getaddrinfo_common_, when we are sure that we'll have to hit a DNS
+ * server. */
+#define EVUTIL_EAI_NEED_RESOLVE -90002
+
+struct evdns_base;
+struct evdns_getaddrinfo_request;
+typedef struct evdns_getaddrinfo_request* (*evdns_getaddrinfo_fn)(
+ struct evdns_base *base,
+ const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in,
+ void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
+EVENT2_EXPORT_SYMBOL
+void evutil_set_evdns_getaddrinfo_fn_(evdns_getaddrinfo_fn fn);
+typedef void (*evdns_getaddrinfo_cancel_fn)(
+ struct evdns_getaddrinfo_request *req);
+EVENT2_EXPORT_SYMBOL
+void evutil_set_evdns_getaddrinfo_cancel_fn_(evdns_getaddrinfo_cancel_fn fn);
+
+EVENT2_EXPORT_SYMBOL
+struct evutil_addrinfo *evutil_new_addrinfo_(struct sockaddr *sa,
+ ev_socklen_t socklen, const struct evutil_addrinfo *hints);
+EVENT2_EXPORT_SYMBOL
+struct evutil_addrinfo *evutil_addrinfo_append_(struct evutil_addrinfo *first,
+ struct evutil_addrinfo *append);
+EVENT2_EXPORT_SYMBOL
+void evutil_adjust_hints_for_addrconfig_(struct evutil_addrinfo *hints);
+EVENT2_EXPORT_SYMBOL
+int evutil_getaddrinfo_common_(const char *nodename, const char *servname,
+ struct evutil_addrinfo *hints, struct evutil_addrinfo **res, int *portnum);
+
+struct evdns_getaddrinfo_request *evutil_getaddrinfo_async_(
+ struct evdns_base *dns_base,
+ const char *nodename, const char *servname,
+ const struct evutil_addrinfo *hints_in,
+ void (*cb)(int, struct evutil_addrinfo *, void *), void *arg);
+void evutil_getaddrinfo_cancel_async_(struct evdns_getaddrinfo_request *data);
+
+/** Return true iff sa is a looback address. (That is, it is 127.0.0.1/8, or
+ * ::1). */
+EVENT2_EXPORT_SYMBOL
+int evutil_sockaddr_is_loopback_(const struct sockaddr *sa);
+
+
+/**
+ Formats a sockaddr sa into a string buffer of size outlen stored in out.
+ Returns a pointer to out. Always writes something into out, so it's safe
+ to use the output of this function without checking it for NULL.
+ */
+EVENT2_EXPORT_SYMBOL
+const char *evutil_format_sockaddr_port_(const struct sockaddr *sa, char *out, size_t outlen);
+
+int evutil_hex_char_to_int_(char c);
+
+
+void evutil_free_secure_rng_globals_(void);
+void evutil_free_globals_(void);
+
+#ifdef _WIN32
+EVENT2_EXPORT_SYMBOL
+HMODULE evutil_load_windows_system_library_(const TCHAR *library_name);
+#endif
+
+#ifndef EV_SIZE_FMT
+#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__)
+#define EV_U64_FMT "%I64u"
+#define EV_I64_FMT "%I64d"
+#define EV_I64_ARG(x) ((__int64)(x))
+#define EV_U64_ARG(x) ((unsigned __int64)(x))
+#else
+#define EV_U64_FMT "%llu"
+#define EV_I64_FMT "%lld"
+#define EV_I64_ARG(x) ((long long)(x))
+#define EV_U64_ARG(x) ((unsigned long long)(x))
+#endif
+#endif
+
+#ifdef _WIN32
+#define EV_SOCK_FMT EV_I64_FMT
+#define EV_SOCK_ARG(x) EV_I64_ARG((x))
+#else
+#define EV_SOCK_FMT "%d"
+#define EV_SOCK_ARG(x) (x)
+#endif
+
+#if defined(__STDC__) && defined(__STDC_VERSION__) && !defined(__MINGW64_VERSION_MAJOR)
+#if (__STDC_VERSION__ >= 199901L)
+#define EV_SIZE_FMT "%zu"
+#define EV_SSIZE_FMT "%zd"
+#define EV_SIZE_ARG(x) (x)
+#define EV_SSIZE_ARG(x) (x)
+#endif
+#endif
+
+#ifndef EV_SIZE_FMT
+#if (EVENT__SIZEOF_SIZE_T <= EVENT__SIZEOF_LONG)
+#define EV_SIZE_FMT "%lu"
+#define EV_SSIZE_FMT "%ld"
+#define EV_SIZE_ARG(x) ((unsigned long)(x))
+#define EV_SSIZE_ARG(x) ((long)(x))
+#else
+#define EV_SIZE_FMT EV_U64_FMT
+#define EV_SSIZE_FMT EV_I64_FMT
+#define EV_SIZE_ARG(x) EV_U64_ARG(x)
+#define EV_SSIZE_ARG(x) EV_I64_ARG(x)
+#endif
+#endif
+
+EVENT2_EXPORT_SYMBOL
+evutil_socket_t evutil_socket_(int domain, int type, int protocol);
+evutil_socket_t evutil_accept4_(evutil_socket_t sockfd, struct sockaddr *addr,
+ ev_socklen_t *addrlen, int flags);
+
+ /* used by one of the test programs.. */
+EVENT2_EXPORT_SYMBOL
+int evutil_make_internal_pipe_(evutil_socket_t fd[2]);
+evutil_socket_t evutil_eventfd_(unsigned initval, int flags);
+
+#ifdef SOCK_NONBLOCK
+#define EVUTIL_SOCK_NONBLOCK SOCK_NONBLOCK
+#else
+#define EVUTIL_SOCK_NONBLOCK 0x4000000
+#endif
+#ifdef SOCK_CLOEXEC
+#define EVUTIL_SOCK_CLOEXEC SOCK_CLOEXEC
+#else
+#define EVUTIL_SOCK_CLOEXEC 0x80000000
+#endif
+#ifdef EFD_NONBLOCK
+#define EVUTIL_EFD_NONBLOCK EFD_NONBLOCK
+#else
+#define EVUTIL_EFD_NONBLOCK 0x4000
+#endif
+#ifdef EFD_CLOEXEC
+#define EVUTIL_EFD_CLOEXEC EFD_CLOEXEC
+#else
+#define EVUTIL_EFD_CLOEXEC 0x8000
+#endif
+
+void evutil_memclear_(void *mem, size_t len);
+
+struct in_addr;
+struct in6_addr;
+
+/* This is a any, loopback, link-local, multicast */
+EVENT2_EXPORT_SYMBOL
+int evutil_v4addr_is_local_(const struct in_addr *in);
+/* This is a reserved, ipv4compat, ipv4map, loopback,
+ * link-local, multicast, or unspecified address. */
+EVENT2_EXPORT_SYMBOL
+int evutil_v6addr_is_local_(const struct in6_addr *in);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/ipc/chromium/src/third_party/libevent/whatsnew-2.0.txt b/ipc/chromium/src/third_party/libevent/whatsnew-2.0.txt
new file mode 100644
index 0000000000..3561fcb94c
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/whatsnew-2.0.txt
@@ -0,0 +1,609 @@
+What's New In Libevent 2.0 so far:
+
+1. Meta-issues
+
+1.1. About this document
+
+ This document describes the key differences between Libevent 1.4 and
+ Libevent 2.0, from a user's point of view. It was most recently
+ updated based on features in git master as of August 2010.
+
+ NOTE: I am very sure that I missed some thing on this list. Caveat
+ haxxor.
+
+1.2. Better documentation
+
+ There is now a book-in-progress that explains how to use Libevent and its
+ growing pile of APIs. As of this writing, it covers everything except the
+ http and rpc code. Check out the latest draft at
+ http://www.wangafu.net/~nickm/libevent-book/ .
+
+2. New and Improved Event APIs
+
+ Many APIs are improved, refactored, or deprecated in Libevent 2.0.
+
+ COMPATIBILITY:
+
+ Nearly all existing code that worked with Libevent 1.4 should still
+ work correctly with Libevent 2.0. However, if you are writing new code,
+ or if you want to port old code, we strongly recommend using the new APIs
+ and avoiding deprecated APIs as much as possible.
+
+ Binaries linked against Libevent 1.4 will need to be recompiled to link
+ against Libevent 2.0. This is nothing new; we have never been good at
+ preserving binary compatibility between releases. We'll try harder in the
+ future, though: see 2.1 below.
+
+2.1. New header layout for improved forward-compatibility
+
+ Libevent 2.0 has a new header layout to make it easier for programmers to
+ write good, well-supported libevent code. The new headers are divided
+ into three types.
+
+ There are *regular headers*, like event2/event.h. These headers contain
+ the functions that most programmers will want to use.
+
+ There are *backward compatibility headers*, like event2/event_compat.h.
+ These headers contain declarations for deprecated functions from older
+ versions of Libevent. Documentation in these headers should suggest what's
+ wrong with the old functions, and what functions you want to start using
+ instead of the old ones. Some of these functions might be removed in a
+ future release. New programs should generally not include these headers.
+
+ Finally, there are *structure headers*, like event2/event_struct.h.
+ These headers contain definitions of some structures that Libevent has
+ historically exposed. Exposing them caused problems in the past,
+ since programs that were compiled to work with one version of Libevent
+ would often stop working with another version that changed the size or
+ layout of some object. We've moving them into separate headers so
+ that programmers can know that their code is not depending on any
+ unstable aspect of the Libvent ABI. New programs should generally not
+ include these headers unless they really know what they are doing, are
+ willing to rebuild their software whenever they want to link it
+ against a new version of Libevent, and are willing to risk their code
+ breaking if and when data structures change.
+
+ Functionality that once was located in event.h is now more subdivided.
+ The core event logic is now in event2/event.h. The "evbuffer" functions
+ for low-level buffer manipulation are in event2/buffer.h. The
+ "bufferevent" functions for higher-level buffered IO are in
+ event2/bufferevent.h.
+
+ COMPATIBILITY:
+
+ All of the old headers (event.h, evdns.h, evhttp.h, evrpc.h, and
+ evutil.h) will continue to work by including the corresponding new
+ headers. Old code should not be broken by this change.
+
+2.2. New thread-safe, binary-compatible, harder-to-mess-up APIs
+
+ Some aspects of the historical Libevent API have encouraged
+ non-threadsafe code, or forced code built against one version of Libevent
+ to no longer build with another. The problems with now-deprecated APIs
+ fell into two categories:
+
+ 1) Dependence on the "current" event_base. In an application with
+ multiple event_bases, Libevent previously had a notion of the
+ "current" event_base. New events were linked to this base, and
+ the caller needed to explicitly reattach them to another base.
+ This was horribly error-prone.
+
+ Functions like "event_set" that worked with the "current" event_base
+ are now deprecated but still available (see 2.1). There are new
+ functions like "event_assign" that take an explicit event_base
+ argument when setting up a structure. Using these functions will help
+ prevent errors in your applications, and to be more threadsafe.
+
+ 2) Structure dependence. Applications needed to allocate 'struct
+ event' themselves, since there was no function in Libevent to do it
+ for them. But since the size and contents of struct event can
+ change between libevent versions, this created binary-compatibility
+ nightmares. All structures of this kind are now isolated in
+ _struct.h header (see 2.1), and there are new allocate-and-
+ initialize functions you can use instead of the old initialize-only
+ functions. For example, instead of malloc and event_set, you
+ can use event_new().
+
+ (For people who do really want to allocate a struct event on the
+ stack, or put one inside another structure, you can still use
+ event2/event_compat.h.)
+
+ So in the case where old code would look like this:
+
+ #include <event.h>
+ ...
+ struct event *ev = malloc(sizeof(struct event));
+ /* This call will cause a buffer overrun if you compile with one version
+ of Libevent and link dynamically against another. */
+ event_set(ev, fd, EV_READ, cb, NULL);
+ /* If you forget this call, your code will break in hard-to-diagnose
+ ways in the presence of multiple event bases. */
+ event_set_base(ev, base);
+
+ New code will look more like this:
+
+ #include <event2/event.h>
+ ...
+ struct event *ev;
+ ev = event_new(base, fd, EV_READ, cb, NULL);
+
+2.3. Overrideable allocation functions
+
+ If you want to override the allocation functions used by libevent
+ (for example, to use a specialized allocator, or debug memory
+ issues, or so on), you can replace them by calling
+ event_set_mem_functions. It takes replacements for malloc(),
+ free(), and realloc().
+
+ If you're going to use this facility, you need to call it _before_
+ Libevent does any memory allocation; otherwise, Libevent may allocate some
+ memory with malloc(), and free it with the free() function you provide.
+
+ You can disable this feature when you are building Libevent by passing
+ the --disable-malloc-replacement argument to configure.
+
+2.4. Configurable event_base creation
+
+ Older versions of Libevent would always got the fastest backend
+ available, unless you reconfigured their behavior with the environment
+ variables EVENT_NOSELECT, EVENT_NOPOLL, and so forth. This was annoying
+ to programmers who wanted to pick a backend explicitly without messing
+ with the environment.
+
+ Also, despite our best efforts, not every backend supports every
+ operation we might like. Some features (like edge-triggered events, or
+ working with non-socket file descriptors) only work with some operating
+ systems' fast backends. Previously, programmers who cared about this
+ needed to know which backends supported what. This tended to get quite
+ ungainly.
+
+ There is now an API to choose backends, either by name or by feature.
+ Here is an example:
+
+ struct event_config_t *config;
+ struct event_base *base;
+
+ /* Create a new configuration object. */
+ config = event_config_new();
+ /* We don't want to use the "select" method. */
+ event_config_avoid_method(config, "select");
+ /* We want a method that can work with non-socket file descriptors */
+ event_config_require_features(config, EV_FEATURE_FDS);
+
+ base = event_base_new_with_config(config);
+ if (!base) {
+ /* There is no backend method that does what we want. */
+ exit(1);
+ }
+ event_config_free(config);
+
+ Supported features are documented in event2/event.h
+
+2.5. Socket is now an abstract type
+
+ All APIs that formerly accepted int as a socket type now accept
+ "evutil_socket_t". On Unix, this is just an alias for "int" as
+ before. On Windows, however, it's an alias for SOCKET, which can
+ be wider than int on 64-bit platforms.
+
+2.6. Timeouts and persistent events work together.
+
+ Previously, it wasn't useful to set a timeout on a persistent event:
+ the timeout would trigger once, and never again. This is not what
+ applications tend to want. Instead, applications tend to want every
+ triggering of the event to re-set the timeout. So now, if you set
+ up an event like this:
+ struct event *ev;
+ struct timeval tv;
+ ev = event_new(base, fd, EV_READ|EV_PERSIST, cb, NULL);
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+ event_add(ev, &tv);
+
+ The callback 'cb' will be invoked whenever fd is ready to read, OR whenever
+ a second has passed since the last invocation of cb.
+
+2.7. Multiple events allowed per fd
+
+ Older versions of Libevent allowed at most one EV_READ event and at most
+ one EV_WRITE event per socket, per event base. This restriction is no
+ longer present.
+
+2.8. evthread_* functions for thread-safe structures.
+
+ Libevent structures can now be built with locking support. This code
+ makes it safe to add, remove, and activate events on an event base from a
+ different thread. (Previously, if you wanted to write multithreaded code
+ with Libevent, you could only an event_base or its events in one thread at
+ a time.)
+
+ If you want threading support and you're using pthreads, you can just
+ call evthread_use_pthreads(). (You'll need to link against the
+ libevent_pthreads library in addition to libevent_core. These functions are
+ not in libevent_core.)
+
+ If you want threading support and you're using Windows, you can just
+ call evthread_use_windows_threads().
+
+ If you are using some locking system besides Windows and pthreads, You
+ can enable this on a per-event-base level by writing functions to
+ implement mutexes, conditions, and thread IDs, and passing them to
+ evthread_set_lock_callbacks and related functions in event2/thread.h.
+
+ Once locking functions are enabled, every new event_base is created with a
+ lock. You can prevent a single event_base from being built with a lock
+ disabled by using the EVENT_BASE_FLAG_NOLOCK flag in its
+ event_config. If an event_base is created with a lock, it is safe to call
+ event_del, event_add, and event_active on its events from any thread. The
+ event callbacks themselves are still all executed from the thread running
+ the event loop.
+
+ To make an evbuffer or a bufferevent object threadsafe, call its
+ *_enable_locking() function.
+
+ The HTTP api is not currently threadsafe.
+
+ To build Libevent with threading support disabled, pass
+ --disable-thread-support to the configure script.
+
+2.9. Edge-triggered events on some backends.
+
+ With some backends, it's now possible to add the EV_ET flag to an event
+ in order to request that the event's semantics be edge-triggered. Right
+ now, epoll and kqueue support this.
+
+ The corresponding event_config feature is EV_FEATURE_ET; see 2.4 for more
+ information.
+
+2.10. Better support for huge numbers of timeouts
+
+ The heap-based priority queue timer implementation for Libevent 1.4 is good
+ for randomly distributed timeouts, but suboptimal if you have huge numbers
+ of timeouts that all expire in the same amount of time after their
+ creation. The new event_base_init_common_timeout() logic lets you signal
+ that a given timeout interval will be very common, and should use a linked
+ list implementation instead of a priority queue.
+
+2.11. Improved debugging support
+
+ It's been pretty easy to forget to delete all your events before you
+ re-initialize them, or otherwise put Libevent in an internally inconsistent
+ state. You can tell libevent to catch these and other common errors with
+ the new event_enable_debug_mode() call. Just invoke it before you do
+ any calls to other libevent functions, and it'll catch many common
+ event-level errors in your code.
+
+2.12. Functions to access all event fields
+
+ So that you don't have to access the struct event fields directly, Libevent
+ now provides accessor functions to retrieve everything from an event that
+ you set during event_new() or event_assign().
+
+3. Backend-specific and performance improvements.
+
+3.1. Change-minimization on O(1) backends
+
+ With previous versions of Libevent, if you called event_del() and
+ event_add() repeatedly on a single event between trips to the backend's
+ dispatch function, the backend might wind up making unnecessary calls or
+ passing unnecessary data to the kernel. The new backend logic batches up
+ redundant adds and deletes, and performs no more operations than necessary
+ at the kernel level.
+
+ This logic is on for the kqueue backend, and available (but off by
+ default) for the epoll backend. To turn it on for the epoll backend,
+ set the EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST flag in the
+ event_base_cofig, or set the EVENT_EPOLL_USE_CHANGELIST environment
+ variable. Doing this with epoll may result in weird bugs if you give
+ any fds closed by dup() or its variants.
+
+3.2. Improved notification on Linux
+
+ When we need to wake the event loop up from another thread, we use
+ an epollfd to do so, instead of a socketpair. This is supposed to be
+ faster.
+
+3.3. Windows: better support for everything
+
+ Bufferevents on Windows can use a new mechanism (off-by-default; see below)
+ to send their data via Windows overlapped IO and get their notifications
+ via the IOCP API. This should be much faster than using event-based
+ notification.
+
+ Other functions throughout the code have been fixed to work more
+ consistently with Windows. Libevent now builds on Windows using either
+ mingw, or using MSVC (with nmake). Libevent works fine with UNICODE
+ defined, or not.
+
+ Data structures are a little smarter: our lookups from socket to pending
+ event are now done with O(1) hash tables rather than O(lg n) red-black
+ trees.
+
+ Unfortunately, the main Windows backend is still select()-based: from
+ testing the IOCP backends on the mailing list, it seems that there isn't
+ actually a way to tell for certain whether a socket is writable with IOCP.
+ Libevent 2.1 may add a multithreaded WaitForMultipleEvents-based
+ backend for better performance with many inactive sockets and better
+ integration with Windows events.
+
+4. Improvements to evbuffers
+
+ Libevent has long had an "evbuffer" implementation to wrap access to an
+ input or output memory buffer. In previous versions, the implementation
+ was very inefficient and lacked some desirable features. We've made many
+ improvements in Libevent 2.0.
+
+4.1. Chunked-memory internal representation
+
+ Previously, each evbuffer was a huge chunk of memory. When we ran out of
+ space in an evbuffer, we used realloc() to grow the chunk of memory. When
+ data was misaligned, we used memmove to move the data back to the front
+ of the buffer.
+
+ Needless to say, this is a terrible interface for networked IO.
+
+ Now, evbuffers are implemented as a linked list of memory chunks, like
+ most Unix kernels use for network IO. (See Linux's skbuf interfaces,
+ or *BSD's mbufs). Data is added at the end of the linked list and
+ removed from the front, so that we don't ever need realloc huge chunks
+ or memmove the whole buffer contents.
+
+ To avoid excessive calls to read and write, we use the readv/writev
+ interfaces (or WSASend/WSARecv on Windows) to do IO on multiple chunks at
+ once with a single system call.
+
+ COMPATIBILITY NOTE:
+ The evbuffer struct is no longer exposed in a header. The code here is
+ too volatile to expose an official evbuffer structure, and there was never
+ any means provided to create an evbuffer except via evbuffer_new which
+ heap-allocated the buffer.
+
+ If you need access to the whole buffer as a linear chunk of memory, the
+ EVBUFFER_DATA() function still works. Watch out, though: it needs to copy
+ the buffer's contents in a linear chunk before you can use it.
+
+4.2. More flexible readline support
+
+ The old evbuffer_readline() function (which accepted any sequence of
+ CR and LF characters as a newline, and which couldn't handle lines
+ containing NUL characters), is now deprecated. The preferred
+ function is evbuffer_readln(), which supports a variety of
+ line-ending styles, and which can return the number of characters in
+ the line returned.
+
+ You can also call evbuffer_search_eol() to find the end of a line
+ in an evbuffer without ever extracting the line.
+
+4.3. Support for file-based IO in evbuffers.
+
+ You can now add chunks of a file into a evbuffer, and Libevent will have
+ your OS use mapped-memory functionality, sendfile, or splice to transfer
+ the data without ever copying it to userspace. On OSs where this is not
+ supported, Libevent just loads the data.
+
+ There are probably some bugs remaining in this code. On some platforms
+ (like Windows), it just reads the relevant parts of the file into RAM.
+
+4.4. Support for zero-copy ("scatter/gather") writes in evbuffers.
+
+ You can add a piece of memory to an evbuffer without copying it.
+ Instead, Libevent adds a new element to the evbuffer's linked list of
+ chunks with a pointer to the memory you supplied. You can do this
+ either with a reference-counted chunk (via evbuffer_add_reference), or
+ by asking Libevent for a pointer to its internal vectors (via
+ evbuffer_reserve_space or evbuffer_peek()).
+
+4.5. Multiple callbacks per evbuffer
+
+ Previously, you could only have one callback active on an evbuffer at a
+ time. In practice, this meant that if one part of Libevent was using an
+ evbuffer callback to notice when an internal evbuffer was reading or
+ writing data, you couldn't have your own callback on that evbuffer.
+
+ Now, you can now use the evbuffer_add_cb() function to add a callback that
+ does not interfere with any other callbacks.
+
+ The evbuffer_setcb() function is now deprecated.
+
+4.6. New callback interface
+
+ Previously, evbuffer callbacks were invoked with the old size of the
+ buffer and the new size of the buffer. This interface could not capture
+ operations that simultaneously filled _and_ drained a buffer, or handle
+ cases where we needed to postpone callbacks until multiple operations were
+ complete.
+
+ Callbacks that are set with evbuffer_setcb still use the old API.
+ Callbacks added with evbuffer_add_cb() use a new interface that takes a
+ pointer to a struct holding the total number of bytes drained read and the
+ total number of bytes written. See event2/buffer.h for full details.
+
+4.7. Misc new evbuffer features
+
+ You can use evbuffer_remove() to move a given number of bytes from one
+ buffer to another.
+
+ The evbuffer_search() function lets you search for repeated instances of
+ a pattern inside an evbuffer.
+
+ You can use evbuffer_freeze() to temporarily suspend drains from or adds
+ to a given evbuffer. This is useful for code that exposes an evbuffer as
+ part of its public API, but wants users to treat it as a pure source or
+ sink.
+
+ There's an evbuffer_copyout() that looks at the data at the start of an
+ evbuffer without doing a drain.
+
+ You can have an evbuffer defer all of its callbacks, so that rather than
+ being invoked immediately when the evbuffer's length changes, they are
+ invoked from within the event_loop. This is useful when you have a
+ complex set of callbacks that can change the length of other evbuffers,
+ and you want to avoid having them recurse and overflow your stack.
+
+5. Bufferevents improvements
+
+ Libevent has long included a "bufferevents" structure and related
+ functions that were useful for generic buffered IO on a TCP connection.
+ This is what Libevent uses for its HTTP implementation. In addition to
+ the improvements that they get for free from the underlying evbuffer
+ implementation above, there are many new features in Libevent 2.0's
+ evbuffers.
+
+5.1. New OO implementations
+
+ The "bufferevent" structure is now an abstract base type with multiple
+ implementations. This should not break existing code, which always
+ allocated bufferevents with bufferevent_new().
+
+ Current implementations of the bufferevent interface are described below.
+
+5.2. bufferevent_socket_new() replaces bufferevent_new()
+
+ Since bufferevents that use a socket are not the only kind,
+ bufferevent_new() is now deprecated. Use bufferevent_socket_new()
+ instead.
+
+5.3. Filtered bufferevent IO
+
+ You can use bufferevent_filter_new() to create a bufferevent that wraps
+ around another bufferevent and transforms data it is sending and
+ receiving. See test/regress_zlib.c for a toy example that uses zlib to
+ compress data before sending it over a bufferevent.
+
+5.3. Linked pairs of bufferevents
+
+ You can use bufferevent_pair_new() to produce two linked
+ bufferevents. This is like using socketpair, but doesn't require
+ system-calls.
+
+5.4. SSL support for bufferevents with OpenSSL
+
+ There is now a bufferevent type that supports SSL/TLS using the
+ OpenSSL library. The code for this is build in a separate
+ library, libevent_openssl, so that your programs don't need to
+ link against OpenSSL unless they actually want SSL support.
+
+ There are two ways to construct one of these bufferevents, both
+ declared in <event2/bufferevent_ssl.h>. If you want to wrap an
+ SSL layer around an existing bufferevent, you would call the
+ bufferevent_openssl_filter_new() function. If you want to do SSL
+ on a socket directly, call bufferevent_openssl_socket_new().
+
+5.5. IOCP support for bufferevents on Windows
+
+ There is now a bufferevents backend that supports IOCP on Windows.
+ Supposedly, this will eventually make Windows IO much faster for
+ programs using bufferevents. We'll have to see; the code is not
+ currently optimized at all. To try it out, call the
+ event_base_start_iocp() method on an event_base before contructing
+ bufferevents.
+
+ This is tricky code; there are probably some bugs hiding here.
+
+5.6. Improved connect support for bufferevents.
+
+ You can now create a bufferevent that is not yet connected to any
+ host, and tell it to connect, either by address or by hostname.
+
+ The functions to do this are bufferevent_socket_connect and
+ bufferevent_socket_connect_hostname.
+
+5.7. Rate-limiting for bufferevents
+
+ If you need to limit the number of bytes read/written by a single
+ bufferevent, or by a group of them, you can do this with a new set of
+ bufferevent rate-limiting calls.
+
+6. Other improvements
+
+6.1. DNS improvements
+
+6.1.1. DNS: IPv6 nameservers
+
+ The evdns code now lets you have nameservers whose addresses are IPv6.
+
+6.1.2. DNS: Better security
+
+ Libevent 2.0 tries harder to resist DNS answer-sniping attacks than
+ earlier versions of evdns. See comments in the code for full details.
+
+ Notably, evdns now supports the "0x20 hack" to make it harder to
+ impersonate a DNS server. Additionally, Libevent now uses a strong
+ internal RNG to generate DNS transaction IDs, so you don't need to supply
+ your own.
+
+6.1.3. DNS: Getaddrinfo support
+
+ There's now an asynchronous getaddrinfo clone, evdns_getaddrinfo(),
+ to make the results of the evdns functions more usable. It doesn't
+ support every feature of a typical platform getaddrinfo() yet, but it
+ is quite close.
+
+ There is also a blocking evutil_getaddrinfo() declared in
+ event2/util.h, to provide a getaddrinfo() implementation for
+ platforms that don't have one, and smooth over the differences in
+ various platforms implementations of RFC3493.
+
+ Bufferevents provide bufferevent_connect_hostname(), which combines
+ the name lookup and connect operations.
+
+6.1.4. DNS: No more evdns globals
+
+ Like an event base, evdns operations are now supposed to use an evdns_base
+ argument. This makes them easier to wrap for other (more OO) languages,
+ and easier to control the lifetime of. The old evdns functions will
+ still, of course, continue working.
+
+6.2. Listener support
+
+ You can now more easily automate setting up a bound socket to listen for
+ TCP connections. Just use the evconnlistener_*() functions in the
+ event2/listener.h header.
+
+ The listener code supports IOCP on Windows if available.
+
+6.3. Secure RNG support
+
+ Network code very frequently needs a secure, hard-to-predict random number
+ generator. Some operating systems provide a good C implementation of one;
+ others do not. Libevent 2.0 now provides a consistent implementation
+ based on the arc4random code originally from OpenBSD. Libevent (and you)
+ can use the evutil_secure_rng_*() functions to access a fairly secure
+ random stream of bytes.
+
+6.4. HTTP
+
+ The evhttp uriencoding and uridecoding APIs have updated versions
+ that behave more correctly, and can handle strings with internal NULs.
+
+ The evhttp query parsing and URI parsing logic can now detect errors
+ more usefully. Moreover, we include an actual URI parsing function
+ (evhttp_uri_parse()) to correctly parse URIs, so as to discourage
+ people from rolling their own ad-hoc parsing functions.
+
+ There are now accessor functions for the useful fields of struct http
+ and friends; it shouldn't be necessary to access them directly any
+ more.
+
+ Libevent now lets you declare support for all specified HTTP methods,
+ including OPTIONS, PATCH, and so on. The default list is unchanged.
+
+ Numerous evhttp bugs also got fixed.
+
+7. Infrastructure improvements
+
+7.1. Better unit test framework
+
+ We now use a unit test framework that Nick wrote called "tinytest".
+ The main benefit from Libevent's point of view is that tests which
+ might mess with global state can all run each in their own
+ subprocess. This way, when there's a bug that makes one unit test
+ crash or mess up global state, it doesn't affect any others.
+
+7.2. Better unit tests
+
+ Despite all the code we've added, our unit tests are much better than
+ before. Right now, iterating over the different backends on various
+ platforms, I'm getting between 78% and 81% test coverage, compared
+ with less than 45% test coverage in Libevent 1.4.
+
diff --git a/ipc/chromium/src/third_party/libevent/whatsnew-2.1.txt b/ipc/chromium/src/third_party/libevent/whatsnew-2.1.txt
new file mode 100644
index 0000000000..c1f4df8f78
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/whatsnew-2.1.txt
@@ -0,0 +1,768 @@
+ What's new in Libevent 2.1
+ Nick Mathewson
+
+0. Before we start
+
+0.1. About this document
+
+ This document describes the key differences between Libevent 2.0 and
+ Libevent 2.1, from a user's point of view. It's a work in progress.
+
+ For better documentation about libevent, see the links at
+ http://libevent.org/
+
+ Libevent 2.1 would not be possible without the generous help of
+ numerous volunteers. For a list of who did what in Libevent 2.1,
+ please see the ChangeLog!
+
+ NOTE: I am very sure that I missed some thing on this list. Caveat
+ haxxor.
+
+0.2. Where to get help
+
+ Try looking at the other documentation too. All of the header files
+ have documentation in the doxygen format; this gets turned into nice
+ HTML and linked to from the libevent.org website.
+
+ There is a work-in-progress book with reference manual at
+ http://www.wangafu.net/~nickm/libevent-book/ .
+
+ You can ask questions on the #libevent IRC channel at irc.oftc.net or
+ on the mailing list at libevent-users@freehaven.net. The mailing list
+ is subscribers-only, so you will need to subscribe before you post.
+
+0.3. Compatibility
+
+ Our source-compatibility policy is that correct code (that is to say,
+ code that uses public interfaces of Libevent and relies only on their
+ documented behavior) should have forward source compatibility: any
+ such code that worked with a previous version of Libevent should work
+ with this version too.
+
+ We don't try to do binary compatibility except within stable release
+ series, so binaries linked against any version of Libevent 2.0 will
+ probably need to be recompiled against Libevent 2.1.4-alpha if you
+ want to use it. It is probable that we'll break binary compatibility
+ again before Libevent 2.1 is stable.
+
+1. New APIs and features
+
+1.1. New ways to build libevent
+
+ We now provide an --enable-gcc-hardening configure option to turn on
+ GCC features designed for increased code security.
+
+ There is also an --enable-silent-rules configure option to make
+ compilation run more quietly with automake 1.11 or later.
+
+ You no longer need to use the --enable-gcc-warnings option to turn on
+ all of the GCC warnings that Libevent uses. The only change from
+ using that option now is to turn warnings into errors.
+
+ For IDE users, files that are not supposed to be built are now
+ surrounded with appropriate #ifdef lines to keep your IDE from getting
+ upset.
+
+ There is now an alternative cmake-based build process; cmake users
+ should see the relevant sections in the README.
+
+
+1.2. New functions for events and the event loop
+
+ If you're running Libevent with multiple event priorities, you might
+ want to make sure that Libevent checks for new events frequently, so
+ that time-consuming or numerous low-priority events don't keep it from
+ checking for new high-priority events. You can now use the
+ event_config_set_max_dispatch_interval() interface to ensure that the
+ loop checks for new events either every N microseconds, every M
+ callbacks, or both.
+
+ When configuring an event base, you can now choose whether you want
+ timers to be more efficient, or more precise. (This only has effect
+ on Linux for now.) Timers are efficient by default: to select more
+ precise timers, use the EVENT_BASE_FLAG_PRECISE_TIMER flag when
+ constructing the event_config, or set the EVENT_PRECISE_TIMER
+ environment variable to a non-empty string.
+
+ There is an EVLOOP_NO_EXIT_ON_EMPTY flag that tells event_base_loop()
+ to keep looping even when there are no pending events. (Ordinarily,
+ event_base_loop() will exit as soon as no events are pending.)
+
+ Past versions of Libevent have been annoying to use with some
+ memory-leak-checking tools, because Libevent allocated some global
+ singletons but provided no means to free them. There is now a
+ function, libevent_global_shutdown(), that you can use to free all
+ globally held resources before exiting, so that your leak-check tools
+ don't complain. (Note: this function doesn't free non-global things
+ like events, bufferevents, and so on; and it doesn't free anything
+ that wouldn't otherwise get cleaned up by the operating system when
+ your process exit()s. If you aren't using a leak-checking tool, there
+ is not much reason to call libevent_global_shutdown().)
+
+ There is a new event_base_get_npriorities() function to return the
+ number of priorities set in the event base.
+
+ Libevent 2.0 added an event_new() function to construct a new struct
+ event on the heap. Unfortunately, with event_new(), there was no
+ equivalent for:
+
+ struct event ev;
+ event_assign(&ev, base, fd, EV_READ, callback, &ev);
+
+ In other words, there was no easy way for event_new() to set up an
+ event so that the event itself would be its callback argument.
+ Libevent 2.1 lets you do this by passing "event_self_cbarg()" as the
+ callback argument:
+
+ struct event *evp;
+ evp = event_new(base, fd, EV_READ, callback,
+ event_self_cbarg());
+
+ There's also a new event_base_get_running_event() function you can
+ call from within a Libevent callback to get a pointer to the current
+ event. This should never be strictly necessary, but it's sometimes
+ convenient.
+
+ The event_base_once() function used to leak some memory if the event
+ that it added was never actually triggered. Now, its memory is
+ tracked in the event_base and freed when the event_base is freed.
+ Note however that Libevent doesn't know how to free any information
+ passed as the callback argument to event_base_once is still something
+ you'll might need a way to de-allocate yourself.
+
+ There is an event_get_priority() function to return an event's
+ priority.
+
+ By analogy to event_base_loopbreak(), there is now an
+ event_base_loopcontinue() that tells Libevent to stop processing
+ active event callbacks, and re-scan for new events right away.
+
+ There's a function, event_base_foreach_event(), that can iterate over
+ every event currently pending or active on an event base, and invoke a
+ user-supplied callback on each. The callback must not alter the events
+ or add or remove anything to the event base.
+
+ We now have an event_remove_timer() function to remove the timeout on
+ an event while leaving its socket and/or signal triggers unchanged.
+ (If we were designing the API from scratch, this would be the behavior
+ of "event_add(ev, NULL)" on an already-added event with a timeout. But
+ that's a no-op in past versions of Libevent, and we don't want to
+ break compatibility.)
+
+ You can use the new event_base_get_num_events() function to find the
+ number of events active or pending on an event_base. To find the
+ largest number of events that there have been since the last call, use
+ event_base_get_max_events().
+
+ You can now activate all the events waiting for a given fd or signal
+ using the event_base_active_by_fd() and event_base_active_by_signal()
+ APIs.
+
+ On backends that support it (currently epoll), there is now an
+ EV_CLOSED flag that programs can use to detect when a socket has
+ closed without having to read all the bytes until receiving an EOF.
+
+1.3. Event finalization
+
+1.3.1. Why event finalization?
+
+ Libevent 2.1 now supports an API for safely "finalizing" events that
+ might be running in multiple threads, and provides a way to slightly
+ change the semantics of event_del() to prevent deadlocks in
+ multithreaded programs.
+
+ To motivate this feature, consider the following code, in the context
+ of a mulithreaded Libevent application:
+
+ struct connection *conn = event_get_callback_arg(ev);
+ event_del(ev);
+ connection_free(conn);
+
+ Suppose that the event's callback might be running in another thread,
+ and using the value of "conn" concurrently. We wouldn't want to
+ execute the connection_free() call until "conn" is no longer in use.
+ How can we make this code safe?
+
+ Libevent 2.0 answered that question by saying that the event_del()
+ call should block if the event's callback is running in another
+ thread. That way, we can be sure that event_del() has canceled the
+ callback (if the callback hadn't started running yet), or has waited
+ for the callback to finish.
+
+ But now suppose that the data structure is protected by a lock, and we
+ have the following code:
+
+ void check_disable(struct connection *connection) {
+ lock(connection);
+ if (should_stop_reading(connection))
+ event_del(connection->read_event);
+ unlock(connection);
+ }
+
+ What happens when we call check_disable() from a callback and from
+ another thread? Let's say that the other thread gets the lock
+ first. If it decides to call event_del(), it will wait for the
+ callback to finish. But meanwhile, the callback will be waiting for
+ the lock on the connection. Since each threads is waiting for the
+ other one to release a resource, the program will deadlock.
+
+ This bug showed up in multithreaded bufferevent programs in 2.1,
+ particularly when freeing bufferevents. (For more information, see
+ the "Deadlock when calling bufferevent_free from an other thread"
+ thread on libevent-users starting on 6 August 2012 and running through
+ February of 2013. You might also like to read my earlier writeup at
+ http://archives.seul.org/libevent/users/Feb-2012/msg00053.html and
+ the ensuing discussion.)
+
+1.3.2. The EV_FINALIZE flag and avoiding deadlock
+
+ To prevent the deadlock condition described above, Libevent
+ 2.1.3-alpha adds a new flag, "EV_FINALIZE". You can pass it to
+ event_new() and event_assign() along with EV_READ, EV_WRITE, and the
+ other event flags.
+
+ When an event is constructed with the EV_FINALIZE flag, event_del()
+ will not block on that event, even when the event's callback is
+ running in another thread. By using EV_FINALIZE, you are therefore
+ promising not to use the "event_del(ev); free(event_get_callback_arg(ev));"
+ pattern, but rather to use one of the finalization functions below to
+ clean up the event.
+
+ EV_FINALIZE has no effect on a single-threaded program, or on a
+ program where events are only used from one thread.
+
+
+ There are also two new variants of event_del() that you can use for
+ more fine-grained control:
+ event_del_noblock(ev)
+ event_del_block(ev)
+ The event_del_noblock() function will never block, even if the event
+ callback is running in another thread and doesn't have the EV_FINALIZE
+ flag. The event_del_block() function will _always_ block if the event
+ callback is running in another thread, even if the event _does_ have
+ the EV_FINALIZE flag.
+
+ [A future version of Libevent may have a way to make the EV_FINALIZE
+ flag the default.]
+
+1.3.3. Safely finalizing events
+
+ To safely tear down an event that may be running, Libevent 2.1.3-alpha
+ introduces event_finalize() and event_free_finalize(). You call them
+ on an event, and provide a finalizer callback to be run on the event
+ and its callback argument once the event is definitely no longer
+ running.
+
+ With event_free_finalize(), the event is also freed once the finalizer
+ callback has been invoked.
+
+ A finalized event cannot be re-added or activated. The finalizer
+ callback must not add events, activate events, or attempt to
+ "resucitate" the event being finalized in any way.
+
+ If any finalizer callbacks are pending as the event_base is being
+ freed, they will be invoked. You can override this behavior with the
+ new function event_base_free_nofinalize().
+
+1.4. New debugging features
+
+ You can now turn on debug logs at runtime using a new function,
+ event_enable_debug_logging().
+
+ The event_enable_lock_debugging() function is now spelled correctly.
+ You can still use the old "event_enable_lock_debuging" name, though,
+ so your old programs shouldnt' break.
+
+ There's also been some work done to try to make the debugging logs
+ more generally useful.
+
+1.5. New evbuffer functions
+
+ In Libevent 2.0, we introduced evbuffer_add_file() to add an entire
+ file's contents to an evbuffer, and then send them using sendfile() or
+ mmap() as appropriate. This API had some drawbacks, however.
+ Notably, it created one mapping or fd for every instance of the same
+ file added to any evbuffer. Also, adding a file to an evbuffer could
+ make that buffer unusable with SSL bufferevents, filtering
+ bufferevents, and any code that tried to read the contents of the
+ evbuffer.
+
+ Libevent 2.1 adds a new evbuffer_file_segment API to solve these
+ problems. Now, you can use evbuffer_file_segment_new() to construct a
+ file-segment object, and evbuffer_add_file_segment() to insert it (or
+ part of it) into an evbuffer. These segments avoid creating redundant
+ maps or fds. Better still, the code is smart enough (when the OS
+ supports sendfile) to map the file when that's necessary, and use
+ sendfile() otherwise.
+
+ File segments can receive callback functions that are invoked when the
+ file segments are freed.
+
+ The evbuffer_ptr interface has been extended so that an evbuffer_ptr
+ can now yield a point just after the end of the buffer. This makes
+ many algorithms simpler to implement.
+
+ There's a new evbuffer_add_buffer() interface that you can use to add
+ one buffer to another nondestructively. When you say
+ evbuffer_add_buffer_reference(outbuf, inbuf), outbuf now contains a
+ reference to the contents of inbuf.
+
+ To aid in adding data in bulk while minimizing evbuffer calls, there
+ is an evbuffer_add_iovec() function.
+
+ There's a new evbuffer_copyout_from() variant function to enable
+ copying data nondestructively from the middle of a buffer.
+
+ evbuffer_readln() now supports an EVBUFFER_EOL_NUL argument to fetch
+ NUL-terminated strings from buffers.
+
+ There's a new evbuffer_set_flags()/evbuffer_clear_flags() that you can use to
+ set EVBUFFER_FLAG_DRAINS_TO_FD.
+
+1.6. New functions and features: bufferevents
+
+ You can now use the bufferevent_getcb() function to find out a
+ bufferevent's callbacks. Previously, there was no supported way to do
+ that.
+
+ The largest chunk readable or writeable in a single bufferevent
+ callback is no longer hardcoded; it's now configurable with
+ the new functions bufferevent_set_max_single_read() and
+ bufferevent_set_max_single_write().
+
+ For consistency, OpenSSL bufferevents now make sure to always set one
+ of BEV_EVENT_READING or BEV_EVENT_WRITING when invoking an event
+ callback.
+
+ Calling bufferevent_set_timeouts(bev, NULL, NULL) now removes the
+ timeouts from socket and ssl bufferevents correctly.
+
+ You can find the priority at which a bufferevent runs with
+ bufferevent_get_priority().
+
+ The function bufferevent_get_token_bucket_cfg() can retrieve the
+ rate-limit settings for a bufferevent; bufferevent_getwatermark() can
+ return a bufferevent's current watermark settings.
+
+ You can manually trigger a bufferevent's callbacks via
+ bufferevent_trigger() and bufferevent_trigger_event().
+
+ Also you can manually increment/decrement reference for bufferevent with
+ bufferevent_incref()/bufferevent_decref(), it is useful in situations where a
+ user may reference the bufferevent somewhere else.
+
+ Now bufferevent_openssl supports "dirty" shutdown (when the peer closes the
+ TCP connection before closing the SSL channel), see
+ bufferevent_openssl_get_allow_dirty_shutdown() and
+ bufferevent_openssl_set_allow_dirty_shutdown().
+
+ And also libevent supports openssl 1.1.
+
+1.7. New functions and features: evdns
+
+ The previous evdns interface used an "open a test UDP socket" trick in
+ order to detect IPv6 support. This was a hack, since it would
+ sometimes badly confuse people's firewall software, even though no
+ packets were sent. The current evdns interface-detection code uses
+ the appropriate OS functions to see which interfaces are configured.
+
+ The evdns_base_new() function now has multiple possible values for its
+ second (flags) argument. Using 1 and 0 have their old meanings, though the
+ 1 flag now has a symbolic name of EVDNS_BASE_INITIALIZE_NAMESERVERS.
+ A second flag is now supported too: the EVDNS_BASE_DISABLE_WHEN_INACTIVE
+ flag, which tells the evdns_base that it should not prevent Libevent from
+ exiting while it has no DNS requests in progress.
+
+ There is a new evdns_base_clear_host_addresses() function to remove
+ all the /etc/hosts addresses registered with an evdns instance.
+
+ Also there is evdns_base_get_nameserver_addr() for retrieve the address of
+ the 'idx'th configured nameserver.
+
+1.8. New functions and features: evconnlistener
+
+ Libevent 2.1 adds the following evconnlistener flags:
+
+ LEV_OPT_DEFERRED_ACCEPT -- Tells the OS that it doesn't need to
+ report sockets as having arrived until the initiator has sent some
+ data too. This can greatly improve performance with protocols like
+ HTTP where the client always speaks first. On operating systems
+ that don't support this functionality, this option has no effect.
+
+ LEV_OPT_REUSEABLE_PORT -- Indicates that we ask to allow multiple servers
+ to bind to the same port if they each set the option Ionly on Linux and
+ >=3.9)
+
+ LEV_OPT_DISABLED -- Creates an evconnlistener in the disabled (not
+ listening) state.
+
+ Libevent 2.1 changes the behavior of the LEV_OPT_CLOSE_ON_EXEC
+ flag. Previously, it would apply to the listener sockets, but not to
+ the accepted sockets themselves. That's almost never what you want.
+ Now, it applies both to the listener and the accepted sockets.
+
+1.9. New functions and features: evhttp
+
+ **********************************************************************
+ NOTE: The evhttp module will eventually be deprecated in favor of Mark
+ Ellzey's libevhtp library. Don't worry -- this won't happen until
+ libevhtp provides every feature that evhttp does, and provides a
+ compatible interface that applications can use to migrate.
+ **********************************************************************
+
+ Previously, you could only set evhttp timeouts in increments of one
+ second. Now, you can use evhttp_set_timeout_tv() and
+ evhttp_connection_set_timeout_tv() to configure
+ microsecond-granularity timeouts.
+
+ Also there is evhttp_connection_set_initial_retry_tv() to change initial
+ retry timeout.
+
+ There are a new pair of functions: evhttp_set_bevcb() and
+ evhttp_connection_base_bufferevent_new(), that you can use to
+ configure which bufferevents will be used for incoming and outgoing
+ http connections respectively. These functions, combined with SSL
+ bufferevents, should enable HTTPS support.
+
+ There's a new evhttp_foreach_bound_socket() function to iterate over
+ every listener on an evhttp object.
+
+ Whitespace between lines in headers is now folded into a single space;
+ whitespace at the end of a header is now removed.
+
+ The socket errno value is now preserved when invoking an http error
+ callback.
+
+ There's a new kind of request callback for errors; you can set it with
+ evhttp_request_set_error_cb(). It gets called when there's a request error,
+ and actually reports the error code and lets you figure out which request
+ failed.
+
+ You can navigate from an evhttp_connection back to its evhttp with the
+ new evhttp_connection_get_server() function.
+
+ You can override the default HTTP Content-Type with the new
+ evhttp_set_default_content_type() function
+
+ There's a new evhttp_connection_get_addr() API to return the peer
+ address of an evhttp_connection.
+
+ The new evhttp_send_reply_chunk_with_cb() is a variant of
+ evhttp_send_reply_chunk() with a callback to be invoked when the
+ chunk is sent.
+
+ The evhttp_request_set_header_cb() facility adds a callback to be
+ invoked while parsing headers.
+
+ The evhttp_request_set_on_complete_cb() facility adds a callback to be
+ invoked on request completion.
+
+ You can add linger-close for http server by passing
+ EVHTTP_SERVER_LINGERING_CLOSE to evhttp_set_flags(), with this flag server
+ read all the clients body, and only after this respond with an error if the
+ clients body exceed max_body_size (since some clients cannot read response
+ otherwise).
+
+ The evhttp_connection_set_family() can bypass family hint to evdns.
+
+ There are some flags available for connections, which can be installed with
+ evhttp_connection_set_flags():
+ - EVHTTP_CON_REUSE_CONNECTED_ADDR -- reuse connection address on retry (avoid
+ extra DNS request).
+ - EVHTTP_CON_READ_ON_WRITE_ERROR - try read error, since server may already
+ close the connection.
+
+ The evhttp_connection_free_on_completion() can be used to tell libevent to
+ free the connection object after the last request has completed or failed.
+
+ There is evhttp_request_get_response_code_line() if
+ evhttp_request_get_response_code() is not enough for you.
+
+ There are *evhttp_uri_parse_with_flags() that accepts
+ EVHTTP_URI_NONCONFORMANT to tolerate URIs that do not conform to RFC3986.
+ The evhttp_uri_set_flags() can changes the flags on URI.
+
+1.10. New functions and features: evutil
+
+ There's a function "evutil_secure_rng_set_urandom_device_file()" that
+ you can use to override the default file that Libevent uses to seed
+ its (sort-of) secure RNG.
+
+ The evutil_date_rfc1123() returns date in RFC1123
+
+ There are new API to work with monotonic timer -- monotonic time is
+ guaranteed never to run in reverse, but is not necessarily epoch-based. Use
+ it to make reliable measurements of elapsed time between events even when the
+ system time may be changed:
+ - evutil_monotonic_timer_new()/evutil_monotonic_timer_free()
+ - evutil_configure_monotonic_time()
+ - evutil_gettime_monotonic()
+
+ Use evutil_make_listen_socket_reuseable_port() to set SO_REUSEPORT (linux >=
+ 3.9)
+
+ The evutil_make_tcp_listen_socket_deferred() can make a tcp listener socket
+ defer accept()s until there is data to read (TCP_DEFER_ACCEPT).
+
+2. Cross-platform performance improvements
+
+2.1. Better data structures
+
+ We replaced several users of the sys/queue.h "TAILQ" data structure
+ with the "LIST" data structure. Because this data type doesn't
+ require FIFO access, it requires fewer pointer checks and
+ manipulations to keep it in line.
+
+ All previous versions of Libevent have kept every pending (added)
+ event in an "eventqueue" data structure. Starting in Libevent 2.0,
+ however, this structure became redundant: every pending timeout event
+ is stored in the timeout heap or in one of the common_timeout queues,
+ and every pending fd or signal event is stored in an evmap. Libevent
+ 2.1 removes this data structure, and thereby saves all of the code
+ that we'd been using to keep it updated.
+
+2.2. Faster activations and timeouts
+
+ It's a common pattern in older code to use event_base_once() with a
+ 0-second timeout to ensure that a callback will get run 'as soon as
+ possible' in the current iteration of the Libevent loop. We optimize
+ this case by calling event_active() directly, and bypassing the
+ timeout pool. (People who are using this pattern should also consider
+ using event_active() themselves.)
+
+ Libevent 2.0 would wake up a polling event loop whenever the first
+ timeout in the event loop was adjusted--whether it had become earlier
+ or later. We now only notify the event loop when a change causes the
+ expiration time to become _sooner_ than it would have been otherwise.
+
+ The timeout heap code is now optimized to perform fewer comparisons
+ and shifts when changing or removing a timeout.
+
+ Instead of checking for a wall-clock time jump every time we call
+ clock_gettime(), we now check only every 5 seconds. This should save
+ a huge number of gettimeofday() calls.
+
+2.3. Microoptimizations
+
+ Internal event list maintainance no longer use the antipattern where
+ we have one function with multiple totally independent behaviors
+ depending on an argument:
+ #define OP1 1
+ #define OP2 2
+ #define OP3 3
+ void func(int operation, struct event *ev) {
+ switch (op) {
+ ...
+ }
+ }
+ Instead, these functions are now split into separate functions for
+ each operation:
+ void func_op1(struct event *ev) { ... }
+ void func_op2(struct event *ev) { ... }
+ void func_op3(struct event *ev) { ... }
+
+ This produces better code generation and inlining decisions on some
+ compilers, and makes the code easier to read and check.
+
+2.4. Evbuffer performance improvements
+
+ The EVBUFFER_EOL_CRLF line-ending type is now much faster, thanks to
+ smart optimizations.
+
+2.5. HTTP performance improvements
+
+ o Performance tweak to evhttp_parse_request_line. (aee1a97 Mark Ellzey)
+ o Add missing break to evhttp_parse_request_line (0fcc536)
+
+2.6. Coarse timers by default on Linux
+
+ Due to limitations of the epoll interface, Libevent programs using epoll
+ have not previously been able to wait for timeouts with accuracy smaller
+ than 1 millisecond. But Libevent had been using CLOCK_MONOTONIC for
+ timekeeping on Linux, which is needlessly expensive: CLOCK_MONOTONIC_COARSE
+ has approximately the resolution corresponding to epoll, and is much faster
+ to invoke than CLOCK_MONOTONIC.
+
+ To disable coarse timers, and get a more plausible precision, use the
+ new EVENT_BASE_FLAG_PRECISE_TIMER flag when setting up your event base.
+
+3. Backend/OS-specific improvements
+
+3.1. Linux-specific improvements
+
+ The logic for deciding which arguements to use with epoll_ctl() is now
+ a table-driven lookup, rather than the previous pile of cascading
+ branches. This should minimize epoll_ctl() calls and make the epoll
+ code run a little faster on change-heavy loads.
+
+ Libevent now takes advantage of Linux's support for enhanced APIs
+ (e.g., SOCK_CLOEXEC, SOCK_NONBLOCK, accept4, pipe2) that allow us to
+ simultaneously create a socket, make it nonblocking, and make it
+ close-on-exec. This should save syscalls throughout our codebase, and
+ avoid race-conditions if an exec() occurs after a socket is socket is
+ created but before we can make it close-on-execute on it.
+
+3.2. Windows-specific improvements
+
+ We now use GetSystemTimeAsFileTime to implement gettimeofday. It's
+ significantly faster and more accurate than our old ftime()-based approach.
+
+3.3. Improvements in the solaris evport backend.
+
+ The evport backend has been updated to use many of the infrastructure
+ improvements from Libevent 2.0. Notably, it keeps track of per-fd
+ information using the evmap infrastructure, and removes a number of
+ linear scans over recently-added events. This last change makes it
+ efficient to receive many more events per evport_getn() call, thereby
+ reducing evport overhead in general.
+
+3.4. OSX backend improvements
+
+ The OSX select backend doesn't like to have more than a certain number
+ of fds set unless an "unlimited select" option has been set.
+ Therefore, we now set it.
+
+3.5. Monotonic clocks on even more platforms
+
+ Libevent previously used a monotonic clock for its internal timekeeping
+ only on platforms supporting the POSIX clock_gettime() interface. Now,
+ Libevent has support for monotonic clocks on OSX and Windows too, and a
+ fallback implementation for systems without monotonic clocks that will at
+ least keep time running forwards.
+
+ Using monotonic timers makes Libevent more resilient to changes in the
+ system time, as can happen in small amounts due to clock adjustments from
+ NTP, or in large amounts due to users who move their system clocks all over
+ the timeline in order to keep nagware from nagging them.
+
+3.6. Faster cross-thread notification on kqueue
+
+ When a thread other than the one in which the main event loop is
+ running needs to wake the thread running the main event loop, Libevent
+ usually writes to a socketpair in order to force the main event loop
+ to wake up. On Linux, we've been able to use eventfd() instead. Now
+ on BSD and OSX systems (any anywhere else that has kqueue with the
+ EVFILT_USER extension), we can use EVFILT_USER to wake up the main
+ thread from kqueue. This should be a tiny bit faster than the
+ previous approach.
+
+4. Infrastructure improvements
+
+4.1. Faster tests
+
+ I've spent some time to try to make the unit tests run faster in
+ Libevent 2.1. Nearly all of this was a matter of searching slow tests
+ for unreasonably long timeouts, and cutting them down to reasonably
+ long delays, though on one or two cases I actually had to parallelize
+ an operation or improve an algorithm.
+
+ On my desktop, a full "make verify" run of Libevent 2.0.18-stable
+ requires about 218 seconds. Libevent 2.1.1-alpha cuts this down to
+ about 78 seconds.
+
+ Faster unit tests are great, since they let programmers test their
+ changes without losing their train of thought.
+
+4.2. Finicky tests are now off-by-default
+
+ The Tinytest unit testing framework now supports optional tests, and
+ Libevent uses them. By default, Libevent's unit testing framework
+ does not run tests that require a working network, and does not run
+ tests that tend to fail on heavily loaded systems because of timing
+ issues. To re-enable all tests, run ./test/regress using the "@all"
+ alias.
+
+4.3. Modernized use of autotools
+
+ Our autotools-based build system has been updated to build without
+ warnings on recent autoconf/automake versions.
+
+ Libevent's autotools makefiles are no longer recursive. This allows
+ make to use the maximum possible parallelism to do the minimally
+ necessary amount of work. See Peter Miller's "Recursive Make
+ Considered Harmful" at http://miller.emu.id.au/pmiller/books/rmch/ for
+ more information here.
+
+ We now use the "quiet build" option to suppress distracting messages
+ about which commandlines are running. You can get them back with
+ "make V=1".
+
+4.4. Portability
+
+ Libevent now uses large-file support internally on platforms where it
+ matters. You shouldn't need to set _LARGEFILE or OFFSET_BITS or
+ anything magic before including the Libevent headers, either, since
+ Libevent now sets the size of ev_off_t to the size of off_t that it
+ received at compile time, not to some (possibly different) size based
+ on current macro definitions when your program is building.
+
+ We now also use the Autoconf AC_USE_SYSTEM_EXTENSIONS mechanism to
+ enable per-system macros needed to enable not-on-by-default features.
+ Unlike the rest of the autoconf macros, we output these to an
+ internal-use-only evconfig-private.h header, since their names need to
+ survive unmangled. This lets us build correctly on more platforms,
+ and avoid inconsistencies when some files define _GNU_SOURCE and
+ others don't.
+
+ Libevent now tries to detect OpenSSL via pkg-config.
+
+4.5. Standards conformance
+
+ Previous Libevent versions had no consistent convention for internal
+ vs external identifiers, and used identifiers starting with the "_"
+ character throughout the codebase. That's no good, since the C
+ standard says that identifiers beginning with _ are reserved. I'm not
+ aware of having any collisions with system identifiers, but it's best
+ to fix these things before they cause trouble.
+
+ We now avoid all use of the _identifiers in the Libevent source code.
+ These changes were made *mainly* through the use of automated scripts,
+ so there shouldn't be any mistakes, but you never know.
+
+ As an exception, the names _EVENT_LOG_DEBUG, _EVENT_LOG_MSG_,
+ _EVENT_LOG_WARN, and _EVENT_LOG_ERR are still exposed in event.h: they
+ are now deprecated, but to support older code, they will need to stay
+ around for a while. New code should use EVENT_LOG_DEBUG,
+ EVENT_LOG_MSG, EVENT_LOG_WARN, and EVENT_LOG_ERR instead.
+
+4.6. Event and callback refactoring
+
+ As a simplification and optimization to Libevent's "deferred callback"
+ logic (introduced in 2.0 to avoid callback recursion), Libevent now
+ treats all of its deferrable callback types using the same logic it
+ uses for active events. Now deferred events no longer cause priority
+ inversion, no longer require special code to cancel them, and so on.
+
+ Regular events and deferred callbacks now both descend from an
+ internal light-weight event_callback supertype, and both support
+ priorities and take part in the other anti-priority-inversion
+ mechanisms in Libevent.
+
+ To avoid starvation from callback recursion (which was the reason we
+ introduced "deferred callbacks" in the first place) the implementation
+ now allows an event callback to be scheduled as "active later":
+ instead of running in the current iteration of the event loop, it runs
+ in the next one.
+
+5. Testing
+
+ Libevent's test coverage level is more or less unchanged since before:
+ we still have over 80% line coverage in our tests on Linux, FreeBSD, NetBSD,
+ Windows, OSX.
+ There are some under-tested modules, though: we need to fix those.
+
+ And now we have CI:
+ - https://travis-ci.org/libevent/libevent
+ - https://ci.appveyor.com/project/nmathewson/libevent
+
+ And code coverage:
+ - https://coveralls.io/github/libevent/libevent
+
+ Plus there is vagrant boxes if you what to test it on more OS'es then
+ travis-ci allows, and there is a wrapper (in python) that will parse logs and
+ provide report:
+ - https://github.com/libevent/libevent-extras/blob/master/tools/vagrant-tests.py
+
+6. Contributing
+
+ From now we have contributing guide and checkpatch.sh.
diff --git a/ipc/chromium/src/third_party/libevent/win32select.c b/ipc/chromium/src/third_party/libevent/win32select.c
new file mode 100644
index 0000000000..d005b587d4
--- /dev/null
+++ b/ipc/chromium/src/third_party/libevent/win32select.c
@@ -0,0 +1,389 @@
+/*
+ * Copyright 2007-2012 Niels Provos and Nick Mathewson
+ * Copyright 2000-2007 Niels Provos <provos@citi.umich.edu>
+ * Copyright 2003 Michael A. Davis <mike@datanerds.net>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+ * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+ * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
+ * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "event2/event-config.h"
+#include "evconfig-private.h"
+
+#ifdef _WIN32
+
+#include <winsock2.h>
+#include <windows.h>
+#include <sys/types.h>
+#include <sys/queue.h>
+#include <limits.h>
+#include <signal.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+
+#include "event2/util.h"
+#include "util-internal.h"
+#include "log-internal.h"
+#include "event2/event.h"
+#include "event-internal.h"
+#include "evmap-internal.h"
+#include "event2/thread.h"
+#include "evthread-internal.h"
+#include "time-internal.h"
+
+#define XFREE(ptr) do { if (ptr) mm_free(ptr); } while (0)
+
+extern struct event_list timequeue;
+extern struct event_list addqueue;
+
+struct win_fd_set {
+ unsigned int fd_count;
+ SOCKET fd_array[1];
+};
+
+/* MSDN says this is required to handle SIGFPE */
+volatile double SIGFPE_REQ = 0.0f;
+
+struct idx_info {
+ int read_pos_plus1;
+ int write_pos_plus1;
+};
+
+struct win32op {
+ unsigned num_fds_in_fd_sets;
+ int resize_out_sets;
+ struct win_fd_set *readset_in;
+ struct win_fd_set *writeset_in;
+ struct win_fd_set *readset_out;
+ struct win_fd_set *writeset_out;
+ struct win_fd_set *exset_out;
+ unsigned signals_are_broken : 1;
+};
+
+static void *win32_init(struct event_base *);
+static int win32_add(struct event_base *, evutil_socket_t, short old, short events, void *idx_);
+static int win32_del(struct event_base *, evutil_socket_t, short old, short events, void *idx_);
+static int win32_dispatch(struct event_base *base, struct timeval *);
+static void win32_dealloc(struct event_base *);
+
+struct eventop win32ops = {
+ "win32",
+ win32_init,
+ win32_add,
+ win32_del,
+ win32_dispatch,
+ win32_dealloc,
+ 0, /* doesn't need reinit */
+ 0, /* No features supported. */
+ sizeof(struct idx_info),
+};
+
+#define FD_SET_ALLOC_SIZE(n) ((sizeof(struct win_fd_set) + ((n)-1)*sizeof(SOCKET)))
+
+static int
+grow_fd_sets(struct win32op *op, unsigned new_num_fds)
+{
+ size_t size;
+
+ EVUTIL_ASSERT(new_num_fds >= op->readset_in->fd_count &&
+ new_num_fds >= op->writeset_in->fd_count);
+ EVUTIL_ASSERT(new_num_fds >= 1);
+
+ size = FD_SET_ALLOC_SIZE(new_num_fds);
+ if (!(op->readset_in = mm_realloc(op->readset_in, size)))
+ return (-1);
+ if (!(op->writeset_in = mm_realloc(op->writeset_in, size)))
+ return (-1);
+ op->resize_out_sets = 1;
+ op->num_fds_in_fd_sets = new_num_fds;
+ return (0);
+}
+
+static int
+do_fd_set(struct win32op *op, struct idx_info *ent, evutil_socket_t s, int read)
+{
+ struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
+ if (read) {
+ if (ent->read_pos_plus1 > 0)
+ return (0);
+ } else {
+ if (ent->write_pos_plus1 > 0)
+ return (0);
+ }
+ if (set->fd_count == op->num_fds_in_fd_sets) {
+ if (grow_fd_sets(op, op->num_fds_in_fd_sets*2))
+ return (-1);
+ /* set pointer will have changed and needs reiniting! */
+ set = read ? op->readset_in : op->writeset_in;
+ }
+ set->fd_array[set->fd_count] = s;
+ if (read)
+ ent->read_pos_plus1 = set->fd_count+1;
+ else
+ ent->write_pos_plus1 = set->fd_count+1;
+ return (set->fd_count++);
+}
+
+static int
+do_fd_clear(struct event_base *base,
+ struct win32op *op, struct idx_info *ent, int read)
+{
+ int i;
+ struct win_fd_set *set = read ? op->readset_in : op->writeset_in;
+ if (read) {
+ i = ent->read_pos_plus1 - 1;
+ ent->read_pos_plus1 = 0;
+ } else {
+ i = ent->write_pos_plus1 - 1;
+ ent->write_pos_plus1 = 0;
+ }
+ if (i < 0)
+ return (0);
+ if (--set->fd_count != (unsigned)i) {
+ struct idx_info *ent2;
+ SOCKET s2;
+ s2 = set->fd_array[i] = set->fd_array[set->fd_count];
+
+ ent2 = evmap_io_get_fdinfo_(&base->io, s2);
+
+ if (!ent2) /* This indicates a bug. */
+ return (0);
+ if (read)
+ ent2->read_pos_plus1 = i+1;
+ else
+ ent2->write_pos_plus1 = i+1;
+ }
+ return (0);
+}
+
+#define NEVENT 32
+void *
+win32_init(struct event_base *base)
+{
+ struct win32op *winop;
+ size_t size;
+ if (!(winop = mm_calloc(1, sizeof(struct win32op))))
+ return NULL;
+ winop->num_fds_in_fd_sets = NEVENT;
+ size = FD_SET_ALLOC_SIZE(NEVENT);
+ if (!(winop->readset_in = mm_malloc(size)))
+ goto err;
+ if (!(winop->writeset_in = mm_malloc(size)))
+ goto err;
+ if (!(winop->readset_out = mm_malloc(size)))
+ goto err;
+ if (!(winop->writeset_out = mm_malloc(size)))
+ goto err;
+ if (!(winop->exset_out = mm_malloc(size)))
+ goto err;
+ winop->readset_in->fd_count = winop->writeset_in->fd_count = 0;
+ winop->readset_out->fd_count = winop->writeset_out->fd_count
+ = winop->exset_out->fd_count = 0;
+
+ if (evsig_init_(base) < 0)
+ winop->signals_are_broken = 1;
+
+ evutil_weakrand_seed_(&base->weakrand_seed, 0);
+
+ return (winop);
+ err:
+ XFREE(winop->readset_in);
+ XFREE(winop->writeset_in);
+ XFREE(winop->readset_out);
+ XFREE(winop->writeset_out);
+ XFREE(winop->exset_out);
+ XFREE(winop);
+ return (NULL);
+}
+
+int
+win32_add(struct event_base *base, evutil_socket_t fd,
+ short old, short events, void *idx_)
+{
+ struct win32op *win32op = base->evbase;
+ struct idx_info *idx = idx_;
+
+ if ((events & EV_SIGNAL) && win32op->signals_are_broken)
+ return (-1);
+
+ if (!(events & (EV_READ|EV_WRITE)))
+ return (0);
+
+ event_debug(("%s: adding event for %d", __func__, (int)fd));
+ if (events & EV_READ) {
+ if (do_fd_set(win32op, idx, fd, 1)<0)
+ return (-1);
+ }
+ if (events & EV_WRITE) {
+ if (do_fd_set(win32op, idx, fd, 0)<0)
+ return (-1);
+ }
+ return (0);
+}
+
+int
+win32_del(struct event_base *base, evutil_socket_t fd, short old, short events,
+ void *idx_)
+{
+ struct win32op *win32op = base->evbase;
+ struct idx_info *idx = idx_;
+
+ event_debug(("%s: Removing event for "EV_SOCK_FMT,
+ __func__, EV_SOCK_ARG(fd)));
+ if (events & EV_READ)
+ do_fd_clear(base, win32op, idx, 1);
+ if (events & EV_WRITE)
+ do_fd_clear(base, win32op, idx, 0);
+
+ return 0;
+}
+
+static void
+fd_set_copy(struct win_fd_set *out, const struct win_fd_set *in)
+{
+ out->fd_count = in->fd_count;
+ memcpy(out->fd_array, in->fd_array, in->fd_count * (sizeof(SOCKET)));
+}
+
+/*
+ static void dump_fd_set(struct win_fd_set *s)
+ {
+ unsigned int i;
+ printf("[ ");
+ for(i=0;i<s->fd_count;++i)
+ printf("%d ",(int)s->fd_array[i]);
+ printf("]\n");
+ }
+*/
+
+int
+win32_dispatch(struct event_base *base, struct timeval *tv)
+{
+ struct win32op *win32op = base->evbase;
+ int res = 0;
+ unsigned j, i;
+ int fd_count;
+ SOCKET s;
+
+ if (win32op->resize_out_sets) {
+ size_t size = FD_SET_ALLOC_SIZE(win32op->num_fds_in_fd_sets);
+ if (!(win32op->readset_out = mm_realloc(win32op->readset_out, size)))
+ return (-1);
+ if (!(win32op->exset_out = mm_realloc(win32op->exset_out, size)))
+ return (-1);
+ if (!(win32op->writeset_out = mm_realloc(win32op->writeset_out, size)))
+ return (-1);
+ win32op->resize_out_sets = 0;
+ }
+
+ fd_set_copy(win32op->readset_out, win32op->readset_in);
+ fd_set_copy(win32op->exset_out, win32op->writeset_in);
+ fd_set_copy(win32op->writeset_out, win32op->writeset_in);
+
+ fd_count =
+ (win32op->readset_out->fd_count > win32op->writeset_out->fd_count) ?
+ win32op->readset_out->fd_count : win32op->writeset_out->fd_count;
+
+ if (!fd_count) {
+ long msec = tv ? evutil_tv_to_msec_(tv) : LONG_MAX;
+ /* Sleep's DWORD argument is unsigned long */
+ if (msec < 0)
+ msec = LONG_MAX;
+ /* Windows doesn't like you to call select() with no sockets */
+ Sleep(msec);
+ return (0);
+ }
+
+ EVBASE_RELEASE_LOCK(base, th_base_lock);
+
+ res = select(fd_count,
+ (struct fd_set*)win32op->readset_out,
+ (struct fd_set*)win32op->writeset_out,
+ (struct fd_set*)win32op->exset_out, tv);
+
+ EVBASE_ACQUIRE_LOCK(base, th_base_lock);
+
+ event_debug(("%s: select returned %d", __func__, res));
+
+ if (res <= 0) {
+ event_debug(("%s: %s", __func__,
+ evutil_socket_error_to_string(EVUTIL_SOCKET_ERROR())));
+ return res;
+ }
+
+ if (win32op->readset_out->fd_count) {
+ i = evutil_weakrand_range_(&base->weakrand_seed,
+ win32op->readset_out->fd_count);
+ for (j=0; j<win32op->readset_out->fd_count; ++j) {
+ if (++i >= win32op->readset_out->fd_count)
+ i = 0;
+ s = win32op->readset_out->fd_array[i];
+ evmap_io_active_(base, s, EV_READ);
+ }
+ }
+ if (win32op->exset_out->fd_count) {
+ i = evutil_weakrand_range_(&base->weakrand_seed,
+ win32op->exset_out->fd_count);
+ for (j=0; j<win32op->exset_out->fd_count; ++j) {
+ if (++i >= win32op->exset_out->fd_count)
+ i = 0;
+ s = win32op->exset_out->fd_array[i];
+ evmap_io_active_(base, s, EV_WRITE);
+ }
+ }
+ if (win32op->writeset_out->fd_count) {
+ i = evutil_weakrand_range_(&base->weakrand_seed,
+ win32op->writeset_out->fd_count);
+ for (j=0; j<win32op->writeset_out->fd_count; ++j) {
+ if (++i >= win32op->writeset_out->fd_count)
+ i = 0;
+ s = win32op->writeset_out->fd_array[i];
+ evmap_io_active_(base, s, EV_WRITE);
+ }
+ }
+ return (0);
+}
+
+void
+win32_dealloc(struct event_base *base)
+{
+ struct win32op *win32op = base->evbase;
+
+ evsig_dealloc_(base);
+ if (win32op->readset_in)
+ mm_free(win32op->readset_in);
+ if (win32op->writeset_in)
+ mm_free(win32op->writeset_in);
+ if (win32op->readset_out)
+ mm_free(win32op->readset_out);
+ if (win32op->writeset_out)
+ mm_free(win32op->writeset_out);
+ if (win32op->exset_out)
+ mm_free(win32op->exset_out);
+ /* XXXXX free the tree. */
+
+ memset(win32op, 0, sizeof(*win32op));
+ mm_free(win32op);
+}
+
+#endif
diff --git a/ipc/chromium/src/third_party/libeventcommon.mozbuild b/ipc/chromium/src/third_party/libeventcommon.mozbuild
new file mode 100644
index 0000000000..5037ec77a5
--- /dev/null
+++ b/ipc/chromium/src/third_party/libeventcommon.mozbuild
@@ -0,0 +1,42 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+os_win = 0
+os_posix = 0
+os_macosx = 0
+os_bsd = 0
+os_linux = 0
+os_solaris = 0
+
+if CONFIG['OS_ARCH'] == 'WINNT':
+ os_win = 1
+else:
+ os_posix = 1
+ if CONFIG['OS_ARCH'] == 'Darwin':
+ os_macosx = 1
+ libevent_include_suffix = 'mac'
+ elif CONFIG['OS_ARCH'] in ['DragonFly', 'FreeBSD', 'GNU_kFreeBSD',
+ 'NetBSD', 'OpenBSD']:
+ os_bsd = 1
+ libevent_include_suffix = 'bsd'
+ elif CONFIG['OS_ARCH'] == 'SunOS':
+ os_solaris = 1
+ libevent_include_suffix = 'solaris'
+ else:
+ os_linux = 1
+ if CONFIG['OS_TARGET'] == 'Android':
+ libevent_include_suffix = 'android'
+ else:
+ libevent_include_suffix = 'linux'
+
+if os_posix and not CONFIG['MOZ_SYSTEM_LIBEVENT']:
+ DEFINES['HAVE_CONFIG_H'] = True
+ LOCAL_INCLUDES += sorted([
+ 'libevent',
+ 'libevent/compat',
+ 'libevent/include',
+ 'libevent/' + libevent_include_suffix,
+ ])
diff --git a/ipc/chromium/src/third_party/moz.build b/ipc/chromium/src/third_party/moz.build
new file mode 100644
index 0000000000..6572d01aa9
--- /dev/null
+++ b/ipc/chromium/src/third_party/moz.build
@@ -0,0 +1,70 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+libevent_path_prefix = '.'
+include(libevent_path_prefix + '/libeventcommon.mozbuild')
+
+if os_win:
+ error('should not reach here on Windows')
+
+if CONFIG['MOZ_SYSTEM_LIBEVENT']:
+ error('should not reach here if we are using a native libevent')
+
+UNIFIED_SOURCES += [
+ 'libevent/buffer.c',
+ 'libevent/bufferevent.c',
+ 'libevent/bufferevent_filter.c',
+ 'libevent/bufferevent_ratelim.c',
+ 'libevent/bufferevent_sock.c',
+ 'libevent/evdns.c',
+ 'libevent/event.c',
+ 'libevent/event_tagging.c',
+ 'libevent/evmap.c',
+ 'libevent/evthread.c',
+ # 'libevent/evthread_pthread.c', # Unused file.
+ 'libevent/evutil.c',
+ 'libevent/evutil_rand.c',
+ 'libevent/evutil_time.c',
+ 'libevent/http.c',
+ 'libevent/listener.c',
+ 'libevent/log.c',
+ 'libevent/poll.c',
+ 'libevent/select.c',
+ 'libevent/signal.c',
+ 'libevent/strlcpy.c',
+]
+
+SOURCES += [
+ 'libevent/bufferevent_pair.c', # conflicting types errors
+ # 'libevent/evrpc.c', # Unused file. # conflicting TAILQ_ENTRY definition
+]
+
+if os_macosx or os_bsd:
+ UNIFIED_SOURCES += [
+ 'libevent/kqueue.c',
+ ]
+
+if os_linux:
+ UNIFIED_SOURCES += [
+ 'libevent/epoll.c',
+ ]
+ if CONFIG['OS_TARGET'] != 'Android':
+ UNIFIED_SOURCES += [
+ 'libevent/epoll_sub.c',
+ ]
+
+if os_solaris:
+ SOURCES += [
+ 'libevent/devpoll.c',
+ 'libevent/evport.c',
+ ]
+
+# We allow warnings for third-party code that can be updated from upstream.
+AllowCompilerWarnings()
+
+Library('libevent')
+
+FINAL_LIBRARY = 'xul'
diff --git a/ipc/contentproc/plugin-container.cpp b/ipc/contentproc/plugin-container.cpp
new file mode 100644
index 0000000000..62543f8826
--- /dev/null
+++ b/ipc/contentproc/plugin-container.cpp
@@ -0,0 +1,59 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsXPCOM.h"
+#include "nsXULAppAPI.h"
+#include "mozilla/Bootstrap.h"
+#include "XREChildData.h"
+
+#ifdef XP_WIN
+# include <windows.h>
+// we want a wmain entry point
+# include "nsWindowsWMain.cpp"
+#else
+// FIXME/cjones testing
+# include <unistd.h>
+#endif
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+# include "mozilla/sandboxing/SandboxInitialization.h"
+# include "mozilla/sandboxing/sandboxLogging.h"
+#endif
+
+int content_process_main(mozilla::Bootstrap* bootstrap, int argc,
+ char* argv[]) {
+ // Check for the absolute minimum number of args we need to move
+ // forward here. We expect the last arg to be the child process type.
+ if (argc < 1) {
+ return 3;
+ }
+
+ XREChildData childData;
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ if (IsSandboxedProcess()) {
+ childData.sandboxTargetServices =
+ mozilla::sandboxing::GetInitializedTargetServices();
+ if (!childData.sandboxTargetServices) {
+ return 1;
+ }
+
+ childData.ProvideLogFunction = mozilla::sandboxing::ProvideLogFunction;
+ }
+#endif
+
+ bootstrap->XRE_SetProcessType(argv[--argc]);
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ if (bootstrap->XRE_GetProcessType() == GeckoProcessType_RemoteSandboxBroker) {
+ childData.sandboxBrokerServices =
+ mozilla::sandboxing::GetInitializedBrokerServices();
+ }
+#endif
+
+ nsresult rv = bootstrap->XRE_InitChildProcess(argc, argv, &childData);
+ return NS_FAILED(rv);
+}
diff --git a/ipc/docs/index.rst b/ipc/docs/index.rst
new file mode 100644
index 0000000000..0485fdd768
--- /dev/null
+++ b/ipc/docs/index.rst
@@ -0,0 +1,20 @@
+Processes, Threads and IPC
+==========================
+
+These pages contain the documentation for Gecko's architecture for platform
+process and thread creation, communication and synchronization. They live
+in mozilla-central in the 'ipc/docs' directory.
+
+.. toctree::
+ :maxdepth: 3
+
+ ipdl
+ processes
+ utility_process
+
+For inter-process communication involving Javascript, see `JSActors`_. They
+are a very limited case, used for communication between elements in the DOM,
+which may exist in separate processes. They only involve the main process and
+content processes -- no other processes run Javascript.
+
+.. _JSActors: /dom/ipc/jsactors.html
diff --git a/ipc/docs/ipdl.rst b/ipc/docs/ipdl.rst
new file mode 100644
index 0000000000..cf35a23f69
--- /dev/null
+++ b/ipc/docs/ipdl.rst
@@ -0,0 +1,1836 @@
+IPDL: Inter-Thread and Inter-Process Message Passing
+====================================================
+
+The Idea
+--------
+
+**IPDL**, the "Inter-[thread|process] Protocol Definition Language", is the
+Mozilla-specific language that allows code to communicate between system
+threads or processes in a standardized, efficient, safe, secure and
+platform-agnostic way. IPDL communications take place between *parent* and
+*child* objects called *actors*. The architecture is inspired by the `actor
+model <https://en.wikipedia.org/wiki/Actor_model>`_.
+
+.. note::
+ IPDL actors differ from the actor model in one significant way -- all
+ IPDL communications are *only* between a parent and its only child.
+
+The actors that constitute a parent/child pair are called **peers**. Peer
+actors communicate through an **endpoint**, which is an end of a message pipe.
+An actor is explicitly bound to its endpoint, which in turn is bound to a
+particular thread soon after it is constructed. An actor never changes its
+endpoint and may only send and receive predeclared **messages** from/to that
+endpoint, on that thread. Violations result in runtime errors. A thread may
+be bound to many otherwise unrelated actors but an endpoint supports
+**top-level** actors and any actors they **manage** (see below).
+
+.. note::
+ More precisely, endpoints can be bound to any ``nsISerialEventTarget``,
+ which are themselves associated with a specific thread. By default,
+ IPDL will bind to the current thread's "main" serial event target,
+ which, if it exists, is retrieved with ``GetCurrentSerialEventTarget``.
+ For the sake of clarity, this document will frequently refer to actors
+ as bound to threads, although the more precise interpretation of serial
+ event targets is also always valid.
+
+.. note::
+ Internally, we use the "Ports" component of the `Chromium Mojo`_ library
+ to *multiplex* multiple endpoints (and, therefore, multiple top-level
+ actors). This means that the endpoints communicate over the same native
+ pipe, which conserves limited OS resources. The implications of this are
+ discussed in `IPDL Best Practices`_.
+
+Parent and child actors may be bound to threads in different processes, in
+different threads in the same process, or even in the same thread in the same
+process. That last option may seem unreasonable but actors are versatile and
+their layout can be established at run-time so this could theoretically arise
+as the result of run-time choices. One large example of this versatility is
+``PCompositorBridge`` actors, which in different cases connect endpoints in the
+main process and the GPU process (for UI rendering on Windows), in a content
+process and the GPU process (for content rendering on Windows), in the main
+process and the content process (for content rendering on Mac, where there is
+no GPU process), or between threads on the main process (UI rendering on Mac).
+For the most part, this does not require elaborate or redundant coding; it
+just needs endpoints to be bound judiciously at runtime. The example in
+:ref:`Connecting With Other Processes` shows one way this can be done. It
+also shows that, without proper plain-language documentation of *all* of the
+ways endpoints are configured, this can quickly lead to unmaintainable code.
+Be sure to document your endpoint bindings thoroughly!!!
+
+.. _Chromium Mojo: https://chromium.googlesource.com/chromium/src/+/refs/heads/main/mojo/core/README.md#Port
+
+The Approach
+------------
+
+The actor framework will schedule tasks to run on its associated event target,
+in response to messages it receives. Messages are specified in an IPDL
+**protocol** file and the response handler tasks are defined per-message by C++
+methods. As actors only communicate in pairs, and each is bound to one thread,
+sending is always done sequentially, never concurrently (same for receiving).
+This means that it can, and does, guarantee that an actor will always receive
+messages in the same order they were sent by its related actor -- and that this
+order is well defined since the related actor can only send from one thread.
+
+.. warning::
+ There are a few (rare) exceptions to the message order guarantee. They
+ include `synchronous nested`_ messages, `interrupt`_ messages, and
+ messages with a ``[Priority]`` or ``[Compress]`` annotation.
+
+An IPDL protocol file specifies the messages that may be sent between parent
+and child actors, as well as the direction and payload of those messages.
+Messages look like function calls but, from the standpoint of their caller,
+they may start and end at any time in the future -- they are *asynchronous*,
+so they won't block their sending actors or any other components that may be
+running in the actor's thread's ``MessageLoop``.
+
+.. note::
+ Not all IPDL messages are asynchronous. Again, we run into exceptions for
+ messages that are synchronous, `synchronous nested`_ or `interrupt`_. Use
+ of synchronous and nested messages is strongly discouraged but may not
+ always be avoidable. They will be defined later, along with superior
+ alternatives to both that should work in nearly all cases. Interrupt
+ messages were prone to misuse and are deprecated, with removal expected in
+ the near future
+ (`Bug 1729044 <https://bugzilla.mozilla.org/show_bug.cgi?id=1729044>`_).
+
+Protocol files are compiled by the *IPDL compiler* in an early stage of the
+build process. The compiler generates C++ code that reflects the protocol.
+Specifically, it creates one C++ class that represents the parent actor and one
+that represents the child. The generated files are then automatically included
+in the C++ build process. The generated classes contain public methods for
+sending the protocol messages, which client code will use as the entry-point to
+IPC communication. The generated methods are built atop our IPC framework,
+defined in `/ipc <https://searchfox.org/mozilla-central/source/ipc>`_, that
+standardizes the safe and secure use of sockets, pipes, shared memory, etc on
+all supported platforms. See `Using The IPDL compiler`_ for more on
+integration with the build process.
+
+Client code must be written that subclasses these generated classes, in order
+to add handlers for the tasks generated to respond to each message. It must
+also add routines (``ParamTraits``) that define serialization and
+deserialization for any types used in the payload of a message that aren't
+already known to the IPDL system. Primitive types, and a bunch of Mozilla
+types, have predefined ``ParamTraits`` (`here
+<https://searchfox.org/mozilla-central/source/ipc/glue/IPCMessageUtils.h>`__
+and `here
+<https://searchfox.org/mozilla-central/source/ipc/glue/IPCMessageUtilsSpecializations.h>`__).
+
+.. note::
+ Among other things, client code that uses the generated code must include
+ ``chromium-config.mozbuild`` in its ``moz.build`` file. See `Using The
+ IPDL compiler`_ for a complete list of required build changes.
+
+.. _interrupt: `The Old Ways`_
+.. _synchronous nested: `The Rest`_
+
+The Steps To Making A New Actor
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+#. Decide what folder you will work in and create:
+
+ #. An IPDL protocol file, named for your actor (e.g. ``PMyActor.ipdl`` --
+ actor protocols must begin with a ``P``). See `The Protocol Language`_.
+ #. Properly-named source files for your actor's parent and child
+ implementations (e.g. ``MyActorParent.h``, ``MyActorChild.h`` and,
+ optionally, adjacent .cpp files). See `The C++ Interface`_.
+ #. IPDL-specific updates to the ``moz.build`` file. See `Using The IPDL
+ compiler`_.
+#. Write your actor protocol (.ipdl) file:
+
+ #. Decide whether you need a top-level actor or a managed actor. See
+ `Top Level Actors`_.
+ #. Find/write the IPDL and C++ data types you will use in communication.
+ Write ``ParamTraits`` for C++ data types that don't have them. See
+ `Generating IPDL-Aware C++ Data Types: IPDL Structs and Unions`_ for IPDL
+ structures. See `Referencing Externally Defined Data Types: IPDL
+ Includes`_ and `ParamTraits`_ for C++ data types.
+ #. Write your actor and its messages. See `Defining Actors`_.
+#. Write C++ code to create and destroy instances of your actor at runtime.
+
+ * For managed actors, see `Actor Lifetimes in C++`_.
+ * For top-level actors, see `Creating Top Level Actors From Other Actors`_.
+ The first actor in a process is a very special exception -- see `Creating
+ First Top Level Actors`_.
+#. Write handlers for your actor's messages. See `Actors and Messages in
+ C++`_.
+#. Start sending messages through your actors! Again, see `Actors and Messages
+ in C++`_.
+
+The Protocol Language
+---------------------
+
+This document will follow the integration of two actors into Firefox --
+``PMyManager`` and ``PMyManaged``. ``PMyManager`` will manage ``PMyManaged``.
+A good place to start is with the IPDL actor definitions. These are files
+that are named for the actor (e.g. ``PMyManager.ipdl``) and that declare the
+messages that a protocol understands. These actors are for demonstration
+purposes and involve quite a bit of functionality. Most actors will use a very
+small fraction of these features.
+
+.. literalinclude:: _static/PMyManager.ipdl
+ :language: c++
+ :name: PMyManager.ipdl
+
+.. literalinclude:: _static/PMyManaged.ipdl
+ :language: c++
+ :name: PMyManaged.ipdl
+
+These files reference three additional files. ``MyTypes.ipdlh`` is an "IPDL
+header" that can be included into ``.ipdl`` files as if it were inline, except
+that it also needs to include any external actors and data types it uses:
+
+.. literalinclude:: _static/MyTypes.ipdlh
+ :language: c++
+ :name: MyTypes.ipdlh
+
+``MyActorUtils.h`` and ``MyDataTypes.h`` are normal C++ header files that
+contain definitions for types passed by these messages, as well as instructions
+for serializing them. They will be covered in `The C++ Interface`_.
+
+Using The IPDL compiler
+~~~~~~~~~~~~~~~~~~~~~~~
+
+To build IPDL files, list them (alphabetically sorted) in a ``moz.build`` file.
+In this example, the ``.ipdl`` and ``.ipdlh`` files would be alongside a
+``moz.build`` containing:
+
+.. code-block:: python
+
+ IPDL_SOURCES += [
+ "MyTypes.ipdlh",
+ "PMyManaged.ipdl",
+ "PMyManager.ipdl",
+ ]
+
+ UNIFIED_SOURCES += [
+ "MyManagedChild.cpp",
+ "MyManagedParent.cpp",
+ "MyManagerChild.cpp",
+ "MyManagerParent.cpp",
+ ]
+
+ include("/ipc/chromium/chromium-config.mozbuild")
+
+``chromium-config.mozbuild`` sets up paths so that generated IPDL header files
+are in the proper scope. If it isn't included, the build will fail with
+``#include`` errors in both your actor code and some internal ipc headers. For
+example:
+
+.. code-block::
+
+ c:/mozilla-src/mozilla-unified/obj-64/dist/include\ipc/IPCMessageUtils.h(13,10): fatal error: 'build/build_config.h' file not found
+
+``.ipdl`` files are compiled to C++ files as one of the earliest post-configure
+build steps. Those files are, in turn, referenced throughout the source code
+and build process. From ``PMyManager.ipdl`` the compiler generates two header
+files added to the build context and exported globally:
+``mozilla/myns/PMyManagerParent.h`` and ``mozilla/myns/PMyManagerChild.h``, as
+discussed in `Namespaces`_ below. These files contain the base classes for the
+actors. It also makes several other files, including C++ source files and
+another header, that are automatically included into the build and should not
+require attention.
+
+C++ definions of the actors are required for IPDL. They define the actions
+that are taken in response to messages -- without this, they would have no
+value. There will be much more on this when we discuss `Actors and Messages in
+C++`_ but note here that C++ header files named for the actor are required by
+the IPDL `compiler`. The example would expect
+``mozilla/myns/MyManagedChild.h``, ``mozilla/myns/MyManagedParent.h``,
+``mozilla/myns/MyManagerChild.h`` and ``mozilla/myns/MyManagerParent.h`` and
+will not build without them.
+
+Referencing Externally Defined Data Types: IPDL Includes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Let's begin with ``PMyManager.ipdl``. It starts by including types that it
+will need from other places:
+
+.. code-block:: cpp
+
+ include protocol PMyManaged;
+ include MyTypes; // for MyActorPair
+
+ using MyActorEnum from "mozilla/myns/MyActorUtils.h";
+ using struct mozilla::myns::MyData from "mozilla/MyDataTypes.h";
+ [MoveOnly] using mozilla::myns::MyOtherData from "mozilla/MyDataTypes.h";
+ [RefCounted] using class mozilla::myns::MyThirdData from "mozilla/MyDataTypes.h";
+
+The first line includes a protocol that PMyManager will manage. That protocol
+is defined in its own ``.ipdl`` file. Cyclic references are expected and pose
+no concern.
+
+The second line includes the file ``MyTypes.ipdlh``, which defines types like
+structs and unions, but in IPDL, which means they have behavior that goes
+beyond the similar C++ concepts. Details can be found in `Generating
+IPDL-Aware C++ Data Types: IPDL Structs and Unions`_.
+
+The final lines include types from C++ headers. Additionally, the [RefCounted]
+and [MoveOnly] attributes tell IPDL that the types have special functionality
+that is important to operations. These are the data type attributes currently
+understood by IPDL:
+
+================ ==============================================================
+``[RefCounted]`` Type ``T`` is reference counted (by ``AddRef``/``Release``).
+ As a parameter to a message or as a type in IPDL
+ structs/unions, it is referenced as a ``RefPtr<T>``.
+``[MoveOnly]`` The type ``T`` is treated as uncopyable. When used as a
+ parameter in a message or an IPDL struct/union, it is as an
+ r-value ``T&&``.
+================ ==============================================================
+
+Finally, note that ``using``, ``using class`` and ``using struct`` are all
+valid syntax. The ``class`` and ``struct`` keywords are optional.
+
+Namespaces
+~~~~~~~~~~
+
+From the IPDL file:
+
+.. code-block:: cpp
+
+ namespace mozilla {
+ namespace myns {
+
+ // ... data type and actor definitions ...
+
+ } // namespace myns
+ } // namespace mozilla
+
+
+Namespaces work similar to the way they do in C++. They also mimic the
+notation, in an attempt to make them comfortable to use. When IPDL actors are
+compiled into C++ actors, the namespace scoping is carried over. As previously
+noted, when C++ types are included into IPDL files, the same is true. The most
+important way in which they differ is that IPDL also uses the namespace to
+establish the path to the generated files. So, the example defines the IPDL
+data type ``mozilla::myns::MyUnion`` and the actors
+``mozilla::myns::PMyManagerParent`` and ``mozilla::myns::PMyManagerChild``,
+which can be included from ``mozilla/myns/PMyManagerParent.h``,
+``mozilla/myns/PMyManagerParent.h`` and ``mozilla/myns/PMyManagerChild.h``,
+respectively. The namespace becomes part of the path.
+
+Generating IPDL-Aware C++ Data Types: IPDL Structs and Unions
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+``PMyManager.ipdl`` and ``MyTypes.ipdlh`` define:
+
+.. code-block:: cpp
+
+ [Comparable] union MyUnion {
+ float;
+ MyOtherData;
+ };
+
+ struct MyActorPair {
+ PMyManaged actor1;
+ nullable PMyManaged actor2;
+ };
+
+From these descriptions, IPDL generates C++ classes that approximate the
+behavior of C++ structs and unions but that come with pre-defined
+``ParamTraits`` implementations. These objects can also be used as usual
+outside of IPDL, although the lack of control over the generated code means
+they are sometimes poorly suited to use as plain data. See `ParamTraits`_ for
+details.
+
+The ``[Comparable]`` attribute tells IPDL to generate ``operator==`` and
+``operator!=`` for the new type. In order for it to do that, the fields inside
+the new type need to define both of those operators.
+
+Finally, the ``nullable`` keyword indicates that, when serialized, the actor
+may be null. It is intended to help users avoid null-object dereference
+errors. It only applies to actor types and may also be attached to parameters
+in message declarations.
+
+Defining Actors
+~~~~~~~~~~~~~~~
+
+The real point of any ``.ipdl`` file is that each defines exactly one actor
+protocol. The definition always matches the ``.ipdl`` filename. Repeating the
+one in ``PMyManager.ipdl``:
+
+.. code-block:: cpp
+
+ [ChildProc=Content]
+ sync protocol PMyManager {
+ manages PMyManaged;
+
+ async PMyManaged();
+ // ... more message declarations ...
+ };
+
+.. important::
+ A form of reference counting is `always` used internally by IPDL to make
+ sure that it and its clients never address an actor the other component
+ deleted but this becomes fragile, and sometimes fails, when the client code
+ does not respect the reference count. For example, when IPDL detects that
+ a connection died due to a crashed remote process, deleting the actor could
+ leave dangling pointers, so IPDL `cannot` delete it. On the other hand,
+ there are many cases where IPDL is the only entity to have references to
+ some actors (this is very common for one side of a managed actor) so IPDL
+ `must` delete it. If all of those objects were reference counted then
+ there would be no complexity here. Indeed, new actors using
+ ``[ManualDealloc]`` should not be approved without a very compelling
+ reason. New ``[ManualDealloc]`` actors may soon be forbidden.
+
+The ``sync`` keyword tells IPDL that the actor contains messages that block the
+sender using ``sync`` blocking, so the sending thread waits for a response to
+the message. There is more on what it and the other blocking modes mean in
+`IPDL messages`_. For now, just know that this is redundant information whose
+value is primarily in making it easy for other developers to know that there
+are ``sync`` messages defined here. This list gives preliminary definitions of
+the options for the actor-blocking policy of messages:
+
+======================= =======================================================
+``async`` Actor may contain only asynchronous messages.
+``sync`` Actor has ``async`` capabilities and adds ``sync``
+ messages. ``sync`` messages
+ can only be sent from the child actor to the parent.
+``intr`` (deprecated) Actor has ``sync`` capabilities and adds ``intr``
+ messages. Some messages can be received while an actor
+ waits for an ``intr`` response. This type will be
+ removed soon.
+======================= =======================================================
+
+Beyond these protocol blocking strategies, IPDL supports annotations that
+indicate the actor has messages that may be received in an order other than
+the one they were sent in. These orderings attempt to handle messages in
+"message thread" order (as in e.g. mailing lists). These behaviors can be
+difficult to design for. Their use is discouraged but is sometimes warranted.
+They will be discussed further in `Nested messages`_.
+
+============================== ================================================
+``[NestedUpTo=inside_sync]`` Actor has high priority messages that can be
+ handled while waiting for a ``sync`` response.
+``[NestedUpTo=inside_cpow]`` Actor has the highest priority messages that
+ can be handled while waiting for a ``sync``
+ response.
+============================== ================================================
+
+In addition, top-level protocols are annotated with which processes each side
+should be bound into using the ``[ParentProc=*]`` and ``[ChildProc=*]``
+attributes. The ``[ParentProc]`` attribute is optional, and defaults to the
+``Parent`` process. The ``[ChildProc]`` attribute is required. See `Process
+Type Attributes`_ for possible values.
+
+The ``manages`` clause tells IPDL that ``PMyManager`` manages the
+``PMyManaged`` actor that was previously ``include`` d. As with any managed
+protocol, it must also be the case that ``PMyManaged.ipdl`` includes
+``PMyManager`` and declares that ``PMyManaged`` is ``managed`` by
+``PMyManager``. Recalling the code:
+
+.. code-block:: cpp
+
+ // PMyManaged.ipdl
+ include protocol PMyManager;
+ // ...
+
+ protocol PMyManaged {
+ manager PMyManager;
+ // ...
+ };
+
+An actor has a ``manager`` (e.g. ``PMyManaged``) or else it is a top-level
+actor (e.g. ``PMyManager``). An actor protocol may be managed by more than one
+actor type. For example, ``PMyManaged`` could have also been managed by some
+``PMyOtherManager`` not shown here. In that case, ``manager`` s are presented
+in a list, separated by ``or`` -- e.g. ``manager PMyManager or
+PMyOtherManager``. Of course, an **instance** of a managed actor type has only
+one manager actor (and is therefore managed by only one of the types of
+manager). The manager of an instance of a managee is always the actor that
+constructed that managee.
+
+Finally, there is the message declaration ``async PMyManaged()``. This message
+is a constructor for ``MyManaged`` actors; unlike C++ classes, it is found in
+``MyManager``. Every manager will need to expose constructors to create its
+managed types. These constructors are the only way to create an actor that is
+managed. They can take parameters and return results, like normal messages.
+The implementation of IPDL constructors are discussed in `Actor Lifetimes in
+C++`_.
+
+We haven't discussed a way to construct new top level actors. This is a more
+advanced topic and is covered separately in `Top Level Actors`_.
+
+.. _IPDL messages: `Declaring IPDL Messages`_
+
+Declaring IPDL Messages
+~~~~~~~~~~~~~~~~~~~~~~~
+
+The final part of the actor definition is the declaration of messages:
+
+.. code-block:: cpp
+
+ sync protocol PMyManager {
+ // ...
+ parent:
+ async __delete__(nsString aNote);
+ sync SomeMsg(MyActorPair? aActors, MyData[] aMyData)
+ returns (int32_t x, int32_t y, MyUnion aUnion);
+ async PMyManaged();
+ both:
+ [Tainted] async AnotherMsg(MyActorEnum aEnum, int32_t a number)
+ returns (MyOtherData aOtherData);
+ };
+
+The messages are grouped into blocks by ``parent:``, ``child:`` and ``both:``.
+These labels work the way ``public:`` and ``private:`` work in C++ -- messages
+after these descriptors are sent/received (only) in the direction specified.
+
+.. note::
+ As a mnemonic to remember which direction they indicate, remember to put
+ the word "to" in front of them. So, for example, ``parent:`` precedes
+ ``__delete__``, meaning ``__delete__`` is sent from the child **to** the
+ parent, and ``both:`` states that ``AnotherMsg`` can be sent **to** either
+ endpoint.
+
+IPDL messages support the following annotations:
+
+======================== ======================================================
+``[Compress]`` Indicates repeated messages of this type will
+ consolidate.
+``[Tainted]`` Parameters are required to be validated before using
+ them.
+``[Priority=Foo]`` Priority of ``MessageTask`` that runs the C++ message
+ handler. ``Foo`` is one of: ``normal``, ``input``,
+ ``vsync``, ``mediumhigh``, or ``control``.
+ See the ``IPC::Message::PriorityValue`` enum.
+``[Nested=inside_sync]`` Indicates that the message can sometimes be handled
+ while a sync message waits for a response.
+``[Nested=inside_cpow]`` Indicates that the message can sometimes be handled
+ while a sync message waits for a response.
+``[LazySend]`` Messages with this annotation will be queued up to be
+ sent together either immediately before a non-LazySend
+ message, or from a direct task.
+======================== ======================================================
+
+``[Compress]`` provides crude protection against spamming with a flood of
+messages. When messages of type ``M`` are compressed, the queue of unprocessed
+messages between actors will never contain an ``M`` beside another one; they
+will always be separated by a message of a different type. This is achieved by
+throwing out the older of the two messages if sending the new one would break
+the rule. This has been used to throttle pointer events between the main and
+content processes.
+
+``[Compress=all]`` is similar but applies whether or not the messages are
+adjacent in the message queue.
+
+``[Tainted]`` is a C++ mechanism designed to encourage paying attentiton to
+parameter security. The values of tainted parameters cannot be used until you
+vouch for their safety. They are discussed in `Actors and Messages in C++`_.
+
+The ``Nested`` annotations are deeply related to the message's blocking policy
+that follows it and which was briefly discussed in `Defining Actors`_. See
+`Nested messages`_ for details.
+
+``[LazySend]`` indicates the message doesn't need to be sent immediately, and
+can be sent later, from a direct task. Worker threads which do not support
+direct task dispatch will ignore this attribute. Messages with this annotation
+will still be delivered in-order with other messages, meaning that if a normal
+message is sent, any queued ``[LazySend]`` messages will be sent first. The
+attribute allows the transport layer to combine messages to be sent together,
+potentially reducing thread wake-ups for I/O and receiving threads.
+
+The following is a complete list of the available blocking policies. It
+resembles the list in `Defining Actors`_:
+
+====================== ========================================================
+``async`` Actor may contain only asynchronous messages.
+``sync`` Actor has ``async`` capabilities and adds ``sync``
+ messages. ``sync`` messages can only be sent from the
+ child actor to the parent.
+``intr`` (deprecated) Actor has ``sync`` capabilities and adds ``intr``
+ messages. This type will be removed soon.
+====================== ========================================================
+
+The policy defines whether an actor will wait for a response when it sends a
+certain type of message. A ``sync`` actor will wait immediately after sending
+a ``sync`` message, stalling its thread, until a response is received. This is
+an easy source of browser stalls. It is rarely required that a message be
+synchronous. New ``sync`` messages are therefore required to get approval from
+an IPC peer. The IPDL compiler will require such messages to be listed in the
+file ``sync-messages.ini``.
+
+The notion that only child actors can send ``sync`` messages was introduced to
+avoid potential deadlocks. It relies on the belief that a cycle (deadlock) of
+sync messages is impossible because they all point in one direction. This is
+no longer the case because any endpoint can be a child `or` parent and some,
+like the main process, sometimes serve as both. This means that sync messages
+should be used with extreme care.
+
+.. note::
+ The notion of sync messages flowing in one direction is still the main
+ mechanism IPDL uses to avoid deadlock. New actors should avoid violating
+ this rule as the consequences are severe (and complex). Actors that break
+ these rules should not be approved without **extreme** extenuating
+ circumstances. If you think you need this, check with the IPC team on
+ Element first (#ipc).
+
+An ``async`` actor will not wait. An ``async`` response is essentially
+identical to sending another ``async`` message back. It may be handled
+whenever received messages are handled. The value over an ``async`` response
+message comes in the ergonomics -- async responses are usually handled by C++
+lambda functions that are more like continuations than methods. This makes
+them easier to write and to read. Additionally, they allow a response to
+return message failure, while there would be no such response if we were
+expecting to send a new async message back, and it failed.
+
+Following synchronization is the name of the message and its parameter list.
+The message ``__delete__`` stands out as strange -- indeed, it terminates the
+actor's connection. `It does not delete any actor objects itself!` It severs
+the connections of the actor `and any actors it manages` at both endpoints. An
+actor will never send or receive any messages after it sends or receives a
+``__delete__``. Note that all sends and receives have to happen on a specific
+*worker* thread for any actor tree so the send/receive order is well defined.
+Anything sent after the actor processes ``__delete__`` is ignored (send returns
+an error, messages yet to be received fail their delivery). In other words,
+some future operations may fail but no unexpected behavior is possible.
+
+In our example, the child can break the connection by sending ``__delete__`` to
+the parent. The only thing the parent can do to sever the connection is to
+fail, such as by crashing. This sort of unidirectional control is both common
+and desirable.
+
+``PMyManaged()`` is a managed actor constructor. Note the asymmetry -- an
+actor contains its managed actor's constructors but its own destructor.
+
+The list of parameters to a message is fairly straight-forward. Parameters
+can be any type that has a C++ ``ParamTraits`` specialization and is imported
+by a directive. That said, there are some surprises in the list of messages:
+
+================= =============================================================
+``int32_t``,... The standard primitive types are included. See `builtin.py`_
+ for a list. Pointer types are, unsurprisingly, forbidden.
+``?`` When following a type T, the parameter is translated into
+ ``Maybe<T>`` in C++.
+``[]`` When following a type T, the parameter is translated into
+ ``nsTArray<T>`` in C++.
+================= =============================================================
+
+Finally, the returns list declares the information sent in response, also as a
+tuple of typed parameters. As previously mentioned, even ``async`` messages
+can receive responses. A ``sync`` message will always wait for a response but
+an ``async`` message will not get one unless it has a ``returns`` clause.
+
+This concludes our tour of the IPDL example file. The connection to C++ is
+discussed in the next chapter; messages in particular are covered in `Actors
+and Messages in C++`_. For suggestions on best practices when designing your
+IPDL actor approach, see `IPDL Best Practices`_.
+
+.. _builtin.py: https://searchfox.org/mozilla-central/source/ipc/ipdl/ipdl/builtin.py
+
+IPDL Syntax Quick Reference
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The following is a list of the keywords and operators that have been introduced
+for use in IPDL files:
+
+============================= =================================================
+``include`` Include a C++ header (quoted file name) or
+ ``.ipdlh`` file (unquoted with no file suffix).
+``using (class|struct) from`` Similar to ``include`` but imports only a
+ specific data type.
+``include protocol`` Include another actor for use in management
+ statements, IPDL data types or as parameters to
+ messages.
+``[RefCounted]`` Indicates that the imported C++ data types are
+ reference counted. Refcounted types require a
+ different ``ParamTraits`` interface than
+ non-reference-counted types.
+``[ManualDealloc]`` Indicates that the IPDL interface uses the legacy
+ manual allocation/deallocation interface, rather
+ than modern reference counting.
+``[MoveOnly]`` Indicates that an imported C++ data type should
+ not be copied. IPDL code will move it instead.
+``namespace`` Specifies the namespace for IPDL generated code.
+``union`` An IPDL union definition.
+``struct`` An IPDL struct definition.
+``[Comparable]`` Indicates that IPDL should generate
+ ``operator==`` and ``operator!=`` for the given
+ IPDL struct/union.
+``nullable`` Indicates that an actor reference in an IPDL type
+ may be null when sent over IPC.
+``protocol`` An IPDL protocol (actor) definition.
+``sync/async`` These are used in two cases: (1) to indicate
+ whether a message blocks as it waits for a result
+ and (2) because an actor that contains ``sync``
+ messages must itself be labeled ``sync`` or
+ ``intr``.
+``[NestedUpTo=inside_sync]`` Indicates that an actor contains
+ [Nested=inside_sync] messages, in addition to
+ normal messages.
+``[NestedUpTo=inside_cpow]`` Indicates that an actor contains
+ [Nested=inside_cpow] messages, in addition to
+ normal messages.
+``intr`` Used to indicate either that (1) an actor
+ contains ``sync``, ``async`` and (deprecated)
+ ``intr`` messages, or (2) a message is ``intr``
+ type.
+``[Nested=inside_sync]`` Indicates that the message can be handled while
+ waiting for lower-priority, or in-message-thread,
+ sync responses.
+``[Nested=inside_cpow]`` Indicates that the message can be handled while
+ waiting for lower-priority, or in-message-thread,
+ sync responses. Cannot be sent by the parent
+ actor.
+``manager`` Used in a protocol definition to indicate that
+ this actor manages another one.
+``manages`` Used in a protocol definition to indicate that
+ this actor is managed by another one.
+``or`` Used in a ``manager`` clause for actors that have
+ multiple potential managers.
+``parent: / child: / both:`` Indicates direction of subsequent actor messages.
+ As a mnemonic to remember which direction they
+ indicate, put the word "to" in front of them.
+``returns`` Defines return values for messages. All types
+ of message, including ``async``, support
+ returning values.
+``__delete__`` A special message that destroys the related
+ actors at both endpoints when sent.
+ ``Recv__delete__`` and ``ActorDestroy`` are
+ called before destroying the actor at the other
+ endpoint, to allow for cleanup.
+``int32_t``,... The standard primitive types are included.
+``String`` Translated into ``nsString`` in C++.
+``?`` When following a type T in an IPDL data structure
+ or message parameter,
+ the parameter is translated into ``Maybe<T>`` in
+ C++.
+``[]`` When following a type T in an IPDL data structure
+ or message parameter,
+ the parameter is translated into ``nsTArray<T>``
+ in C++.
+``[Tainted]`` Used to indicate that a message's handler should
+ receive parameters that it is required to
+ manually validate. Parameters of type ``T``
+ become ``Tainted<T>`` in C++.
+``[Compress]`` Indicates repeated messages of this type will
+ consolidate. When two messages of this type are
+ sent and end up side-by-side in the message queue
+ then the older message is discarded (not sent).
+``[Compress=all]`` Like ``[Compress]`` but discards the older
+ message regardless of whether they are adjacent
+ in the message queue.
+``[Priority=Foo]`` Priority of ``MessageTask`` that runs the C++
+ message handler. ``Foo`` is one of: ``normal``,
+ ``input``, ``vsync``, ``mediumhigh``, or
+ ``control``.
+``[LazySend]`` Messages with this annotation will be queued up to
+ be sent together immediately before a non-LazySend
+ message, or from a direct task.
+``[ChildImpl="RemoteFoo"]`` Indicates that the child side implementation of
+ the actor is a class named ``RemoteFoo``, and the
+ definition is included by one of the
+ ``include "...";`` statements in the file.
+ *New uses of this attribute are discouraged.*
+``[ParentImpl="FooImpl"]`` Indicates that the parent side implementation of
+ the actor is a class named ``FooImpl``, and the
+ definition is included by one of the
+ ``include "...";`` statements in the file.
+ *New uses of this attribute are discouraged.*
+``[ChildImpl=virtual]`` Indicates that the child side implementation of
+ the actor is not exported by a header, so virtual
+ ``Recv`` methods should be used instead of direct
+ function calls. *New uses of this attribute are
+ discouraged.*
+``[ParentImpl=virtual]`` Indicates that the parent side implementation of
+ the actor is not exported by a header, so virtual
+ ``Recv`` methods should be used instead of direct
+ function calls. *New uses of this attribute are
+ discouraged.*
+``[ChildProc=...]`` Indicates which process the child side of the actor
+ is expected to be bound in. This will be release
+ asserted when creating the actor. Required for
+ top-level actors. See `Process Type Attributes`_
+ for possible values.
+``[ParentProc=...]`` Indicates which process the parent side of the
+ actor is expected to be bound in. This will be
+ release asserted when creating the actor.
+ Defaults to ``Parent`` for top-level actors. See
+ `Process Type Attributes`_ for possible values.
+============================= =================================================
+
+.. _Process Type Attributes:
+
+Process Type Attributes
+^^^^^^^^^^^^^^^^^^^^^^^
+
+The following are valid values for the ``[ChildProc=...]`` and
+``[ParentProc=...]`` attributes on protocols, each corresponding to a specific
+process type:
+
+============================= =================================================
+``Parent`` The primary "parent" or "main" process
+``Content`` A content process, such as those used to host web
+ pages, workers, and extensions
+``IPDLUnitTest`` Test-only process used in IPDL gtests
+``GMPlugin`` Gecko Media Plugin (GMP) process
+``GPU`` GPU process
+``VR`` VR process
+``RDD`` Remote Data Decoder (RDD) process
+``Socket`` Socket/Networking process
+``RemoteSandboxBroker`` Remote Sandbox Broker process
+``ForkServer`` Fork Server process
+``Utility`` Utility process
+============================= =================================================
+
+The attributes also support some wildcard values, which can be used when an
+actor can be bound in multiple processes. If you are adding an actor which
+needs a new wildcard value, please reach out to the IPC team, and we can add one
+for your use-case. They are as follows:
+
+============================= =================================================
+``any`` Any process. If a more specific value is
+ applicable, it should be preferred where possible.
+``anychild`` Any process other than ``Parent``. Often used for
+ utility actors which are bound on a per-process
+ basis, such as profiling.
+``compositor`` Either the ``GPU`` or ``Parent`` process. Often
+ used for actors bound to the compositor thread.
+``anydom`` Either the ``Parent`` or a ``Content`` process.
+ Often used for actors used to implement DOM APIs.
+============================= =================================================
+
+Note that these assertions do not provide security guarantees, and are primarily
+intended for use when auditing and as documentation for how actors are being
+used.
+
+
+The C++ Interface
+-----------------
+
+ParamTraits
+~~~~~~~~~~~
+
+Before discussing how C++ represents actors and messages, we look at how IPDL
+connects to the imported C++ data types. In order for any C++ type to be
+(de)serialized, it needs an implementation of the ``ParamTraits`` C++ type
+class. ``ParamTraits`` is how your code tells IPDL what bytes to write to
+serialize your objects for sending, and how to convert those bytes back to
+objects at the other endpoint. Since ``ParamTraits`` need to be reachable by
+IPDL code, they need to be declared in a C++ header and imported by your
+protocol file. Failure to do so will result in a build error.
+
+Most basic types and many essential Mozilla types are always available for use
+without inclusion. An incomplete list includes: C++ primitives, strings
+(``std`` and ``mozilla``), vectors (``std`` and ``mozilla``), ``RefPtr<T>``
+(for serializable ``T``), ``UniquePtr<T>``, ``nsCOMPtr<T>``, ``nsTArray<T>``,
+``std::unordered_map<T>``, ``nsresult``, etc. See `builtin.py
+<https://searchfox.org/mozilla-central/source/ipc/ipdl/ipdl/builtin.py>`_,
+`ipc_message_utils.h
+<https://searchfox.org/mozilla-central/source/ipc/chromium/src/chrome/common/ipc_message_utils.h>`_
+and `IPCMessageUtilsSpecializations.h
+<https://searchfox.org/mozilla-central/source/ipc/glue/IPCMessageUtilsSpecializations.h>`_.
+
+``ParamTraits`` typically bootstrap with the ``ParamTraits`` of more basic
+types, until they hit bedrock (e.g. one of the basic types above). In the most
+extreme cases, a ``ParamTraits`` author may have to resort to designing a
+binary data format for a type. Both options are available.
+
+We haven't seen any of this C++ yet. Let's look at the data types included
+from ``MyDataTypes.h``:
+
+.. code-block:: cpp
+
+ // MyDataTypes.h
+ namespace mozilla::myns {
+ struct MyData {
+ nsCString s;
+ uint8_t bytes[17];
+ MyData(); // IPDL requires the default constructor to be public
+ };
+
+ struct MoveonlyData {
+ MoveonlyData();
+ MoveonlyData& operator=(const MoveonlyData&) = delete;
+
+ MoveonlyData(MoveonlyData&& m);
+ MoveonlyData& operator=(MoveonlyData&& m);
+ };
+
+ typedef MoveonlyData MyOtherData;
+
+ class MyUnusedData {
+ public:
+ NS_INLINE_DECL_REFCOUNTING(MyUnusedData)
+ int x;
+ };
+ };
+
+ namespace IPC {
+ // Basic type
+ template<>
+ struct ParamTraits<mozilla::myns::MyData> {
+ typedef mozilla::myns::MyData paramType;
+ static void Write(MessageWriter* m, const paramType& in);
+ static bool Read(MessageReader* m, paramType* out);
+ };
+
+ // [MoveOnly] type
+ template<>
+ struct ParamTraits<mozilla::myns::MyOtherData> {
+ typedef mozilla::myns::MyOtherData paramType;
+ static void Write(MessageWriter* m, const paramType& in);
+ static bool Read(MessageReader* m, paramType* out);
+ };
+
+ // [RefCounted] type
+ template<>
+ struct ParamTraits<mozilla::myns::MyUnusedData*> {
+ typedef mozilla::myns::MyUnusedData paramType;
+ static void Write(MessageWriter* m, paramType* in);
+ static bool Read(MessageReader* m, RefPtr<paramType>* out);
+ };
+ }
+
+MyData is a struct and MyOtherData is a typedef. IPDL is fine with both.
+Additionally, MyOtherData is not copyable, matching its IPDL ``[MoveOnly]``
+annotation.
+
+``ParamTraits`` are required to be defined in the ``IPC`` namespace. They must
+contain a ``Write`` method with the proper signature that is used for
+serialization and a ``Read`` method, again with the correct signature, for
+deserialization.
+
+Here we have three examples of declarations: one for an unannotated type, one
+for ``[MoveOnly]`` and a ``[RefCounted]`` one. Notice the difference in the
+``[RefCounted]`` type's method signatures. The only difference that may not be
+clear from the function types is that, in the non-reference-counted case, a
+default-constructed object is supplied to ``Read`` but, in the
+reference-counted case, ``Read`` is given an empty ``RefPtr<MyUnusedData>`` and
+should only allocate a ``MyUnusedData`` to return if it so desires.
+
+These are straight-forward implementations of the ``ParamTraits`` methods for
+``MyData``:
+
+.. code-block:: cpp
+
+ /* static */ void IPC::ParamTraits<MyData>::Write(MessageWriter* m, const paramType& in) {
+ WriteParam(m, in.s);
+ m->WriteBytes(in.bytes, sizeof(in.bytes));
+ }
+ /* static */ bool IPC::ParamTraits<MyData>::Read(MessageReader* m, paramType* out) {
+ return ReadParam(m, &out->s) &&
+ m->ReadBytesInto(out->bytes, sizeof(out->bytes));
+ }
+
+``WriteParam`` and ``ReadParam`` call the ``ParamTraits`` for the data you pass
+them, determined using the type of the object as supplied. ``WriteBytes`` and
+``ReadBytesInto`` work on raw, contiguous bytes as expected. ``MessageWriter``
+and ``MessageReader`` are IPDL internal objects which hold the incoming/outgoing
+message as a stream of bytes and the current spot in the stream. It is *very*
+rare for client code to need to create or manipulate these objects. Their
+advanced use is beyond the scope of this document.
+
+.. important::
+ Potential failures in ``Read`` include everyday C++ failures like
+ out-of-memory conditions, which can be handled as usual. But ``Read`` can
+ also fail due to things like data validation errors. ``ParamTraits`` read
+ data that is considered insecure. It is important that they catch
+ corruption and properly handle it. Returning false from ``Read`` will
+ usually result in crashing the process (everywhere except in the main
+ process). This is the right behavior as the browser would be in an
+ unexpected state, even if the serialization failure was not malicious
+ (since it cannot process the message). Other responses, such as failing
+ with a crashing assertion, are inferior. IPDL fuzzing relies on
+ ``ParamTraits`` not crashing due to corruption failures.
+ Occasionally, validation will require access to state that ``ParamTraits``
+ can't easily reach. (Only) in those cases, validation can be reasonably
+ done in the message handler. Such cases are a good use of the ``Tainted``
+ annotation. See `Actors and Messages in C++`_ for more.
+
+.. note::
+ In the past, it was required to specialize ``mozilla::ipc::IPDLParamTraits<T>``
+ instead of ``IPC::ParamTraits<T>`` if you needed the actor object itself during
+ serialization or deserialization. These days the actor can be fetched using
+ ``IPC::Message{Reader,Writer}::GetActor()`` in ``IPC::ParamTraits``, so that
+ trait should be used for all new serializations.
+
+A special case worth mentioning is that of enums. Enums are a common source of
+security holes since code is rarely safe with enum values that are not valid.
+Since data obtained through IPDL messages should be considered tainted, enums
+are of principal concern. ``ContiguousEnumSerializer`` and
+``ContiguousEnumSerializerInclusive`` safely implement ``ParamTraits`` for
+enums that are only valid for a contiguous set of values, which is most of
+them. The generated ``ParamTraits`` confirm that the enum is in valid range;
+``Read`` will return false otherwise. As an example, here is the
+``MyActorEnum`` included from ``MyActorUtils.h``:
+
+.. code-block:: cpp
+
+ enum MyActorEnum { e1, e2, e3, e4, e5 };
+
+ template<>
+ struct ParamTraits<MyActorEnum>
+ : public ContiguousEnumSerializerInclusive<MyActorEnum, MyActorEnum::e1, MyActorEnum::e5> {};
+
+IPDL Structs and Unions in C++
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+IPDL structs and unions become C++ classes that provide interfaces that are
+fairly self-explanatory. Recalling ``MyUnion`` and ``MyActorPair`` from
+`IPDL Structs and Unions`_ :
+
+.. code-block:: cpp
+
+ union MyUnion {
+ float;
+ MyOtherData;
+ };
+
+ struct MyActorPair {
+ PMyManaged actor1;
+ nullable PMyManaged actor2;
+ };
+
+These compile to:
+
+.. code-block:: cpp
+
+ class MyUnion {
+ enum Type { Tfloat, TMyOtherData };
+ Type type();
+ MyUnion(float f);
+ MyUnion(MyOtherData&& aOD);
+ MyUnion& operator=(float f);
+ MyUnion& operator=(MyOtherData&& aOD);
+ operator float&();
+ operator MyOtherData&();
+ };
+
+ class MyActorPair {
+ MyActorPair(PMyManagedParent* actor1Parent, PMyManagedChild* actor1Child,
+ PMyManagedParent* actor2Parent, PMyManagedChild* actor2Child);
+ // Exactly one of { actor1Parent(), actor1Child() } must be non-null.
+ PMyManagedParent*& actor1Parent();
+ PMyManagedChild*& actor1Child();
+ // As nullable, zero or one of { actor2Parent(), actor2Child() } will be non-null.
+ PMyManagedParent*& actor2Parent();
+ PMyManagedChild*& actor2Child();
+ }
+
+The generated ``ParamTraits`` use the ``ParamTraits`` for the types referenced
+by the IPDL struct or union. Fields respect any annotations for their type
+(see `IPDL Includes`_). For example, a ``[RefCounted]`` type ``T`` generates
+``RefPtr<T>`` fields.
+
+Note that actor members result in members of both the parent and child actor
+types, as seen in ``MyActorPair``. When actors are used to bridge processes,
+only one of those could ever be used at a given endpoint. IPDL makes sure
+that, when you send one type (say, ``PMyManagedChild``), the adjacent actor of
+the other type (``PMyManagedParent``) is received. This is not only true for
+message parameters and IPDL structs/unions but also for custom ``ParamTraits``
+implementations. If you ``Write`` a ``PFooParent*`` then you must ``Read`` a
+``PFooChild*``. This is hard to confuse in message handlers since they are
+members of a class named for the side they operate on, but this cannot be
+enforced by the compiler. If you are writing
+``MyManagerParent::RecvSomeMsg(Maybe<MyActorPair>&& aActors, nsTArray<MyData>&& aMyData)``
+then the ``actor1Child`` and ``actor2Child`` fields cannot be valid since the
+child (usually) exists in another process.
+
+.. _IPDL Structs and Unions: `Generating IPDL-Aware C++ Data Types: IPDL Structs and Unions`_
+.. _IPDL Includes: `Referencing Externally Defined Data Types: IPDL Includes`_
+
+Actors and Messages in C++
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+As mentioned in `Using The IPDL compiler`_, the IPDL compiler generates two
+header files for the protocol ``PMyManager``: ``PMyManagerParent.h`` and
+``PMyManagerChild.h``, which declare the actor's base classes. There, we
+discussed how the headers are visible to C++ components that include
+``chromium-config.mozbuild``. We, in turn, always need to define two files
+that declare our actor implementation subclasses (``MyManagerParent.h`` and
+``MyManagerChild.h``). The IPDL file looked like this:
+
+.. literalinclude:: _static/PMyManager.ipdl
+ :language: c++
+ :name: PMyManager.ipdl
+
+So ``MyManagerParent.h`` looks like this:
+
+.. code-block:: cpp
+
+ #include "PMyManagerParent.h"
+
+ namespace mozilla {
+ namespace myns {
+
+ class MyManagerParent : public PMyManagerParent {
+ NS_INLINE_DECL_REFCOUNTING(MyManagerParent, override)
+ protected:
+ IPCResult Recv__delete__(const nsString& aNote);
+ IPCResult RecvSomeMsg(const Maybe<MyActorPair>& aActors, const nsTArray<MyData>& aMyData,
+ int32_t* x, int32_t* y, MyUnion* aUnion);
+ IPCResult RecvAnotherMsg(const Tainted<MyActorEnum>& aEnum, const Tainted<int32_t>& a number,
+ AnotherMsgResolver&& aResolver);
+
+ already_AddRefed<PMyManagerParent> AllocPMyManagedParent();
+ IPCResult RecvPMyManagedConstructor(PMyManagedConstructor* aActor);
+
+ // ... etc ...
+ };
+
+ } // namespace myns
+ } // namespace mozilla
+
+All messages that can be sent to the actor must be handled by ``Recv`` methods
+in the proper actor subclass. They should return ``IPC_OK()`` on success and
+``IPC_FAIL(actor, reason)`` if an error occurred (where ``actor`` is ``this``
+and ``reason`` is a human text explanation) that should be considered a failure
+to process the message. The handling of such a failure is specific to the
+process type.
+
+``Recv`` methods are called by IPDL by enqueueing a task to run them on the
+``MessageLoop`` for the thread on which they are bound. This thread is the
+actor's *worker thread*. All actors in a managed actor tree have the same
+worker thread -- in other words, actors inherit the worker thread from their
+managers. Top level actors establish their worker thread when they are
+*bound*. More information on threads can be found in `Top Level Actors`_. For
+the most part, client code will never engage with an IPDL actor outside of its
+worker thread.
+
+Received parameters become stack variables that are ``std::move``-d into the
+``Recv`` method. They can be received as a const l-value reference,
+rvalue-reference, or by value (type-permitting). ``[MoveOnly]`` types should
+not be received as const l-values. Return values for sync messages are
+assigned by writing to non-const (pointer) parameters. Return values for async
+messages are handled differently -- they are passed to a resolver function. In
+our example, ``AnotherMsgResolver`` would be a ``std::function<>`` and
+``aResolver`` would be given the value to return by passing it a reference to a
+``MyOtherData`` object.
+
+``MyManagerParent`` is also capable of ``sending`` an async message that
+returns a value: ``AnotherMsg``. This is done with ``SendAnotherMsg``, which
+is defined automatically by IPDL in the base class ``PMyManagerParent``. There
+are two signatures for ``Send`` and they look like this:
+
+.. code-block:: cpp
+
+ // Return a Promise that IPDL will resolve with the response or reject.
+ RefPtr<MozPromise<MyOtherData, ResponseRejectReason, true>>
+ SendAnotherMsg(const MyActorEnum& aEnum, int32_t a number);
+
+ // Provide callbacks to process response / reject. The callbacks are just
+ // std::functions.
+ void SendAnotherMsg(const MyActorEnum& aEnum, int32_t a number,
+ ResolveCallback<MyOtherData>&& aResolve, RejectCallback&& aReject);
+
+The response is usually handled by lambda functions defined at the site of the
+``Send`` call, either by attaching them to the returned promise with e.g.
+``MozPromise::Then``, or by passing them as callback parameters. See docs on
+``MozPromise`` for more on its use. The promise itself is either resolved or
+rejected by IPDL when a valid reply is received or when the endpoint determines
+that the communication failed. ``ResponseRejectReason`` is an enum IPDL
+provides to explain failures.
+
+Additionally, the ``AnotherMsg`` handler has ``Tainted`` parameters, as a
+result of the [Tainted] annotation in the protocol file. Recall that
+``Tainted`` is used to force explicit validation of parameters in the message
+handler before their values can be used (as opposed to validation in
+``ParamTraits``). They therefore have access to any state that the message
+handler does. Their APIs, along with a list of macros that are used to
+validate them, are detailed `here
+<https://searchfox.org/mozilla-central/source/mfbt/Tainting.h>`__.
+
+Send methods that are not for async messages with return values follow a
+simpler form; they return a ``bool`` indicating success or failure and return
+response values in non-const parameters, as the ``Recv`` methods do. For
+example, ``PMyManagerChild`` defines this to send the sync message ``SomeMsg``:
+
+.. code-block:: cpp
+
+ // generated in PMyManagerChild
+ bool SendSomeMsg(const Maybe<MyActorPair>& aActors, const nsTArray<MyData>& aMyData,
+ int32_t& x, int32_t& y, MyUnion& aUnion);
+
+Since it is sync, this method will not return to its caller until the response
+is received or an error is detected.
+
+All calls to ``Send`` methods, like all messages handler ``Recv`` methods, must
+only be called on the worker thread for the actor.
+
+Constructors, like the one for ``MyManaged``, are clearly an exception to these
+rules. They are discussed in the next section.
+
+.. _Actor Lifetimes in C++:
+
+Actor Lifetimes in C++
+~~~~~~~~~~~~~~~~~~~~~~
+
+The constructor message for ``MyManaged`` becomes *two* methods at the
+receiving end. ``AllocPMyManagedParent`` constructs the managed actor, then
+``RecvPMyManagedConstructor`` is called to update the new actor. The following
+diagram shows the construction of the ``MyManaged`` actor pair:
+
+.. mermaid::
+ :align: center
+ :caption: A ``MyManaged`` actor pair being created by some ``Driver``
+ object. Internal IPC objects in the parent and child processes
+ are combined for compactness. Connected **par** blocks run
+ concurrently. This shows that messages can be safely sent while
+ the parent is still being constructed.
+
+ %%{init: {'sequence': {'boxMargin': 4, 'actorMargin': 10} }}%%
+ sequenceDiagram
+ participant d as Driver
+ participant mgdc as MyManagedChild
+ participant mgrc as MyManagerChild
+ participant ipc as IPC Child/Parent
+ participant mgrp as MyManagerParent
+ participant mgdp as MyManagedParent
+ d->>mgdc: new
+ mgdc->>d: [mgd_child]
+ d->>mgrc: SendPMyManagedConstructor<br/>[mgd_child, params]
+ mgrc->>ipc: Form actor pair<br/>[mgd_child, params]
+ par
+ mgdc->>ipc: early PMyManaged messages
+ and
+ ipc->>mgrp: AllocPMyManagedParent<br/>[params]
+ mgrp->>mgdp: new
+ mgdp->>mgrp: [mgd_parent]
+ ipc->>mgrp: RecvPMyManagedConstructor<br/>[mgd_parent, params]
+ mgrp->>mgdp: initialization
+ ipc->>mgdp: early PMyManaged messages
+ end
+ Note over mgdc,mgdp: Bi-directional sending and receiving will now happen concurrently.
+
+The next diagram shows the destruction of the ``MyManaged`` actor pair, as
+initiated by a call to ``Send__delete__``. ``__delete__`` is sent from the
+child process because that is the only side that can call it, as declared in
+the IPDL protocol file.
+
+.. mermaid::
+ :align: center
+ :caption: A ``MyManaged`` actor pair being disconnected due to some
+ ``Driver`` object in the child process sending ``__delete__``.
+
+ %%{init: {'sequence': {'boxMargin': 4, 'actorMargin': 10} }}%%
+ sequenceDiagram
+ participant d as Driver
+ participant mgdc as MyManagedChild
+ participant ipc as IPC Child/Parent
+ participant mgdp as MyManagedParent
+ d->>mgdc: Send__delete__
+ mgdc->>ipc: Disconnect<br/>actor pair
+ par
+ ipc->>mgdc: ActorDestroy
+ ipc->>mgdc: Release
+ and
+ ipc->>mgdp: Recv__delete__
+ ipc->>mgdp: ActorDestroy
+ ipc->>mgdp: Release
+ end
+
+Finally, let's take a look at the behavior of an actor whose peer has been lost
+(e.g. due to a crashed process).
+
+.. mermaid::
+ :align: center
+ :caption: A ``MyManaged`` actor pair being disconnected when its peer is
+ lost due to a fatal error. Note that ``Recv__delete__`` is not
+ called.
+
+ %%{init: {'sequence': {'boxMargin': 4, 'actorMargin': 10} }}%%
+ sequenceDiagram
+ participant mgdc as MyManagedChild
+ participant ipc as IPC Child/Parent
+ participant mgdp as MyManagedParent
+ Note over mgdc: CRASH!!!
+ ipc->>ipc: Notice fatal error.
+ ipc->>mgdp: ActorDestroy
+ ipc->>mgdp: Release
+
+The ``Alloc`` and ``Recv...Constructor`` methods are somewhat mirrored by
+``Recv__delete__`` and ``ActorDestroy`` but there are a few differences.
+First, the ``Alloc`` method really does create the actor but the
+``ActorDestroy`` method does not delete it. Additionally, ``ActorDestroy``
+is run at *both* endpoints, during ``Send__delete__`` or after
+``Recv__delete__``. Finally and most importantly, ``Recv__delete__`` is only
+called if the ``__delete__`` message is received but it may not be if, for
+example, the remote process crashes. ``ActorDestroy``, on the other hand, is
+guaranteed to run for *every* actor unless the process terminates uncleanly.
+For this reason, ``ActorDestroy`` is the right place for most actor shutdown
+code. ``Recv__delete__`` is rarely useful, although it is occasionally
+beneficial to have it receive some final data.
+
+The relevant part of the parent class looks like this:
+
+.. code-block:: cpp
+
+ class MyManagerParent : public PMyManagerParent {
+ already_AddRefed<PMyManagedParent> AllocPMyManagedParent();
+ IPCResult RecvPMyManagedConstructor(PMyManagedParent* aActor);
+
+ IPCResult Recv__delete__(const nsString& aNote);
+ void ActorDestroy(ActorDestroyReason why);
+
+ // ... etc ...
+ };
+
+The ``Alloc`` method is required for managed actors that are constructed by
+IPDL receiving a ``Send`` message. It is not required for the actor at the
+endpoint that calls ``Send``. The ``Recv...Constructor`` message is not
+required -- it has a base implementation that does nothing.
+
+If the constructor message has parameters, they are sent to both methods.
+Parameters are given to the ``Alloc`` method by const reference but are moved
+into the ``Recv`` method. They differ in that messages can be sent from the
+``Recv`` method but, in ``Alloc``, the newly created actor is not yet
+operational.
+
+The ``Send`` method for a constructor is similarly different from other
+``Send`` methods. In the child actor, ours looks like this:
+
+.. code-block:: cpp
+
+ IPCResult SendPMyManagedConstructor(PMyManagedChild* aActor);
+
+The method expects a ``PMyManagedChild`` that the caller will have constructed,
+presumably using ``new`` (this is why it does not require an ``Alloc`` method).
+Once ``Send...Constructor`` is called, the actor can be used to send and
+receive messages. It does not matter that the remote actor may not have been
+created yet due to asynchronicity.
+
+The destruction of actors is as unusual as their construction. Unlike
+construction, it is the same for managed and top-level actors. Avoiding
+``[ManualDealloc]`` actors removes a lot of the complexity but there is still
+a process to understand. Actor destruction begins when an ``__delete__``
+message is sent. In ``PMyManager``, this message is declared from child to
+parent. The actor calling ``Send__delete__`` is no longer connected to
+anything when the method returns. Future calls to ``Send`` return an error
+and no future messages will be received. This is also the case for an actor
+that has run ``Recv__delete__``; it is no longer connected to the other
+endpoint.
+
+.. note::
+ Since ``Send__delete__`` may release the final reference to itself, it
+ cannot safely be a class instance method. Instead, unlike other ``Send``
+ methods, it's a ``static`` class method and takes the actor as a parameter:
+
+ .. code-block:: cpp
+
+ static IPCResult Send__delete__(PMyManagerChild* aToDelete);
+
+ Additionally, the ``__delete__`` message tells IPDL to disconnect both the
+ given actor *and all of its managed actors*. So it is really deleting the
+ actor subtree, although ``Recv__delete__`` is only called for the actor it
+ was sent to.
+
+During the call to ``Send__delete__``, or after the call to ``Recv__delete__``,
+the actor's ``ActorDestroy`` method is called. This method gives client code a
+chance to do any teardown that must happen in `all` circumstances were it is
+possible -- both expected and unexpected. This means that ``ActorDestroy``
+will also be called when, for example, IPDL detects that the other endpoint has
+terminated unexpectedly, so it is releasing its reference to the actor, or
+because an ancestral manager (manager or manager's manager...) received a
+``__delete__``. The only way for an actor to avoid ``ActorDestroy`` is for its
+process to crash first. ``ActorDestroy`` is always run after its actor is
+disconnected so it is pointless to try to send messages from it.
+
+Why use ``ActorDestroy`` instead of the actor's destructor? ``ActorDestroy``
+gives a chance to clean up things that are only used for communication and
+therefore don't need to live for however long the actor's (reference-counted)
+object does. For example, you might have references to shared memory (Shmems)
+that are no longer valid. Or perhaps the actor can now release a cache of data
+that was only needed for processing messages. It is cleaner to deal with
+communication-related objects in ``ActorDestroy``, where they become invalid,
+than to leave them in limbo until the destructor is run.
+
+Consider actors to be like normal reference-counted objects, but where IPDL
+holds a reference while the connection will or does exist. One common
+architecture has IPDL holding the `only` reference to an actor. This is common
+with actors created by sending constructor messages but the idea is available to
+any actor. That only reference is then released when the ``__delete__``
+message is sent or received.
+
+The dual of IPDL holding the only reference is to have client code hold the
+only reference. A common pattern to achieve this has been to override the
+actor's ``AddRef`` to have it send ``__delete__`` only when it's count is down
+to one reference (which must be IPDL if ``actor.CanSend()`` is true). A better
+approach would be to create a reference-counted delegate for your actor that
+can send ``__delete__`` from its destructor. IPDL does not guarantee that it
+will not hold more than one reference to your actor.
+
+.. _Top Level Actors:
+
+Top Level Actors
+----------------
+
+Recall that top level actors are actors that have no manager. They are at the
+root of every actor tree. There are two settings in which we use top-level
+actors that differ pretty dramatically. The first type are top-level actors
+that are created and maintained in a way that resembles managed actors, but
+with some important differences we will cover in this section. The second type
+of top-level actors are the very first actors in a new process -- these actors
+are created through different means and closing them (usually) terminates the
+process. The `new process example
+<https://phabricator.services.mozilla.com/D119038>`_ demonstrates both of
+these. It is discussed in detail in :ref:`Adding a New Type of Process`.
+
+Value of Top Level Actors
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Top-level actors are harder to create and destroy than normal actors. They
+used to be more heavyweight than managed actors but this has recently been
+dramatically reduced.
+
+.. note::
+ Top-level actors previously required a dedicated *message channel*, which
+ are limited OS resources. This is no longer the case -- message channels
+ are now shared by actors that connect the same two processes. This
+ *message interleaving* can affect message delivery latency but profiling
+ suggests that the change was basically inconsequential.
+
+So why use a new top level actor?
+
+* The most dramatic property distinguishing top-level actors is the ability to
+ *bind* to whatever ``EventTarget`` they choose. This means that any thread
+ that runs a ``MessageLoop`` can use the event target for that loop as the
+ place to send incoming messages. In other words, ``Recv`` methods would be
+ run by that message loop, on that thread. The IPDL apparatus will
+ asynchronously dispatch messages to these event targets, meaning that
+ multiple threads can be handling incoming messages at the same time. The
+ `PBackground`_ approach was born of a desire to make it easier to exploit
+ this, although it has some complications, detailed in that section, that
+ limit its value.
+* Top level actors suggest modularity. Actor protocols are tough to debug, as
+ is just about anything that spans process boundaries. Modularity can give
+ other developers a clue as to what they need to know (and what they don't)
+ when reading an actor's code. The alternative is proverbial *dumpster
+ classes* that are as critical to operations (because they do so much) as they
+ are difficult to learn (because they do so much).
+* Top level actors are required to connect two processes, regardless of whether
+ the actors are the first in the process or not. As said above, the first
+ actor is created through special means but other actors are created through
+ messages. In Gecko, apart from the launcher and main processes, all new
+ processes X are created with their first actor being between X and the main
+ process. To create a connection between X and, say, a content process, the
+ main process has to send connected ``Endpoints`` to X and to the content
+ process, which in turn use those endpoints to create new top level actors
+ that form an actor pair. This is discussed at length in :ref:`Connecting
+ With Other Processes`.
+
+Top-level actors are not as frictionless as desired but they are probably
+under-utilized relative to their power. In cases where it is supported,
+``PBackground`` is sometimes a simpler alternative to achieve the same goals.
+
+Creating Top Level Actors From Other Actors
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The most common way to create new top level actors is by creating a pair of
+connected Endpoints and sending one to the other actor. This is done exactly
+the way it sounds. For example:
+
+.. code-block:: cpp
+
+ bool MyPreexistingActorParent::MakeMyActor() {
+ Endpoint<PMyActorParent> parentEnd;
+ Endpoint<PMyActorChild> childEnd;
+ if (NS_WARN_IF(NS_FAILED(PMyActor::CreateEndpoints(
+ base::GetCurrentProcId(), OtherPid(), &parentEnd, &childEnd)))) {
+ // ... handle failure ...
+ return false;
+ }
+ RefPtr<MyActorParent> parent = new MyActorParent;
+ if (!parentEnd.Bind(parent)) {
+ // ... handle failure ...
+ delete parent;
+ return false;
+ }
+ // Do this second so we skip child if parent failed to connect properly.
+ if (!SendCreateMyActorChild(std::move(childEnd))) {
+ // ... assume an IPDL error will destroy parent. Handle failure beyond that ...
+ return false;
+ }
+ return true;
+ }
+
+Here ``MyPreexistingActorParent`` is used to send a child endpoint for the new
+top level actor to ``MyPreexistingActorChild``, after it hooks up the parent
+end. In this example, we bind our new actor to the same thread we are running
+on -- which must be the same thread ``MyPreexistingActorParent`` is bound to
+since we are sending ``CreateMyActorChild`` from it. We could have bound on a
+different thread.
+
+At this point, messages can be sent on the parent. Eventually, it will start
+receiving them as well.
+
+``MyPreexistingActorChild`` still has to receive the create message. The code
+for that handler is pretty similar:
+
+.. code-block:: cpp
+
+ IPCResult MyPreexistingActorChild::RecvCreateMyActorChild(Endpoint<PMyActorChild>&& childEnd) {
+ RefPtr<MyActorChild> child = new MyActorChild;
+ if (!childEnd.Bind(child)) {
+ // ... handle failure and return ok, assuming a related IPDL error will alert the other side to failure ...
+ return IPC_OK();
+ }
+ return IPC_OK();
+ }
+
+Like the parent, the child is ready to send as soon as ``Bind`` is complete.
+It will start receiving messages soon afterward on the event target for the
+thread on which it is bound.
+
+Creating First Top Level Actors
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The first actor in a process is an advanced topic that is covered in
+:ref:`the documentation for adding a new process<Adding a New Type of Process>`.
+
+PBackground
+-----------
+
+Developed as a convenient alternative to top level actors, ``PBackground`` is
+an IPDL protocol whose managees choose their worker threads in the child
+process and share a thread dedicated solely to them in the parent process.
+When an actor (parent or child) should run without hogging the main thread,
+making that actor a managee of ``PBackground`` (aka a *background actor*) is an
+option.
+
+.. warning::
+ Background actors can be difficult to use correctly, as spelled out in this
+ section. It is recommended that other options -- namely, top-level actors
+ -- be adopted instead.
+
+Background actors can only be used in limited circumstances:
+
+* ``PBackground`` only supports the following process connections (where
+ ordering is parent <-> child): main <-> main, main <-> content,
+ main <-> socket and socket <-> content.
+
+.. important::
+
+ Socket process ``PBackground`` actor support was added after the other
+ options. It has some rough edges that aren't easy to anticipate. In the
+ future, their support may be broken out into a different actor or removed
+ altogether. You are strongly encouraged to use new `Top Level Actors`_
+ instead of ``PBackground`` actor when communicating with socket process
+ worker threads.
+
+* Background actor creation is always initiated by the child. Of course, a
+ request to create one can be sent to the child by any other means.
+* All parent background actors run in the same thread. This thread is
+ dedicated to serving as the worker for parent background actors. While it
+ has no other functions, it should remain responsive to all connected
+ background actors. For this reason, it is a bad idea to conduct long
+ operations in parent background actors. For such cases, create a top level
+ actor and an independent thread on the parent side instead.
+* Background actors are currently *not* reference-counted. IPDL's ownership
+ has to be carefully respected and the (de-)allocators for the new actors have
+ to be defined. See `The Old Ways`_ for details.
+
+A hypothetical layout of ``PBackground`` threads, demonstrating some of the
+process-type limitations, is shown in the diagram below.
+
+.. mermaid::
+ :align: center
+ :caption: Hypothetical ``PBackground`` thread setup. Arrow direction
+ indicates child-to-parent ``PBackground``-managee relationships.
+ Parents always share a thread and may be connected to multiple
+ processes. Child threads can be any thread, including main.
+
+ flowchart LR
+ subgraph content #1
+ direction TB
+ c1tm[main]
+ c1t1[worker #1]
+ c1t2[worker #2]
+ c1t3[worker #3]
+ end
+ subgraph content #2
+ direction TB
+ c2tm[main]
+ c2t1[worker #1]
+ c2t2[worker #2]
+ end
+ subgraph socket
+ direction TB
+ stm[main]
+ st1[background parent /\nworker #1]
+ st2[worker #2]
+ end
+ subgraph main
+ direction TB
+ mtm[main]
+ mt1[background parent]
+ end
+
+ %% PBackground connections
+ c1tm --> mt1
+ c1t1 --> mt1
+ c1t2 --> mt1
+
+ c1t3 --> mt1
+ c1t3 --> st1
+
+ c2t1 --> st1
+ c2t1 --> mt1
+
+ c2t2 --> mt1
+
+ c2tm --> st1
+
+ stm --> mt1
+ st1 --> mt1
+ st2 --> mt1
+
+Creating background actors is done a bit differently than normal managees. The
+new managed type and constructor are still added to ``PBackground.ipdl`` as
+with normal managees but, instead of ``new``-ing the child actor and then
+passing it in a ``SendFooConstructor`` call, background actors issue the send
+call to the ``BackgroundChild`` manager, which returns the new child:
+
+.. code-block:: cpp
+
+ // Bind our new PMyBackgroundActorChild to the current thread.
+ PBackgroundChild* bc = BackgroundChild::GetOrCreateForCurrentThread();
+ if (!bc) {
+ return false;
+ }
+ PMyBackgroundActorChild* pmyBac = bac->SendMyBackgroundActor(constructorParameters);
+ if (!pmyBac) {
+ return false;
+ }
+ auto myBac = static_cast<MyBackgroundActorChild*>(pmyBac);
+
+.. note::
+ ``PBackgroundParent`` still needs a ``RecvMyBackgroundActorConstructor``
+ handler, as usual. This must be done in the ``ParentImpl`` class.
+ ``ParentImpl`` is the non-standard name used for the implementation of
+ ``PBackgroundParent``.
+
+To summarize, ``PBackground`` attempts to simplify a common desire in Gecko:
+to run tasks that communicate between the main and content processes but avoid
+having much to do with the main thread of either. Unfortunately, it can be
+complicated to use correctly and has missed on some favorable IPDL
+improvements, like reference counting. While top level actors are always a
+complete option for independent jobs that need a lot of resources,
+``PBackground`` offers a compromise for some cases.
+
+IPDL Best Practices
+-------------------
+
+IPC performance is affected by a lot of factors. Many of them are out of our
+control, like the influence of the system thread scheduler on latency or
+messages whose travel internally requires multiple legs for security reasons.
+On the other hand, some things we can and should control for:
+
+* Messages incur inherent performance overhead for a number of reasons: IPDL
+ internal thread latency (e.g. the I/O thread), parameter (de-)serialization,
+ etc. While not usually dramatic, this cost can add up. What's more, each
+ message generates a fair amount of C++ code. For these reasons, it is wise
+ to reduce the number of messages being sent as far as is reasonable. This
+ can be as simple as consolidating two asynchronous messages that are always
+ in succession. Or it can be more complex, like consolidating two
+ somewhat-overlapping messages by merging their parameter lists and marking
+ parameters that may not be needed as optional. It is easy to go too far down
+ this path but careful message optimization can show big gains.
+* Even ``[moveonly]`` parameters are "copied" in the sense that they are
+ serialized. The pipes that transmit the data are limited in size and require
+ allocation. So understand that the performance of your transmission will be
+ inversely proportional to the size of your content. Filter out data you
+ won't need. For complex reasons related to Linux pipe write atomicity, it is
+ highly desirable to keep message sizes below 4K (including a small amount for
+ message metadata).
+* On the flip side, very large messages are not permitted by IPDL and will
+ result in a runtime error. The limit is currently 256M but message failures
+ frequently arise even with slightly smaller messages.
+* Parameters to messages are C++ types and therefore can be very complex in the
+ sense that they generally represent a tree (or graph) of objects. If this
+ tree has a lot of objects in it, and each of them is serialized by
+ ``ParamTraits``, then we will find that serialization is allocating and
+ constructing a lot of objects, which will stress the allocator and cause
+ memory fragmentation. Avoid this by using larger objects or by sharing this
+ kind of data through careful use of shared memory.
+* As it is with everything, concurrency is critical to the performance of IPDL.
+ For actors, this mostly manifests in the choice of bound thread. While
+ adding a managed actor to an existing actor tree may be a quick
+ implementation, this new actor will be bound to the same thread as the old
+ one. This contention may be undesirable. Other times it may be necessary
+ since message handlers may need to use data that isn't thread safe or may
+ need a guarantee that the two actors' messages are received in order. Plan
+ up front for your actor hierarchy and its thread model. Recognize when you
+ are better off with a new top level actor or ``PBackground`` managee that
+ facilitates processing messages simultaneously.
+* Remember that latency will slow your entire thread, including any other
+ actors/messages on that thread. If you have messages that will need a long
+ time to be processed but can run concurrently then they should use actors
+ that run on a separate thread.
+* Top-level actors decide a lot of properties for their managees. Probably the
+ most important are the process layout of the actor (including which process
+ is "Parent" and which is "Child") and the thread. Every top-level actor
+ should clearly document this, ideally in their .ipdl file.
+
+The Old Ways
+------------
+
+TODO:
+
+The FUD
+-------
+
+TODO:
+
+The Rest
+--------
+
+Nested messages
+~~~~~~~~~~~~~~~
+
+The ``Nested`` message annotations indicate the nesting type of the message.
+They attempt to process messages in the nested order of the "conversation
+thread", as found in e.g. a mailing-list client. This is an advanced concept
+that should be considered to be discouraged, legacy functionality.
+Essentially, ``Nested`` messages can make other ``sync`` messages break the
+policy of blocking their thread -- nested messages are allowed to be received
+while a sync messagee is waiting for a response. The rules for when a nested
+message can be handled are somewhat complex but they try to safely allow a
+``sync`` message ``M`` to handle and respond to some special (nested) messages
+that may be needed for the other endpoint to finish processing ``M``. There is
+a `comment in MessageChannel`_ with info on how the decision to handle nested
+messages is made. For sync nested messages, note that this implies a relay
+between the endpoints, which could dramatically affect their throughput.
+
+Declaring messages to nest requires an annotation on the actor and one on the
+message itself. The nesting annotations were listed in `Defining Actors`_ and
+`Declaring IPDL Messages`_. We repeat them here. The actor annotations
+specify the maximum priority level of messages in the actor. It is validated
+by the IPDL compiler. The annotations are:
+
+============================== ================================================
+``[NestedUpTo=inside_sync]`` Indicates that an actor contains messages of
+ priority [Nested=inside_sync] or lower.
+``[NestedUpTo=inside_cpow]`` Indicates that an actor contains messages of
+ priority [Nested=inside_cpow] or lower.
+============================== ================================================
+
+.. note::
+
+ The order of the nesting priorities is:
+ (no nesting priority) < ``inside_sync`` < ``inside_cpow``.
+
+The message annotations are:
+
+========================== ====================================================
+``[Nested=inside_sync]`` Indicates that the message can be handled while
+ waiting for lower-priority, or in-message-thread,
+ sync responses.
+``[Nested=inside_cpow]`` Indicates that the message can be handled while
+ waiting for lower-priority, or in-message-thread,
+ sync responses. Cannot be sent by the parent actor.
+========================== ====================================================
+
+.. note::
+
+ ``[Nested=inside_sync]`` messages must be sync (this is enforced by the
+ IPDL compiler) but ``[Nested=inside_cpow]`` may be async.
+
+Nested messages are obviously only interesting when sent to an actor that is
+performing a synchronous wait. Therefore, we will assume we are in such a
+state. Say ``actorX`` is waiting for a sync reply from ``actorY`` for message
+``m1`` when ``actorY`` sends ``actorX`` a message ``m2``. We distinguish two
+cases here: (1) when ``m2`` is sent while processing ``m1`` (so ``m2`` is sent
+by the ``RecvM1()`` method -- this is what we mean when we say "nested") and
+(2) when ``m2`` is unrelated to ``m1``. Case (2) is easy; ``m2`` is only
+dispatched while ``m1`` waits if
+``priority(m2) > priority(m1) > (no priority)`` and the message is being
+received by the parent, or if ``priority(m2) >= priority(m1) > (no priority)``
+and the message is being received by the child. Case (1) is less
+straightforward.
+
+To analyze case (1), we again distinguish the two possible ways we can end up
+in the nested case: (A) ``m1`` is sent by the parent to the child and ``m2``
+is sent by the child to the parent, or (B) where the directions are reversed.
+The following tables explain what happens in all cases:
+
+.. |strike| raw:: html
+
+ <strike>
+
+.. |endstrike| raw:: html
+
+ </strike>
+
+.. |br| raw:: html
+
+ <br/>
+
+.. table :: Case (A): Child sends message to a parent that is awaiting a sync response
+ :align: center
+
+ ============================== ======================== ========================================================
+ sync ``m1`` type (from parent) ``m2`` type (from child) ``m2`` handled or rejected
+ ============================== ======================== ========================================================
+ sync (no priority) \* IPDL compiler error: parent cannot send sync (no priority)
+ sync inside_sync async (no priority) |strike| ``m2`` delayed until after ``m1`` completes |endstrike| |br|
+ Currently ``m2`` is handled during the sync wait (bug?)
+ sync inside_sync sync (no priority) |strike| ``m2`` send fails: lower priority than ``m1`` |endstrike| |br|
+ Currently ``m2`` is handled during the sync wait (bug?)
+ sync inside_sync sync inside_sync ``m2`` handled during ``m1`` sync wait: same message thread and same priority
+ sync inside_sync async inside_cpow ``m2`` handled during ``m1`` sync wait: higher priority
+ sync inside_sync sync inside_cpow ``m2`` handled during ``m1`` sync wait: higher priority
+ sync inside_cpow \* IPDL compiler error: parent cannot use inside_cpow priority
+ ============================== ======================== ========================================================
+
+.. table :: Case (B): Parent sends message to a child that is awaiting a sync response
+ :align: center
+
+ ============================= ========================= ========================================================
+ sync ``m1`` type (from child) ``m2`` type (from parent) ``m2`` handled or rejected
+ ============================= ========================= ========================================================
+ \* async (no priority) ``m2`` delayed until after ``m1`` completes
+ \* sync (no priority) IPDL compiler error: parent cannot send sync (no priority)
+ sync (no priority) sync inside_sync ``m2`` send fails: no-priority sync messages cannot handle
+ incoming messages during wait
+ sync inside_sync sync inside_sync ``m2`` handled during ``m1`` sync wait: same message thread and same priority
+ sync inside_cpow sync inside_sync ``m2`` send fails: lower priority than ``m1``
+ \* async inside_cpow IPDL compiler error: parent cannot use inside_cpow priority
+ \* sync inside_cpow IPDL compiler error: parent cannot use inside_cpow priority
+ ============================= ========================= ========================================================
+
+We haven't seen rule #2 from the `comment in MessageChannel`_ in action but, as
+the comment mentions, it is needed to break deadlocks in cases where both the
+parent and child are initiating message-threads simultaneously. It
+accomplishes this by favoring the parent's sent messages over the child's when
+deciding which message-thread to pursue first (and blocks the other until the
+first completes). Since this distinction is entirely thread-timing based,
+client code needs only to be aware that IPDL internals will not deadlock
+because of this type of race, and that this protection is limited to a single
+actor tree -- the parent/child messages are only well-ordered when under the
+same top-level actor so simultaneous sync messages across trees are still
+capable of deadlock.
+
+Clearly, tight control over these types of protocols is required to predict how
+they will coordinate within themselves and with the rest of the application
+objects. Control flow, and hence state, can be very difficult to predict and
+are just as hard to maintain. This is one of the key reasons why we have
+stressed that message priorities should be avoided whenever possible.
+
+.. _comment in MessageChannel: https://searchfox.org/mozilla-central/rev/077501b34cca91763ae04f4633a42fddd919fdbd/ipc/glue/MessageChannel.cpp#54-118
+
+.. _Message Logging:
+
+Message Logging
+~~~~~~~~~~~~~~~
+
+The environment variable ``MOZ_IPC_MESSAGE_LOG`` controls the logging of IPC
+messages. It logs details about the transmission and reception of messages.
+This isn't controlled by ``MOZ_LOG`` -- it is a separate system. Set this
+variable to ``1`` to log information on all IPDL messages, or specify a
+comma-separated list of protocols to log.
+If the ``Child`` or ``Parent`` suffix is given, then only activity on the given
+side is logged; otherwise, both sides are logged. All protocol names must
+include the ``P`` prefix.
+
+For example:
+
+.. code-block::
+
+ MOZ_IPC_MESSAGE_LOG="PMyManagerChild,PMyManaged"
+
+This requests logging of child-side activity on ``PMyManager``, and both
+parent- and child-side activity on ``PMyManaged``.
+
+:ref:`Debugging with IPDL Logging` has an example where IPDL logging is useful
+in tracking down a bug.
diff --git a/ipc/docs/processes.rst b/ipc/docs/processes.rst
new file mode 100644
index 0000000000..89ec5e8013
--- /dev/null
+++ b/ipc/docs/processes.rst
@@ -0,0 +1,1252 @@
+Gecko Processes
+===============
+
+Before Creating a New Process
+-----------------------------
+
+Firefox started out as a one process application. Then, one became two as
+NPAPI plugins like Flash were pushed into their own process (plugin processes)
+for security and stability reasons. Then, it split again so that the browser
+could also disentangle itself from web content (content processes). Then,
+implementations on some platforms developed processes for graphics ("GPU"
+processes). And for media codecs. And VR. And file URLs. And sockets. And
+even more content processes. And so on...
+
+Here is an incomplete list of *good* reasons we've created new processes:
+
+* Separating HTML and JS from the browser makes it possible to secure the
+ browser and the rest of the system from them, even when those APIs are
+ compromised.
+* Browser stability was also improved by separating HTML and JS from the
+ browser, since catastrophic failures related to a tab could be limited to the
+ tab instead of crashing the browser.
+* Site isolation requires additional processes to separate HTML and JS for
+ different sites. The separation of memory spaces undermines many types of
+ exploits.
+* Sandboxing processes offers great security guarantees but requires making
+ tradeoffs between power and protection. More processes means more options.
+ For example, we heavily sandbox content processes to protect from external
+ code, while the File process, which is a content process that can access
+ ``file://`` URLs, has a sandbox that is similar but allows access to local
+ files.
+* One of the benefits of the GPU process was that it improved browser
+ stability by separating a system component that had frequent stability
+ issues -- GPU drivers. The same logic inspired the NPAPI (Flash) plugin
+ process.
+
+Informed by this history, there is some of non-obvious preparation that you
+should do before starting down this path. This falls under the category of
+"First, do no harm":
+
+* **Consult the Platform and IPC teams** (#ipc) to develop the plan for the
+ way your process will integrate with the systems in which it will exist, as
+ well as how it will be handled on any platforms where it will *not* exist.
+ For example, an application's process hierarchy forms a tree where one process
+ spawns another. Currently, all processes in Firefox are spawned by the main
+ process (excepting the `launcher process`_). There is good reason for this,
+ mostly based on our sandboxing restrictions that forbid non-main processes
+ from launching new processes themselves. But it means that the main process
+ will need to know to create your process. If you make the decision to do
+ this from, say, a content process, you will need a safe, performant and
+ stable way to request this of the main process. You will also need a way to
+ efficiently communicate directly with your new process. And you will need to
+ consider limitations of some platforms (think Android) where you may not want
+ to or not be able to spawn the new process.
+* **Consult the sandboxing team** (#hardening) to discuss what the sandbox for
+ your new process will look like. Anything that compromises security is a
+ non-starter. You may, for instance, want to create a new process to escape
+ the confines of the sandbox in a content process. This can be legitimate,
+ for example you may need access to some device API that is unavailable to a
+ content process, but the security for your new process will then have to come
+ from a different source. "I won't run Javascript" is not sufficient. Keep
+ in mind that your process will have to have some mechanism for communication
+ with other processes to be useful, so it is always a potential target.
+
+.. note::
+ Firefox has, to date, undergone exactly one occurrence of the *removal* of
+ a process type. In 2020, the NPAPI plugin process was removed when the
+ last supported plugin, Adobe's FlashPlayer, reached its end-of-life.
+
+.. _launcher process: https://wiki.mozilla.org/Platform/Integration/InjectEject/Launcher_Process/
+
+Firefox Process Hierarchy
+-------------------------
+
+This diagram shows the primary process types in Firefox.
+
+.. mermaid::
+
+ graph TD
+ RDD -->|PRemoteDecoderManager| Content
+ RDD(Data Decoder) ==>|PRDD| Main
+
+ Launcher --> Main
+
+ Main ==>|PContent| Content
+ Main ==>|PSocketProcess| Socket(Network Socket)
+ Main ==>|PGMP| GMP(Gecko Media Plugins)
+ VR ==>|PVR| Main
+ GPU ==>|PGPU| Main
+
+ Socket -->|PSocketProcessBridge| Content
+
+ GPU -->|PCompositorManager| Main
+ GPU -->|PCompositorManager| Content
+
+ Content -->|PGMPContent| GMP
+
+ VR -->|PVRGPU| GPU
+
+.. warning::
+ The main process is sometimes called the UI process, the chrome process,
+ the browser process or the parent process. This is true for documentation,
+ conversation and, most significantly, **code**. Due to the syntactic
+ overlap with IPDL actors, that last name can get pretty confusing. Less
+ commonly, the content process is called the renderer process, which is it's
+ name in Chromium code. Since the content process sandbox won't allow it,
+ Firefox never does (hardware) rendering in the content/rendering process!
+
+The arrows point from the parent side to the child. Bolded arrows indicate the
+first top-level actors for the various process types. The other arrows show
+important actors that are usually the first connections established between the
+two processes. These relationships difficult to discern from code. Processes
+should clearly document their top-level connections in their IPDL files.
+
+Some process types only exist on some platforms and some processes may only be
+created on demand. For example, Mac builds do not use a GPU process but
+instead fold the same actor connections into its main process (except ``PGPU``,
+which it does not use). These exceptions are also very hard to learn from code
+and should be clearly documented.
+
+``about:processes`` shows statistics for the processes in a currently running
+browser. It is also useful to see the distribution of web pages across content
+processes.
+
+.. _Adding a New Type of Process:
+
+Adding a New Type of Process
+----------------------------
+
+Adding a new process type doesn't require any especially difficult steps but it
+does require a lot of steps that are not obvious. This section will focus on
+the steps as it builds an example. It will be light on the details of the
+classes and protocols involved. Some implementations may need to seek out a
+deeper understanding of the components set up here but most should instead
+strive for simplicity.
+
+In the spirit of creating a *responsible* process, the sample will connect
+several components that any deployed Gecko process is likely to need. These
+include configuring a sandbox, `registration with the CrashReporter service`_
+and ("minimal") XPCOM initialization. Consult documentation for these
+components for more information on their integration.
+
+This example will be loosely based on the old (now defunct) IPDL **Extending a
+Protocol** example for adding a new actor. We will add a command to the
+browser's ``navigator`` JS object, ``navigator.getAssistance()``. When the
+user enters the new command in, say, the browser's console window, it will
+create a new process of our new **Demo** process type and ask that process for
+"assistance" in the form of a string that it will then print to the console.
+Once that is done, the new process will be cleanly destroyed.
+
+Code for the complete demo can be found `here
+<https://phabricator.services.mozilla.com/D119038>`_.
+
+.. _registration with the CrashReporter service: `Crash Reporter`_
+
+Common Architecture
+~~~~~~~~~~~~~~~~~~~
+
+Every type of process (besides the launcher and main processes) needs two
+classes and an actor pair to launch. This sample will be adding a process type
+we call **Demo**.
+
+* An actor pair where the parent actor is a top-level actor in the main process
+ and the child is the (first) top-level actor in the new process. It is common
+ for this actor to simply take the name of the process type. The sample uses
+ ``PDemo``, so it creates ``DemoParent`` and ``DemoChild`` actor subclasses
+ as usual (see :ref:`IPDL: Inter-Thread and Inter-Process Message Passing`).
+* A subclass of `GeckoChildProcessHost
+ <https://searchfox.org/mozilla-central/source/ipc/glue/GeckoChildProcessHost.h>`_
+ that exists in the main process (where new processes are created) and handles
+ most of the machinery needed for new process creation. It is common for these
+ names to be the process type plus ``ProcessParent`` or ``ProcessHost``. The
+ sample uses ``DemoParent::Host``, a private class, which keeps
+ ``GeckoChildProcessHost`` out of the **Demo** process' *public interface*
+ since it is large, complicated and mostly unimportant externally. This
+ complexity is also why it is a bad idea to add extra responsibilities to the
+ ``Host`` object that inherits it.
+* A subclass of `ProcessChild
+ <https://searchfox.org/mozilla-central/source/ipc/glue/ProcessChild.h>`_ that
+ exists in the new process. These names are usually generated by affixing
+ ``ProcessChild`` or ``ProcessImpl`` to the type. The sample will use
+ ``DemoChild::Process``, another private class, for the same reasons it did
+ with the ``Host``.
+
+A fifth class is optional but integration with common services requires
+something like it:
+
+* A singleton class that "manages" the collective of processes (usually the
+ Host objects) of the new type in the main process. In many instances, there
+ is at most one instance of a process type, so this becomes a singleton that
+ manages a singleton... that manages a singleton. Object ownership is often
+ hard to establish between manager objects and the hosts they manage. It is
+ wise to limit the power of these classes. This class will often get its name
+ by appending ``ProcessManager`` to the process type. The sample provides a
+ very simple manager in ``DemoParent::Manager``.
+
+Finally, it is highly probable and usually desirable for the new process to
+include another new top-level actor that represents the top-level operations
+and communications of the new process. This actor will use the new process as
+a child but may have any other process as the parent, unlike ``PDemo`` whose
+parent is always the main process. This new actor will be created by the main
+process, which creates a pair of ``Endpoint`` objects specifically for the
+desired process pairing, and then sends those ``Endpoint`` objects to their
+respective processes. The **Demo** example is interesting because the user can
+issue the command from a content process or the main one, by opening the
+console in a normal or a privileged page (e.g. ``about:sessionrestore``),
+respectively. Supporting both of these cases will involve very little
+additional effort. The sample will show this as part of implementing the
+second top-level actor pair ``PDemoHelpline`` in `Connecting With Other
+Processes`_, where the parent can be in either the main or a content process.
+
+The rest of the sections will explain how to compose these classes and
+integrate them with Gecko.
+
+Process Bookkeeping
+~~~~~~~~~~~~~~~~~~~
+
+To begin with, look at the `geckoprocesstypes generator
+<https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/geckoprocesstypes_generator/geckoprocesstypes/__init__.py>`_
+which adds the bones for a new process (by defining enum values and so on).
+Some further manual intervention is still required, and you need to follow the
+following checklists depending on your needs.
+
+Basic requirements
+^^^^^^^^^^^^^^^^^^
+
+* Add a new entry to the `enum WebIDLProcType
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/dom/chrome-webidl/ChromeUtils.webidl#610-638>`_
+* Update the `static_assert
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/xre/nsAppRunner.cpp#988-990>`_
+ call checking for boundary against ``GeckoProcessType_End``
+* Add your process to the correct ``MessageLoop::TYPE_x`` in the first
+ ``switch(XRE_GetProcessType())`` in `XRE_InitChildProcess
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/xre/nsEmbedFunctions.cpp#572-590>`_.
+ You can get more information about that topic in `this comment
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/ipc/chromium/src/base/message_loop.h#159-187>`_
+* Instantiate your child within the second ``switch (XRE_GetProcessType())`` in
+ `XRE_InitChildProcess
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/xre/nsEmbedFunctions.cpp#615-671>`_
+* Add a new entry ``PROCESS_TYPE_x`` in `nsIXULRuntime interface
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/system/nsIXULRuntime.idl#183-196>`_
+
+Graphics
+########
+
+If you need graphics-related interaction, hack into `gfxPlatform
+<https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/gfx/thebes/gfxPlatform.cpp>`_
+
+- Add a call to your process manager init in ``gfxPlatform::Init()`` in
+ `gfxPlatform
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/gfx/thebes/gfxPlatform.cpp#808-810>`_
+- Add a call to your process manager shutdown in ``gfxPlatform::Shutdown()`` in
+ `gfxPlatform
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/gfx/thebes/gfxPlatform.cpp#1255-1259>`_
+
+Android
+#######
+
+You might want to talk with `#geckoview` maintainers to ensure if this is
+required or applicable to your new process type.
+
+- Add a new ``<service>`` entry against
+ ``org.mozilla.gecko.process.GeckoChildProcessServices$XXX`` in the
+ `AndroidManifest
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/mobile/android/geckoview/src/main/AndroidManifest.xml#45-81>`_
+- Add matching class inheritance from `GeckoChildProcessServices
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/mobile/android/geckoview/src/main/java/org/mozilla/gecko/process/GeckoChildProcessServices.jinja#10-13>`_
+- Add new entry in `public enum GeckoProcessType
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/mobile/android/geckoview/src/main/java/org/mozilla/gecko/process/GeckoProcessType.java#11-23>`_
+
+Crash reporting
+###############
+
+- Add ``InitCrashReporter`` message to the parent-side `InitCrashReporter
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#30>`_
+- Ensure your parent class inherits `public ipc::CrashReporterHelper<GeckoProcessType_Xxx>
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessParent.h#23>`_
+- Add new ``Xxx*Status`` `annotations
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/crashreporter/CrashAnnotations.yaml#968-971>`_
+ entry for your new process type description. The link here points to
+ `UtilityProcessStatus` so you can see the similar description you have to
+ write, but you might want to respect ordering in that file and put your new
+ code at the appropriate place.
+- Add entry in `PROCESS_CRASH_SUBMIT_ATTEMPT
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/telemetry/Histograms.json#13403-13422>`_
+
+Memory reporting
+################
+
+Throughout the linked code, please consider those methods more as boilerplate code that will require some trivial modification to fit your exact usecase.
+
+- Add definition of memory reporter to your new :ref:`top-level actor <Top Level Actors>`
+
+ + Type inclusion `MemoryReportTypes <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#6>`_
+ + To parent-side `AddMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#32>`_
+ + To child-side `RequestMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#44-48>`_
+
+- Add handling for your new process within `nsMemoryReporterManager::GetReportsExtended <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/xpcom/base/nsMemoryReporterManager.cpp#1813-1819>`_
+- Provide a process manager level abstraction
+
+ + Implement a new class deriving ``MemoryReportingProcess`` such as `UtilityMemoryReporter <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessManager.cpp#253-292>`_
+ + Write a `GetProcessMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessManager.cpp#294-300>`_
+
+- On the child side, provide an implementation for `RequestMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessChild.cpp#153-166>`_
+- On the parent side
+
+ + Provide an implementation for `RequestMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessParent.cpp#41-69>`_
+ + Provide an implementation for `AddMemoryReport <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessParent.cpp#71-77>`_
+
+If you want to add a test that ensures proper behavior, you can have a look at the `utility process memory report test <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/test/browser/browser_utility_memoryReport.js>`_
+
+Process reporting
+#################
+
+Those elements will be used for exposing processes to users in some `about:`
+pages. You might want to ping `#fluent-reviewers` to ensure if you need your
+process there.
+
+- Add a `user-facing localizable name
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/locales/en-US/toolkit/global/processTypes.ftl#39-57>`_
+ for your process, if needed
+- Hashmap from process type to user-facing string above in `const ProcessType
+ <https://searchfox.org/mozilla-central/rev/c5c002f81f08a73e04868e0c2bf0eb113f200b03/toolkit/modules/ProcessType.sys.mjs#10-16`_
+- For `about:processes` you will probably want to follow the following steps:
+
+ + Add handling for your new process type producing a unique `fluentName <https://searchfox.org/mozilla-central/rev/be4604e4be8c71b3c1dbff2398a5b05f15411673/toolkit/components/aboutprocesses/content/aboutProcesses.js#472-539>`_, i.e., constructing a dynamic name is highly discouraged
+ + Add matching localization strings within `fluent localization file <https://searchfox.org/mozilla-central/rev/be4604e4be8c71b3c1dbff2398a5b05f15411673/toolkit/locales/en-US/toolkit/about/aboutProcesses.ftl#35-55>`_
+
+Profiler
+########
+
+- Add definition of ``PProfiler`` to your new IPDL
+
+ + Type inclusion `protocol PProfiler <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#9>`_
+ + Child-side `InitProfiler <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#42>`_
+
+- Make sure your initialization path contains a `SendInitProfiler <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessHost.cpp#222-223>`_. You will want to perform the call once a ``OnChannelConnected`` is issued, thus ensuring your new process is connected to IPC.
+- Provide an implementation for `InitProfiler <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessChild.cpp#147-151>`_
+
+- You will probably want to make sure your child process code register within the profiler a proper name, otherwise it will default to ``GeckoMain`` ; this can be done by issuing ``profiler_set_process_name(nsCString("XxX"))`` on the child init side.
+
+Static Components
+#################
+
+The amount of changes required here are significant, `Bug 1740485: Improve
+StaticComponents code generation
+<https://bugzilla.mozilla.org/show_bug.cgi?id=1740485>`_ tracks improving that.
+
+- Update allowance in those configuration files to match new process selector
+ that includes your new process. When exploring those components definitions,
+ keep in mind that you are looking at updating `processes` field in the
+ `Classes` object. The `ProcessSelector` value will come from what the reader
+ writes based on the instructions below. Some of these also contains several
+ services, so you might have to ensure you have all your bases covered. Some of
+ the components might not need to be updated as well.
+
+ + `libpref <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/modules/libpref/components.conf>`_
+ + `telemetry <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/telemetry/core/components.conf>`_
+ + `android <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/widget/android/components.conf>`_
+ + `gtk <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/widget/gtk/components.conf>`_
+ + `windows <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/widget/windows/components.conf>`_
+ + `base <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/base/components.conf>`_
+ + `components <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/components/components.conf>`_
+ + `ds <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/ds/components.conf>`_
+ + `threads <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/threads/components.conf>`_
+ + `cocoa kWidgetModule <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/widget/cocoa/nsWidgetFactory.mm#194-202>`_
+ + `build <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/build/components.conf>`_
+ + `XPCOMinit kXPCOMModule <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/build/XPCOMInit.cpp#172-180>`_
+
+- Within `static components generator
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/components/gen_static_components.py>`_
+
+ + Add new definition in ``ProcessSelector`` for your new process
+ ``ALLOW_IN_x_PROCESS = 0x..``
+ + Add new process selector masks including your new process definition
+ + Also add those into the ``PROCESSES`` structure
+
+- Within `module definition <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/components/Module.h>`_
+
+ + Add new definition in ``enum ProcessSelector``
+ + Add new process selector mask including the new definition
+ + Update ``kMaxProcessSelector``
+
+- Within `nsComponentManager <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/xpcom/components/nsComponentManager.cpp>`_
+
+ + Add new selector match in ``ProcessSelectorMatches`` for your new process
+ (needed?)
+ + Add new process selector for ``gProcessMatchTable`` in
+ ``nsComponentManagerImpl::Init()``
+
+Glean telemetry
+###############
+
+- Ensure your new IPDL includes on the child side
+
+ + `FlushFOGData
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#55>`_
+ + `TestTriggerMetrics
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/PUtilityProcess.ipdl#60>`_
+
+- Provide a parent-side implementation for `FOGData
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessParent.cpp#79-82>`_
+- Provide a child-side implementation for `FlushFOGData
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessChild.cpp#179-183>`_
+- Child-side should flush its FOG data at IPC `ActorDestroy
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessChild.cpp#199-201>`_
+- Child-side `test metrics
+ <https://searchfox.org/mozilla-central/rev/fc4d4a8d01b0e50d20c238acbb1739ccab317ebc/ipc/glue/UtilityProcessChild.cpp#185-191>`_
+- Within `FOGIPC
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/glean/ipc/FOGIPC.cpp>`_
+
+ + Add handling of your new process type within ``FlushAllChildData()`` `here
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/glean/ipc/FOGIPC.cpp#106-121>`_
+ and ``SendFOGData()`` `here
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/glean/ipc/FOGIPC.cpp#165-182>`_
+ + Add support for sending test metrics in ``TestTriggerMetrics()`` `here
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/glean/ipc/FOGIPC.cpp#208-232>`_
+
+- Handle process shutdown in ``register_process_shutdown()`` of `glean
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/toolkit/components/glean/api/src/ipc.rs>`_
+
+Third-Party Modules
+###################
+
+- Ensure your new IPDL includes on the child side
+
+ + `GetUntrustedModulesData
+ <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/PUtilityProcess.ipdl#106>`_
+ + `UnblockUntrustedModulesThread
+ <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/PUtilityProcess.ipdl#113>`_
+
+- Provide a parent side implementation for both
+
+- Add handling of your new process type in ``MultiGetUntrustedModulesData::GetUntrustedModuleLoadEvents()`` `here <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/toolkit/components/telemetry/other/UntrustedModules.cpp#145-151>`_
+
+- `Update your IPDL <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/PUtilityProcess.ipdl#75>`_ and make sure your ``Init()`` can receive a boolean for
+ ``isReadyForBackgroundProcessing`` `like here <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/UtilityProcessChild.cpp#157-160>`_, then within the child's ``RecvInit()``
+ make sure a call to ``DllServices``'s ``StartUntrustedModulesProcessor()`` `is
+ performed <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/UtilityProcessChild.cpp#185-186>`_.
+
+- Ensure your new IPDL includes for the parent side
+
+ + `GetModulesTrust <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/PUtilityProcess.ipdl#60-61>`_
+
+- Provide an implementation on the `parent side <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/ipc/glue/UtilityProcessParent.cpp#69-81>`_
+
+- Expose your new process type as supported in ``UntrustedModulesProcessor::IsSupportedProcessType()`` `like others <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/toolkit/xre/dllservices/UntrustedModulesProcessor.cpp#76-91>`_
+
+- Update ``UntrustedModulesProcessor::SendGetModulesTrust()`` to call `your new child process <https://searchfox.org/mozilla-central/rev/2ce39261ea6a69e49d87f76a119494b2a7a7e42a/toolkit/xre/dllservices/UntrustedModulesProcessor.cpp#757-761>`_
+
+Sandboxing
+##########
+
+Sandboxing changes related to a new process can be non-trivial, so it is
+strongly advised that you reach to the Sandboxing team in ``#hardening`` to
+discuss your needs prior to making changes.
+
+Linux Sandbox
+_____________
+
+Linux sandboxing mostly works by allowing / blocking system calls for child
+process and redirecting (brokering) some from the child to the parent. Rules
+are written in a specific DSL: `BPF
+<https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h#21-72>`_.
+
+- Add new ``SetXXXSandbox()`` function within `linux sandbox
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/Sandbox.cpp#719-748>`_
+- Within `sandbox filter
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/SandboxFilter.cpp>`_
+
+ + Add new helper ``GetXXXSandboxPolicy()`` `like this one
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/SandboxFilter.cpp#2036-2040>`_
+ called by ``SetXXXSandbox()``
+ + Derive new class `similar to this
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/SandboxFilter.cpp#2000-2034>`_
+ inheriting ``SandboxPolicyCommon`` or ``SandboxPolicyBase`` and defining
+ the sandboxing policy
+
+- Add new ``SandboxBrokerPolicyFactory::GetXXXProcessPolicy()`` in `sandbox
+ broker
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/broker/SandboxBrokerPolicyFactory.cpp#881-932>`_
+- Add new case handling in ``GetEffectiveSandboxLevel()`` in `sandbox launch
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/launch/SandboxLaunch.cpp#243-271>`_
+- Add new entry in ``enum class ProcType`` of `sandbox reporter header
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/reporter/SandboxReporterCommon.h#32-39>`_
+- Add new case handling in ``SubmitToTelemetry()`` in `sandbox reporter
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/reporter/SandboxReporter.cpp#131-152>`_
+- Add new case handling in ``SandboxReportWrapper::GetProcType()`` of `sandbox
+ reporter wrapper
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/linux/reporter/SandboxReporterWrappers.cpp#69-91>`_
+
+MacOS Sandbox
+_____________
+
+- Add new case handling in ``GeckoChildProcessHost::StartMacSandbox()`` of
+ `GeckoChildProcessHost <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/ipc/glue/GeckoChildProcessHost.cpp#1720-1743>`_
+- Add new entry in ``enum MacSandboxType`` defined in `macOS sandbox header
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/Sandbox.h#12-20>`_
+- Within `macOS sandbox core
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/Sandbox.mm>`_
+ handle the new ``MacSandboxType`` in
+
+ + ``MacSandboxInfo::AppendAsParams()`` in the `switch statement
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/Sandbox.mm#164-188>`_
+ + ``StartMacSandbox()`` in the `series of if/else statements
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/Sandbox.mm#286-436>`_.
+ This code sets template values for the sandbox string rendering, and is
+ running on the side of the main process.
+ + ``StartMacSandboxIfEnabled()`` in this `switch statement
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/Sandbox.mm#753-782>`_.
+ You might also need a ``GetXXXSandboxParamsFromArgs()`` that performs CLI
+ parsing on behalf of ``StartMacSandbox()``.
+
+- Create the new sandbox definition file
+ ``security/sandbox/mac/SandboxPolicy<XXX>.h`` for your new process ``<XXX>``,
+ and make it exposed in the ``EXPORTS.mozilla`` section of `moz.build
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/mac/moz.build#7-13>`_.
+ Those rules follows a specific Scheme-like language. You can learn more about
+ it in `Apple Sandbox Guide
+ <https://reverse.put.as/wp-content/uploads/2011/09/Apple-Sandbox-Guide-v1.0.pdf>`_
+ as well as on your system within ``/System/Library/Sandbox/Profiles/``.
+
+Windows Sandbox
+_______________
+
+- Introduce a new ``SandboxBroker::SetSecurityLevelForXXXProcess()`` that
+ defines the new sandbox in both
+
+ + the sandbox broker basing yourself on that `example
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/win/src/sandboxbroker/sandboxBroker.cpp#1241-1344>`_
+ + the remote sandbox broker getting `inspired by
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/win/src/remotesandboxbroker/remoteSandboxBroker.cpp#161-165>`_
+
+- Add new case handling in ``WindowsProcessLauncher::DoSetup()`` calling
+ ``SandboxBroker::SetSecurityLevelForXXXProcess()`` in `GeckoChildProcessHost
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/ipc/glue/GeckoChildProcessHost.cpp#1391-1470>`_.
+ This will apply actual sandboxing rules to your process.
+
+Sandbox tests
+_____________
+
+- New process' first top level actor needs to `include PSandboxTesting
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/common/test/PSandboxTesting.ipdl>`_
+ and implement ``RecvInitSandboxTesting`` `like there
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/ipc/glue/UtilityProcessChild.cpp#165-174>`_.
+- Add your new process ``string_name`` in the ``processTypes`` list of `sandbox
+ tests <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/test/browser_sandbox_test.js#17>`_
+- Add a new case in ``SandboxTest::StartTests()`` in `test core
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/common/test/SandboxTest.cpp#100-232>`_
+ to handle your new process
+- Add a new if branch for your new process in ``SandboxTestingChild::Bind()``
+ in `testing child
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/common/test/SandboxTestingChild.cpp#68-96>`_
+- Add a new ``RunTestsXXX`` function for your new process (called by ``Bind()``
+ above) `similar to that implementation
+ <https://searchfox.org/mozilla-central/rev/d4b9c457db637fde655592d9e2048939b7ab2854/security/sandbox/common/test/SandboxTestingChildTests.h#333-363>`_
+
+Creating the New Process
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+The sample does this in ``DemoParent::LaunchDemoProcess``. The core
+behavior is fairly clear:
+
+.. code-block:: cpp
+
+ /* static */
+ bool DemoParent::LaunchDemoProcess(
+ base::ProcessId aParentPid, LaunchDemoProcessResolver&& aResolver) {
+ UniqueHost host(new Host(aParentPid, std::move(aResolver)));
+
+ // Prepare "command line" startup args for new process
+ std::vector<std::string> extraArgs;
+ if (!host->BuildProcessArgs(&extraArgs)) {
+ return false;
+ }
+
+ // Async launch creates a promise that we use below.
+ if (!host->AsyncLaunch(extraArgs)) {
+ return false;
+ }
+
+ host->WhenProcessHandleReady()->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [host = std::move(host)](
+ const ipc::ProcessHandlePromise::ResolveOrRejectValue&
+ aResult) mutable {
+ if (aResult.IsReject()) {
+ host->ResolveAsFailure();
+ return;
+ }
+
+ auto actor = MakeRefPtr<DemoParent>(std::move(host));
+ actor->Init();
+ });
+ }
+
+First, it creates an object of our ``GeckoChildProcessHost`` subclass (storing
+some stuff for later). ``GeckoChildProcessHost`` is a base class that
+abstracts the system-level operations involved in launching the new process.
+It is the most substantive part of the launch procedure. After its
+construction, the code prepares a bunch of strings to pass on the "command
+line", which is the only way to pass data to the new process before IPDL is
+established. All new processes will at least include ``-parentBuildId`` for
+validating that dynamic libraries are properly versioned, and shared memory for
+passing user preferences, which can affect early process behavior. Finally, it
+tells ``GeckoChildProcessHost`` to asynchronously launch the process and run
+the given lambda when it has a result. The lambda creates ``DemoParent`` with
+the new host, if successful.
+
+In this sample, the ``DemoParent`` is owned (in the reference-counting sense)
+by IPDL, which is why it doesn't get assigned to anything. This simplifies the
+design dramatically. IPDL takes ownership when the actor calls ``Bind`` from
+the ``Init`` method:
+
+.. code-block:: cpp
+
+ DemoParent::DemoParent(UniqueHost&& aHost)
+ : mHost(std::move(aHost)) {}
+
+ DemoParent::Init() {
+ mHost->TakeInitialEndpoint().Bind(this);
+ // ...
+ mHost->MakeBridgeAndResolve();
+ }
+
+After the ``Bind`` call, the actor is live and communication with the new
+process can begin. The constructor concludes by initiating the process of
+connecting the ``PDemoHelpline`` actors; ``Host::MakeBridgeAndResolve`` will be
+covered in `Creating a New Top Level Actor`_. However, before we get into
+that, we should finish defining the lifecycle of the process. In the next
+section we look at launching the new process from the new process' perspective.
+
+.. warning::
+ The code could have chosen to create a ``DemoChild`` instead of a
+ ``DemoParent`` and the choice may seem cosmetic but it has substantial
+ implications that could affect browser stability. The most
+ significant is that the prohibitibition on synchronous IPDL messages going
+ from parent to child can no longer guarantee freedom from multiprocess
+ deadlock.
+
+Initializing the New Process
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+The new process first adopts the **Demo** process type in
+``XRE_InitChildProcess``, where it responds to the **Demo** values we added to
+some enums above. Specifically, we need to choose the type of MessageLoop our
+main thread will run (this is discussed later) and we need to create our
+``ProcessChild`` subclass. This is not an insignificant choice so pay close
+attention to the `MessageLoop` options:
+
+.. code-block:: cpp
+
+ MessageLoop::Type uiLoopType;
+ switch (XRE_GetProcessType()) {
+ case GeckoProcessType_Demo:
+ uiLoopType = MessageLoop::TYPE_MOZILLA_CHILD; break;
+ // ...
+ }
+
+ // ...
+
+ UniquePtr<ProcessChild> process;
+ switch (XRE_GetProcessType()) {
+ // ...
+ case GeckoProcessType_Demo:
+ process = MakeUnique<DemoChild::Process>(parentPID);
+ break;
+ }
+
+We then need to create our singleton ``DemoChild`` object, which can occur in
+the constructor or the ``Process::Init()`` call, which is common. We store a
+strong reference to the actor (as does IPDL) so that we are guaranteed that it
+exists as long as the ``ProcessChild`` does -- although the message channel may
+be closed. We will release the reference either when the process is properly
+shutting down or when an IPC error closes the channel.
+
+``Init`` is given the command line arguments constructed above so it will need
+to be overridden to parse them. It does this, binds our actor by
+calling ``Bind`` as was done with the parent, then initializes a bunch of
+components that the process expects to use:
+
+.. code-block:: cpp
+
+ bool DemoChild::Init(int aArgc, char* aArgv[]) {
+ #if defined(MOZ_SANDBOX) && defined(XP_WIN)
+ mozilla::SandboxTarget::Instance()->StartSandbox();
+ #elif defined(__OpenBSD__) && defined(MOZ_SANDBOX)
+ StartOpenBSDSandbox(GeckoProcessType_Demo);
+ #endif
+
+ if (!mozilla::ipc::ProcessChild::InitPrefs(aArgc, aArgv)) {
+ return false;
+ }
+
+ if (NS_WARN_IF(NS_FAILED(nsThreadManager::get().Init()))) {
+ return false;
+ }
+
+ if (NS_WARN_IF(!TakeInitialEndpoint().Bind(this))) {
+ return false;
+ }
+
+ // ... initializing components ...
+
+ if (NS_FAILED(NS_InitMinimalXPCOM())) {
+ return false;
+ }
+
+ return true;
+ }
+
+This is a slimmed down version of the real ``Init`` method. We see that it
+establishes a sandbox (more on this later) and then reads the command line and
+preferences that we sent from the main process. It then initializes the thread
+manager, which is required by for the subsequent ``Bind`` call.
+
+Among the list of components we initialize in the sample code, XPCOM is
+special. XPCOM includes a suite of components, including the component
+manager, and is usually required for serious Gecko development. It is also
+heavyweight and should be avoided if possible. We will leave the details of
+XPCOM development to that module but we mention XPCOM configuration that is
+special to new processes, namely ``ProcessSelector``. ``ProcessSelector``
+is used to determine what process types have access to what XPCOM components.
+By default, a process has access to none. The code adds enums for selecting
+a subset of process types, like
+``ALLOW_IN_GPU_RDD_VR_SOCKET_UTILITY_AND_DEMO_PROCESS``, to the
+``ProcessSelector`` enum in `gen_static_components.py
+<https://searchfox.org/mozilla-central/source/xpcom/components/gen_static_components.py>`_
+and `Module.h
+<https://searchfox.org/mozilla-central/source/xpcom/components/Module.h>`_.
+It then updates the selectors in various ``components.conf`` files and
+hardcoded spots like ``nsComponentManager.cpp`` to add the **Demo** processes
+to the list that can use them. Some modules are required to bootstrap XPCOM
+and will cause it to fail to initialize if they are not permitted.
+
+At this point, the new process is idle, waiting for messages from the main
+process that will start the ``PDemoHelpline`` actor. We discuss that in
+`Creating a New Top Level Actor`_ below but, first, let's look at how the main
+and **Demo** processes will handle clean destruction.
+
+Destroying the New Process
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Gecko processes have a clean way for clients to request that they shutdown.
+Simply calling ``Close()`` on the top level actor at either endpoint will begin
+the shutdown procedure (so, ``PDemoParent::Close`` or ``PDemoChild::Close``).
+The only other way for a child process to terminate is to crash. Each of these
+three options requires some special handling.
+
+.. note::
+ There is no need to consider the case where the parent (main) process
+ crashed, because the **Demo** process would be quickly terminated by Gecko.
+
+In cases where ``Close()`` is called, the shutdown procedure is fairly
+straightforward. Once the call completes, the actor is no longer connected to
+a channel -- messages will not be sent or received, as is the case with any
+normal top-level actor (or any managed actor after calling
+``Send__delete__()``). In the sample code, we ``Close`` the ``DemoChild``
+when some (as yet unwritten) **Demo** process code calls
+``DemoChild::Shutdown``.
+
+.. code-block:: cpp
+
+ /* static */
+ void DemoChild::Shutdown() {
+ if (gDemoChild) {
+ // Wait for the other end to get everything we sent before shutting down.
+ // We never want to Close during a message (response) handler, so
+ // we dispatch a new runnable.
+ auto dc = gDemoChild;
+ RefPtr<nsIRunnable> runnable = NS_NewRunnableFunction(
+ "DemoChild::FinishShutdown",
+ [dc2 = std::move(gDemoChild)]() { dc2->Close(); });
+ dc->SendEmptyMessageQueue(
+ [runnable](bool) { NS_DispatchToMainThread(runnable); },
+ [runnable](mozilla::ipc::ResponseRejectReason) {
+ NS_DispatchToMainThread(runnable);
+ });
+ }
+ }
+
+The comment in the code makes two important points:
+
+* ``Close`` should never be called from a message handler (e.g. in a
+ ``RecvFoo`` method). We schedule it to run later.
+* If the ``DemoParent`` hasn't finished handling messages the ``DemoChild``
+ sent, or vice-versa, those messages will be lost. For that reason, we have a
+ trivial sentinel message ``EmptyMessageQueue`` that we simply send and wait
+ to respond before we ``Close``. This guarantees that the main process will
+ have handled all of the messages we sent before it. Because we know the
+ details of the ``PDemo`` protocol, we know that this means we won't lose any
+ important messages this way. Note that we say "important" messages because
+ we could still lose messages sent *from* the main process. For example, a
+ ``RequestMemoryReport`` message sent by the MemoryReporter could be lost.
+ The actor would need a more complex shutdown protocol to catch all of these
+ messages but in our case there would be no point. A process that is
+ terminating is probably not going to produce useful memory consumption data.
+ Those messages can safely be lost.
+
+`Debugging Process Startup`_ looks at what happens if we omit the
+``EmptyMessageQueue`` message.
+
+We can also see that, once the ``EmptyMessageQueue`` response is run, we are
+releasing ``gDemoChild``, which will result in the termination of the process.
+
+.. code-block:: cpp
+
+ DemoChild::~DemoChild() {
+ // ...
+ XRE_ShutdownChildProcess();
+ }
+
+At this point, the ``DemoParent`` in the main process is alerted to the
+channel closure because IPDL will call its :ref:`ActorDestroy <Actor Lifetimes
+in C++>` method.
+
+.. code-block:: cpp
+
+ void DemoParent::ActorDestroy(ActorDestroyReason aWhy) {
+ if (aWhy == AbnormalShutdown) {
+ GenerateCrashReport(OtherPid());
+ }
+ // ...
+ }
+
+IPDL then releases its (sole) reference to ``DemoParent`` and the destruction
+of the process apparatus is complete.
+
+The ``ActorDestroy`` code shows how we handle the one remaining shutdown case:
+a crash in the **Demo** process. In this case, IPDL will *detect* the dead
+process and free the ``DemoParent`` actor as above, only with an
+``AbnormalShutdown`` reason. We generate a crash report, which requires crash
+reporter integration, but no additional "special" steps need to be taken.
+
+Creating a New Top Level Actor
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+We now have a framework that creates the new process and connects it to the
+main process. We now want to make another top-level actor but this one will be
+responsible for our intended behavior, not just bootstrapping the new process.
+Above, we saw that this is started by ``Host::MakeBridgeAndResolve`` after the
+``DemoParent`` connection is established.
+
+.. code-block:: cpp
+
+ bool DemoParent::Host::MakeBridgeAndResolve() {
+ ipc::Endpoint<PDemoHelplineParent> parent;
+ ipc::Endpoint<PDemoHelplineChild> child;
+
+ auto resolveFail = MakeScopeExit([&] { mResolver(Nothing()); });
+
+ // Parent side is first PID (main/content), child is second (demo).
+ nsresult rv = PDempHelpline::CreateEndpoints(
+ mParentPid, base::GetProcId(GetChildProcessHandle()), &parent, &child);
+
+ // ...
+
+ if (!mActor->SendCreateDemoHelplineChild(std::move(child))) {
+ NS_WARNING("Failed to SendCreateDemoHelplineChild");
+ return false;
+ }
+
+ resolveFail.release();
+ mResolver(Some(std::move(parent)));
+ return true;
+ }
+
+Because the operation of launching a process is asynchronous, we have
+configured this so that it creates the two endpoints for the new top-level
+actors, then we send the child one to the new process and resolve a promise
+with the other. The **Demo** process creates its ``PDemoHelplineChild``
+easily:
+
+.. code-block:: cpp
+
+ mozilla::ipc::IPCResult DemoChild::RecvCreateDemoHelplineChild(
+ Endpoint<PDemoHelplineChild>&& aEndpoint) {
+ mDemoHelplineChild = new DemoHelplineChild();
+ if (!aEndpoint.Bind(mDemoHelplineChild)) {
+ return IPC_FAIL(this, "Unable to bind DemoHelplineChild");
+ }
+ return IPC_OK();
+ }
+
+``MakeProcessAndGetAssistance`` binds the same way:
+
+.. code-block:: cpp
+
+ RefPtr<DemoHelplineParent> demoHelplineParent = new DemoHelplineParent();
+ if (!endpoint.Bind(demoHelplineParent)) {
+ NS_WARNING("Unable to bind DemoHelplineParent");
+ return false;
+ }
+ MOZ_ASSERT(ok);
+
+However, the parent may be in the main process or in content. We handle both
+cases in the next section.
+
+.. _Connecting With Other Processes:
+
+Connecting With Other Processes
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+``DemoHelplineParent::MakeProcessAndGetAssistance`` is the method that we run
+from either the main or the content process and that should kick off the
+procedure that will result in sending a string (that we get from a new **Demo**
+process) to a DOM promise. It starts by constructing a different promise --
+one like the ``mResolver`` in ``Host::MakeBridgeAndResolve`` in the last
+section that produced a ``Maybe<Endpoint<PDemoHelplineParent>>``. In the main
+process, we just make the promise ourselves and call
+``DemoParent::LaunchDemoProcess`` to start the procedure that will result in
+it being resolved as already described. If we are calling from the content
+process, we simply write an async ``PContent`` message that calls
+``DemoParent::LaunchDemoProcess`` and use the message handler's promise as
+our promise:
+
+.. code-block:: cpp
+
+ /* static */
+ bool DemoHelplineParent::MakeProcessAndGetAssistance(
+ RefPtr<mozilla::dom::Promise> aPromise) {
+ RefPtr<LaunchDemoProcessPromise> resolver;
+
+ if (XRE_IsContentProcess()) {
+ auto* contentChild = mozilla::dom::ContentChild::GetSingleton();
+ MOZ_ASSERT(contentChild);
+
+ resolver = contentChild->SendLaunchDemoProcess();
+ } else {
+ MOZ_ASSERT(XRE_IsParentProcess());
+ auto promise = MakeRefPtr<LaunchDemoProcessPromise::Private>(__func__);
+ resolver = promise;
+
+ if (!DemoParent::LaunchDemoProcess(
+ base::GetCurrentProcId(),
+ [promise = std::move(promise)](
+ Maybe<Endpoint<PDemoHelplineParent>>&& aMaybeEndpoint) mutable {
+ promise->Resolve(std::move(aMaybeEndpoint), __func__);
+ })) {
+ NS_WARNING("Failed to launch Demo process");
+ resolver->Reject(NS_ERROR_FAILURE);
+ return false;
+ }
+ }
+
+ resolver->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [aPromise](Maybe<Endpoint<PDemoHelplineParent>>&& maybeEndpoint) mutable {
+ if (!maybeEndpoint) {
+ aPromise->MaybeReject(NS_ERROR_FAILURE);
+ return;
+ }
+
+ RefPtr<DemoHelplineParent> demoHelplineParent = new DemoHelplineParent();
+ Endpoint<PDemoHelplineParent> endpoint = maybeEndpoint.extract();
+ if (!endpoint.Bind(demoHelplineParent)) {
+ NS_WARNING("Unable to bind DemoHelplineParent");
+ return false;
+ }
+ MOZ_ASSERT(ok);
+
+ // ... communicate with PDemoHelpline and write message to console ...
+ },
+ [aPromise](mozilla::ipc::ResponseRejectReason&& aReason) {
+ aPromise->MaybeReject(NS_ERROR_FAILURE);
+ });
+
+ return true;
+ }
+
+ mozilla::ipc::IPCResult ContentParent::RecvLaunchDemoProcess(
+ LaunchDemoProcessResolver&& aResolver) {
+ if (!DemoParent::LaunchDemoProcess(OtherPid(),
+ std::move(aResolver))) {
+ NS_WARNING("Failed to launch Demo process");
+ }
+ return IPC_OK();
+ }
+
+To summarize, connecting processes always requires endpoints to be constructed
+by the main process, even when neither process being connected is the main
+process. It is the only process that creates ``Endpoint`` objects. From that
+point, connecting is just a matter of sending the endpoints to the right
+processes, constructing an actor for them, and then calling ``Endpoint::Bind``.
+
+Completing the Sample
+~~~~~~~~~~~~~~~~~~~~~
+
+We have covered the main parts needed for the sample. Now we just need to wire
+it all up. First, we add the new JS command to ``Navigator.webidl`` and
+``Navigator.h``/``Navigator.cpp``:
+
+.. code-block:: cpp
+
+ partial interface Navigator {
+ [Throws]
+ Promise<DOMString> getAssistance();
+ };
+
+ already_AddRefed<Promise> Navigator::GetAssistance(ErrorResult& aRv) {
+ if (!mWindow || !mWindow->GetDocShell()) {
+ aRv.Throw(NS_ERROR_UNEXPECTED);
+ return nullptr;
+ }
+
+ RefPtr<Promise> echoPromise = Promise::Create(mWindow->AsGlobal(), aRv);
+ if (NS_WARN_IF(aRv.Failed())) {
+ return nullptr;
+ }
+
+ if (!DemoHelplineParent::MakeProcessAndGetAssistance(echoPromise)) {
+ aRv.Throw(NS_ERROR_FAILURE);
+ return nullptr;
+ }
+
+ return echoPromise.forget();
+ }
+
+Then, we need to add the part that gets the string we use to resolve the
+promise in ``MakeProcessAndGetAssistance`` (or reject it if it hasn't been
+resolved by the time ``ActorDestroy`` is called):
+
+.. code-block:: cpp
+
+ using DemoPromise = MozPromise<nsString, nsresult, true>;
+
+ /* static */
+ bool DemoHelplineParent::MakeProcessAndGetAssistance(
+ RefPtr<mozilla::dom::Promise> aPromise) {
+
+ // ... construct and connect demoHelplineParent ...
+
+ RefPtr<DemoPromise> promise = demoHelplineParent->mPromise.Ensure(__func__);
+ promise->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [demoHelplineParent, aPromise](nsString aMessage) mutable {
+ aPromise->MaybeResolve(aMessage);
+ },
+ [demoHelplineParent, aPromise](nsresult aErr) mutable {
+ aPromise->MaybeReject(aErr);
+ });
+
+ if (!demoHelplineParent->SendRequestAssistance()) {
+ NS_WARNING("DemoHelplineParent::SendRequestAssistance failed");
+ }
+ }
+
+ mozilla::ipc::IPCResult DemoHelplineParent::RecvAssistance(
+ nsString&& aMessage, const AssistanceResolver& aResolver) {
+ mPromise.Resolve(aMessage, __func__);
+ aResolver(true);
+ return IPC_OK();
+ }
+
+ void DemoHelplineParent::ActorDestroy(ActorDestroyReason aWhy) {
+ mPromise.RejectIfExists(NS_ERROR_FAILURE, __func__);
+ }
+
+The ``DemoHelplineChild`` has to respond to the ``RequestAssistance`` method,
+which it does by returning a string and then calling ``Close`` on itself when
+the string has been received (but we do not call ``Close`` in the ``Recv``
+method!). We use an async response to the ``GiveAssistance`` message to detect
+that the string was received. During closing, the actor's ``ActorDestroy``
+method then calls the ``DemoChild::Shutdown`` method we defined in `Destroying
+the New Process`_:
+
+.. code-block:: cpp
+
+ mozilla::ipc::IPCResult DemoHelplineChild::RecvRequestAssistance() {
+ RefPtr<DemoHelplineChild> me = this;
+ RefPtr<nsIRunnable> runnable =
+ NS_NewRunnableFunction("DemoHelplineChild::Close", [me]() { me->Close(); });
+
+ SendAssistance(
+ nsString(HelpMessage()),
+ [runnable](bool) { NS_DispatchToMainThread(runnable); },
+ [runnable](mozilla::ipc::ResponseRejectReason) {
+ NS_DispatchToMainThread(runnable);
+ });
+
+ return IPC_OK();
+ }
+
+ void DemoHelplineChild::ActorDestroy(ActorDestroyReason aWhy) {
+ DemoChild::Shutdown();
+ }
+
+During the **Demo** process lifetime, there are two references to the
+``DemoHelplineChild``, one from IPDL and one from the ``DemoChild``. The call
+to ``Close`` releases the one held by IPDL and the other isn't released until
+the ``DemoChild`` is destroyed.
+
+Running the Sample
+~~~~~~~~~~~~~~~~~~
+
+To run the sample, build and run and open the console. The new command is
+``navigator.getAssistance().then(console.log)``. The message sent by
+``SendAssistance`` is then logged to the console. The sample code also
+includes the name of the type of process that was used for the
+``DemoHelplineParent`` so you can confirm that it works from main and from
+content.
+
+Debugging Process Startup
+-------------------------
+
+Debugging a child process at the start of its life is tricky. With most
+platforms/toolchains, it is surprisingly difficult to connect a debugger before
+the main routine begins execution. You may also find that console logging is
+not yet established by the operating system, especially when working with
+sandboxed child processes. Gecko has some facilities that make this less
+painful.
+
+.. _Debugging with IPDL Logging:
+
+Debugging with IPDL Logging
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+This is also best seen with an example. To start, we can create a bug in the
+sample by removing the ``EmptyMessageQueue`` message sent to ``DemoParent``.
+This message was intended to guarantee that the ``DemoParent`` had handled all
+messages sent before it, so we could ``Close`` with the knowledge that we
+didn't miss anything. This sort of bug can be very difficult to track down
+because it is likely to be intermittent and may manifest more easily on some
+platforms/architectures than others. To create this bug, replace the
+``SendEmptyMessageQueue`` call in ``DemoChild::Shutdown``:
+
+.. code-block:: cpp
+
+ auto dc = gDemoChild;
+ RefPtr<nsIRunnable> runnable = NS_NewRunnableFunction(
+ "DemoChild::FinishShutdown",
+ [dc2 = std::move(gDemoChild)]() { dc2->Close(); });
+ dc->SendEmptyMessageQueue(
+ [runnable](bool) { NS_DispatchToMainThread(runnable); },
+ [runnable](mozilla::ipc::ResponseRejectReason) {
+ NS_DispatchToMainThread(runnable);
+ });
+
+with just an (asynchronous) call to ``Close``:
+
+.. code-block:: cpp
+
+ NS_DispatchToMainThread(NS_NewRunnableFunction(
+ "DemoChild::FinishShutdown",
+ [dc = std::move(gDemoChild)]() { dc->Close(); }));
+
+When we run the sample now, everything seems to behave ok but we see messages
+like these in the console: ::
+
+ ###!!! [Parent][RunMessage] Error: (msgtype=0x410001,name=PDemo::Msg_InitCrashReporter) Channel closing: too late to send/recv, messages will be lost
+
+ [Parent 16672, IPC I/O Parent] WARNING: file c:/mozilla-src/mozilla-unified/ipc/chromium/src/base/process_util_win.cc:167
+ [Parent 16672, Main Thread] WARNING: Not resolving response because actor is dead.: file c:/mozilla-src/mozilla-unified/ipc/glue/ProtocolUtils.cpp:931
+ [Parent 16672, Main Thread] WARNING: IPDL resolver dropped without being called!: file c:/mozilla-src/mozilla-unified/ipc/glue/ProtocolUtils.cpp:959
+
+We could probably figure out what is happening here from the messages but,
+with more complex protocols, understanding what led to this may not be so easy.
+To begin diagnosing, we can turn on IPC Logging, which was defined in the IPDL
+section on :ref:`Message Logging`. We just need to set an environment variable
+before starting the browser. Let's turn it on for all ``PDemo`` and
+``PDemoHelpline`` actors: ::
+
+ MOZ_IPC_MESSAGE_LOG="PDemo,PDemoHelpline"
+
+To underscore what we said above, when logging is active, the change in timing
+makes the error message go away and everything closes properly on a tested
+Windows desktop. However, the issue remains on a Macbook Pro and the log
+shows the issue rather clearly: ::
+
+ [time: 1627075553937959][63096->63085] [PDemoChild] Sending PDemo::Msg_InitCrashReporter
+ [time: 1627075553949441][63085->63096] [PDemoParent] Sending PDemo::Msg_CreateDemoHelplineChild
+ [time: 1627075553950293][63092->63096] [PDemoHelplineParent] Sending PDemoHelpline::Msg_RequestAssistance
+ [time: 1627075553979151][63096<-63085] [PDemoChild] Received PDemo::Msg_CreateDemoHelplineChild
+ [time: 1627075553979433][63096<-63092] [PDemoHelplineChild] Received PDemoHelpline::Msg_RequestAssistance
+ [time: 1627075553979498][63096->63092] [PDemoHelplineChild] Sending PDemoHelpline::Msg_GiveAssistance
+ [time: 1627075553980105][63092<-63096] [PDemoHelplineParent] Received PDemoHelpline::Msg_GiveAssistance
+ [time: 1627075553980181][63092->63096] [PDemoHelplineParent] Sending reply PDemoHelpline::Reply_GiveAssistance
+ [time: 1627075553980449][63096<-63092] [PDemoHelplineChild] Received PDemoHelpline::Reply_GiveAssistance
+ [tab 63092] NOTE: parent actor received `Goodbye' message. Closing channel.
+ [default 63085] NOTE: parent actor received `Goodbye' message. Closing channel.
+ [...]
+ ###!!! [Parent][RunMessage] Error: (msgtype=0x420001,name=PDemo::Msg_InitCrashReporter) Channel closing: too late to send/recv, messages will be lost
+ [...]
+ [default 63085] NOTE: parent actor received `Goodbye' message. Closing channel.
+
+The imbalance with ``Msg_InitCrashReporter`` is clear. The message was not
+*Received* before the channel was closed. Note that the first ``Goodbye`` for
+the main (default) process is for the ``PDemoHelpline`` actor -- in this case,
+its child actor was in a content (tab) process. The second default process
+``Goodbye`` is from the **Demo** process, sent when doing ``Close``. It might
+seem that it should handle the ``Msg_InitCrashReporter`` if it can handle the
+later ``Goodbye`` but this does not happen for safety reasons.
+
+Early Debugging For A New Process
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Let's assume now that we still don't understand the problem -- maybe we don't
+know that the ``InitCrashReporter`` message is sent internally by the
+``CrashReporterClient`` we initialized. Or maybe we're only looking at Windows
+builds. We decide we'd like to be able to hook a debugger to the new process
+so that we can break on the ``SendInitCrashReporter`` call. Attaching the
+debugger has to happen fast -- process startup probably completes in under a
+second. Debugging this is not always easy.
+
+Windows users have options that work with both the Visual Studio and WinDbg
+debuggers. For Visual Studio users, there is an easy-to-use VS addon called
+the `Child Process Debugging Tool`_ that allows you to connect to *all*
+processes that are launched by a process you are debugging. So, if the VS
+debugger is connected to the main process, it will automatically connect to the
+new **Demo** process (and every other launched process) at the point that they
+are spawned. This way, the new process never does anything outside of the
+debugger. Breakpoints, etc work as expected. The addon mostly works like a
+toggle and will remain on until it is disabled from the VS menu.
+
+WinDbg users can achieve essentially the same behavior with the `.childdbg`_
+command. See the docs for details but essentially all there is to know is that
+``.childdbg 1`` enables it and ``.childdbg 0`` disables it. You might add it
+to a startup config file (see the WinDbg ``-c`` command line option)
+
+Linux and mac users should reference gdb's ``detach-on-fork``. The command to
+debug child processes is ``set detach-on-fork off``. Again, the behavior is
+largely what you would expect -- that all spawned processes are added to the
+current debug session. The command can be added to ``.gdbinit`` for ease. At
+the time of this writing, lldb does not support automatically connecting to
+newly spawned processes.
+
+Finally, Linux users can use ``rr`` for time-travel debugging. See `Debugging
+Firefox with rr`_ for details.
+
+These solutions are not always desirable. For example, the fact that they hook
+*all* spawned processes can mean that targeting breakpoints to one process
+requires us to manually disconnect many other processes. In these cases, an
+easier solution may be to use Gecko environment variables that will cause the
+process to sleep for some number of seconds. During that time, you can find
+the process ID (PID) for the process you want to debug and connect your
+debugger to it. OS tools like ``ProcessMonitor`` can give you the PID but it
+will also be clearly logged to the console just before the process waits.
+
+Set ``MOZ_DEBUG_CHILD_PROCESS=1`` to turn on process startup pausing. You can
+also set ``MOZ_DEBUG_CHILD_PAUSE=N`` where N is the number of seconds to sleep.
+The default is 10 seconds on Windows and 30 on other platforms.
+
+Pausing for the debugger is not a panacea. Since the environmental variables
+are not specific to process type, you will be forced to wait for all of the
+processes Gecko creates before you wait for it to get to yours. The pauses can
+also end up exposing unknown concurrency bugs in the browser before it even
+gets to your issue, which is good to discover but doesn't fix your bug. That
+said, any of these strategies would be enough to facilitate easily breaking on
+``SendInitCrashReporter`` and finding our sender.
+
+.. _Child Process Debugging Tool: https://marketplace.visualstudio.com/items?itemName=vsdbgplat.MicrosoftChildProcessDebuggingPowerTool
+.. _.childdbg: https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/-childdbg--debug-child-processes-
diff --git a/ipc/docs/utility_process.rst b/ipc/docs/utility_process.rst
new file mode 100644
index 0000000000..8940a56317
--- /dev/null
+++ b/ipc/docs/utility_process.rst
@@ -0,0 +1,69 @@
+Utility Process
+===============
+
+.. warning::
+ As of january 2022, this process is under heavy work, and many things can
+ evolve. Documentation might not always be as accurate as it should be.
+ Please reach to #ipc if you intent to add a new utility.
+
+The utility process is used to provide a simple way to implement IPC actor with
+some more specific sandboxing properties, in case where you don't need or want
+to deal with the extra complexity of adding a whole new process type but you
+just want to apply different sandboxing policies.
+To implement such an actor, you will have to follow a few steps like for
+implementing the trivial example visible in `EmptyUtil
+<https://phabricator.services.mozilla.com/D126402>`_:
+
+ - Define a new IPC actor, e.g., ``PEmptyUtil`` that allows to get some string
+ via ``GetSomeString()`` from the child to the parent
+
+ - In the ``PUtilityProcess`` definition, expose a new child-level method,
+ e.g., ``StartEmptyUtilService(Endpoint<PEmptyUtilChild>)``
+
+ - Implement ``EmptyUtilChild`` and ``EmptyUtilParent`` classes both deriving
+ from their ``PEmptyUtilXX``. If you want or need to run things from a
+ different thread, you can have a look at ``UtilityProcessGenericActor``
+
+ - Make sure both are refcounted
+
+ - Expose your new service on ``UtilityProcessManager`` with a method
+ performing the heavy lifting of starting your process, you can take
+ inspiration from ``StartEmptyUtil()`` in the sample.
+
+ - Ideally, this starting method should rely on `StartUtility() <https://searchfox.org/mozilla-central/rev/fb511723f821ceabeea23b123f1c50c9e93bde9d/ipc/glue/UtilityProcessManager.cpp#210-258,266>`_
+
+ - To use ``StartUtility()`` mentioned above, please ensure that you provide
+ a ``nsresult BindToUtilityProcess(RefPtr<UtilityProcessParent>
+ aUtilityParent)``. Usually, it should be in charge of creating a set of
+ endpoints and performing ``Bind()`` to setup the IPC. You can see some example for `Utility AudioDecoder <https://searchfox.org/mozilla-central/rev/4b3039b48c3cb67774270ebcc2a7d8624d888092/ipc/glue/UtilityAudioDecoderChild.h#31-51>`_
+
+ - For proper user-facing exposition in ``about:processes`` you will have to also provide an actor
+ name via a method ``UtilityActorName GetActorName() { return UtilityActorName::EmptyUtil; }``
+
+ + Add member within `enum WebIDLUtilityActorName in <https://searchfox.org/mozilla-central/rev/fb511723f821ceabeea23b123f1c50c9e93bde9d/dom/chrome-webidl/ChromeUtils.webidl#686-689>`_
+
+ - Handle reception of ``StartEmptyUtilService`` on the child side of
+ ``UtilityProcess`` within ``RecvStartEmptyUtilService()``
+
+ - In ``UtilityProcessChild::ActorDestroy``, release any resources that
+ you stored a reference to in ``RecvStartEmptyUtilService()``. This
+ will probably include a reference to the ``EmptyUtilChild``.
+
+ - The specific sandboxing requirements can be implemented by tracking
+ ``SandboxingKind``, and it starts within `UtilityProcessSandboxing header
+ <https://searchfox.org/mozilla-central/source/ipc/glue/UtilityProcessSandboxing.h>`_
+
+ - Try and make sure you at least add some ``gtest`` coverage of your new
+ actor, for example like in `existing gtest
+ <https://searchfox.org/mozilla-central/source/ipc/glue/test/gtest/TestUtilityProcess.cpp>`_
+
+ - Also ensure actual sandbox testing within
+
+ + ``SandboxTest`` to start your new process,
+ `<https://searchfox.org/mozilla-central/source/security/sandbox/common/test/SandboxTest.cpp>`_
+
+ + ``SandboxTestingChildTests`` to define the test
+ `<https://searchfox.org/mozilla-central/source/security/sandbox/common/test/SandboxTestingChildTests.h>`_
+
+ + ``SandboxTestingChild`` to run your test
+ `<https://searchfox.org/mozilla-central/source/security/sandbox/common/test/SandboxTestingChild.cpp>`_
diff --git a/ipc/glue/AsyncBlockers.h b/ipc/glue/AsyncBlockers.h
new file mode 100644
index 0000000000..16e7aa7528
--- /dev/null
+++ b/ipc/glue/AsyncBlockers.h
@@ -0,0 +1,82 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set sw=2 ts=8 et ft=cpp : */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_AsyncBlockers_h
+#define mozilla_ipc_AsyncBlockers_h
+
+#include "mozilla/MozPromise.h"
+#include "mozilla/ThreadSafety.h"
+#include "nsTArray.h"
+
+// FIXME: when bug 1760855 is fixed, it should not be required anymore
+
+namespace mozilla::ipc {
+
+/**
+ * AsyncBlockers provide a simple registration service that allows to suspend
+ * completion of a particular task until all registered entries have been
+ * cleared. This can be used to implement a similar service to
+ * nsAsyncShutdownService in processes where it wouldn't normally be available.
+ * This class is thread-safe.
+ */
+class AsyncBlockers {
+ public:
+ AsyncBlockers()
+ : mLock("AsyncRegistrar"),
+ mPromise(new GenericPromise::Private(__func__)) {}
+ void Register(void* aBlocker) {
+ MutexAutoLock lock(mLock);
+ mBlockers.InsertElementSorted(aBlocker);
+ }
+ void Deregister(void* aBlocker) {
+ MutexAutoLock lock(mLock);
+ MOZ_ASSERT(mBlockers.ContainsSorted(aBlocker));
+ MOZ_ALWAYS_TRUE(mBlockers.RemoveElementSorted(aBlocker));
+ MaybeResolve();
+ }
+ RefPtr<GenericPromise> WaitUntilClear(uint32_t aTimeOutInMs = 0) {
+ {
+ MutexAutoLock lock(mLock);
+ MaybeResolve();
+ }
+
+ if (aTimeOutInMs > 0) {
+ GetCurrentSerialEventTarget()->DelayedDispatch(
+ NS_NewRunnableFunction("AsyncBlockers::WaitUntilClear",
+ [promise = mPromise]() {
+ // The AsyncBlockers object may have been
+ // deleted by now and the object isn't
+ // refcounted (nor do we want it to be). We
+ // can unconditionally resolve the promise
+ // even it has already been resolved as
+ // MozPromise are thread-safe and will just
+ // ignore the action if already resolved.
+ promise->Resolve(true, __func__);
+ }),
+ aTimeOutInMs);
+ }
+
+ return mPromise;
+ }
+
+ virtual ~AsyncBlockers() { mPromise->Resolve(true, __func__); }
+
+ private:
+ void MaybeResolve() MOZ_REQUIRES(mLock) {
+ mLock.AssertCurrentThreadOwns();
+ if (!mBlockers.IsEmpty()) {
+ return;
+ }
+ mPromise->Resolve(true, __func__);
+ }
+ Mutex mLock;
+ nsTArray<void*> mBlockers MOZ_GUARDED_BY(mLock);
+ const RefPtr<GenericPromise::Private> mPromise;
+};
+
+} // namespace mozilla::ipc
+
+#endif // mozilla_ipc_AsyncBlockers_h
diff --git a/ipc/glue/BackgroundChild.h b/ipc/glue/BackgroundChild.h
new file mode 100644
index 0000000000..89de00795f
--- /dev/null
+++ b/ipc/glue/BackgroundChild.h
@@ -0,0 +1,76 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_backgroundchild_h__
+#define mozilla_ipc_backgroundchild_h__
+
+#include "mozilla/Attributes.h"
+
+class nsIEventTarget;
+
+namespace mozilla {
+namespace dom {
+
+class BlobImpl;
+class ContentChild;
+class ContentParent;
+class ContentProcess;
+
+} // namespace dom
+
+namespace ipc {
+
+class PBackgroundChild;
+class PBackgroundStarterChild;
+
+// This class allows access to the PBackground protocol. PBackground allows
+// communication between any thread (in the parent or a child process) and a
+// single background thread in the parent process. Each PBackgroundChild
+// instance is tied to the thread on which it is created and must not be shared
+// across threads. Each PBackgroundChild is unique and valid as long as its
+// designated thread lives.
+//
+// Creation of PBackground is synchronous. GetOrCreateForCurrentThread will
+// create the actor if it doesn't exist yet. Thereafter (assuming success)
+// GetForCurrentThread() will return the same actor every time.
+//
+// CloseForCurrentThread() will close the current PBackground actor. Subsequent
+// calls to GetForCurrentThread will return null. CloseForCurrentThread() may
+// only be called exactly once for each thread-specific actor. Currently it is
+// illegal to call this before the PBackground actor has been created.
+//
+// The PBackgroundChild actor and all its sub-protocol actors will be
+// automatically destroyed when its designated thread completes.
+//
+// InitContentStarter must be called on the main thread
+// with an actor bridging to the relevant target process type before these
+// methods can be used.
+class BackgroundChild final {
+ friend class mozilla::dom::ContentParent;
+ friend class mozilla::dom::ContentProcess;
+
+ public:
+ // See above.
+ static PBackgroundChild* GetForCurrentThread();
+
+ // See above.
+ static PBackgroundChild* GetOrCreateForCurrentThread();
+
+ // See above.
+ static void CloseForCurrentThread();
+
+ // See above.
+ static void InitContentStarter(mozilla::dom::ContentChild* aContent);
+
+ private:
+ // Only called by this class's friends.
+ static void Startup();
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_backgroundchild_h__
diff --git a/ipc/glue/BackgroundChildImpl.cpp b/ipc/glue/BackgroundChildImpl.cpp
new file mode 100644
index 0000000000..5bcfbd2838
--- /dev/null
+++ b/ipc/glue/BackgroundChildImpl.cpp
@@ -0,0 +1,459 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "BackgroundChildImpl.h"
+
+#include "BroadcastChannelChild.h"
+#ifdef MOZ_WEBRTC
+# include "CamerasChild.h"
+#endif
+#include "mozilla/Assertions.h"
+#include "mozilla/SchedulerGroup.h"
+#include "mozilla/dom/ClientManagerActors.h"
+#include "mozilla/dom/FileCreatorChild.h"
+#include "mozilla/dom/PBackgroundLSDatabaseChild.h"
+#include "mozilla/dom/PBackgroundLSObserverChild.h"
+#include "mozilla/dom/PBackgroundLSRequestChild.h"
+#include "mozilla/dom/PBackgroundLSSimpleRequestChild.h"
+#include "mozilla/dom/PBackgroundSDBConnectionChild.h"
+#include "mozilla/dom/PFileSystemRequestChild.h"
+#include "mozilla/dom/EndpointForReportChild.h"
+#include "mozilla/dom/PVsync.h"
+#include "mozilla/dom/TemporaryIPCBlobChild.h"
+#include "mozilla/dom/cache/ActorUtils.h"
+#include "mozilla/dom/indexedDB/PBackgroundIndexedDBUtilsChild.h"
+#include "mozilla/dom/indexedDB/ThreadLocal.h"
+#include "mozilla/dom/quota/PQuotaChild.h"
+#include "mozilla/dom/RemoteWorkerChild.h"
+#include "mozilla/dom/RemoteWorkerControllerChild.h"
+#include "mozilla/dom/RemoteWorkerServiceChild.h"
+#include "mozilla/dom/ServiceWorkerChild.h"
+#include "mozilla/dom/SharedWorkerChild.h"
+#include "mozilla/dom/StorageIPC.h"
+#include "mozilla/dom/MessagePortChild.h"
+#include "mozilla/dom/ServiceWorkerContainerChild.h"
+#include "mozilla/dom/ServiceWorkerManagerChild.h"
+#include "mozilla/ipc/PBackgroundTestChild.h"
+#include "mozilla/net/PUDPSocketChild.h"
+#include "mozilla/dom/network/UDPSocketChild.h"
+#include "mozilla/dom/WebAuthnTransactionChild.h"
+#include "mozilla/dom/MIDIPortChild.h"
+#include "mozilla/dom/MIDIManagerChild.h"
+#include "nsID.h"
+
+namespace {
+
+class TestChild final : public mozilla::ipc::PBackgroundTestChild {
+ friend class mozilla::ipc::BackgroundChildImpl;
+
+ nsCString mTestArg;
+
+ explicit TestChild(const nsACString& aTestArg) : mTestArg(aTestArg) {
+ MOZ_COUNT_CTOR(TestChild);
+ }
+
+ protected:
+ ~TestChild() override { MOZ_COUNT_DTOR(TestChild); }
+
+ public:
+ mozilla::ipc::IPCResult Recv__delete__(const nsACString& aTestArg) override;
+};
+
+} // namespace
+
+namespace mozilla::ipc {
+
+using mozilla::dom::UDPSocketChild;
+using mozilla::net::PUDPSocketChild;
+
+using mozilla::dom::PRemoteWorkerChild;
+using mozilla::dom::PServiceWorkerChild;
+using mozilla::dom::PServiceWorkerContainerChild;
+using mozilla::dom::PServiceWorkerRegistrationChild;
+using mozilla::dom::RemoteWorkerChild;
+using mozilla::dom::StorageDBChild;
+using mozilla::dom::cache::PCacheChild;
+using mozilla::dom::cache::PCacheStreamControlChild;
+
+using mozilla::dom::WebAuthnTransactionChild;
+
+using mozilla::dom::PMIDIManagerChild;
+using mozilla::dom::PMIDIPortChild;
+
+// -----------------------------------------------------------------------------
+// BackgroundChildImpl::ThreadLocal
+// -----------------------------------------------------------------------------
+
+BackgroundChildImpl::ThreadLocal::ThreadLocal() : mCurrentFileHandle(nullptr) {
+ // May happen on any thread!
+ MOZ_COUNT_CTOR(mozilla::ipc::BackgroundChildImpl::ThreadLocal);
+}
+
+BackgroundChildImpl::ThreadLocal::~ThreadLocal() {
+ // May happen on any thread!
+ MOZ_COUNT_DTOR(mozilla::ipc::BackgroundChildImpl::ThreadLocal);
+}
+
+// -----------------------------------------------------------------------------
+// BackgroundChildImpl
+// -----------------------------------------------------------------------------
+
+BackgroundChildImpl::BackgroundChildImpl() {
+ // May happen on any thread!
+ MOZ_COUNT_CTOR(mozilla::ipc::BackgroundChildImpl);
+}
+
+BackgroundChildImpl::~BackgroundChildImpl() {
+ // May happen on any thread!
+ MOZ_COUNT_DTOR(mozilla::ipc::BackgroundChildImpl);
+}
+
+void BackgroundChildImpl::ProcessingError(Result aCode, const char* aReason) {
+ // May happen on any thread!
+
+ nsAutoCString abortMessage;
+
+ switch (aCode) {
+ case MsgDropped:
+ return;
+
+#define HANDLE_CASE(_result) \
+ case _result: \
+ abortMessage.AssignLiteral(#_result); \
+ break
+
+ HANDLE_CASE(MsgNotKnown);
+ HANDLE_CASE(MsgNotAllowed);
+ HANDLE_CASE(MsgPayloadError);
+ HANDLE_CASE(MsgProcessingError);
+ HANDLE_CASE(MsgRouteError);
+ HANDLE_CASE(MsgValueError);
+
+#undef HANDLE_CASE
+
+ default:
+ MOZ_CRASH("Unknown error code!");
+ }
+
+ nsDependentCString reason(aReason);
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::ipc_channel_error, reason);
+
+ MOZ_CRASH_UNSAFE_PRINTF("%s: %s", abortMessage.get(), aReason);
+}
+
+void BackgroundChildImpl::ActorDestroy(ActorDestroyReason aWhy) {
+ // May happen on any thread!
+}
+
+PBackgroundTestChild* BackgroundChildImpl::AllocPBackgroundTestChild(
+ const nsACString& aTestArg) {
+ return new TestChild(aTestArg);
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundTestChild(
+ PBackgroundTestChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete static_cast<TestChild*>(aActor);
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundIndexedDBUtilsChild*
+BackgroundChildImpl::AllocPBackgroundIndexedDBUtilsChild() {
+ MOZ_CRASH(
+ "PBackgroundIndexedDBUtilsChild actors should be manually "
+ "constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundIndexedDBUtilsChild(
+ PBackgroundIndexedDBUtilsChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete aActor;
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundLSObserverChild*
+BackgroundChildImpl::AllocPBackgroundLSObserverChild(
+ const uint64_t& aObserverId) {
+ MOZ_CRASH("PBackgroundLSObserverChild actor should be manually constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundLSObserverChild(
+ PBackgroundLSObserverChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete aActor;
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundLSRequestChild*
+BackgroundChildImpl::AllocPBackgroundLSRequestChild(
+ const LSRequestParams& aParams) {
+ MOZ_CRASH("PBackgroundLSRequestChild actor should be manually constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundLSRequestChild(
+ PBackgroundLSRequestChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete aActor;
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundLocalStorageCacheChild*
+BackgroundChildImpl::AllocPBackgroundLocalStorageCacheChild(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) {
+ MOZ_CRASH(
+ "PBackgroundLocalStorageChild actors should be manually "
+ "constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundLocalStorageCacheChild(
+ PBackgroundLocalStorageCacheChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete aActor;
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundLSSimpleRequestChild*
+BackgroundChildImpl::AllocPBackgroundLSSimpleRequestChild(
+ const LSSimpleRequestParams& aParams) {
+ MOZ_CRASH(
+ "PBackgroundLSSimpleRequestChild actor should be manually "
+ "constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundLSSimpleRequestChild(
+ PBackgroundLSSimpleRequestChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ delete aActor;
+ return true;
+}
+
+BackgroundChildImpl::PBackgroundStorageChild*
+BackgroundChildImpl::AllocPBackgroundStorageChild(
+ const nsAString& aProfilePath, const uint32_t& aPrivateBrowsingId) {
+ MOZ_CRASH("PBackgroundStorageChild actors should be manually constructed!");
+}
+
+bool BackgroundChildImpl::DeallocPBackgroundStorageChild(
+ PBackgroundStorageChild* aActor) {
+ MOZ_ASSERT(aActor);
+
+ StorageDBChild* child = static_cast<StorageDBChild*>(aActor);
+ child->ReleaseIPDLReference();
+ return true;
+}
+
+already_AddRefed<PRemoteWorkerChild>
+BackgroundChildImpl::AllocPRemoteWorkerChild(const RemoteWorkerData& aData) {
+ return MakeAndAddRef<RemoteWorkerChild>(aData);
+}
+
+IPCResult BackgroundChildImpl::RecvPRemoteWorkerConstructor(
+ PRemoteWorkerChild* aActor, const RemoteWorkerData& aData) {
+ dom::RemoteWorkerChild* actor = static_cast<dom::RemoteWorkerChild*>(aActor);
+ actor->ExecWorker(aData);
+ return IPC_OK();
+}
+
+dom::PSharedWorkerChild* BackgroundChildImpl::AllocPSharedWorkerChild(
+ const dom::RemoteWorkerData& aData, const uint64_t& aWindowID,
+ const dom::MessagePortIdentifier& aPortIdentifier) {
+ RefPtr<dom::SharedWorkerChild> agent = new dom::SharedWorkerChild();
+ return agent.forget().take();
+}
+
+bool BackgroundChildImpl::DeallocPSharedWorkerChild(
+ dom::PSharedWorkerChild* aActor) {
+ RefPtr<dom::SharedWorkerChild> actor =
+ dont_AddRef(static_cast<dom::SharedWorkerChild*>(aActor));
+ return true;
+}
+
+dom::PTemporaryIPCBlobChild*
+BackgroundChildImpl::AllocPTemporaryIPCBlobChild() {
+ MOZ_CRASH("This is not supposed to be called.");
+ return nullptr;
+}
+
+bool BackgroundChildImpl::DeallocPTemporaryIPCBlobChild(
+ dom::PTemporaryIPCBlobChild* aActor) {
+ RefPtr<dom::TemporaryIPCBlobChild> actor =
+ dont_AddRef(static_cast<dom::TemporaryIPCBlobChild*>(aActor));
+ return true;
+}
+
+dom::PFileCreatorChild* BackgroundChildImpl::AllocPFileCreatorChild(
+ const nsAString& aFullPath, const nsAString& aType, const nsAString& aName,
+ const Maybe<int64_t>& aLastModified, const bool& aExistenceCheck,
+ const bool& aIsFromNsIFile) {
+ return new dom::FileCreatorChild();
+}
+
+bool BackgroundChildImpl::DeallocPFileCreatorChild(PFileCreatorChild* aActor) {
+ delete static_cast<dom::FileCreatorChild*>(aActor);
+ return true;
+}
+
+PUDPSocketChild* BackgroundChildImpl::AllocPUDPSocketChild(
+ const Maybe<PrincipalInfo>& aPrincipalInfo, const nsACString& aFilter) {
+ MOZ_CRASH("AllocPUDPSocket should not be called");
+ return nullptr;
+}
+
+bool BackgroundChildImpl::DeallocPUDPSocketChild(PUDPSocketChild* child) {
+ UDPSocketChild* p = static_cast<UDPSocketChild*>(child);
+ p->ReleaseIPDLReference();
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// BroadcastChannel API
+// -----------------------------------------------------------------------------
+
+dom::PBroadcastChannelChild* BackgroundChildImpl::AllocPBroadcastChannelChild(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOrigin,
+ const nsAString& aChannel) {
+ RefPtr<dom::BroadcastChannelChild> agent = new dom::BroadcastChannelChild();
+ return agent.forget().take();
+}
+
+bool BackgroundChildImpl::DeallocPBroadcastChannelChild(
+ PBroadcastChannelChild* aActor) {
+ RefPtr<dom::BroadcastChannelChild> child =
+ dont_AddRef(static_cast<dom::BroadcastChannelChild*>(aActor));
+ MOZ_ASSERT(child);
+ return true;
+}
+
+camera::PCamerasChild* BackgroundChildImpl::AllocPCamerasChild() {
+#ifdef MOZ_WEBRTC
+ RefPtr<camera::CamerasChild> agent = new camera::CamerasChild();
+ return agent.forget().take();
+#else
+ return nullptr;
+#endif
+}
+
+bool BackgroundChildImpl::DeallocPCamerasChild(camera::PCamerasChild* aActor) {
+#ifdef MOZ_WEBRTC
+ RefPtr<camera::CamerasChild> child =
+ dont_AddRef(static_cast<camera::CamerasChild*>(aActor));
+ MOZ_ASSERT(aActor);
+ camera::Shutdown();
+#endif
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// ServiceWorkerManager
+// -----------------------------------------------------------------------------
+
+dom::PServiceWorkerManagerChild*
+BackgroundChildImpl::AllocPServiceWorkerManagerChild() {
+ RefPtr<dom::ServiceWorkerManagerChild> agent =
+ new dom::ServiceWorkerManagerChild();
+ return agent.forget().take();
+}
+
+bool BackgroundChildImpl::DeallocPServiceWorkerManagerChild(
+ PServiceWorkerManagerChild* aActor) {
+ RefPtr<dom::ServiceWorkerManagerChild> child =
+ dont_AddRef(static_cast<dom::ServiceWorkerManagerChild*>(aActor));
+ MOZ_ASSERT(child);
+ return true;
+}
+
+// -----------------------------------------------------------------------------
+// Cache API
+// -----------------------------------------------------------------------------
+
+already_AddRefed<PCacheChild> BackgroundChildImpl::AllocPCacheChild() {
+ return dom::cache::AllocPCacheChild();
+}
+
+already_AddRefed<PCacheStreamControlChild>
+BackgroundChildImpl::AllocPCacheStreamControlChild() {
+ return dom::cache::AllocPCacheStreamControlChild();
+}
+
+// -----------------------------------------------------------------------------
+// MessageChannel/MessagePort API
+// -----------------------------------------------------------------------------
+
+dom::PMessagePortChild* BackgroundChildImpl::AllocPMessagePortChild(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) {
+ RefPtr<dom::MessagePortChild> agent = new dom::MessagePortChild();
+ return agent.forget().take();
+}
+
+bool BackgroundChildImpl::DeallocPMessagePortChild(PMessagePortChild* aActor) {
+ RefPtr<dom::MessagePortChild> child =
+ dont_AddRef(static_cast<dom::MessagePortChild*>(aActor));
+ MOZ_ASSERT(child);
+ return true;
+}
+
+dom::PWebAuthnTransactionChild*
+BackgroundChildImpl::AllocPWebAuthnTransactionChild() {
+ MOZ_CRASH("PWebAuthnTransaction actor should be manually constructed!");
+ return nullptr;
+}
+
+bool BackgroundChildImpl::DeallocPWebAuthnTransactionChild(
+ PWebAuthnTransactionChild* aActor) {
+ MOZ_ASSERT(aActor);
+ RefPtr<dom::WebAuthnTransactionChild> child =
+ dont_AddRef(static_cast<dom::WebAuthnTransactionChild*>(aActor));
+ return true;
+}
+
+already_AddRefed<PServiceWorkerChild>
+BackgroundChildImpl::AllocPServiceWorkerChild(
+ const IPCServiceWorkerDescriptor&) {
+ MOZ_CRASH("Shouldn't be called.");
+ return {};
+}
+
+already_AddRefed<PServiceWorkerContainerChild>
+BackgroundChildImpl::AllocPServiceWorkerContainerChild() {
+ return mozilla::dom::ServiceWorkerContainerChild::Create();
+}
+
+already_AddRefed<PServiceWorkerRegistrationChild>
+BackgroundChildImpl::AllocPServiceWorkerRegistrationChild(
+ const IPCServiceWorkerRegistrationDescriptor&) {
+ MOZ_CRASH("Shouldn't be called.");
+ return {};
+}
+
+dom::PEndpointForReportChild* BackgroundChildImpl::AllocPEndpointForReportChild(
+ const nsAString& aGroupName, const PrincipalInfo& aPrincipalInfo) {
+ return new dom::EndpointForReportChild();
+}
+
+bool BackgroundChildImpl::DeallocPEndpointForReportChild(
+ PEndpointForReportChild* aActor) {
+ MOZ_ASSERT(aActor);
+ delete static_cast<dom::EndpointForReportChild*>(aActor);
+ return true;
+}
+
+} // namespace mozilla::ipc
+
+mozilla::ipc::IPCResult TestChild::Recv__delete__(const nsACString& aTestArg) {
+ MOZ_RELEASE_ASSERT(aTestArg == mTestArg,
+ "BackgroundTest message was corrupted!");
+
+ return IPC_OK();
+}
diff --git a/ipc/glue/BackgroundChildImpl.h b/ipc/glue/BackgroundChildImpl.h
new file mode 100644
index 0000000000..bedae64c2c
--- /dev/null
+++ b/ipc/glue/BackgroundChildImpl.h
@@ -0,0 +1,193 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_backgroundchildimpl_h__
+#define mozilla_ipc_backgroundchildimpl_h__
+
+#include "mozilla/ipc/PBackgroundChild.h"
+#include "mozilla/UniquePtr.h"
+
+namespace mozilla {
+namespace dom {
+
+class IDBFileHandle;
+
+namespace indexedDB {
+
+class ThreadLocal;
+
+} // namespace indexedDB
+} // namespace dom
+
+namespace ipc {
+
+// Instances of this class should never be created directly. This class is meant
+// to be inherited in BackgroundImpl.
+class BackgroundChildImpl : public PBackgroundChild {
+ public:
+ class ThreadLocal;
+
+ // Get the ThreadLocal for the current thread if
+ // BackgroundChild::GetOrCreateForCurrentThread() has been called and true was
+ // returned (e.g. a valid PBackgroundChild actor has been created or is in the
+ // process of being created). Otherwise this function returns null.
+ // This functions is implemented in BackgroundImpl.cpp.
+ static ThreadLocal* GetThreadLocalForCurrentThread();
+
+ protected:
+ BackgroundChildImpl();
+ virtual ~BackgroundChildImpl();
+
+ virtual void ProcessingError(Result aCode, const char* aReason) override;
+
+ virtual void ActorDestroy(ActorDestroyReason aWhy) override;
+
+ virtual PBackgroundTestChild* AllocPBackgroundTestChild(
+ const nsACString& aTestArg) override;
+
+ virtual bool DeallocPBackgroundTestChild(
+ PBackgroundTestChild* aActor) override;
+
+ virtual PBackgroundIndexedDBUtilsChild* AllocPBackgroundIndexedDBUtilsChild()
+ override;
+
+ virtual bool DeallocPBackgroundIndexedDBUtilsChild(
+ PBackgroundIndexedDBUtilsChild* aActor) override;
+
+ virtual PBackgroundLSObserverChild* AllocPBackgroundLSObserverChild(
+ const uint64_t& aObserverId) override;
+
+ virtual bool DeallocPBackgroundLSObserverChild(
+ PBackgroundLSObserverChild* aActor) override;
+
+ virtual PBackgroundLSRequestChild* AllocPBackgroundLSRequestChild(
+ const LSRequestParams& aParams) override;
+
+ virtual bool DeallocPBackgroundLSRequestChild(
+ PBackgroundLSRequestChild* aActor) override;
+
+ virtual PBackgroundLSSimpleRequestChild* AllocPBackgroundLSSimpleRequestChild(
+ const LSSimpleRequestParams& aParams) override;
+
+ virtual bool DeallocPBackgroundLSSimpleRequestChild(
+ PBackgroundLSSimpleRequestChild* aActor) override;
+
+ virtual PBackgroundLocalStorageCacheChild*
+ AllocPBackgroundLocalStorageCacheChild(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ virtual bool DeallocPBackgroundLocalStorageCacheChild(
+ PBackgroundLocalStorageCacheChild* aActor) override;
+
+ virtual PBackgroundStorageChild* AllocPBackgroundStorageChild(
+ const nsAString& aProfilePath,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ virtual bool DeallocPBackgroundStorageChild(
+ PBackgroundStorageChild* aActor) override;
+
+ virtual PTemporaryIPCBlobChild* AllocPTemporaryIPCBlobChild() override;
+
+ virtual bool DeallocPTemporaryIPCBlobChild(
+ PTemporaryIPCBlobChild* aActor) override;
+
+ virtual PFileCreatorChild* AllocPFileCreatorChild(
+ const nsAString& aFullPath, const nsAString& aType,
+ const nsAString& aName, const Maybe<int64_t>& aLastModified,
+ const bool& aExistenceCheck, const bool& aIsFromNsIFile) override;
+
+ virtual bool DeallocPFileCreatorChild(PFileCreatorChild* aActor) override;
+
+ already_AddRefed<mozilla::dom::PRemoteWorkerChild> AllocPRemoteWorkerChild(
+ const RemoteWorkerData& aData) override;
+
+ virtual mozilla::ipc::IPCResult RecvPRemoteWorkerConstructor(
+ PRemoteWorkerChild* aActor, const RemoteWorkerData& aData) override;
+
+ virtual mozilla::dom::PSharedWorkerChild* AllocPSharedWorkerChild(
+ const mozilla::dom::RemoteWorkerData& aData, const uint64_t& aWindowID,
+ const mozilla::dom::MessagePortIdentifier& aPortIdentifier) override;
+
+ virtual bool DeallocPSharedWorkerChild(
+ mozilla::dom::PSharedWorkerChild* aActor) override;
+
+ virtual PCamerasChild* AllocPCamerasChild() override;
+
+ virtual bool DeallocPCamerasChild(PCamerasChild* aActor) override;
+
+ virtual PUDPSocketChild* AllocPUDPSocketChild(
+ const Maybe<PrincipalInfo>& aPrincipalInfo,
+ const nsACString& aFilter) override;
+ virtual bool DeallocPUDPSocketChild(PUDPSocketChild* aActor) override;
+
+ virtual PBroadcastChannelChild* AllocPBroadcastChannelChild(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOrigin,
+ const nsAString& aChannel) override;
+
+ virtual bool DeallocPBroadcastChannelChild(
+ PBroadcastChannelChild* aActor) override;
+
+ virtual PServiceWorkerManagerChild* AllocPServiceWorkerManagerChild()
+ override;
+
+ virtual bool DeallocPServiceWorkerManagerChild(
+ PServiceWorkerManagerChild* aActor) override;
+
+ virtual already_AddRefed<dom::cache::PCacheChild> AllocPCacheChild() override;
+
+ virtual already_AddRefed<dom::cache::PCacheStreamControlChild>
+ AllocPCacheStreamControlChild() override;
+
+ virtual PMessagePortChild* AllocPMessagePortChild(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) override;
+
+ virtual bool DeallocPMessagePortChild(PMessagePortChild* aActor) override;
+
+ virtual PWebAuthnTransactionChild* AllocPWebAuthnTransactionChild() override;
+
+ virtual bool DeallocPWebAuthnTransactionChild(
+ PWebAuthnTransactionChild* aActor) override;
+
+ already_AddRefed<PServiceWorkerChild> AllocPServiceWorkerChild(
+ const IPCServiceWorkerDescriptor&);
+
+ already_AddRefed<PServiceWorkerContainerChild>
+ AllocPServiceWorkerContainerChild();
+
+ already_AddRefed<PServiceWorkerRegistrationChild>
+ AllocPServiceWorkerRegistrationChild(
+ const IPCServiceWorkerRegistrationDescriptor&);
+
+ virtual PEndpointForReportChild* AllocPEndpointForReportChild(
+ const nsAString& aGroupName,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ virtual bool DeallocPEndpointForReportChild(
+ PEndpointForReportChild* aActor) override;
+};
+
+class BackgroundChildImpl::ThreadLocal final {
+ friend class mozilla::DefaultDelete<ThreadLocal>;
+
+ public:
+ mozilla::UniquePtr<mozilla::dom::indexedDB::ThreadLocal>
+ mIndexedDBThreadLocal;
+ mozilla::dom::IDBFileHandle* mCurrentFileHandle;
+
+ public:
+ ThreadLocal();
+
+ private:
+ // Only destroyed by UniquePtr<ThreadLocal>.
+ ~ThreadLocal();
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_backgroundchildimpl_h__
diff --git a/ipc/glue/BackgroundImpl.cpp b/ipc/glue/BackgroundImpl.cpp
new file mode 100644
index 0000000000..bba09c261a
--- /dev/null
+++ b/ipc/glue/BackgroundImpl.cpp
@@ -0,0 +1,1268 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "BackgroundChild.h"
+#include "BackgroundParent.h"
+
+#include "BackgroundChildImpl.h"
+#include "BackgroundParentImpl.h"
+#include "MainThreadUtils.h"
+#include "base/process_util.h"
+#include "base/task.h"
+#include "FileDescriptor.h"
+#include "GeckoProfiler.h"
+#include "InputStreamUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/MozPromise.h"
+#include "mozilla/Services.h"
+#include "mozilla/SpinEventLoopUntil.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/Unused.h"
+#include "mozilla/dom/ContentChild.h"
+#include "mozilla/dom/ContentParent.h"
+#include "mozilla/dom/File.h"
+#include "mozilla/dom/WorkerPrivate.h"
+#include "mozilla/dom/WorkerRef.h"
+#include "mozilla/ipc/BackgroundStarterChild.h"
+#include "mozilla/ipc/BackgroundStarterParent.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/PBackgroundStarter.h"
+#include "mozilla/ipc/ProtocolTypes.h"
+#include "nsCOMPtr.h"
+#include "nsIEventTarget.h"
+#include "nsIObserver.h"
+#include "nsIObserverService.h"
+#include "nsIRunnable.h"
+#include "nsISupportsImpl.h"
+#include "nsIThread.h"
+#include "nsITimer.h"
+#include "nsTArray.h"
+#include "nsThreadUtils.h"
+#include "nsTraceRefcnt.h"
+#include "nsXULAppAPI.h"
+#include "nsXPCOMPrivate.h"
+#include "prthread.h"
+
+#include <functional>
+
+#ifdef RELEASE_OR_BETA
+# define THREADSAFETY_ASSERT MOZ_ASSERT
+#else
+# define THREADSAFETY_ASSERT MOZ_RELEASE_ASSERT
+#endif
+
+#define CRASH_IN_CHILD_PROCESS(_msg) \
+ do { \
+ if (XRE_IsParentProcess()) { \
+ MOZ_ASSERT(false, _msg); \
+ } else { \
+ MOZ_CRASH(_msg); \
+ } \
+ } while (0)
+
+using namespace mozilla;
+using namespace mozilla::dom;
+using namespace mozilla::ipc;
+using namespace mozilla::net;
+
+namespace {
+
+class ChildImpl;
+
+// -----------------------------------------------------------------------------
+// Utility Functions
+// -----------------------------------------------------------------------------
+
+void AssertIsOnMainThread() { THREADSAFETY_ASSERT(NS_IsMainThread()); }
+
+// -----------------------------------------------------------------------------
+// ParentImpl Declaration
+// -----------------------------------------------------------------------------
+
+class ParentImpl final : public BackgroundParentImpl {
+ friend class ChildImpl;
+ friend class mozilla::ipc::BackgroundParent;
+ friend class mozilla::ipc::BackgroundStarterParent;
+
+ private:
+ class ShutdownObserver;
+
+ struct MOZ_STACK_CLASS TimerCallbackClosure {
+ nsIThread* mThread;
+ nsTArray<IToplevelProtocol*>* mLiveActors;
+
+ TimerCallbackClosure(nsIThread* aThread,
+ nsTArray<IToplevelProtocol*>* aLiveActors)
+ : mThread(aThread), mLiveActors(aLiveActors) {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT(aThread);
+ MOZ_ASSERT(aLiveActors);
+ }
+ };
+
+ // The length of time we will wait at shutdown for all actors to clean
+ // themselves up before forcing them to be destroyed.
+ static const uint32_t kShutdownTimerDelayMS = 10000;
+
+ // This is only modified on the main thread. It is null if the thread does not
+ // exist or is shutting down.
+ static StaticRefPtr<nsIThread> sBackgroundThread;
+
+ // This is created and destroyed on the main thread but only modified on the
+ // background thread. It is specific to each instance of sBackgroundThread.
+ static nsTArray<IToplevelProtocol*>* sLiveActorsForBackgroundThread;
+
+ // This is only modified on the main thread.
+ static StaticRefPtr<nsITimer> sShutdownTimer;
+
+ // This exists so that that [Assert]IsOnBackgroundThread() can continue to
+ // work during shutdown.
+ static Atomic<PRThread*> sBackgroundPRThread;
+
+ // Maintains a count of live actors so that the background thread can be shut
+ // down when it is no longer needed.
+ // May be incremented on either the background thread (by an existing actor)
+ // or on the main thread, but must be decremented on the main thread.
+ static Atomic<uint64_t> sLiveActorCount;
+
+ // This is only modified on the main thread. It is true after the shutdown
+ // observer is registered and is never unset thereafter.
+ static bool sShutdownObserverRegistered;
+
+ // This is only modified on the main thread. It prevents us from trying to
+ // create the background thread after application shutdown has started.
+ static bool sShutdownHasStarted;
+
+ // null if this is a same-process actor.
+ const RefPtr<ThreadsafeContentParentHandle> mContent;
+
+ // Set when the actor is opened successfully and used to handle shutdown
+ // hangs. Only touched on the background thread.
+ nsTArray<IToplevelProtocol*>* mLiveActorArray;
+
+ // Set at construction to indicate whether this parent actor corresponds to a
+ // child actor in another process or to a child actor from a different thread
+ // in the same process.
+ const bool mIsOtherProcessActor;
+
+ // Set after ActorDestroy has been called. Only touched on the background
+ // thread.
+ bool mActorDestroyed;
+
+ public:
+ static bool IsOnBackgroundThread() {
+ return PR_GetCurrentThread() == sBackgroundPRThread;
+ }
+
+ static void AssertIsOnBackgroundThread() {
+ THREADSAFETY_ASSERT(IsOnBackgroundThread());
+ }
+
+ // `ParentImpl` instances need to be deleted on the main thread, despite IPC
+ // controlling them on a background thread. Use `_WITH_DELETE_ON_MAIN_THREAD`
+ // to force destruction to occur on the desired thread.
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DELETE_ON_MAIN_THREAD(ParentImpl,
+ override)
+
+ void Destroy();
+
+ private:
+ // Forwarded from BackgroundParent.
+ static bool IsOtherProcessActor(PBackgroundParent* aBackgroundActor);
+
+ // Forwarded from BackgroundParent.
+ static ThreadsafeContentParentHandle* GetContentParentHandle(
+ PBackgroundParent* aBackgroundActor);
+
+ // Forwarded from BackgroundParent.
+ static uint64_t GetChildID(PBackgroundParent* aBackgroundActor);
+
+ // Forwarded from BackgroundParent.
+ static void KillHardAsync(PBackgroundParent* aBackgroundActor,
+ const nsACString& aReason);
+
+ // Forwarded from BackgroundParent.
+ static bool AllocStarter(ContentParent* aContent,
+ Endpoint<PBackgroundStarterParent>&& aEndpoint,
+ bool aCrossProcess = true);
+
+ static bool CreateBackgroundThread();
+
+ static void ShutdownBackgroundThread();
+
+ static void ShutdownTimerCallback(nsITimer* aTimer, void* aClosure);
+
+ // NOTE: ParentImpl could be used in 2 cases below.
+ // 1. Within the parent process.
+ // 2. Between parent process and content process.
+ // |aContent| should be not null for case 2. For cases 1, it's null.
+ explicit ParentImpl(ThreadsafeContentParentHandle* aContent,
+ bool aIsOtherProcessActor)
+ : mContent(aContent),
+ mLiveActorArray(nullptr),
+ mIsOtherProcessActor(aIsOtherProcessActor),
+ mActorDestroyed(false) {
+ AssertIsInMainProcess();
+ MOZ_ASSERT_IF(!aIsOtherProcessActor, XRE_IsParentProcess());
+ }
+
+ ~ParentImpl() {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ }
+
+ void MainThreadActorDestroy();
+
+ void SetLiveActorArray(nsTArray<IToplevelProtocol*>* aLiveActorArray) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aLiveActorArray);
+ MOZ_ASSERT(!aLiveActorArray->Contains(this));
+ MOZ_ASSERT(!mLiveActorArray);
+ MOZ_ASSERT(mIsOtherProcessActor);
+
+ mLiveActorArray = aLiveActorArray;
+ mLiveActorArray->AppendElement(this);
+ }
+
+ // These methods are only called by IPDL.
+ virtual void ActorDestroy(ActorDestroyReason aWhy) override;
+};
+
+// -----------------------------------------------------------------------------
+// ChildImpl Declaration
+// -----------------------------------------------------------------------------
+
+class ChildImpl final : public BackgroundChildImpl {
+ friend class mozilla::ipc::BackgroundChild;
+ friend class mozilla::ipc::BackgroundChildImpl;
+ friend class mozilla::ipc::BackgroundStarterChild;
+
+ typedef base::ProcessId ProcessId;
+
+ class ShutdownObserver;
+
+ public:
+ struct ThreadLocalInfo {
+ ThreadLocalInfo()
+#ifdef DEBUG
+ : mClosed(false)
+#endif
+ {
+ }
+
+ RefPtr<ChildImpl> mActor;
+ UniquePtr<BackgroundChildImpl::ThreadLocal> mConsumerThreadLocal;
+#ifdef DEBUG
+ bool mClosed;
+#endif
+ };
+
+ private:
+ // A thread-local index that is not valid.
+ static constexpr unsigned int kBadThreadLocalIndex =
+ static_cast<unsigned int>(-1);
+
+ // ThreadInfoWrapper encapsulates ThreadLocalInfo and ThreadLocalIndex and
+ // also provides some common functions for creating PBackground IPC actor.
+ class ThreadInfoWrapper final {
+ friend class ChildImpl;
+
+ public:
+ using ActorCreateFunc = void (*)(ThreadLocalInfo*, unsigned int,
+ nsIEventTarget*, ChildImpl**);
+
+ ThreadInfoWrapper() = default;
+
+ void Startup() {
+ MOZ_ASSERT(mThreadLocalIndex == kBadThreadLocalIndex,
+ "ThreadInfoWrapper::Startup() called more than once!");
+
+ PRStatus status =
+ PR_NewThreadPrivateIndex(&mThreadLocalIndex, ThreadLocalDestructor);
+ MOZ_RELEASE_ASSERT(status == PR_SUCCESS,
+ "PR_NewThreadPrivateIndex failed!");
+
+ MOZ_ASSERT(mThreadLocalIndex != kBadThreadLocalIndex);
+ }
+
+ void Shutdown() {
+ if (sShutdownHasStarted) {
+ MOZ_ASSERT_IF(mThreadLocalIndex != kBadThreadLocalIndex,
+ !PR_GetThreadPrivate(mThreadLocalIndex));
+ return;
+ }
+
+ if (mThreadLocalIndex == kBadThreadLocalIndex) {
+ return;
+ }
+
+ RefPtr<BackgroundStarterChild> starter;
+ {
+ auto lock = mStarter.Lock();
+ starter = lock->forget();
+ }
+ if (starter) {
+ CloseStarter(starter);
+ }
+
+ ThreadLocalInfo* threadLocalInfo;
+#ifdef DEBUG
+ threadLocalInfo =
+ static_cast<ThreadLocalInfo*>(PR_GetThreadPrivate(mThreadLocalIndex));
+ MOZ_ASSERT(!threadLocalInfo);
+#endif
+
+ threadLocalInfo = mMainThreadInfo;
+ if (threadLocalInfo) {
+#ifdef DEBUG
+ MOZ_ASSERT(!threadLocalInfo->mClosed);
+ threadLocalInfo->mClosed = true;
+#endif
+
+ ThreadLocalDestructor(threadLocalInfo);
+ mMainThreadInfo = nullptr;
+ }
+ }
+
+ template <typename Actor>
+ void InitStarter(Actor* aActor) {
+ AssertIsOnMainThread();
+
+ // Create a pair of endpoints and send them to the other process.
+ Endpoint<PBackgroundStarterParent> parent;
+ Endpoint<PBackgroundStarterChild> child;
+ MOZ_ALWAYS_SUCCEEDS(PBackgroundStarter::CreateEndpoints(
+ aActor->OtherPid(), base::GetCurrentProcId(), &parent, &child));
+ MOZ_ALWAYS_TRUE(aActor->SendInitBackground(std::move(parent)));
+
+ InitStarter(std::move(child));
+ }
+
+ void InitStarter(Endpoint<PBackgroundStarterChild>&& aEndpoint) {
+ AssertIsOnMainThread();
+
+ base::ProcessId otherPid = aEndpoint.OtherPid();
+
+ nsCOMPtr<nsISerialEventTarget> taskQueue;
+ MOZ_ALWAYS_SUCCEEDS(NS_CreateBackgroundTaskQueue(
+ "PBackgroundStarter Queue", getter_AddRefs(taskQueue)));
+
+ RefPtr<BackgroundStarterChild> starter =
+ new BackgroundStarterChild(otherPid, taskQueue);
+
+ taskQueue->Dispatch(NS_NewRunnableFunction(
+ "PBackgroundStarterChild Init",
+ [starter, endpoint = std::move(aEndpoint)]() mutable {
+ MOZ_ALWAYS_TRUE(endpoint.Bind(starter));
+ }));
+
+ // Swap in the newly initialized `BackgroundStarterChild`, and close the
+ // previous one if we're replacing an existing PBackgroundStarterChild
+ // instance.
+ RefPtr<BackgroundStarterChild> prevStarter;
+ {
+ auto lock = mStarter.Lock();
+ prevStarter = lock->forget();
+ *lock = starter.forget();
+ }
+ if (prevStarter) {
+ CloseStarter(prevStarter);
+ }
+ }
+
+ void CloseForCurrentThread() {
+ MOZ_ASSERT(!NS_IsMainThread());
+
+ if (mThreadLocalIndex == kBadThreadLocalIndex) {
+ return;
+ }
+
+ auto* threadLocalInfo =
+ static_cast<ThreadLocalInfo*>(PR_GetThreadPrivate(mThreadLocalIndex));
+
+ if (!threadLocalInfo) {
+ return;
+ }
+
+#ifdef DEBUG
+ MOZ_ASSERT(!threadLocalInfo->mClosed);
+ threadLocalInfo->mClosed = true;
+#endif
+
+ // Clearing the thread local will synchronously close the actor.
+ DebugOnly<PRStatus> status =
+ PR_SetThreadPrivate(mThreadLocalIndex, nullptr);
+ MOZ_ASSERT(status == PR_SUCCESS);
+ }
+
+ PBackgroundChild* GetOrCreateForCurrentThread() {
+ // Processes can be told to do final CC's during shutdown even though
+ // they never finished starting (and thus call this), because they
+ // hadn't gotten far enough to call Startup() before shutdown began.
+ if (mThreadLocalIndex == kBadThreadLocalIndex) {
+ NS_ERROR("BackgroundChild::Startup() was never called");
+ return nullptr;
+ }
+ if (NS_IsMainThread() && ChildImpl::sShutdownHasStarted) {
+ return nullptr;
+ }
+
+ auto* threadLocalInfo = NS_IsMainThread()
+ ? mMainThreadInfo
+ : static_cast<ThreadLocalInfo*>(
+ PR_GetThreadPrivate(mThreadLocalIndex));
+
+ if (!threadLocalInfo) {
+ auto newInfo = MakeUnique<ThreadLocalInfo>();
+
+ if (NS_IsMainThread()) {
+ mMainThreadInfo = newInfo.get();
+ } else {
+ if (PR_SetThreadPrivate(mThreadLocalIndex, newInfo.get()) !=
+ PR_SUCCESS) {
+ CRASH_IN_CHILD_PROCESS("PR_SetThreadPrivate failed!");
+ return nullptr;
+ }
+ }
+
+ threadLocalInfo = newInfo.release();
+ }
+
+ if (threadLocalInfo->mActor) {
+ return threadLocalInfo->mActor;
+ }
+
+ RefPtr<BackgroundStarterChild> starter;
+ {
+ auto lock = mStarter.Lock();
+ starter = *lock;
+ }
+ if (!starter) {
+ CRASH_IN_CHILD_PROCESS("No BackgroundStarterChild");
+ return nullptr;
+ }
+
+ Endpoint<PBackgroundParent> parent;
+ Endpoint<PBackgroundChild> child;
+ nsresult rv;
+ rv = PBackground::CreateEndpoints(
+ starter->mOtherPid, base::GetCurrentProcId(), &parent, &child);
+ if (NS_FAILED(rv)) {
+ NS_WARNING("Failed to create top level actor!");
+ return nullptr;
+ }
+
+ RefPtr<ChildImpl> strongActor = new ChildImpl();
+ if (!child.Bind(strongActor)) {
+ CRASH_IN_CHILD_PROCESS("Failed to bind ChildImpl!");
+ return nullptr;
+ }
+ strongActor->SetActorAlive();
+ threadLocalInfo->mActor = strongActor;
+
+ // Dispatch to the background task queue to create the relevant actor in
+ // the remote process.
+ starter->mTaskQueue->Dispatch(NS_NewRunnableFunction(
+ "PBackground GetOrCreateForCurrentThread",
+ [starter, endpoint = std::move(parent)]() mutable {
+ if (!starter->SendInitBackground(std::move(endpoint))) {
+ NS_WARNING("Failed to create toplevel actor");
+ }
+ }));
+ return strongActor;
+ }
+
+ private:
+ static void CloseStarter(BackgroundStarterChild* aStarter) {
+ aStarter->mTaskQueue->Dispatch(NS_NewRunnableFunction(
+ "PBackgroundStarterChild Close",
+ [starter = RefPtr{aStarter}] { starter->Close(); }));
+ }
+
+ // This is only modified on the main thread. It is the thread-local index
+ // that we use to store the BackgroundChild for each thread.
+ unsigned int mThreadLocalIndex = kBadThreadLocalIndex;
+
+ // On the main thread, we store TLS in this global instead of in
+ // mThreadLocalIndex. That way, cooperative main threads all share the same
+ // thread info.
+ ThreadLocalInfo* mMainThreadInfo = nullptr;
+
+ // The starter which will be used to launch PBackground instances of this
+ // type. Only modified on the main thread, but may be read by any thread
+ // wanting to start background actors.
+ StaticDataMutex<StaticRefPtr<BackgroundStarterChild>> mStarter{"mStarter"};
+ };
+
+ // For PBackground between parent and content process.
+ static ThreadInfoWrapper sParentAndContentProcessThreadInfo;
+
+ // This is only modified on the main thread. It prevents us from trying to
+ // create the background thread after application shutdown has started.
+ static bool sShutdownHasStarted;
+
+#if defined(DEBUG) || !defined(RELEASE_OR_BETA)
+ nsISerialEventTarget* mOwningEventTarget;
+#endif
+
+#ifdef DEBUG
+ bool mActorWasAlive;
+ bool mActorDestroyed;
+#endif
+
+ public:
+ static void Shutdown();
+
+ void AssertIsOnOwningThread() {
+ THREADSAFETY_ASSERT(mOwningEventTarget);
+
+#ifdef RELEASE_OR_BETA
+ DebugOnly<bool> current;
+#else
+ bool current;
+#endif
+ THREADSAFETY_ASSERT(
+ NS_SUCCEEDED(mOwningEventTarget->IsOnCurrentThread(&current)));
+ THREADSAFETY_ASSERT(current);
+ }
+
+ void AssertActorDestroyed() {
+ MOZ_ASSERT(mActorDestroyed, "ChildImpl::ActorDestroy not called in time");
+ }
+
+ explicit ChildImpl()
+#if defined(DEBUG) || !defined(RELEASE_OR_BETA)
+ : mOwningEventTarget(GetCurrentSerialEventTarget())
+#endif
+#ifdef DEBUG
+ ,
+ mActorWasAlive(false),
+ mActorDestroyed(false)
+#endif
+ {
+ AssertIsOnOwningThread();
+ }
+
+ void SetActorAlive() {
+ AssertIsOnOwningThread();
+ MOZ_ASSERT(!mActorWasAlive);
+ MOZ_ASSERT(!mActorDestroyed);
+
+#ifdef DEBUG
+ mActorWasAlive = true;
+#endif
+ }
+
+ NS_INLINE_DECL_REFCOUNTING(ChildImpl, override)
+
+ private:
+ // Forwarded from BackgroundChild.
+ static void Startup();
+
+ // Forwarded from BackgroundChild.
+ static PBackgroundChild* GetForCurrentThread();
+
+ // Forwarded from BackgroundChild.
+ static PBackgroundChild* GetOrCreateForCurrentThread();
+
+ static void CloseForCurrentThread();
+
+ // Forwarded from BackgroundChildImpl.
+ static BackgroundChildImpl::ThreadLocal* GetThreadLocalForCurrentThread();
+
+ // Forwarded from BackgroundChild.
+ static void InitContentStarter(mozilla::dom::ContentChild* aContent);
+
+ static void ThreadLocalDestructor(void* aThreadLocal);
+
+ // This class is reference counted.
+ ~ChildImpl() { MOZ_ASSERT_IF(mActorWasAlive, mActorDestroyed); }
+
+ // Only called by IPDL.
+ virtual void ActorDestroy(ActorDestroyReason aWhy) override;
+};
+
+// -----------------------------------------------------------------------------
+// ParentImpl Helper Declarations
+// -----------------------------------------------------------------------------
+
+class ParentImpl::ShutdownObserver final : public nsIObserver {
+ public:
+ ShutdownObserver() { AssertIsOnMainThread(); }
+
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+
+ private:
+ ~ShutdownObserver() { AssertIsOnMainThread(); }
+};
+
+// -----------------------------------------------------------------------------
+// ChildImpl Helper Declarations
+// -----------------------------------------------------------------------------
+
+class ChildImpl::ShutdownObserver final : public nsIObserver {
+ public:
+ ShutdownObserver() { AssertIsOnMainThread(); }
+
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+
+ private:
+ ~ShutdownObserver() { AssertIsOnMainThread(); }
+};
+
+} // namespace
+
+namespace mozilla {
+namespace ipc {
+
+bool IsOnBackgroundThread() { return ParentImpl::IsOnBackgroundThread(); }
+
+#ifdef DEBUG
+
+void AssertIsOnBackgroundThread() { ParentImpl::AssertIsOnBackgroundThread(); }
+
+#endif // DEBUG
+
+} // namespace ipc
+} // namespace mozilla
+
+// -----------------------------------------------------------------------------
+// BackgroundParent Public Methods
+// -----------------------------------------------------------------------------
+
+// static
+bool BackgroundParent::IsOtherProcessActor(
+ PBackgroundParent* aBackgroundActor) {
+ return ParentImpl::IsOtherProcessActor(aBackgroundActor);
+}
+
+// static
+ThreadsafeContentParentHandle* BackgroundParent::GetContentParentHandle(
+ PBackgroundParent* aBackgroundActor) {
+ return ParentImpl::GetContentParentHandle(aBackgroundActor);
+}
+
+// static
+uint64_t BackgroundParent::GetChildID(PBackgroundParent* aBackgroundActor) {
+ return ParentImpl::GetChildID(aBackgroundActor);
+}
+
+// static
+void BackgroundParent::KillHardAsync(PBackgroundParent* aBackgroundActor,
+ const nsACString& aReason) {
+ ParentImpl::KillHardAsync(aBackgroundActor, aReason);
+}
+
+// static
+bool BackgroundParent::AllocStarter(
+ ContentParent* aContent, Endpoint<PBackgroundStarterParent>&& aEndpoint) {
+ return ParentImpl::AllocStarter(aContent, std::move(aEndpoint));
+}
+
+// -----------------------------------------------------------------------------
+// BackgroundChild Public Methods
+// -----------------------------------------------------------------------------
+
+// static
+void BackgroundChild::Startup() { ChildImpl::Startup(); }
+
+// static
+PBackgroundChild* BackgroundChild::GetForCurrentThread() {
+ return ChildImpl::GetForCurrentThread();
+}
+
+// static
+PBackgroundChild* BackgroundChild::GetOrCreateForCurrentThread() {
+ return ChildImpl::GetOrCreateForCurrentThread();
+}
+
+// static
+void BackgroundChild::CloseForCurrentThread() {
+ ChildImpl::CloseForCurrentThread();
+}
+
+// static
+void BackgroundChild::InitContentStarter(ContentChild* aContent) {
+ ChildImpl::InitContentStarter(aContent);
+}
+
+// -----------------------------------------------------------------------------
+// BackgroundChildImpl Public Methods
+// -----------------------------------------------------------------------------
+
+// static
+BackgroundChildImpl::ThreadLocal*
+BackgroundChildImpl::GetThreadLocalForCurrentThread() {
+ return ChildImpl::GetThreadLocalForCurrentThread();
+}
+
+// -----------------------------------------------------------------------------
+// ParentImpl Static Members
+// -----------------------------------------------------------------------------
+
+StaticRefPtr<nsIThread> ParentImpl::sBackgroundThread;
+
+nsTArray<IToplevelProtocol*>* ParentImpl::sLiveActorsForBackgroundThread;
+
+StaticRefPtr<nsITimer> ParentImpl::sShutdownTimer;
+
+Atomic<PRThread*> ParentImpl::sBackgroundPRThread;
+
+Atomic<uint64_t> ParentImpl::sLiveActorCount;
+
+bool ParentImpl::sShutdownObserverRegistered = false;
+
+bool ParentImpl::sShutdownHasStarted = false;
+
+// -----------------------------------------------------------------------------
+// ChildImpl Static Members
+// -----------------------------------------------------------------------------
+
+ChildImpl::ThreadInfoWrapper ChildImpl::sParentAndContentProcessThreadInfo;
+
+bool ChildImpl::sShutdownHasStarted = false;
+
+// -----------------------------------------------------------------------------
+// ParentImpl Implementation
+// -----------------------------------------------------------------------------
+
+// static
+bool ParentImpl::IsOtherProcessActor(PBackgroundParent* aBackgroundActor) {
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aBackgroundActor);
+
+ return static_cast<ParentImpl*>(aBackgroundActor)->mIsOtherProcessActor;
+}
+
+// static
+ThreadsafeContentParentHandle* ParentImpl::GetContentParentHandle(
+ PBackgroundParent* aBackgroundActor) {
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aBackgroundActor);
+
+ return static_cast<ParentImpl*>(aBackgroundActor)->mContent.get();
+}
+
+// static
+uint64_t ParentImpl::GetChildID(PBackgroundParent* aBackgroundActor) {
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aBackgroundActor);
+
+ auto actor = static_cast<ParentImpl*>(aBackgroundActor);
+ if (actor->mContent) {
+ return actor->mContent->ChildID();
+ }
+
+ return 0;
+}
+
+// static
+void ParentImpl::KillHardAsync(PBackgroundParent* aBackgroundActor,
+ const nsACString& aReason) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aBackgroundActor);
+ MOZ_ASSERT(BackgroundParent::IsOtherProcessActor(aBackgroundActor));
+
+ RefPtr<ThreadsafeContentParentHandle> handle =
+ GetContentParentHandle(aBackgroundActor);
+ MOZ_ASSERT(handle);
+
+ MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
+ NS_NewRunnableFunction(
+ "ParentImpl::KillHardAsync",
+ [handle = std::move(handle), reason = nsCString{aReason}]() {
+ mozilla::AssertIsOnMainThread();
+
+ if (RefPtr<ContentParent> contentParent =
+ handle->GetContentParent()) {
+ contentParent->KillHard(reason.get());
+ }
+ }),
+ NS_DISPATCH_NORMAL));
+
+ // After we've scheduled killing of the remote process, also ensure we induce
+ // a connection error in the IPC channel to immediately stop all IPC
+ // communication on this channel.
+ if (aBackgroundActor->CanSend()) {
+ aBackgroundActor->GetIPCChannel()->InduceConnectionError();
+ }
+}
+
+// static
+bool ParentImpl::AllocStarter(ContentParent* aContent,
+ Endpoint<PBackgroundStarterParent>&& aEndpoint,
+ bool aCrossProcess) {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+
+ MOZ_ASSERT(aEndpoint.IsValid());
+
+ if (!sBackgroundThread && !CreateBackgroundThread()) {
+ NS_WARNING("Failed to create background thread!");
+ return false;
+ }
+
+ sLiveActorCount++;
+
+ RefPtr<BackgroundStarterParent> actor = new BackgroundStarterParent(
+ aContent ? aContent->ThreadsafeHandle() : nullptr, aCrossProcess);
+
+ if (NS_FAILED(sBackgroundThread->Dispatch(NS_NewRunnableFunction(
+ "BackgroundStarterParent::ConnectActorRunnable",
+ [actor = std::move(actor), endpoint = std::move(aEndpoint),
+ liveActorArray = sLiveActorsForBackgroundThread]() mutable {
+ MOZ_ASSERT(endpoint.IsValid());
+ MOZ_ALWAYS_TRUE(endpoint.Bind(actor));
+ actor->SetLiveActorArray(liveActorArray);
+ })))) {
+ NS_WARNING("Failed to dispatch connect runnable!");
+
+ MOZ_ASSERT(sLiveActorCount);
+ sLiveActorCount--;
+ }
+
+ return true;
+}
+
+// static
+bool ParentImpl::CreateBackgroundThread() {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT(!sBackgroundThread);
+ MOZ_ASSERT(!sLiveActorsForBackgroundThread);
+
+ if (sShutdownHasStarted) {
+ NS_WARNING(
+ "Trying to create background thread after shutdown has "
+ "already begun!");
+ return false;
+ }
+
+ nsCOMPtr<nsITimer> newShutdownTimer;
+
+ if (!sShutdownTimer) {
+ newShutdownTimer = NS_NewTimer();
+ if (!newShutdownTimer) {
+ return false;
+ }
+ }
+
+ if (!sShutdownObserverRegistered) {
+ nsCOMPtr<nsIObserverService> obs = services::GetObserverService();
+ if (NS_WARN_IF(!obs)) {
+ return false;
+ }
+
+ nsCOMPtr<nsIObserver> observer = new ShutdownObserver();
+
+ nsresult rv = obs->AddObserver(
+ observer, NS_XPCOM_SHUTDOWN_THREADS_OBSERVER_ID, false);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return false;
+ }
+
+ sShutdownObserverRegistered = true;
+ }
+
+ nsCOMPtr<nsIThread> thread;
+ if (NS_FAILED(NS_NewNamedThread(
+ "IPDL Background", getter_AddRefs(thread),
+ NS_NewRunnableFunction(
+ "Background::ParentImpl::CreateBackgroundThreadRunnable", []() {
+ DebugOnly<PRThread*> oldBackgroundThread =
+ sBackgroundPRThread.exchange(PR_GetCurrentThread());
+
+ MOZ_ASSERT_IF(oldBackgroundThread,
+ PR_GetCurrentThread() != oldBackgroundThread);
+ })))) {
+ NS_WARNING("NS_NewNamedThread failed!");
+ return false;
+ }
+
+ sBackgroundThread = thread.forget();
+
+ sLiveActorsForBackgroundThread = new nsTArray<IToplevelProtocol*>(1);
+
+ if (!sShutdownTimer) {
+ MOZ_ASSERT(newShutdownTimer);
+ sShutdownTimer = newShutdownTimer;
+ }
+
+ return true;
+}
+
+// static
+void ParentImpl::ShutdownBackgroundThread() {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT(sShutdownHasStarted);
+ MOZ_ASSERT_IF(!sBackgroundThread, !sLiveActorCount);
+ MOZ_ASSERT_IF(sBackgroundThread, sShutdownTimer);
+
+ nsCOMPtr<nsITimer> shutdownTimer = sShutdownTimer.get();
+ sShutdownTimer = nullptr;
+
+ if (sBackgroundThread) {
+ nsCOMPtr<nsIThread> thread = sBackgroundThread.get();
+ sBackgroundThread = nullptr;
+
+ UniquePtr<nsTArray<IToplevelProtocol*>> liveActors(
+ sLiveActorsForBackgroundThread);
+ sLiveActorsForBackgroundThread = nullptr;
+
+ MOZ_ASSERT_IF(!sShutdownHasStarted, !sLiveActorCount);
+
+ if (sLiveActorCount) {
+ // We need to spin the event loop while we wait for all the actors to be
+ // cleaned up. We also set a timeout to force-kill any hanging actors.
+ TimerCallbackClosure closure(thread, liveActors.get());
+
+ MOZ_ALWAYS_SUCCEEDS(shutdownTimer->InitWithNamedFuncCallback(
+ &ShutdownTimerCallback, &closure, kShutdownTimerDelayMS,
+ nsITimer::TYPE_ONE_SHOT, "ParentImpl::ShutdownTimerCallback"));
+
+ SpinEventLoopUntil("ParentImpl::ShutdownBackgroundThread"_ns,
+ [&]() { return !sLiveActorCount; });
+
+ MOZ_ASSERT(liveActors->IsEmpty());
+
+ MOZ_ALWAYS_SUCCEEDS(shutdownTimer->Cancel());
+ }
+
+ // Dispatch this runnable to unregister the PR thread from the profiler.
+ MOZ_ALWAYS_SUCCEEDS(thread->Dispatch(NS_NewRunnableFunction(
+ "Background::ParentImpl::ShutdownBackgroundThreadRunnable", []() {
+ // It is possible that another background thread was created while
+ // this thread was shutting down. In that case we can't assert
+ // anything about sBackgroundPRThread and we should not modify it
+ // here.
+ sBackgroundPRThread.compareExchange(PR_GetCurrentThread(), nullptr);
+ })));
+
+ MOZ_ALWAYS_SUCCEEDS(thread->Shutdown());
+ }
+}
+
+// static
+void ParentImpl::ShutdownTimerCallback(nsITimer* aTimer, void* aClosure) {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT(sShutdownHasStarted);
+ MOZ_ASSERT(sLiveActorCount);
+
+ auto closure = static_cast<TimerCallbackClosure*>(aClosure);
+ MOZ_ASSERT(closure);
+
+ // Don't let the stack unwind until the ForceCloseBackgroundActorsRunnable has
+ // finished.
+ sLiveActorCount++;
+
+ InvokeAsync(
+ closure->mThread, __func__,
+ [liveActors = closure->mLiveActors]() {
+ MOZ_ASSERT(liveActors);
+
+ if (!liveActors->IsEmpty()) {
+ // Copy the array since calling Close() could mutate the
+ // actual array.
+ nsTArray<IToplevelProtocol*> actorsToClose(liveActors->Clone());
+ for (IToplevelProtocol* actor : actorsToClose) {
+ actor->Close();
+ }
+ }
+ return GenericPromise::CreateAndResolve(true, __func__);
+ })
+ ->Then(GetCurrentSerialEventTarget(), __func__, []() {
+ MOZ_ASSERT(sLiveActorCount);
+ sLiveActorCount--;
+ });
+}
+
+void ParentImpl::Destroy() {
+ // May be called on any thread!
+
+ AssertIsInMainProcess();
+
+ MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
+ NewNonOwningRunnableMethod("ParentImpl::MainThreadActorDestroy", this,
+ &ParentImpl::MainThreadActorDestroy)));
+}
+
+void ParentImpl::MainThreadActorDestroy() {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT_IF(!mIsOtherProcessActor, !mContent);
+
+ MOZ_ASSERT(sLiveActorCount);
+ sLiveActorCount--;
+
+ // This may be the last reference!
+ Release();
+}
+
+void ParentImpl::ActorDestroy(ActorDestroyReason aWhy) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(!mActorDestroyed);
+ MOZ_ASSERT_IF(mIsOtherProcessActor, mLiveActorArray);
+
+ BackgroundParentImpl::ActorDestroy(aWhy);
+
+ mActorDestroyed = true;
+
+ if (mLiveActorArray) {
+ MOZ_ALWAYS_TRUE(mLiveActorArray->RemoveElement(this));
+ mLiveActorArray = nullptr;
+ }
+
+ // This is tricky. We should be able to call Destroy() here directly because
+ // we're not going to touch 'this' or our MessageChannel any longer on this
+ // thread. Destroy() dispatches the MainThreadActorDestroy runnable and when
+ // it runs it will destroy 'this' and our associated MessageChannel. However,
+ // IPDL is about to call MessageChannel::Clear() on this thread! To avoid
+ // racing with the main thread we must ensure that the MessageChannel lives
+ // long enough to be cleared in this call stack.
+
+ MOZ_ALWAYS_SUCCEEDS(NS_DispatchToCurrentThread(NewNonOwningRunnableMethod(
+ "ParentImpl::Destroy", this, &ParentImpl::Destroy)));
+}
+
+NS_IMPL_ISUPPORTS(ParentImpl::ShutdownObserver, nsIObserver)
+
+NS_IMETHODIMP
+ParentImpl::ShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
+ const char16_t* aData) {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+ MOZ_ASSERT(!sShutdownHasStarted);
+ MOZ_ASSERT(!strcmp(aTopic, NS_XPCOM_SHUTDOWN_THREADS_OBSERVER_ID));
+
+ sShutdownHasStarted = true;
+
+ // Do this first before calling (and spinning the event loop in)
+ // ShutdownBackgroundThread().
+ ChildImpl::Shutdown();
+
+ ShutdownBackgroundThread();
+
+ return NS_OK;
+}
+
+BackgroundStarterParent::BackgroundStarterParent(
+ ThreadsafeContentParentHandle* aContent, bool aCrossProcess)
+ : mCrossProcess(aCrossProcess), mContent(aContent) {
+ AssertIsOnMainThread();
+ AssertIsInMainProcess();
+ MOZ_ASSERT_IF(!mCrossProcess, !mContent);
+ MOZ_ASSERT_IF(!mCrossProcess, XRE_IsParentProcess());
+}
+
+void BackgroundStarterParent::SetLiveActorArray(
+ nsTArray<IToplevelProtocol*>* aLiveActorArray) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aLiveActorArray);
+ MOZ_ASSERT(!aLiveActorArray->Contains(this));
+ MOZ_ASSERT(!mLiveActorArray);
+ MOZ_ASSERT_IF(!mCrossProcess, OtherPid() == base::GetCurrentProcId());
+
+ mLiveActorArray = aLiveActorArray;
+ mLiveActorArray->AppendElement(this);
+}
+
+IPCResult BackgroundStarterParent::RecvInitBackground(
+ Endpoint<PBackgroundParent>&& aEndpoint) {
+ AssertIsOnBackgroundThread();
+
+ if (!aEndpoint.IsValid()) {
+ return IPC_FAIL(this,
+ "Cannot initialize PBackground with invalid endpoint");
+ }
+
+ ParentImpl* actor = new ParentImpl(mContent, mCrossProcess);
+
+ // Take a reference on this thread. If Open() fails then we will release this
+ // reference in Destroy.
+ NS_ADDREF(actor);
+
+ ParentImpl::sLiveActorCount++;
+
+ if (!aEndpoint.Bind(actor)) {
+ actor->Destroy();
+ return IPC_OK();
+ }
+
+ if (mCrossProcess) {
+ actor->SetLiveActorArray(mLiveActorArray);
+ }
+ return IPC_OK();
+}
+
+void BackgroundStarterParent::ActorDestroy(ActorDestroyReason aReason) {
+ AssertIsOnBackgroundThread();
+
+ if (mLiveActorArray) {
+ MOZ_ALWAYS_TRUE(mLiveActorArray->RemoveElement(this));
+ mLiveActorArray = nullptr;
+ }
+
+ // Make sure to decrement `sLiveActorCount` on the main thread.
+ MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(
+ NS_NewRunnableFunction("BackgroundStarterParent::MainThreadDestroy",
+ [] { ParentImpl::sLiveActorCount--; })));
+}
+
+// -----------------------------------------------------------------------------
+// ChildImpl Implementation
+// -----------------------------------------------------------------------------
+
+// static
+void ChildImpl::Startup() {
+ // This happens on the main thread but before XPCOM has started so we can't
+ // assert that we're being called on the main thread here.
+
+ sParentAndContentProcessThreadInfo.Startup();
+
+ nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
+ MOZ_RELEASE_ASSERT(observerService);
+
+ nsCOMPtr<nsIObserver> observer = new ShutdownObserver();
+
+ nsresult rv = observerService->AddObserver(
+ observer, NS_XPCOM_SHUTDOWN_THREADS_OBSERVER_ID, false);
+ MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
+
+ // Initialize a starter actor to allow starting PBackground within the parent
+ // process.
+ if (XRE_IsParentProcess()) {
+ Endpoint<PBackgroundStarterParent> parent;
+ Endpoint<PBackgroundStarterChild> child;
+ MOZ_ALWAYS_SUCCEEDS(PBackgroundStarter::CreateEndpoints(
+ base::GetCurrentProcId(), base::GetCurrentProcId(), &parent, &child));
+
+ MOZ_ALWAYS_TRUE(ParentImpl::AllocStarter(nullptr, std::move(parent),
+ /* aCrossProcess */ false));
+ sParentAndContentProcessThreadInfo.InitStarter(std::move(child));
+ }
+}
+
+// static
+void ChildImpl::Shutdown() {
+ AssertIsOnMainThread();
+
+ sParentAndContentProcessThreadInfo.Shutdown();
+
+ sShutdownHasStarted = true;
+}
+
+// static
+PBackgroundChild* ChildImpl::GetForCurrentThread() {
+ MOZ_ASSERT(sParentAndContentProcessThreadInfo.mThreadLocalIndex !=
+ kBadThreadLocalIndex);
+
+ auto threadLocalInfo =
+ NS_IsMainThread()
+ ? sParentAndContentProcessThreadInfo.mMainThreadInfo
+ : static_cast<ThreadLocalInfo*>(PR_GetThreadPrivate(
+ sParentAndContentProcessThreadInfo.mThreadLocalIndex));
+
+ if (!threadLocalInfo) {
+ return nullptr;
+ }
+
+ return threadLocalInfo->mActor;
+}
+
+/* static */
+PBackgroundChild* ChildImpl::GetOrCreateForCurrentThread() {
+ return sParentAndContentProcessThreadInfo.GetOrCreateForCurrentThread();
+}
+
+// static
+void ChildImpl::CloseForCurrentThread() {
+ MOZ_ASSERT(!NS_IsMainThread(),
+ "PBackground for the main thread should be shut down via "
+ "ChildImpl::Shutdown().");
+
+ sParentAndContentProcessThreadInfo.CloseForCurrentThread();
+}
+
+// static
+BackgroundChildImpl::ThreadLocal* ChildImpl::GetThreadLocalForCurrentThread() {
+ MOZ_ASSERT(sParentAndContentProcessThreadInfo.mThreadLocalIndex !=
+ kBadThreadLocalIndex,
+ "BackgroundChild::Startup() was never called!");
+
+ auto threadLocalInfo =
+ NS_IsMainThread()
+ ? sParentAndContentProcessThreadInfo.mMainThreadInfo
+ : static_cast<ThreadLocalInfo*>(PR_GetThreadPrivate(
+ sParentAndContentProcessThreadInfo.mThreadLocalIndex));
+
+ if (!threadLocalInfo) {
+ return nullptr;
+ }
+
+ if (!threadLocalInfo->mConsumerThreadLocal) {
+ threadLocalInfo->mConsumerThreadLocal =
+ MakeUnique<BackgroundChildImpl::ThreadLocal>();
+ }
+
+ return threadLocalInfo->mConsumerThreadLocal.get();
+}
+
+// static
+void ChildImpl::InitContentStarter(mozilla::dom::ContentChild* aContent) {
+ sParentAndContentProcessThreadInfo.InitStarter(aContent);
+}
+
+// static
+void ChildImpl::ThreadLocalDestructor(void* aThreadLocal) {
+ auto threadLocalInfo = static_cast<ThreadLocalInfo*>(aThreadLocal);
+
+ if (threadLocalInfo) {
+ MOZ_ASSERT(threadLocalInfo->mClosed);
+
+ if (threadLocalInfo->mActor) {
+ threadLocalInfo->mActor->Close();
+ threadLocalInfo->mActor->AssertActorDestroyed();
+ }
+
+ delete threadLocalInfo;
+ }
+}
+
+void ChildImpl::ActorDestroy(ActorDestroyReason aWhy) {
+ AssertIsOnOwningThread();
+
+#ifdef DEBUG
+ MOZ_ASSERT(!mActorDestroyed);
+ mActorDestroyed = true;
+#endif
+
+ BackgroundChildImpl::ActorDestroy(aWhy);
+}
+
+NS_IMPL_ISUPPORTS(ChildImpl::ShutdownObserver, nsIObserver)
+
+NS_IMETHODIMP
+ChildImpl::ShutdownObserver::Observe(nsISupports* aSubject, const char* aTopic,
+ const char16_t* aData) {
+ AssertIsOnMainThread();
+ MOZ_ASSERT(!strcmp(aTopic, NS_XPCOM_SHUTDOWN_THREADS_OBSERVER_ID));
+
+ ChildImpl::Shutdown();
+
+ return NS_OK;
+}
diff --git a/ipc/glue/BackgroundParent.h b/ipc/glue/BackgroundParent.h
new file mode 100644
index 0000000000..6afad501af
--- /dev/null
+++ b/ipc/glue/BackgroundParent.h
@@ -0,0 +1,112 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_backgroundparent_h__
+#define mozilla_ipc_backgroundparent_h__
+
+#include "base/process.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/dom/ContentParent.h"
+#include "nsStringFwd.h"
+#include "nsTArrayForwardDeclare.h"
+
+#ifdef DEBUG
+# include "nsXULAppAPI.h"
+#endif
+
+template <class>
+struct already_AddRefed;
+
+namespace mozilla {
+
+namespace net {
+
+class SocketProcessBridgeParent;
+class SocketProcessParent;
+
+} // namespace net
+
+namespace dom {
+
+class BlobImpl;
+class ContentParent;
+
+} // namespace dom
+
+namespace ipc {
+
+class BackgroundStarterParent;
+class PBackgroundParent;
+class PBackgroundStarterParent;
+
+template <class PFooSide>
+class Endpoint;
+
+// This class is not designed for public consumption beyond the few static
+// member functions.
+class BackgroundParent final {
+ friend class mozilla::ipc::BackgroundStarterParent;
+ friend class mozilla::dom::ContentParent;
+ friend class mozilla::net::SocketProcessBridgeParent;
+ friend class mozilla::net::SocketProcessParent;
+
+ using ProcessId = base::ProcessId;
+ using BlobImpl = mozilla::dom::BlobImpl;
+ using ContentParent = mozilla::dom::ContentParent;
+ using ThreadsafeContentParentHandle =
+ mozilla::dom::ThreadsafeContentParentHandle;
+
+ public:
+ // This function allows the caller to determine if the given parent actor
+ // corresponds to a child actor from another process or a child actor from a
+ // different thread in the same process.
+ // This function may only be called on the background thread.
+ static bool IsOtherProcessActor(PBackgroundParent* aBackgroundActor);
+
+ // This function returns a handle to the ContentParent associated with the
+ // parent actor if the parent actor corresponds to a child actor from another
+ // content process. If the parent actor corresponds to a child actor from a
+ // different thread in the same process then this function returns null.
+ //
+ // This function may only be called on the background thread.
+ static ThreadsafeContentParentHandle* GetContentParentHandle(
+ PBackgroundParent* aBackgroundActor);
+
+ static uint64_t GetChildID(PBackgroundParent* aBackgroundActor);
+
+ static void KillHardAsync(PBackgroundParent* aBackgroundActor,
+ const nsACString& aReason);
+
+ private:
+ // Only called by ContentParent for cross-process actors.
+ static bool AllocStarter(ContentParent* aContent,
+ Endpoint<PBackgroundStarterParent>&& aEndpoint);
+
+ // Called by SocketProcessBridgeParent and SocketProcessParent for
+ // cross-process actors.
+ static bool AllocStarter(Endpoint<PBackgroundStarterParent>&& aEndpoint);
+};
+
+// Implemented in BackgroundImpl.cpp.
+bool IsOnBackgroundThread();
+
+#ifdef DEBUG
+
+// Implemented in BackgroundImpl.cpp.
+void AssertIsOnBackgroundThread();
+
+#else
+
+inline void AssertIsOnBackgroundThread() {}
+
+#endif // DEBUG
+
+inline void AssertIsInMainProcess() { MOZ_ASSERT(XRE_IsParentProcess()); }
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_backgroundparent_h__
diff --git a/ipc/glue/BackgroundParentImpl.cpp b/ipc/glue/BackgroundParentImpl.cpp
new file mode 100644
index 0000000000..e9d0adbb94
--- /dev/null
+++ b/ipc/glue/BackgroundParentImpl.cpp
@@ -0,0 +1,1397 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "BackgroundParentImpl.h"
+
+#include "BroadcastChannelParent.h"
+#ifdef MOZ_WEBRTC
+# include "CamerasParent.h"
+#endif
+#include "mozilla/Assertions.h"
+#include "mozilla/RDDProcessManager.h"
+#include "mozilla/ipc/UtilityProcessManager.h"
+#include "mozilla/RemoteDecodeUtils.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/dom/BackgroundSessionStorageServiceParent.h"
+#include "mozilla/dom/ClientManagerActors.h"
+#include "mozilla/dom/ContentParent.h"
+#include "mozilla/dom/DOMTypes.h"
+#include "mozilla/dom/EndpointForReportParent.h"
+#include "mozilla/dom/FetchParent.h"
+#include "mozilla/dom/FileCreatorParent.h"
+#include "mozilla/dom/FileSystemManagerParentFactory.h"
+#include "mozilla/dom/FileSystemRequestParent.h"
+#include "mozilla/dom/GamepadEventChannelParent.h"
+#include "mozilla/dom/GamepadTestChannelParent.h"
+#include "mozilla/dom/MIDIManagerParent.h"
+#include "mozilla/dom/MIDIPlatformService.h"
+#include "mozilla/dom/MIDIPortParent.h"
+#include "mozilla/dom/MessagePortParent.h"
+#include "mozilla/dom/PGamepadEventChannelParent.h"
+#include "mozilla/dom/PGamepadTestChannelParent.h"
+#include "mozilla/dom/RemoteWorkerControllerParent.h"
+#include "mozilla/dom/RemoteWorkerServiceParent.h"
+#include "mozilla/dom/ReportingHeader.h"
+#include "mozilla/dom/ServiceWorkerActors.h"
+#include "mozilla/dom/ServiceWorkerContainerParent.h"
+#include "mozilla/dom/ServiceWorkerManagerParent.h"
+#include "mozilla/dom/ServiceWorkerParent.h"
+#include "mozilla/dom/ServiceWorkerRegistrar.h"
+#include "mozilla/dom/ServiceWorkerRegistrationParent.h"
+#include "mozilla/dom/SessionStorageManager.h"
+#include "mozilla/dom/SharedWorkerParent.h"
+#include "mozilla/dom/StorageActivityService.h"
+#include "mozilla/dom/StorageIPC.h"
+#include "mozilla/dom/TemporaryIPCBlobParent.h"
+#include "mozilla/dom/WebAuthnTransactionParent.h"
+#include "mozilla/dom/WebTransportParent.h"
+#include "mozilla/dom/cache/ActorUtils.h"
+#include "mozilla/dom/indexedDB/ActorsParent.h"
+#include "mozilla/dom/locks/LockManagerParent.h"
+#include "mozilla/dom/localstorage/ActorsParent.h"
+#include "mozilla/dom/network/UDPSocketParent.h"
+#include "mozilla/dom/quota/ActorsParent.h"
+#include "mozilla/dom/quota/QuotaParent.h"
+#include "mozilla/dom/simpledb/ActorsParent.h"
+#include "mozilla/dom/VsyncParent.h"
+#include "mozilla/ipc/BackgroundParent.h"
+#include "mozilla/ipc/BackgroundUtils.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/IdleSchedulerParent.h"
+#include "mozilla/ipc/PBackgroundSharedTypes.h"
+#include "mozilla/ipc/PBackgroundTestParent.h"
+#include "mozilla/net/BackgroundDataBridgeParent.h"
+#include "mozilla/net/HttpBackgroundChannelParent.h"
+#include "nsIHttpChannelInternal.h"
+#include "nsIPrincipal.h"
+#include "nsProxyRelease.h"
+#include "nsThreadUtils.h"
+#include "nsXULAppAPI.h"
+
+using mozilla::AssertIsOnMainThread;
+using mozilla::dom::FileSystemRequestParent;
+using mozilla::dom::MessagePortParent;
+using mozilla::dom::MIDIManagerParent;
+using mozilla::dom::MIDIPlatformService;
+using mozilla::dom::MIDIPortParent;
+using mozilla::dom::PMessagePortParent;
+using mozilla::dom::PMIDIManagerParent;
+using mozilla::dom::PMIDIPortParent;
+using mozilla::dom::PServiceWorkerContainerParent;
+using mozilla::dom::PServiceWorkerParent;
+using mozilla::dom::PServiceWorkerRegistrationParent;
+using mozilla::dom::ServiceWorkerParent;
+using mozilla::dom::UDPSocketParent;
+using mozilla::dom::WebAuthnTransactionParent;
+using mozilla::dom::cache::PCacheParent;
+using mozilla::dom::cache::PCacheStorageParent;
+using mozilla::dom::cache::PCacheStreamControlParent;
+using mozilla::ipc::AssertIsOnBackgroundThread;
+
+namespace {
+
+class TestParent final : public mozilla::ipc::PBackgroundTestParent {
+ friend class mozilla::ipc::BackgroundParentImpl;
+
+ MOZ_COUNTED_DEFAULT_CTOR(TestParent)
+
+ protected:
+ ~TestParent() override { MOZ_COUNT_DTOR(TestParent); }
+
+ public:
+ void ActorDestroy(ActorDestroyReason aWhy) override;
+};
+
+} // namespace
+
+namespace mozilla::ipc {
+
+using mozilla::dom::BroadcastChannelParent;
+using mozilla::dom::ContentParent;
+using mozilla::dom::ThreadsafeContentParentHandle;
+
+BackgroundParentImpl::BackgroundParentImpl() {
+ AssertIsInMainProcess();
+
+ MOZ_COUNT_CTOR(mozilla::ipc::BackgroundParentImpl);
+}
+
+BackgroundParentImpl::~BackgroundParentImpl() {
+ AssertIsInMainProcess();
+ AssertIsOnMainThread();
+
+ MOZ_COUNT_DTOR(mozilla::ipc::BackgroundParentImpl);
+}
+
+void BackgroundParentImpl::ProcessingError(Result aCode, const char* aReason) {
+ if (MsgDropped == aCode) {
+ return;
+ }
+
+ // XXX Remove this cut-out once bug 1858621 is fixed. Some parent actors
+ // currently return nullptr in actor allocation methods for non fatal errors.
+ // We don't want to crash the parent process or child processes in that case.
+ if (MsgValueError == aCode) {
+ return;
+ }
+
+ // Other errors are big deals.
+ nsDependentCString reason(aReason);
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+#ifndef FUZZING
+ BackgroundParent::KillHardAsync(this, reason);
+#endif
+ if (CanSend()) {
+ GetIPCChannel()->InduceConnectionError();
+ }
+ } else {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::ipc_channel_error, reason);
+
+ MOZ_CRASH("in-process BackgroundParent abort due to IPC error");
+ }
+}
+
+void BackgroundParentImpl::ActorDestroy(ActorDestroyReason aWhy) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+}
+
+BackgroundParentImpl::PBackgroundTestParent*
+BackgroundParentImpl::AllocPBackgroundTestParent(const nsACString& aTestArg) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return new TestParent();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPBackgroundTestConstructor(
+ PBackgroundTestParent* aActor, const nsACString& aTestArg) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!PBackgroundTestParent::Send__delete__(aActor, aTestArg)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundTestParent(
+ PBackgroundTestParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ delete static_cast<TestParent*>(aActor);
+ return true;
+}
+
+auto BackgroundParentImpl::AllocPBackgroundIDBFactoryParent(
+ const LoggingInfo& aLoggingInfo)
+ -> already_AddRefed<PBackgroundIDBFactoryParent> {
+ using mozilla::dom::indexedDB::AllocPBackgroundIDBFactoryParent;
+
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return AllocPBackgroundIDBFactoryParent(aLoggingInfo);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundIDBFactoryConstructor(
+ PBackgroundIDBFactoryParent* aActor, const LoggingInfo& aLoggingInfo) {
+ using mozilla::dom::indexedDB::RecvPBackgroundIDBFactoryConstructor;
+
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!RecvPBackgroundIDBFactoryConstructor(aActor, aLoggingInfo)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+auto BackgroundParentImpl::AllocPBackgroundIndexedDBUtilsParent()
+ -> PBackgroundIndexedDBUtilsParent* {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::indexedDB::AllocPBackgroundIndexedDBUtilsParent();
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundIndexedDBUtilsParent(
+ PBackgroundIndexedDBUtilsParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::indexedDB::DeallocPBackgroundIndexedDBUtilsParent(
+ aActor);
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvFlushPendingFileDeletions() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (!mozilla::dom::indexedDB::RecvFlushPendingFileDeletions()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+already_AddRefed<BackgroundParentImpl::PBackgroundSDBConnectionParent>
+BackgroundParentImpl::AllocPBackgroundSDBConnectionParent(
+ const PersistenceType& aPersistenceType,
+ const PrincipalInfo& aPrincipalInfo) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundSDBConnectionParent(aPersistenceType,
+ aPrincipalInfo);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundSDBConnectionConstructor(
+ PBackgroundSDBConnectionParent* aActor,
+ const PersistenceType& aPersistenceType,
+ const PrincipalInfo& aPrincipalInfo) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!mozilla::dom::RecvPBackgroundSDBConnectionConstructor(
+ aActor, aPersistenceType, aPrincipalInfo)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+already_AddRefed<BackgroundParentImpl::PBackgroundLSDatabaseParent>
+BackgroundParentImpl::AllocPBackgroundLSDatabaseParent(
+ const PrincipalInfo& aPrincipalInfo, const uint32_t& aPrivateBrowsingId,
+ const uint64_t& aDatastoreId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundLSDatabaseParent(
+ aPrincipalInfo, aPrivateBrowsingId, aDatastoreId);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundLSDatabaseConstructor(
+ PBackgroundLSDatabaseParent* aActor, const PrincipalInfo& aPrincipalInfo,
+ const uint32_t& aPrivateBrowsingId, const uint64_t& aDatastoreId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!mozilla::dom::RecvPBackgroundLSDatabaseConstructor(
+ aActor, aPrincipalInfo, aPrivateBrowsingId, aDatastoreId)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+BackgroundParentImpl::PBackgroundLSObserverParent*
+BackgroundParentImpl::AllocPBackgroundLSObserverParent(
+ const uint64_t& aObserverId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundLSObserverParent(aObserverId);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundLSObserverConstructor(
+ PBackgroundLSObserverParent* aActor, const uint64_t& aObserverId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!mozilla::dom::RecvPBackgroundLSObserverConstructor(aActor,
+ aObserverId)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundLSObserverParent(
+ PBackgroundLSObserverParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::DeallocPBackgroundLSObserverParent(aActor);
+}
+
+BackgroundParentImpl::PBackgroundLSRequestParent*
+BackgroundParentImpl::AllocPBackgroundLSRequestParent(
+ const LSRequestParams& aParams) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundLSRequestParent(this, aParams);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundLSRequestConstructor(
+ PBackgroundLSRequestParent* aActor, const LSRequestParams& aParams) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!mozilla::dom::RecvPBackgroundLSRequestConstructor(aActor, aParams)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundLSRequestParent(
+ PBackgroundLSRequestParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::DeallocPBackgroundLSRequestParent(aActor);
+}
+
+BackgroundParentImpl::PBackgroundLSSimpleRequestParent*
+BackgroundParentImpl::AllocPBackgroundLSSimpleRequestParent(
+ const LSSimpleRequestParams& aParams) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundLSSimpleRequestParent(this, aParams);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundLSSimpleRequestConstructor(
+ PBackgroundLSSimpleRequestParent* aActor,
+ const LSSimpleRequestParams& aParams) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ if (!mozilla::dom::RecvPBackgroundLSSimpleRequestConstructor(aActor,
+ aParams)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundLSSimpleRequestParent(
+ PBackgroundLSSimpleRequestParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::DeallocPBackgroundLSSimpleRequestParent(aActor);
+}
+
+BackgroundParentImpl::PBackgroundLocalStorageCacheParent*
+BackgroundParentImpl::AllocPBackgroundLocalStorageCacheParent(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundLocalStorageCacheParent(
+ aPrincipalInfo, aOriginKey, aPrivateBrowsingId);
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPBackgroundLocalStorageCacheConstructor(
+ PBackgroundLocalStorageCacheParent* aActor,
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::RecvPBackgroundLocalStorageCacheConstructor(
+ this, aActor, aPrincipalInfo, aOriginKey, aPrivateBrowsingId);
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundLocalStorageCacheParent(
+ PBackgroundLocalStorageCacheParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::DeallocPBackgroundLocalStorageCacheParent(aActor);
+}
+
+auto BackgroundParentImpl::AllocPBackgroundStorageParent(
+ const nsAString& aProfilePath, const uint32_t& aPrivateBrowsingId)
+ -> PBackgroundStorageParent* {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::AllocPBackgroundStorageParent(aProfilePath,
+ aPrivateBrowsingId);
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPBackgroundStorageConstructor(
+ PBackgroundStorageParent* aActor, const nsAString& aProfilePath,
+ const uint32_t& aPrivateBrowsingId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::RecvPBackgroundStorageConstructor(aActor, aProfilePath,
+ aPrivateBrowsingId);
+}
+
+bool BackgroundParentImpl::DeallocPBackgroundStorageParent(
+ PBackgroundStorageParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ return mozilla::dom::DeallocPBackgroundStorageParent(aActor);
+}
+
+already_AddRefed<BackgroundParentImpl::PBackgroundSessionStorageManagerParent>
+BackgroundParentImpl::AllocPBackgroundSessionStorageManagerParent(
+ const uint64_t& aTopContextId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return dom::AllocPBackgroundSessionStorageManagerParent(aTopContextId);
+}
+
+already_AddRefed<mozilla::dom::PBackgroundSessionStorageServiceParent>
+BackgroundParentImpl::AllocPBackgroundSessionStorageServiceParent() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return MakeAndAddRef<mozilla::dom::BackgroundSessionStorageServiceParent>();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvCreateFileSystemManagerParent(
+ const PrincipalInfo& aPrincipalInfo,
+ Endpoint<PFileSystemManagerParent>&& aParentEndpoint,
+ CreateFileSystemManagerParentResolver&& aResolver) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::CreateFileSystemManagerParent(
+ aPrincipalInfo, std::move(aParentEndpoint), std::move(aResolver));
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvCreateWebTransportParent(
+ const nsAString& aURL, nsIPrincipal* aPrincipal,
+ const mozilla::Maybe<IPCClientInfo>& aClientInfo, const bool& aDedicated,
+ const bool& aRequireUnreliable, const uint32_t& aCongestionControl,
+ nsTArray<WebTransportHash>&& aServerCertHashes,
+ Endpoint<PWebTransportParent>&& aParentEndpoint,
+ CreateWebTransportParentResolver&& aResolver) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<mozilla::dom::WebTransportParent> webt =
+ new mozilla::dom::WebTransportParent();
+ webt->Create(aURL, aPrincipal, aClientInfo, aDedicated, aRequireUnreliable,
+ aCongestionControl, std::move(aServerCertHashes),
+ std::move(aParentEndpoint), std::move(aResolver));
+ return IPC_OK();
+}
+
+already_AddRefed<PIdleSchedulerParent>
+BackgroundParentImpl::AllocPIdleSchedulerParent() {
+ AssertIsOnBackgroundThread();
+ RefPtr<IdleSchedulerParent> actor = new IdleSchedulerParent();
+ return actor.forget();
+}
+
+already_AddRefed<dom::PRemoteWorkerControllerParent>
+BackgroundParentImpl::AllocPRemoteWorkerControllerParent(
+ const dom::RemoteWorkerData& aRemoteWorkerData) {
+ RefPtr<dom::RemoteWorkerControllerParent> actor =
+ new dom::RemoteWorkerControllerParent(aRemoteWorkerData);
+ return actor.forget();
+}
+
+IPCResult BackgroundParentImpl::RecvPRemoteWorkerControllerConstructor(
+ dom::PRemoteWorkerControllerParent* aActor,
+ const dom::RemoteWorkerData& aRemoteWorkerData) {
+ MOZ_ASSERT(aActor);
+
+ return IPC_OK();
+}
+
+already_AddRefed<dom::PRemoteWorkerServiceParent>
+BackgroundParentImpl::AllocPRemoteWorkerServiceParent() {
+ return MakeAndAddRef<dom::RemoteWorkerServiceParent>();
+}
+
+IPCResult BackgroundParentImpl::RecvPRemoteWorkerServiceConstructor(
+ PRemoteWorkerServiceParent* aActor) {
+ mozilla::dom::RemoteWorkerServiceParent* actor =
+ static_cast<mozilla::dom::RemoteWorkerServiceParent*>(aActor);
+
+ RefPtr<ThreadsafeContentParentHandle> parent =
+ BackgroundParent::GetContentParentHandle(this);
+ // If the ContentParent is null we are dealing with a same-process actor.
+ if (!parent) {
+ actor->Initialize(NOT_REMOTE_TYPE);
+ } else {
+ actor->Initialize(parent->GetRemoteType());
+ }
+ return IPC_OK();
+}
+
+mozilla::dom::PSharedWorkerParent*
+BackgroundParentImpl::AllocPSharedWorkerParent(
+ const mozilla::dom::RemoteWorkerData& aData, const uint64_t& aWindowID,
+ const mozilla::dom::MessagePortIdentifier& aPortIdentifier) {
+ RefPtr<dom::SharedWorkerParent> agent =
+ new mozilla::dom::SharedWorkerParent();
+ return agent.forget().take();
+}
+
+IPCResult BackgroundParentImpl::RecvPSharedWorkerConstructor(
+ PSharedWorkerParent* aActor, const mozilla::dom::RemoteWorkerData& aData,
+ const uint64_t& aWindowID,
+ const mozilla::dom::MessagePortIdentifier& aPortIdentifier) {
+ mozilla::dom::SharedWorkerParent* actor =
+ static_cast<mozilla::dom::SharedWorkerParent*>(aActor);
+ actor->Initialize(aData, aWindowID, aPortIdentifier);
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPSharedWorkerParent(
+ mozilla::dom::PSharedWorkerParent* aActor) {
+ RefPtr<mozilla::dom::SharedWorkerParent> actor =
+ dont_AddRef(static_cast<mozilla::dom::SharedWorkerParent*>(aActor));
+ return true;
+}
+
+dom::PFileCreatorParent* BackgroundParentImpl::AllocPFileCreatorParent(
+ const nsAString& aFullPath, const nsAString& aType, const nsAString& aName,
+ const Maybe<int64_t>& aLastModified, const bool& aExistenceCheck,
+ const bool& aIsFromNsIFile) {
+ RefPtr<dom::FileCreatorParent> actor = new dom::FileCreatorParent();
+ return actor.forget().take();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPFileCreatorConstructor(
+ dom::PFileCreatorParent* aActor, const nsAString& aFullPath,
+ const nsAString& aType, const nsAString& aName,
+ const Maybe<int64_t>& aLastModified, const bool& aExistenceCheck,
+ const bool& aIsFromNsIFile) {
+ bool isFileRemoteType = false;
+
+ // If the ContentParentHandle is null we are dealing with a same-process
+ // actor.
+ RefPtr<ThreadsafeContentParentHandle> parent =
+ BackgroundParent::GetContentParentHandle(this);
+ if (!parent) {
+ isFileRemoteType = true;
+ } else {
+ isFileRemoteType = parent->GetRemoteType() == FILE_REMOTE_TYPE;
+ }
+
+ dom::FileCreatorParent* actor = static_cast<dom::FileCreatorParent*>(aActor);
+
+ // We allow the creation of File via this IPC call only for the 'file' process
+ // or for testing.
+ if (!isFileRemoteType && !StaticPrefs::dom_file_createInChild()) {
+ Unused << dom::FileCreatorParent::Send__delete__(
+ actor, dom::FileCreationErrorResult(NS_ERROR_DOM_INVALID_STATE_ERR));
+ return IPC_OK();
+ }
+
+ return actor->CreateAndShareFile(aFullPath, aType, aName, aLastModified,
+ aExistenceCheck, aIsFromNsIFile);
+}
+
+bool BackgroundParentImpl::DeallocPFileCreatorParent(
+ dom::PFileCreatorParent* aActor) {
+ RefPtr<dom::FileCreatorParent> actor =
+ dont_AddRef(static_cast<dom::FileCreatorParent*>(aActor));
+ return true;
+}
+
+dom::PTemporaryIPCBlobParent*
+BackgroundParentImpl::AllocPTemporaryIPCBlobParent() {
+ return new dom::TemporaryIPCBlobParent();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPTemporaryIPCBlobConstructor(
+ dom::PTemporaryIPCBlobParent* aActor) {
+ dom::TemporaryIPCBlobParent* actor =
+ static_cast<dom::TemporaryIPCBlobParent*>(aActor);
+ return actor->CreateAndShareFile();
+}
+
+bool BackgroundParentImpl::DeallocPTemporaryIPCBlobParent(
+ dom::PTemporaryIPCBlobParent* aActor) {
+ delete aActor;
+ return true;
+}
+
+already_AddRefed<BackgroundParentImpl::PVsyncParent>
+BackgroundParentImpl::AllocPVsyncParent() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<mozilla::dom::VsyncParent> actor = new mozilla::dom::VsyncParent();
+
+ RefPtr<mozilla::VsyncDispatcher> vsyncDispatcher =
+ gfxPlatform::GetPlatform()->GetGlobalVsyncDispatcher();
+ actor->UpdateVsyncDispatcher(vsyncDispatcher);
+ return actor.forget();
+}
+
+camera::PCamerasParent* BackgroundParentImpl::AllocPCamerasParent() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+#ifdef MOZ_WEBRTC
+ RefPtr<mozilla::camera::CamerasParent> actor =
+ mozilla::camera::CamerasParent::Create();
+ return actor.forget().take();
+#else
+ return nullptr;
+#endif
+}
+
+#ifdef MOZ_WEBRTC
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPCamerasConstructor(
+ camera::PCamerasParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+ return static_cast<camera::CamerasParent*>(aActor)->RecvPCamerasConstructor();
+}
+#endif
+
+bool BackgroundParentImpl::DeallocPCamerasParent(
+ camera::PCamerasParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+#ifdef MOZ_WEBRTC
+ RefPtr<mozilla::camera::CamerasParent> actor =
+ dont_AddRef(static_cast<mozilla::camera::CamerasParent*>(aActor));
+#endif
+ return true;
+}
+
+auto BackgroundParentImpl::AllocPUDPSocketParent(
+ const Maybe<PrincipalInfo>& /* unused */, const nsACString& /* unused */)
+ -> PUDPSocketParent* {
+ RefPtr<UDPSocketParent> p = new UDPSocketParent(this);
+
+ return p.forget().take();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPUDPSocketConstructor(
+ PUDPSocketParent* aActor, const Maybe<PrincipalInfo>& aOptionalPrincipal,
+ const nsACString& aFilter) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (aOptionalPrincipal.isSome()) {
+ // Support for checking principals (for non-mtransport use) will be handled
+ // in bug 1167039
+ return IPC_FAIL_NO_REASON(this);
+ }
+ // No principal - This must be from mtransport (WebRTC/ICE) - We'd want
+ // to DispatchToMainThread() here, but if we do we must block RecvBind()
+ // until Init() gets run. Since we don't have a principal, and we verify
+ // we have a filter, we can safely skip the Dispatch and just invoke Init()
+ // to install the filter.
+
+ // For mtransport, this will always be "stun", which doesn't allow outbound
+ // packets if they aren't STUN packets until a STUN response is seen.
+ if (!aFilter.EqualsASCII(NS_NETWORK_SOCKET_FILTER_HANDLER_STUN_SUFFIX)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!static_cast<UDPSocketParent*>(aActor)->Init(nullptr, aFilter)) {
+ MOZ_CRASH("UDPSocketCallback - failed init");
+ }
+
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPUDPSocketParent(PUDPSocketParent* actor) {
+ UDPSocketParent* p = static_cast<UDPSocketParent*>(actor);
+ p->Release();
+ return true;
+}
+
+mozilla::dom::PBroadcastChannelParent*
+BackgroundParentImpl::AllocPBroadcastChannelParent(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOrigin,
+ const nsAString& aChannel) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ nsString originChannelKey;
+
+ // The format of originChannelKey is:
+ // <channelName>|<origin+OriginAttributes>
+
+ originChannelKey.Assign(aChannel);
+
+ originChannelKey.AppendLiteral("|");
+
+ originChannelKey.Append(NS_ConvertUTF8toUTF16(aOrigin));
+
+ return new BroadcastChannelParent(originChannelKey);
+}
+
+namespace {
+
+class CheckPrincipalRunnable final : public Runnable {
+ public:
+ CheckPrincipalRunnable(
+ already_AddRefed<ThreadsafeContentParentHandle> aParent,
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOrigin)
+ : Runnable("ipc::CheckPrincipalRunnable"),
+ mContentParent(aParent),
+ mPrincipalInfo(aPrincipalInfo),
+ mOrigin(aOrigin) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ MOZ_ASSERT(mContentParent);
+ }
+
+ NS_IMETHOD Run() override {
+ AssertIsOnMainThread();
+ RefPtr<ContentParent> contentParent = mContentParent->GetContentParent();
+ if (!contentParent) {
+ return NS_OK;
+ }
+
+ auto principalOrErr = PrincipalInfoToPrincipal(mPrincipalInfo);
+ if (NS_WARN_IF(principalOrErr.isErr())) {
+ contentParent->KillHard(
+ "BroadcastChannel killed: PrincipalInfoToPrincipal failed.");
+ return NS_OK;
+ }
+
+ nsAutoCString origin;
+ nsresult rv = principalOrErr.unwrap()->GetOrigin(origin);
+ if (NS_FAILED(rv)) {
+ contentParent->KillHard(
+ "BroadcastChannel killed: principal::GetOrigin failed.");
+ return NS_OK;
+ }
+
+ if (NS_WARN_IF(!mOrigin.Equals(origin))) {
+ contentParent->KillHard("BroadcastChannel killed: origins do not match.");
+ return NS_OK;
+ }
+
+ return NS_OK;
+ }
+
+ private:
+ RefPtr<ThreadsafeContentParentHandle> mContentParent;
+ PrincipalInfo mPrincipalInfo;
+ nsCString mOrigin;
+};
+
+} // namespace
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPBroadcastChannelConstructor(
+ PBroadcastChannelParent* actor, const PrincipalInfo& aPrincipalInfo,
+ const nsACString& aOrigin, const nsAString& aChannel) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<ThreadsafeContentParentHandle> parent =
+ BackgroundParent::GetContentParentHandle(this);
+
+ // If the ContentParent is null we are dealing with a same-process actor.
+ if (!parent) {
+ return IPC_OK();
+ }
+
+ // XXX The principal can be checked right here on the PBackground thread
+ // since BackgroundParentImpl now overrides the ProcessingError method and
+ // kills invalid child processes (IPC_FAIL triggers a processing error).
+
+ RefPtr<CheckPrincipalRunnable> runnable =
+ new CheckPrincipalRunnable(parent.forget(), aPrincipalInfo, aOrigin);
+ MOZ_ALWAYS_SUCCEEDS(NS_DispatchToMainThread(runnable));
+
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPBroadcastChannelParent(
+ PBroadcastChannelParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ delete static_cast<BroadcastChannelParent*>(aActor);
+ return true;
+}
+
+mozilla::dom::PServiceWorkerManagerParent*
+BackgroundParentImpl::AllocPServiceWorkerManagerParent() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<dom::ServiceWorkerManagerParent> agent =
+ new dom::ServiceWorkerManagerParent();
+ return agent.forget().take();
+}
+
+bool BackgroundParentImpl::DeallocPServiceWorkerManagerParent(
+ PServiceWorkerManagerParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ RefPtr<dom::ServiceWorkerManagerParent> parent =
+ dont_AddRef(static_cast<dom::ServiceWorkerManagerParent*>(aActor));
+ MOZ_ASSERT(parent);
+ return true;
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvShutdownServiceWorkerRegistrar() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ RefPtr<dom::ServiceWorkerRegistrar> service =
+ dom::ServiceWorkerRegistrar::Get();
+ MOZ_ASSERT(service);
+
+ service->Shutdown();
+ return IPC_OK();
+}
+
+already_AddRefed<PCacheStorageParent>
+BackgroundParentImpl::AllocPCacheStorageParent(
+ const Namespace& aNamespace, const PrincipalInfo& aPrincipalInfo) {
+ return dom::cache::AllocPCacheStorageParent(this, aNamespace, aPrincipalInfo);
+}
+
+PMessagePortParent* BackgroundParentImpl::AllocPMessagePortParent(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return new MessagePortParent(aUUID);
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPMessagePortConstructor(
+ PMessagePortParent* aActor, const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ MessagePortParent* mp = static_cast<MessagePortParent*>(aActor);
+ if (!mp->Entangle(aDestinationUUID, aSequenceID)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPMessagePortParent(
+ PMessagePortParent* aActor) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+ MOZ_ASSERT(aActor);
+
+ delete static_cast<MessagePortParent*>(aActor);
+ return true;
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvMessagePortForceClose(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (!MessagePortParent::ForceClose(aUUID, aDestinationUUID, aSequenceID)) {
+ return IPC_FAIL(this, "MessagePortParent::ForceClose failed.");
+ }
+
+ return IPC_OK();
+}
+
+already_AddRefed<BackgroundParentImpl::PQuotaParent>
+BackgroundParentImpl::AllocPQuotaParent() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ return mozilla::dom::quota::AllocPQuotaParent();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvShutdownQuotaManager() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!mozilla::dom::quota::RecvShutdownQuotaManager()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvShutdownBackgroundSessionStorageManagers() {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!mozilla::dom::RecvShutdownBackgroundSessionStorageManagers()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPropagateBackgroundSessionStorageManager(
+ const uint64_t& aCurrentTopContextId, const uint64_t& aTargetTopContextId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL(this, "Wrong actor");
+ }
+
+ mozilla::dom::RecvPropagateBackgroundSessionStorageManager(
+ aCurrentTopContextId, aTargetTopContextId);
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvRemoveBackgroundSessionStorageManager(
+ const uint64_t& aTopContextId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!mozilla::dom::RecvRemoveBackgroundSessionStorageManager(aTopContextId)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvGetSessionStorageManagerData(
+ const uint64_t& aTopContextId, const uint32_t& aSizeLimit,
+ const bool& aCancelSessionStoreTimer,
+ GetSessionStorageManagerDataResolver&& aResolver) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL(this, "Wrong actor");
+ }
+
+ if (!mozilla::dom::RecvGetSessionStorageData(aTopContextId, aSizeLimit,
+ aCancelSessionStoreTimer,
+ std::move(aResolver))) {
+ return IPC_FAIL(this, "Couldn't get session storage data");
+ }
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvLoadSessionStorageManagerData(
+ const uint64_t& aTopContextId,
+ nsTArray<mozilla::dom::SSCacheCopy>&& aOriginCacheCopy) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL(this, "Wrong actor");
+ }
+
+ if (!mozilla::dom::RecvLoadSessionStorageData(aTopContextId,
+ std::move(aOriginCacheCopy))) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ return IPC_OK();
+}
+
+already_AddRefed<dom::PFileSystemRequestParent>
+BackgroundParentImpl::AllocPFileSystemRequestParent(
+ const FileSystemParams& aParams) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<FileSystemRequestParent> result = new FileSystemRequestParent();
+
+ if (NS_WARN_IF(!result->Initialize(aParams))) {
+ return nullptr;
+ }
+
+ return result.forget();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPFileSystemRequestConstructor(
+ PFileSystemRequestParent* aActor, const FileSystemParams& params) {
+ static_cast<FileSystemRequestParent*>(aActor)->Start();
+ return IPC_OK();
+}
+
+// Gamepad API Background IPC
+already_AddRefed<dom::PGamepadEventChannelParent>
+BackgroundParentImpl::AllocPGamepadEventChannelParent() {
+ return dom::GamepadEventChannelParent::Create();
+}
+
+already_AddRefed<dom::PGamepadTestChannelParent>
+BackgroundParentImpl::AllocPGamepadTestChannelParent() {
+ return dom::GamepadTestChannelParent::Create();
+}
+
+dom::PWebAuthnTransactionParent*
+BackgroundParentImpl::AllocPWebAuthnTransactionParent() {
+ return new dom::WebAuthnTransactionParent();
+}
+
+bool BackgroundParentImpl::DeallocPWebAuthnTransactionParent(
+ dom::PWebAuthnTransactionParent* aActor) {
+ MOZ_ASSERT(aActor);
+ delete aActor;
+ return true;
+}
+
+already_AddRefed<net::PHttpBackgroundChannelParent>
+BackgroundParentImpl::AllocPHttpBackgroundChannelParent(
+ const uint64_t& aChannelId) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ RefPtr<net::HttpBackgroundChannelParent> actor =
+ new net::HttpBackgroundChannelParent();
+ return actor.forget();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPHttpBackgroundChannelConstructor(
+ net::PHttpBackgroundChannelParent* aActor, const uint64_t& aChannelId) {
+ MOZ_ASSERT(aActor);
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ net::HttpBackgroundChannelParent* aParent =
+ static_cast<net::HttpBackgroundChannelParent*>(aActor);
+
+ if (NS_WARN_IF(NS_FAILED(aParent->Init(aChannelId)))) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvCreateMIDIPort(
+ Endpoint<PMIDIPortParent>&& aEndpoint, const MIDIPortInfo& aPortInfo,
+ const bool& aSysexEnabled) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (!aEndpoint.IsValid()) {
+ return IPC_FAIL(this, "invalid endpoint for MIDIPort");
+ }
+
+ MIDIPlatformService::OwnerThread()->Dispatch(NS_NewRunnableFunction(
+ "CreateMIDIPortRunnable", [=, endpoint = std::move(aEndpoint)]() mutable {
+ RefPtr<MIDIPortParent> result =
+ new MIDIPortParent(aPortInfo, aSysexEnabled);
+ endpoint.Bind(result);
+ }));
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvCreateMIDIManager(
+ Endpoint<PMIDIManagerParent>&& aEndpoint) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ if (!aEndpoint.IsValid()) {
+ return IPC_FAIL(this, "invalid endpoint for MIDIManager");
+ }
+
+ MIDIPlatformService::OwnerThread()->Dispatch(NS_NewRunnableFunction(
+ "CreateMIDIManagerRunnable",
+ [=, endpoint = std::move(aEndpoint)]() mutable {
+ RefPtr<MIDIManagerParent> result = new MIDIManagerParent();
+ endpoint.Bind(result);
+ MIDIPlatformService::Get()->AddManager(result);
+ }));
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvHasMIDIDevice(
+ HasMIDIDeviceResolver&& aResolver) {
+ AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+
+ InvokeAsync(MIDIPlatformService::OwnerThread(), __func__,
+ []() {
+ bool hasDevice = MIDIPlatformService::Get()->HasDevice();
+ return BoolPromise::CreateAndResolve(hasDevice, __func__);
+ })
+ ->Then(GetCurrentSerialEventTarget(), __func__,
+ [resolver = std::move(aResolver)](
+ const BoolPromise::ResolveOrRejectValue& r) {
+ resolver(r.IsResolve() && r.ResolveValue());
+ });
+
+ return IPC_OK();
+}
+
+already_AddRefed<mozilla::dom::PClientManagerParent>
+BackgroundParentImpl::AllocPClientManagerParent() {
+ return mozilla::dom::AllocClientManagerParent();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPClientManagerConstructor(
+ mozilla::dom::PClientManagerParent* aActor) {
+ mozilla::dom::InitClientManagerParent(aActor);
+ return IPC_OK();
+}
+
+IPCResult BackgroundParentImpl::RecvStorageActivity(
+ const PrincipalInfo& aPrincipalInfo) {
+ dom::StorageActivityService::SendActivity(aPrincipalInfo);
+ return IPC_OK();
+}
+
+IPCResult BackgroundParentImpl::RecvPServiceWorkerManagerConstructor(
+ PServiceWorkerManagerParent* const aActor) {
+ // Only the parent process is allowed to construct this actor.
+ if (BackgroundParent::IsOtherProcessActor(this)) {
+ return IPC_FAIL_NO_REASON(aActor);
+ }
+ return IPC_OK();
+}
+
+already_AddRefed<PServiceWorkerParent>
+BackgroundParentImpl::AllocPServiceWorkerParent(
+ const IPCServiceWorkerDescriptor&) {
+ return MakeAndAddRef<ServiceWorkerParent>();
+}
+
+IPCResult BackgroundParentImpl::RecvPServiceWorkerConstructor(
+ PServiceWorkerParent* aActor,
+ const IPCServiceWorkerDescriptor& aDescriptor) {
+ dom::InitServiceWorkerParent(aActor, aDescriptor);
+ return IPC_OK();
+}
+
+already_AddRefed<PServiceWorkerContainerParent>
+BackgroundParentImpl::AllocPServiceWorkerContainerParent() {
+ return MakeAndAddRef<mozilla::dom::ServiceWorkerContainerParent>();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPServiceWorkerContainerConstructor(
+ PServiceWorkerContainerParent* aActor) {
+ dom::InitServiceWorkerContainerParent(aActor);
+ return IPC_OK();
+}
+
+already_AddRefed<PServiceWorkerRegistrationParent>
+BackgroundParentImpl::AllocPServiceWorkerRegistrationParent(
+ const IPCServiceWorkerRegistrationDescriptor&) {
+ return MakeAndAddRef<mozilla::dom::ServiceWorkerRegistrationParent>();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvPServiceWorkerRegistrationConstructor(
+ PServiceWorkerRegistrationParent* aActor,
+ const IPCServiceWorkerRegistrationDescriptor& aDescriptor) {
+ dom::InitServiceWorkerRegistrationParent(aActor, aDescriptor);
+ return IPC_OK();
+}
+
+dom::PEndpointForReportParent*
+BackgroundParentImpl::AllocPEndpointForReportParent(
+ const nsAString& aGroupName, const PrincipalInfo& aPrincipalInfo) {
+ RefPtr<dom::EndpointForReportParent> actor =
+ new dom::EndpointForReportParent();
+ return actor.forget().take();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvPEndpointForReportConstructor(
+ PEndpointForReportParent* aActor, const nsAString& aGroupName,
+ const PrincipalInfo& aPrincipalInfo) {
+ static_cast<dom::EndpointForReportParent*>(aActor)->Run(aGroupName,
+ aPrincipalInfo);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvEnsureRDDProcessAndCreateBridge(
+ EnsureRDDProcessAndCreateBridgeResolver&& aResolver) {
+ using Type = std::tuple<const nsresult&,
+ Endpoint<mozilla::PRemoteDecoderManagerChild>&&>;
+
+ RefPtr<ThreadsafeContentParentHandle> parent =
+ BackgroundParent::GetContentParentHandle(this);
+ if (NS_WARN_IF(!parent)) {
+ aResolver(
+ Type(NS_ERROR_NOT_AVAILABLE, Endpoint<PRemoteDecoderManagerChild>()));
+ return IPC_OK();
+ }
+
+ RDDProcessManager* rdd = RDDProcessManager::Get();
+ if (!rdd) {
+ aResolver(
+ Type(NS_ERROR_NOT_AVAILABLE, Endpoint<PRemoteDecoderManagerChild>()));
+ return IPC_OK();
+ }
+
+ rdd->EnsureRDDProcessAndCreateBridge(OtherPid(), parent->ChildID())
+ ->Then(GetCurrentSerialEventTarget(), __func__,
+ [resolver = std::move(aResolver)](
+ mozilla::RDDProcessManager::EnsureRDDPromise::
+ ResolveOrRejectValue&& aValue) mutable {
+ if (aValue.IsReject()) {
+ resolver(Type(aValue.RejectValue(),
+ Endpoint<PRemoteDecoderManagerChild>()));
+ return;
+ }
+ resolver(Type(NS_OK, std::move(aValue.ResolveValue())));
+ });
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+BackgroundParentImpl::RecvEnsureUtilityProcessAndCreateBridge(
+ const RemoteDecodeIn& aLocation,
+ EnsureUtilityProcessAndCreateBridgeResolver&& aResolver) {
+ base::ProcessId otherPid = OtherPid();
+ RefPtr<ThreadsafeContentParentHandle> parent =
+ BackgroundParent::GetContentParentHandle(this);
+ if (NS_WARN_IF(!parent)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ dom::ContentParentId childId = parent->ChildID();
+ nsCOMPtr<nsISerialEventTarget> managerThread = GetCurrentSerialEventTarget();
+ if (!managerThread) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ NS_DispatchToMainThread(NS_NewRunnableFunction(
+ "BackgroundParentImpl::RecvEnsureUtilityProcessAndCreateBridge()",
+ [aResolver, managerThread, otherPid, childId, aLocation]() {
+ RefPtr<UtilityProcessManager> upm =
+ UtilityProcessManager::GetSingleton();
+ using Type =
+ std::tuple<const nsresult&,
+ Endpoint<mozilla::PRemoteDecoderManagerChild>&&>;
+ if (!upm) {
+ managerThread->Dispatch(NS_NewRunnableFunction(
+ "BackgroundParentImpl::RecvEnsureUtilityProcessAndCreateBridge::"
+ "Failure",
+ [aResolver]() {
+ aResolver(Type(NS_ERROR_NOT_AVAILABLE,
+ Endpoint<PRemoteDecoderManagerChild>()));
+ }));
+ } else {
+ SandboxingKind sbKind = GetSandboxingKindFromLocation(aLocation);
+ upm->StartProcessForRemoteMediaDecoding(otherPid, childId, sbKind)
+ ->Then(managerThread, __func__,
+ [resolver = aResolver](
+ mozilla::ipc::UtilityProcessManager::
+ StartRemoteDecodingUtilityPromise::
+ ResolveOrRejectValue&& aValue) mutable {
+ if (aValue.IsReject()) {
+ resolver(Type(aValue.RejectValue(),
+ Endpoint<PRemoteDecoderManagerChild>()));
+ return;
+ }
+ resolver(Type(NS_OK, std::move(aValue.ResolveValue())));
+ });
+ }
+ }));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvRequestCameraAccess(
+ const bool& aAllowPermissionRequest,
+ RequestCameraAccessResolver&& aResolver) {
+#ifdef MOZ_WEBRTC
+ mozilla::camera::CamerasParent::RequestCameraAccess(aAllowPermissionRequest)
+ ->Then(GetCurrentSerialEventTarget(), __func__,
+ [resolver = std::move(aResolver)](
+ const mozilla::camera::CamerasParent::
+ CameraAccessRequestPromise::ResolveOrRejectValue& aValue) {
+ if (aValue.IsResolve()) {
+ resolver(aValue.ResolveValue());
+ } else {
+ resolver(CamerasAccessStatus::Error);
+ }
+ });
+#else
+ aResolver(CamerasAccessStatus::Error);
+#endif
+ return IPC_OK();
+}
+
+bool BackgroundParentImpl::DeallocPEndpointForReportParent(
+ PEndpointForReportParent* aActor) {
+ RefPtr<dom::EndpointForReportParent> actor =
+ dont_AddRef(static_cast<dom::EndpointForReportParent*>(aActor));
+ return true;
+}
+
+mozilla::ipc::IPCResult BackgroundParentImpl::RecvRemoveEndpoint(
+ const nsAString& aGroupName, const nsACString& aEndpointURL,
+ const PrincipalInfo& aPrincipalInfo) {
+ NS_DispatchToMainThread(NS_NewRunnableFunction(
+ "BackgroundParentImpl::RecvRemoveEndpoint(",
+ [aGroupName = nsString(aGroupName),
+ aEndpointURL = nsCString(aEndpointURL), aPrincipalInfo]() {
+ dom::ReportingHeader::RemoveEndpoint(aGroupName, aEndpointURL,
+ aPrincipalInfo);
+ }));
+
+ return IPC_OK();
+}
+
+already_AddRefed<dom::locks::PLockManagerParent>
+BackgroundParentImpl::AllocPLockManagerParent(NotNull<nsIPrincipal*> aPrincipal,
+ const nsID& aClientId) {
+ return MakeAndAddRef<mozilla::dom::locks::LockManagerParent>(aPrincipal,
+ aClientId);
+}
+
+already_AddRefed<dom::PFetchParent> BackgroundParentImpl::AllocPFetchParent() {
+ return MakeAndAddRef<dom::FetchParent>();
+}
+
+} // namespace mozilla::ipc
+
+void TestParent::ActorDestroy(ActorDestroyReason aWhy) {
+ mozilla::ipc::AssertIsInMainProcess();
+ AssertIsOnBackgroundThread();
+}
diff --git a/ipc/glue/BackgroundParentImpl.h b/ipc/glue/BackgroundParentImpl.h
new file mode 100644
index 0000000000..42f40a1a2b
--- /dev/null
+++ b/ipc/glue/BackgroundParentImpl.h
@@ -0,0 +1,363 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_backgroundparentimpl_h__
+#define mozilla_ipc_backgroundparentimpl_h__
+
+#include "mozilla/ipc/PBackgroundParent.h"
+
+namespace mozilla::ipc {
+
+// Instances of this class should never be created directly. This class is meant
+// to be inherited in BackgroundImpl.
+class BackgroundParentImpl : public PBackgroundParent {
+ protected:
+ BackgroundParentImpl();
+ virtual ~BackgroundParentImpl();
+
+ void ProcessingError(Result aCode, const char* aReason) override;
+
+ void ActorDestroy(ActorDestroyReason aWhy) override;
+
+ PBackgroundTestParent* AllocPBackgroundTestParent(
+ const nsACString& aTestArg) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundTestConstructor(
+ PBackgroundTestParent* aActor, const nsACString& aTestArg) override;
+
+ bool DeallocPBackgroundTestParent(PBackgroundTestParent* aActor) override;
+
+ already_AddRefed<PBackgroundIDBFactoryParent>
+ AllocPBackgroundIDBFactoryParent(const LoggingInfo& aLoggingInfo) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundIDBFactoryConstructor(
+ PBackgroundIDBFactoryParent* aActor,
+ const LoggingInfo& aLoggingInfo) override;
+
+ PBackgroundIndexedDBUtilsParent* AllocPBackgroundIndexedDBUtilsParent()
+ override;
+
+ bool DeallocPBackgroundIndexedDBUtilsParent(
+ PBackgroundIndexedDBUtilsParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvFlushPendingFileDeletions() override;
+
+ already_AddRefed<PBackgroundSDBConnectionParent>
+ AllocPBackgroundSDBConnectionParent(
+ const PersistenceType& aPersistenceType,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundSDBConnectionConstructor(
+ PBackgroundSDBConnectionParent* aActor,
+ const PersistenceType& aPersistenceType,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ already_AddRefed<PBackgroundLSDatabaseParent>
+ AllocPBackgroundLSDatabaseParent(const PrincipalInfo& aPrincipalInfo,
+ const uint32_t& aPrivateBrowsingId,
+ const uint64_t& aDatastoreId) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundLSDatabaseConstructor(
+ PBackgroundLSDatabaseParent* aActor, const PrincipalInfo& aPrincipalInfo,
+ const uint32_t& aPrivateBrowsingId,
+ const uint64_t& aDatastoreId) override;
+
+ PBackgroundLSObserverParent* AllocPBackgroundLSObserverParent(
+ const uint64_t& aObserverId) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundLSObserverConstructor(
+ PBackgroundLSObserverParent* aActor,
+ const uint64_t& aObserverId) override;
+
+ bool DeallocPBackgroundLSObserverParent(
+ PBackgroundLSObserverParent* aActor) override;
+
+ PBackgroundLSRequestParent* AllocPBackgroundLSRequestParent(
+ const LSRequestParams& aParams) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundLSRequestConstructor(
+ PBackgroundLSRequestParent* aActor,
+ const LSRequestParams& aParams) override;
+
+ bool DeallocPBackgroundLSRequestParent(
+ PBackgroundLSRequestParent* aActor) override;
+
+ PBackgroundLSSimpleRequestParent* AllocPBackgroundLSSimpleRequestParent(
+ const LSSimpleRequestParams& aParams) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundLSSimpleRequestConstructor(
+ PBackgroundLSSimpleRequestParent* aActor,
+ const LSSimpleRequestParams& aParams) override;
+
+ bool DeallocPBackgroundLSSimpleRequestParent(
+ PBackgroundLSSimpleRequestParent* aActor) override;
+
+ PBackgroundLocalStorageCacheParent* AllocPBackgroundLocalStorageCacheParent(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundLocalStorageCacheConstructor(
+ PBackgroundLocalStorageCacheParent* aActor,
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOriginKey,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ bool DeallocPBackgroundLocalStorageCacheParent(
+ PBackgroundLocalStorageCacheParent* aActor) override;
+
+ PBackgroundStorageParent* AllocPBackgroundStorageParent(
+ const nsAString& aProfilePath,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ mozilla::ipc::IPCResult RecvPBackgroundStorageConstructor(
+ PBackgroundStorageParent* aActor, const nsAString& aProfilePath,
+ const uint32_t& aPrivateBrowsingId) override;
+
+ bool DeallocPBackgroundStorageParent(
+ PBackgroundStorageParent* aActor) override;
+
+ already_AddRefed<PBackgroundSessionStorageManagerParent>
+ AllocPBackgroundSessionStorageManagerParent(
+ const uint64_t& aTopContextId) override;
+
+ already_AddRefed<PBackgroundSessionStorageServiceParent>
+ AllocPBackgroundSessionStorageServiceParent() override;
+
+ mozilla::ipc::IPCResult RecvCreateFileSystemManagerParent(
+ const PrincipalInfo& aPrincipalInfo,
+ Endpoint<mozilla::dom::PFileSystemManagerParent>&& aParentEndpoint,
+ CreateFileSystemManagerParentResolver&& aResolver) override;
+
+ mozilla::ipc::IPCResult RecvCreateWebTransportParent(
+ const nsAString& aURL, nsIPrincipal* aPrincipal,
+ const mozilla::Maybe<IPCClientInfo>& aClientInfo, const bool& aDedicated,
+ const bool& aRequireUnreliable, const uint32_t& aCongestionControl,
+ nsTArray<WebTransportHash>&& aServerCertHashes,
+ Endpoint<PWebTransportParent>&& aParentEndpoint,
+ CreateWebTransportParentResolver&& aResolver) override;
+
+ already_AddRefed<PIdleSchedulerParent> AllocPIdleSchedulerParent() override;
+
+ PTemporaryIPCBlobParent* AllocPTemporaryIPCBlobParent() override;
+
+ mozilla::ipc::IPCResult RecvPTemporaryIPCBlobConstructor(
+ PTemporaryIPCBlobParent* actor) override;
+
+ bool DeallocPTemporaryIPCBlobParent(PTemporaryIPCBlobParent* aActor) override;
+
+ PFileCreatorParent* AllocPFileCreatorParent(
+ const nsAString& aFullPath, const nsAString& aType,
+ const nsAString& aName, const Maybe<int64_t>& aLastModified,
+ const bool& aExistenceCheck, const bool& aIsFromNsIFile) override;
+
+ mozilla::ipc::IPCResult RecvPFileCreatorConstructor(
+ PFileCreatorParent* actor, const nsAString& aFullPath,
+ const nsAString& aType, const nsAString& aName,
+ const Maybe<int64_t>& aLastModified, const bool& aExistenceCheck,
+ const bool& aIsFromNsIFile) override;
+
+ bool DeallocPFileCreatorParent(PFileCreatorParent* aActor) override;
+
+ already_AddRefed<mozilla::dom::PRemoteWorkerControllerParent>
+ AllocPRemoteWorkerControllerParent(
+ const mozilla::dom::RemoteWorkerData& aRemoteWorkerData) override;
+
+ mozilla::ipc::IPCResult RecvPRemoteWorkerControllerConstructor(
+ mozilla::dom::PRemoteWorkerControllerParent* aActor,
+ const mozilla::dom::RemoteWorkerData& aRemoteWorkerData) override;
+
+ already_AddRefed<PRemoteWorkerServiceParent> AllocPRemoteWorkerServiceParent()
+ override;
+
+ mozilla::ipc::IPCResult RecvPRemoteWorkerServiceConstructor(
+ PRemoteWorkerServiceParent* aActor) override;
+
+ mozilla::dom::PSharedWorkerParent* AllocPSharedWorkerParent(
+ const mozilla::dom::RemoteWorkerData& aData, const uint64_t& aWindowID,
+ const mozilla::dom::MessagePortIdentifier& aPortIdentifier) override;
+
+ mozilla::ipc::IPCResult RecvPSharedWorkerConstructor(
+ PSharedWorkerParent* aActor, const mozilla::dom::RemoteWorkerData& aData,
+ const uint64_t& aWindowID,
+ const mozilla::dom::MessagePortIdentifier& aPortIdentifier) override;
+
+ bool DeallocPSharedWorkerParent(PSharedWorkerParent* aActor) override;
+
+ already_AddRefed<PVsyncParent> AllocPVsyncParent() override;
+
+ PBroadcastChannelParent* AllocPBroadcastChannelParent(
+ const PrincipalInfo& aPrincipalInfo, const nsACString& aOrigin,
+ const nsAString& aChannel) override;
+
+ mozilla::ipc::IPCResult RecvPBroadcastChannelConstructor(
+ PBroadcastChannelParent* actor, const PrincipalInfo& aPrincipalInfo,
+ const nsACString& origin, const nsAString& channel) override;
+
+ bool DeallocPBroadcastChannelParent(PBroadcastChannelParent* aActor) override;
+
+ PServiceWorkerManagerParent* AllocPServiceWorkerManagerParent() override;
+
+ bool DeallocPServiceWorkerManagerParent(
+ PServiceWorkerManagerParent* aActor) override;
+
+ PCamerasParent* AllocPCamerasParent() override;
+#ifdef MOZ_WEBRTC
+ mozilla::ipc::IPCResult RecvPCamerasConstructor(
+ PCamerasParent* aActor) override;
+#endif
+ bool DeallocPCamerasParent(PCamerasParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvShutdownServiceWorkerRegistrar() override;
+
+ already_AddRefed<dom::cache::PCacheStorageParent> AllocPCacheStorageParent(
+ const dom::cache::Namespace& aNamespace,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ PUDPSocketParent* AllocPUDPSocketParent(const Maybe<PrincipalInfo>& pInfo,
+ const nsACString& aFilter) override;
+ mozilla::ipc::IPCResult RecvPUDPSocketConstructor(
+ PUDPSocketParent*, const Maybe<PrincipalInfo>& aPrincipalInfo,
+ const nsACString& aFilter) override;
+ bool DeallocPUDPSocketParent(PUDPSocketParent*) override;
+
+ PMessagePortParent* AllocPMessagePortParent(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) override;
+
+ mozilla::ipc::IPCResult RecvPMessagePortConstructor(
+ PMessagePortParent* aActor, const nsID& aUUID,
+ const nsID& aDestinationUUID, const uint32_t& aSequenceID) override;
+
+ bool DeallocPMessagePortParent(PMessagePortParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvMessagePortForceClose(
+ const nsID& aUUID, const nsID& aDestinationUUID,
+ const uint32_t& aSequenceID) override;
+
+ already_AddRefed<PQuotaParent> AllocPQuotaParent() override;
+
+ mozilla::ipc::IPCResult RecvShutdownQuotaManager() override;
+
+ mozilla::ipc::IPCResult RecvShutdownBackgroundSessionStorageManagers()
+ override;
+
+ mozilla::ipc::IPCResult RecvPropagateBackgroundSessionStorageManager(
+ const uint64_t& aCurrentTopContextId,
+ const uint64_t& aTargetTopContextId) override;
+
+ mozilla::ipc::IPCResult RecvRemoveBackgroundSessionStorageManager(
+ const uint64_t& aTopContextId) override;
+
+ mozilla::ipc::IPCResult RecvLoadSessionStorageManagerData(
+ const uint64_t& aTopContextId,
+ nsTArray<mozilla::dom::SSCacheCopy>&& aOriginCacheCopy) override;
+
+ mozilla::ipc::IPCResult RecvGetSessionStorageManagerData(
+ const uint64_t& aTopContextId, const uint32_t& aSizeLimit,
+ const bool& aCancelSessionStoreTimer,
+ GetSessionStorageManagerDataResolver&& aResolver) override;
+
+ already_AddRefed<PFileSystemRequestParent> AllocPFileSystemRequestParent(
+ const FileSystemParams&) override;
+
+ mozilla::ipc::IPCResult RecvPFileSystemRequestConstructor(
+ PFileSystemRequestParent* actor, const FileSystemParams& params) override;
+
+ // Gamepad API Background IPC
+ already_AddRefed<PGamepadEventChannelParent> AllocPGamepadEventChannelParent()
+ override;
+
+ already_AddRefed<PGamepadTestChannelParent> AllocPGamepadTestChannelParent()
+ override;
+
+ PWebAuthnTransactionParent* AllocPWebAuthnTransactionParent() override;
+
+ bool DeallocPWebAuthnTransactionParent(
+ PWebAuthnTransactionParent* aActor) override;
+
+ already_AddRefed<PHttpBackgroundChannelParent>
+ AllocPHttpBackgroundChannelParent(const uint64_t& aChannelId) override;
+
+ mozilla::ipc::IPCResult RecvPHttpBackgroundChannelConstructor(
+ PHttpBackgroundChannelParent* aActor,
+ const uint64_t& aChannelId) override;
+
+ already_AddRefed<PClientManagerParent> AllocPClientManagerParent() override;
+
+ mozilla::ipc::IPCResult RecvPClientManagerConstructor(
+ PClientManagerParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvCreateMIDIPort(
+ Endpoint<PMIDIPortParent>&& aEndpoint, const MIDIPortInfo& aPortInfo,
+ const bool& aSysexEnabled) override;
+
+ mozilla::ipc::IPCResult RecvCreateMIDIManager(
+ Endpoint<PMIDIManagerParent>&& aEndpoint) override;
+
+ mozilla::ipc::IPCResult RecvHasMIDIDevice(
+ HasMIDIDeviceResolver&& aResolver) override;
+
+ mozilla::ipc::IPCResult RecvStorageActivity(
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ already_AddRefed<PServiceWorkerParent> AllocPServiceWorkerParent(
+ const IPCServiceWorkerDescriptor&) final;
+
+ mozilla::ipc::IPCResult RecvPServiceWorkerManagerConstructor(
+ PServiceWorkerManagerParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvPServiceWorkerConstructor(
+ PServiceWorkerParent* aActor,
+ const IPCServiceWorkerDescriptor& aDescriptor) override;
+
+ already_AddRefed<PServiceWorkerContainerParent>
+ AllocPServiceWorkerContainerParent() final;
+
+ mozilla::ipc::IPCResult RecvPServiceWorkerContainerConstructor(
+ PServiceWorkerContainerParent* aActor) override;
+
+ already_AddRefed<PServiceWorkerRegistrationParent>
+ AllocPServiceWorkerRegistrationParent(
+ const IPCServiceWorkerRegistrationDescriptor&) final;
+
+ mozilla::ipc::IPCResult RecvPServiceWorkerRegistrationConstructor(
+ PServiceWorkerRegistrationParent* aActor,
+ const IPCServiceWorkerRegistrationDescriptor& aDescriptor) override;
+
+ PEndpointForReportParent* AllocPEndpointForReportParent(
+ const nsAString& aGroupName,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ mozilla::ipc::IPCResult RecvPEndpointForReportConstructor(
+ PEndpointForReportParent* actor, const nsAString& aGroupName,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ mozilla::ipc::IPCResult RecvEnsureRDDProcessAndCreateBridge(
+ EnsureRDDProcessAndCreateBridgeResolver&& aResolver) override;
+
+ mozilla::ipc::IPCResult RecvEnsureUtilityProcessAndCreateBridge(
+ const RemoteDecodeIn& aLocation,
+ EnsureUtilityProcessAndCreateBridgeResolver&& aResolver) override;
+
+ mozilla::ipc::IPCResult RecvRequestCameraAccess(
+ const bool& aAllowPermissionRequest,
+ RequestCameraAccessResolver&& aResolver) override;
+
+ bool DeallocPEndpointForReportParent(
+ PEndpointForReportParent* aActor) override;
+
+ mozilla::ipc::IPCResult RecvRemoveEndpoint(
+ const nsAString& aGroupName, const nsACString& aEndpointURL,
+ const PrincipalInfo& aPrincipalInfo) override;
+
+ already_AddRefed<PLockManagerParent> AllocPLockManagerParent(
+ NotNull<nsIPrincipal*> aPrincipal, const nsID& aClientId) final;
+
+ already_AddRefed<PFetchParent> AllocPFetchParent() override;
+};
+
+} // namespace mozilla::ipc
+
+#endif // mozilla_ipc_backgroundparentimpl_h__
diff --git a/ipc/glue/BackgroundStarterChild.h b/ipc/glue/BackgroundStarterChild.h
new file mode 100644
index 0000000000..1a0b5386f8
--- /dev/null
+++ b/ipc/glue/BackgroundStarterChild.h
@@ -0,0 +1,35 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_BackgroundStarterChild_h
+#define mozilla_ipc_BackgroundStarterChild_h
+
+#include "mozilla/ipc/PBackgroundStarterChild.h"
+#include "mozilla/dom/ContentChild.h"
+
+namespace mozilla::ipc {
+
+class BackgroundStarterChild final : public PBackgroundStarterChild {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(BackgroundStarterChild, override)
+
+ BackgroundStarterChild(base::ProcessId aOtherPid,
+ nsISerialEventTarget* aTaskQueue)
+ : mOtherPid(aOtherPid), mTaskQueue(aTaskQueue) {}
+
+ // Unlike the methods on `IToplevelProtocol`, may be accessed on any thread
+ // and will not be modified after construction.
+ const base::ProcessId mOtherPid;
+ const nsCOMPtr<nsISerialEventTarget> mTaskQueue;
+
+ private:
+ friend class PBackgroundStarterChild;
+ ~BackgroundStarterChild() = default;
+};
+
+} // namespace mozilla::ipc
+
+#endif // mozilla_ipc_BackgroundStarterChild_h
diff --git a/ipc/glue/BackgroundStarterParent.h b/ipc/glue/BackgroundStarterParent.h
new file mode 100644
index 0000000000..4312b9ab2a
--- /dev/null
+++ b/ipc/glue/BackgroundStarterParent.h
@@ -0,0 +1,48 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_BackgroundStarterParent_h
+#define mozilla_ipc_BackgroundStarterParent_h
+
+#include "mozilla/ipc/PBackgroundStarterParent.h"
+#include "mozilla/dom/ContentParent.h"
+#include "nsISupportsImpl.h"
+
+namespace mozilla::ipc {
+
+class BackgroundStarterParent final : public PBackgroundStarterParent {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DELETE_ON_MAIN_THREAD(
+ BackgroundStarterParent, override)
+
+ // Implemented in BackgroundImpl.cpp
+ BackgroundStarterParent(mozilla::dom::ThreadsafeContentParentHandle* aContent,
+ bool aCrossProcess);
+
+ void SetLiveActorArray(nsTArray<IToplevelProtocol*>* aLiveActorArray);
+
+ private:
+ friend class PBackgroundStarterParent;
+ ~BackgroundStarterParent() = default;
+
+ // Implemented in BackgroundImpl.cpp
+ void ActorDestroy(ActorDestroyReason aReason) override;
+
+ // Implemented in BackgroundImpl.cpp
+ IPCResult RecvInitBackground(Endpoint<PBackgroundParent>&& aEndpoint);
+
+ const bool mCrossProcess;
+
+ const RefPtr<mozilla::dom::ThreadsafeContentParentHandle> mContent;
+
+ // Set when the actor is opened successfully and used to handle shutdown
+ // hangs. Only touched on the background thread.
+ nsTArray<IToplevelProtocol*>* mLiveActorArray = nullptr;
+};
+
+} // namespace mozilla::ipc
+
+#endif // mozilla_ipc_BackgroundStarterParent_h
diff --git a/ipc/glue/BackgroundUtils.cpp b/ipc/glue/BackgroundUtils.cpp
new file mode 100644
index 0000000000..435e29f635
--- /dev/null
+++ b/ipc/glue/BackgroundUtils.cpp
@@ -0,0 +1,1158 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "BackgroundUtils.h"
+
+#include "MainThreadUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/BasePrincipal.h"
+#include "mozilla/ContentPrincipal.h"
+#include "mozilla/NullPrincipal.h"
+#include "mozilla/SystemPrincipal.h"
+#include "mozilla/ipc/PBackgroundSharedTypes.h"
+#include "mozilla/ipc/URIUtils.h"
+#include "mozilla/net/CookieJarSettings.h"
+#include "mozilla/net/InterceptionInfo.h"
+#include "mozilla/net/NeckoChannelParams.h"
+#include "ExpandedPrincipal.h"
+#include "nsIScriptSecurityManager.h"
+#include "nsIURI.h"
+#include "nsNetUtil.h"
+#include "mozilla/LoadInfo.h"
+#include "nsContentUtils.h"
+#include "nsString.h"
+#include "nsTArray.h"
+#include "mozilla/nsRedirectHistoryEntry.h"
+#include "mozilla/dom/nsCSPUtils.h"
+#include "mozilla/dom/nsCSPContext.h"
+#include "mozilla/dom/BrowsingContext.h"
+#include "mozilla/dom/CanonicalBrowsingContext.h"
+#include "mozilla/dom/Document.h"
+#include "mozilla/dom/WindowGlobalParent.h"
+#include "mozilla/LoadInfo.h"
+
+using namespace mozilla::dom;
+using namespace mozilla::net;
+
+namespace mozilla {
+
+namespace ipc {
+
+Result<nsCOMPtr<nsIPrincipal>, nsresult> PrincipalInfoToPrincipal(
+ const PrincipalInfo& aPrincipalInfo) {
+ MOZ_ASSERT(aPrincipalInfo.type() != PrincipalInfo::T__None);
+
+ nsCOMPtr<nsIPrincipal> principal;
+ nsresult rv;
+
+ switch (aPrincipalInfo.type()) {
+ case PrincipalInfo::TSystemPrincipalInfo: {
+ principal = SystemPrincipal::Get();
+ if (NS_WARN_IF(!principal)) {
+ return Err(NS_ERROR_NOT_INITIALIZED);
+ }
+
+ return principal;
+ }
+
+ case PrincipalInfo::TNullPrincipalInfo: {
+ const NullPrincipalInfo& info = aPrincipalInfo.get_NullPrincipalInfo();
+
+ nsCOMPtr<nsIURI> uri;
+ rv = NS_NewURI(getter_AddRefs(uri), info.spec());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return Err(rv);
+ }
+
+ if (!uri->SchemeIs(NS_NULLPRINCIPAL_SCHEME)) {
+ return Err(NS_ERROR_ILLEGAL_VALUE);
+ }
+
+ principal = NullPrincipal::Create(info.attrs(), uri);
+ return principal;
+ }
+
+ case PrincipalInfo::TContentPrincipalInfo: {
+ const ContentPrincipalInfo& info =
+ aPrincipalInfo.get_ContentPrincipalInfo();
+
+ nsCOMPtr<nsIURI> uri;
+ rv = NS_NewURI(getter_AddRefs(uri), info.spec());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return Err(rv);
+ }
+
+ nsCOMPtr<nsIURI> domain;
+ if (info.domain()) {
+ rv = NS_NewURI(getter_AddRefs(domain), *info.domain());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return Err(rv);
+ }
+ }
+
+ principal =
+ BasePrincipal::CreateContentPrincipal(uri, info.attrs(), domain);
+ if (NS_WARN_IF(!principal)) {
+ return Err(NS_ERROR_NULL_POINTER);
+ }
+
+ // Origin must match what the_new_principal.getOrigin returns.
+ nsAutoCString originNoSuffix;
+ rv = principal->GetOriginNoSuffix(originNoSuffix);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return Err(rv);
+ }
+
+ if (NS_WARN_IF(!info.originNoSuffix().Equals(originNoSuffix))) {
+ return Err(NS_ERROR_FAILURE);
+ }
+
+ if (!info.baseDomain().IsVoid()) {
+ nsAutoCString baseDomain;
+ rv = principal->GetBaseDomain(baseDomain);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return Err(rv);
+ }
+
+ if (NS_WARN_IF(!info.baseDomain().Equals(baseDomain))) {
+ return Err(NS_ERROR_FAILURE);
+ }
+ }
+ return principal;
+ }
+
+ case PrincipalInfo::TExpandedPrincipalInfo: {
+ const ExpandedPrincipalInfo& info =
+ aPrincipalInfo.get_ExpandedPrincipalInfo();
+
+ nsTArray<nsCOMPtr<nsIPrincipal>> allowlist;
+ nsCOMPtr<nsIPrincipal> alPrincipal;
+
+ for (uint32_t i = 0; i < info.allowlist().Length(); i++) {
+ auto principalOrErr = PrincipalInfoToPrincipal(info.allowlist()[i]);
+ if (NS_WARN_IF(principalOrErr.isErr())) {
+ nsresult ret = principalOrErr.unwrapErr();
+ return Err(ret);
+ }
+ // append that principal to the allowlist
+ allowlist.AppendElement(principalOrErr.unwrap());
+ }
+
+ RefPtr<ExpandedPrincipal> expandedPrincipal =
+ ExpandedPrincipal::Create(allowlist, info.attrs());
+ if (!expandedPrincipal) {
+ return Err(NS_ERROR_FAILURE);
+ }
+
+ principal = expandedPrincipal;
+ return principal;
+ }
+
+ default:
+ return Err(NS_ERROR_FAILURE);
+ }
+}
+
+bool StorageKeysEqual(const PrincipalInfo& aLeft, const PrincipalInfo& aRight) {
+ MOZ_RELEASE_ASSERT(aLeft.type() == PrincipalInfo::TContentPrincipalInfo ||
+ aLeft.type() == PrincipalInfo::TSystemPrincipalInfo);
+ MOZ_RELEASE_ASSERT(aRight.type() == PrincipalInfo::TContentPrincipalInfo ||
+ aRight.type() == PrincipalInfo::TSystemPrincipalInfo);
+
+ if (aLeft.type() != aRight.type()) {
+ return false;
+ }
+
+ if (aLeft.type() == PrincipalInfo::TContentPrincipalInfo) {
+ const ContentPrincipalInfo& leftContent = aLeft.get_ContentPrincipalInfo();
+ const ContentPrincipalInfo& rightContent =
+ aRight.get_ContentPrincipalInfo();
+
+ return leftContent.attrs() == rightContent.attrs() &&
+ leftContent.originNoSuffix() == rightContent.originNoSuffix();
+ }
+
+ // Storage keys for the System principal always equal.
+ return true;
+}
+
+already_AddRefed<nsIContentSecurityPolicy> CSPInfoToCSP(
+ const CSPInfo& aCSPInfo, Document* aRequestingDoc,
+ nsresult* aOptionalResult) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ nsresult stackResult;
+ nsresult& rv = aOptionalResult ? *aOptionalResult : stackResult;
+
+ RefPtr<nsCSPContext> csp = new nsCSPContext();
+
+ if (aRequestingDoc) {
+ rv = csp->SetRequestContextWithDocument(aRequestingDoc);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return nullptr;
+ }
+ } else {
+ auto principalOrErr =
+ PrincipalInfoToPrincipal(aCSPInfo.requestPrincipalInfo());
+ if (NS_WARN_IF(principalOrErr.isErr())) {
+ return nullptr;
+ }
+
+ nsCOMPtr<nsIURI> selfURI;
+ if (!aCSPInfo.selfURISpec().IsEmpty()) {
+ rv = NS_NewURI(getter_AddRefs(selfURI), aCSPInfo.selfURISpec());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return nullptr;
+ }
+ }
+
+ nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
+
+ rv = csp->SetRequestContextWithPrincipal(
+ principal, selfURI, aCSPInfo.referrer(), aCSPInfo.innerWindowID());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return nullptr;
+ }
+ }
+ csp->SetSkipAllowInlineStyleCheck(aCSPInfo.skipAllowInlineStyleCheck());
+
+ for (uint32_t i = 0; i < aCSPInfo.policyInfos().Length(); i++) {
+ csp->AddIPCPolicy(aCSPInfo.policyInfos()[i]);
+ }
+ return csp.forget();
+}
+
+nsresult CSPToCSPInfo(nsIContentSecurityPolicy* aCSP, CSPInfo* aCSPInfo) {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(aCSP);
+ MOZ_ASSERT(aCSPInfo);
+
+ if (!aCSP || !aCSPInfo) {
+ return NS_ERROR_FAILURE;
+ }
+
+ nsCOMPtr<nsIPrincipal> requestPrincipal = aCSP->GetRequestPrincipal();
+
+ PrincipalInfo requestingPrincipalInfo;
+ nsresult rv =
+ PrincipalToPrincipalInfo(requestPrincipal, &requestingPrincipalInfo);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+
+ nsCOMPtr<nsIURI> selfURI = aCSP->GetSelfURI();
+ nsAutoCString selfURISpec;
+ if (selfURI) {
+ selfURI->GetSpec(selfURISpec);
+ }
+
+ nsAutoString referrer;
+ aCSP->GetReferrer(referrer);
+
+ uint64_t windowID = aCSP->GetInnerWindowID();
+ bool skipAllowInlineStyleCheck = aCSP->GetSkipAllowInlineStyleCheck();
+
+ nsTArray<ContentSecurityPolicy> policies;
+ static_cast<nsCSPContext*>(aCSP)->SerializePolicies(policies);
+
+ *aCSPInfo = CSPInfo(std::move(policies), requestingPrincipalInfo, selfURISpec,
+ referrer, windowID, skipAllowInlineStyleCheck);
+ return NS_OK;
+}
+
+nsresult PrincipalToPrincipalInfo(nsIPrincipal* aPrincipal,
+ PrincipalInfo* aPrincipalInfo,
+ bool aSkipBaseDomain) {
+ MOZ_ASSERT(aPrincipal);
+ MOZ_ASSERT(aPrincipalInfo);
+
+ nsresult rv;
+ if (aPrincipal->GetIsNullPrincipal()) {
+ nsAutoCString spec;
+ rv = aPrincipal->GetAsciiSpec(spec);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+
+ *aPrincipalInfo =
+ NullPrincipalInfo(aPrincipal->OriginAttributesRef(), spec);
+ return NS_OK;
+ }
+
+ if (aPrincipal->IsSystemPrincipal()) {
+ *aPrincipalInfo = SystemPrincipalInfo();
+ return NS_OK;
+ }
+
+ // might be an expanded principal
+ auto* basePrin = BasePrincipal::Cast(aPrincipal);
+ if (basePrin->Is<ExpandedPrincipal>()) {
+ auto* expanded = basePrin->As<ExpandedPrincipal>();
+
+ nsTArray<PrincipalInfo> allowlistInfo;
+ PrincipalInfo info;
+
+ for (auto& prin : expanded->AllowList()) {
+ rv = PrincipalToPrincipalInfo(prin, &info, aSkipBaseDomain);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+ // append that spec to the allowlist
+ allowlistInfo.AppendElement(info);
+ }
+
+ *aPrincipalInfo = ExpandedPrincipalInfo(aPrincipal->OriginAttributesRef(),
+ std::move(allowlistInfo));
+ return NS_OK;
+ }
+
+ nsAutoCString spec;
+ rv = aPrincipal->GetAsciiSpec(spec);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+
+ nsCString originNoSuffix;
+ rv = aPrincipal->GetOriginNoSuffix(originNoSuffix);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+
+ nsCOMPtr<nsIURI> domainUri;
+ rv = aPrincipal->GetDomain(getter_AddRefs(domainUri));
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+
+ Maybe<nsCString> domain;
+ if (domainUri) {
+ domain.emplace();
+ rv = domainUri->GetSpec(domain.ref());
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return rv;
+ }
+ }
+
+ // This attribute is not crucial.
+ nsCString baseDomain;
+ if (aSkipBaseDomain) {
+ baseDomain.SetIsVoid(true);
+ } else {
+ if (NS_FAILED(aPrincipal->GetBaseDomain(baseDomain))) {
+ // No warning here. Some principal URLs do not have a base-domain.
+ baseDomain.SetIsVoid(true);
+ }
+ }
+
+ *aPrincipalInfo =
+ ContentPrincipalInfo(aPrincipal->OriginAttributesRef(), originNoSuffix,
+ spec, domain, baseDomain);
+ return NS_OK;
+}
+
+bool IsPrincipalInfoPrivate(const PrincipalInfo& aPrincipalInfo) {
+ if (aPrincipalInfo.type() != ipc::PrincipalInfo::TContentPrincipalInfo) {
+ return false;
+ }
+
+ const ContentPrincipalInfo& info = aPrincipalInfo.get_ContentPrincipalInfo();
+ return !!info.attrs().mPrivateBrowsingId;
+}
+
+already_AddRefed<nsIRedirectHistoryEntry> RHEntryInfoToRHEntry(
+ const RedirectHistoryEntryInfo& aRHEntryInfo) {
+ auto principalOrErr = PrincipalInfoToPrincipal(aRHEntryInfo.principalInfo());
+ if (NS_WARN_IF(principalOrErr.isErr())) {
+ return nullptr;
+ }
+
+ nsCOMPtr<nsIPrincipal> principal = principalOrErr.unwrap();
+ nsCOMPtr<nsIURI> referrerUri = DeserializeURI(aRHEntryInfo.referrerUri());
+
+ nsCOMPtr<nsIRedirectHistoryEntry> entry = new nsRedirectHistoryEntry(
+ principal, referrerUri, aRHEntryInfo.remoteAddress());
+
+ return entry.forget();
+}
+
+nsresult RHEntryToRHEntryInfo(nsIRedirectHistoryEntry* aRHEntry,
+ RedirectHistoryEntryInfo* aRHEntryInfo) {
+ MOZ_ASSERT(aRHEntry);
+ MOZ_ASSERT(aRHEntryInfo);
+
+ nsresult rv;
+ aRHEntry->GetRemoteAddress(aRHEntryInfo->remoteAddress());
+
+ nsCOMPtr<nsIURI> referrerUri;
+ rv = aRHEntry->GetReferrerURI(getter_AddRefs(referrerUri));
+ NS_ENSURE_SUCCESS(rv, rv);
+ SerializeURI(referrerUri, aRHEntryInfo->referrerUri());
+
+ nsCOMPtr<nsIPrincipal> principal;
+ rv = aRHEntry->GetPrincipal(getter_AddRefs(principal));
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return PrincipalToPrincipalInfo(principal, &aRHEntryInfo->principalInfo());
+}
+
+nsresult LoadInfoToLoadInfoArgs(nsILoadInfo* aLoadInfo,
+ LoadInfoArgs* outLoadInfoArgs) {
+ nsresult rv = NS_OK;
+ Maybe<PrincipalInfo> loadingPrincipalInfo;
+ if (nsIPrincipal* loadingPrin = aLoadInfo->GetLoadingPrincipal()) {
+ loadingPrincipalInfo.emplace();
+ rv = PrincipalToPrincipalInfo(loadingPrin, loadingPrincipalInfo.ptr());
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ PrincipalInfo triggeringPrincipalInfo;
+ rv = PrincipalToPrincipalInfo(aLoadInfo->TriggeringPrincipal(),
+ &triggeringPrincipalInfo);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ Maybe<PrincipalInfo> principalToInheritInfo;
+ if (nsIPrincipal* principalToInherit = aLoadInfo->PrincipalToInherit()) {
+ principalToInheritInfo.emplace();
+ rv = PrincipalToPrincipalInfo(principalToInherit,
+ principalToInheritInfo.ptr());
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ Maybe<PrincipalInfo> topLevelPrincipalInfo;
+ if (nsIPrincipal* topLevenPrin = aLoadInfo->GetTopLevelPrincipal()) {
+ topLevelPrincipalInfo.emplace();
+ rv = PrincipalToPrincipalInfo(topLevenPrin, topLevelPrincipalInfo.ptr());
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ Maybe<URIParams> optionalResultPrincipalURI;
+ nsCOMPtr<nsIURI> resultPrincipalURI;
+ Unused << aLoadInfo->GetResultPrincipalURI(
+ getter_AddRefs(resultPrincipalURI));
+ if (resultPrincipalURI) {
+ SerializeURI(resultPrincipalURI, optionalResultPrincipalURI);
+ }
+
+ nsCString triggeringRemoteType;
+ rv = aLoadInfo->GetTriggeringRemoteType(triggeringRemoteType);
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ nsTArray<RedirectHistoryEntryInfo> redirectChainIncludingInternalRedirects;
+ for (const nsCOMPtr<nsIRedirectHistoryEntry>& redirectEntry :
+ aLoadInfo->RedirectChainIncludingInternalRedirects()) {
+ RedirectHistoryEntryInfo* entry =
+ redirectChainIncludingInternalRedirects.AppendElement();
+ rv = RHEntryToRHEntryInfo(redirectEntry, entry);
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ nsTArray<RedirectHistoryEntryInfo> redirectChain;
+ for (const nsCOMPtr<nsIRedirectHistoryEntry>& redirectEntry :
+ aLoadInfo->RedirectChain()) {
+ RedirectHistoryEntryInfo* entry = redirectChain.AppendElement();
+ rv = RHEntryToRHEntryInfo(redirectEntry, entry);
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ Maybe<IPCClientInfo> ipcClientInfo;
+ const Maybe<ClientInfo>& clientInfo = aLoadInfo->GetClientInfo();
+ if (clientInfo.isSome()) {
+ ipcClientInfo.emplace(clientInfo.ref().ToIPC());
+ }
+
+ Maybe<IPCClientInfo> ipcReservedClientInfo;
+ const Maybe<ClientInfo>& reservedClientInfo =
+ aLoadInfo->GetReservedClientInfo();
+ if (reservedClientInfo.isSome()) {
+ ipcReservedClientInfo.emplace(reservedClientInfo.ref().ToIPC());
+ }
+
+ Maybe<IPCClientInfo> ipcInitialClientInfo;
+ const Maybe<ClientInfo>& initialClientInfo =
+ aLoadInfo->GetInitialClientInfo();
+ if (initialClientInfo.isSome()) {
+ ipcInitialClientInfo.emplace(initialClientInfo.ref().ToIPC());
+ }
+
+ Maybe<IPCServiceWorkerDescriptor> ipcController;
+ const Maybe<ServiceWorkerDescriptor>& controller = aLoadInfo->GetController();
+ if (controller.isSome()) {
+ ipcController.emplace(controller.ref().ToIPC());
+ }
+
+ nsAutoString cspNonce;
+ Unused << NS_WARN_IF(NS_FAILED(aLoadInfo->GetCspNonce(cspNonce)));
+
+ nsAutoString integrityMetadata;
+ Unused << NS_WARN_IF(
+ NS_FAILED(aLoadInfo->GetIntegrityMetadata(integrityMetadata)));
+
+ nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
+ rv = aLoadInfo->GetCookieJarSettings(getter_AddRefs(cookieJarSettings));
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ CookieJarSettingsArgs cookieJarSettingsArgs;
+ static_cast<CookieJarSettings*>(cookieJarSettings.get())
+ ->Serialize(cookieJarSettingsArgs);
+
+ Maybe<CSPInfo> maybeCspToInheritInfo;
+ nsCOMPtr<nsIContentSecurityPolicy> cspToInherit =
+ aLoadInfo->GetCspToInherit();
+ if (cspToInherit) {
+ CSPInfo cspToInheritInfo;
+ Unused << NS_WARN_IF(
+ NS_FAILED(CSPToCSPInfo(cspToInherit, &cspToInheritInfo)));
+ maybeCspToInheritInfo.emplace(cspToInheritInfo);
+ }
+
+ nsCOMPtr<nsIURI> unstrippedURI;
+ Unused << aLoadInfo->GetUnstrippedURI(getter_AddRefs(unstrippedURI));
+
+ Maybe<bool> isThirdPartyContextToTopWindow;
+ if (static_cast<LoadInfo*>(aLoadInfo)
+ ->HasIsThirdPartyContextToTopWindowSet()) {
+ isThirdPartyContextToTopWindow.emplace(
+ aLoadInfo->GetIsThirdPartyContextToTopWindow());
+ }
+
+ Maybe<InterceptionInfoArg> interceptionInfoArg;
+ nsIInterceptionInfo* interceptionInfo = aLoadInfo->InterceptionInfo();
+ if (interceptionInfo) {
+ Maybe<PrincipalInfo> triggeringPrincipalInfo;
+ if (interceptionInfo->TriggeringPrincipal()) {
+ triggeringPrincipalInfo.emplace();
+ rv = PrincipalToPrincipalInfo(interceptionInfo->TriggeringPrincipal(),
+ triggeringPrincipalInfo.ptr());
+ }
+
+ nsTArray<RedirectHistoryEntryInfo> redirectChain;
+ for (const nsCOMPtr<nsIRedirectHistoryEntry>& redirectEntry :
+ interceptionInfo->RedirectChain()) {
+ RedirectHistoryEntryInfo* entry = redirectChain.AppendElement();
+ rv = RHEntryToRHEntryInfo(redirectEntry, entry);
+ NS_ENSURE_SUCCESS(rv, rv);
+ }
+
+ interceptionInfoArg = Some(InterceptionInfoArg(
+ triggeringPrincipalInfo, interceptionInfo->ContentPolicyType(),
+ redirectChain, interceptionInfo->FromThirdParty()));
+ }
+
+ Maybe<uint64_t> overriddenFingerprintingSettingsArg;
+ Maybe<RFPTarget> overriddenFingerprintingSettings =
+ aLoadInfo->GetOverriddenFingerprintingSettings();
+
+ if (overriddenFingerprintingSettings) {
+ overriddenFingerprintingSettingsArg =
+ Some(uint64_t(overriddenFingerprintingSettings.ref()));
+ }
+
+ *outLoadInfoArgs = LoadInfoArgs(
+ loadingPrincipalInfo, triggeringPrincipalInfo, principalToInheritInfo,
+ topLevelPrincipalInfo, optionalResultPrincipalURI, triggeringRemoteType,
+ aLoadInfo->GetSandboxedNullPrincipalID(), aLoadInfo->GetSecurityFlags(),
+ aLoadInfo->GetSandboxFlags(), aLoadInfo->GetTriggeringSandboxFlags(),
+ aLoadInfo->GetTriggeringWindowId(),
+ aLoadInfo->GetTriggeringStorageAccess(),
+ aLoadInfo->InternalContentPolicyType(),
+ static_cast<uint32_t>(aLoadInfo->GetTainting()),
+ aLoadInfo->GetBlockAllMixedContent(),
+ aLoadInfo->GetUpgradeInsecureRequests(),
+ aLoadInfo->GetBrowserUpgradeInsecureRequests(),
+ aLoadInfo->GetBrowserDidUpgradeInsecureRequests(),
+ aLoadInfo->GetBrowserWouldUpgradeInsecureRequests(),
+ aLoadInfo->GetForceAllowDataURI(),
+ aLoadInfo->GetAllowInsecureRedirectToDataURI(),
+ aLoadInfo->GetSkipContentPolicyCheckForWebRequest(),
+ aLoadInfo->GetOriginalFrameSrcLoad(),
+ aLoadInfo->GetForceInheritPrincipalDropped(),
+ aLoadInfo->GetInnerWindowID(), aLoadInfo->GetBrowsingContextID(),
+ aLoadInfo->GetFrameBrowsingContextID(),
+ aLoadInfo->GetInitialSecurityCheckDone(),
+ aLoadInfo->GetIsInThirdPartyContext(), isThirdPartyContextToTopWindow,
+ aLoadInfo->GetIsFormSubmission(), aLoadInfo->GetSendCSPViolationEvents(),
+ aLoadInfo->GetOriginAttributes(), redirectChainIncludingInternalRedirects,
+ redirectChain, aLoadInfo->GetHasInjectedCookieForCookieBannerHandling(),
+ aLoadInfo->GetWasSchemelessInput(), ipcClientInfo, ipcReservedClientInfo,
+ ipcInitialClientInfo, ipcController, aLoadInfo->CorsUnsafeHeaders(),
+ aLoadInfo->GetForcePreflight(), aLoadInfo->GetIsPreflight(),
+ aLoadInfo->GetLoadTriggeredFromExternal(),
+ aLoadInfo->GetServiceWorkerTaintingSynthesized(),
+ aLoadInfo->GetDocumentHasUserInteracted(),
+ aLoadInfo->GetAllowListFutureDocumentsCreatedFromThisRedirectChain(),
+ aLoadInfo->GetNeedForCheckingAntiTrackingHeuristic(), cspNonce,
+ integrityMetadata, aLoadInfo->GetSkipContentSniffing(),
+ aLoadInfo->GetHttpsOnlyStatus(), aLoadInfo->GetHstsStatus(),
+ aLoadInfo->GetHasValidUserGestureActivation(),
+ aLoadInfo->GetAllowDeprecatedSystemRequests(),
+ aLoadInfo->GetIsInDevToolsContext(), aLoadInfo->GetParserCreatedScript(),
+ aLoadInfo->GetIsFromProcessingFrameAttributes(),
+ aLoadInfo->GetIsMediaRequest(), aLoadInfo->GetIsMediaInitialRequest(),
+ aLoadInfo->GetIsFromObjectOrEmbed(), cookieJarSettingsArgs,
+ aLoadInfo->GetRequestBlockingReason(), maybeCspToInheritInfo,
+ aLoadInfo->GetStoragePermission(), overriddenFingerprintingSettingsArg,
+ aLoadInfo->GetIsMetaRefresh(), aLoadInfo->GetLoadingEmbedderPolicy(),
+ aLoadInfo->GetIsOriginTrialCoepCredentiallessEnabledForTopLevel(),
+ unstrippedURI, interceptionInfoArg);
+
+ return NS_OK;
+}
+
+nsresult LoadInfoArgsToLoadInfo(const LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsILoadInfo** outLoadInfo) {
+ return LoadInfoArgsToLoadInfo(aLoadInfoArgs, aOriginRemoteType, nullptr,
+ outLoadInfo);
+}
+nsresult LoadInfoArgsToLoadInfo(const LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsINode* aCspToInheritLoadingContext,
+ nsILoadInfo** outLoadInfo) {
+ RefPtr<LoadInfo> loadInfo;
+ nsresult rv = LoadInfoArgsToLoadInfo(aLoadInfoArgs, aOriginRemoteType,
+ aCspToInheritLoadingContext,
+ getter_AddRefs(loadInfo));
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ loadInfo.forget(outLoadInfo);
+ return NS_OK;
+}
+
+nsresult LoadInfoArgsToLoadInfo(const LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ LoadInfo** outLoadInfo) {
+ return LoadInfoArgsToLoadInfo(aLoadInfoArgs, aOriginRemoteType, nullptr,
+ outLoadInfo);
+}
+nsresult LoadInfoArgsToLoadInfo(const LoadInfoArgs& loadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsINode* aCspToInheritLoadingContext,
+ LoadInfo** outLoadInfo) {
+ nsCOMPtr<nsIPrincipal> loadingPrincipal;
+ if (loadInfoArgs.requestingPrincipalInfo().isSome()) {
+ auto loadingPrincipalOrErr =
+ PrincipalInfoToPrincipal(loadInfoArgs.requestingPrincipalInfo().ref());
+ if (NS_WARN_IF(loadingPrincipalOrErr.isErr())) {
+ return loadingPrincipalOrErr.unwrapErr();
+ }
+ loadingPrincipal = loadingPrincipalOrErr.unwrap();
+ }
+
+ auto triggeringPrincipalOrErr =
+ PrincipalInfoToPrincipal(loadInfoArgs.triggeringPrincipalInfo());
+ if (NS_WARN_IF(triggeringPrincipalOrErr.isErr())) {
+ return triggeringPrincipalOrErr.unwrapErr();
+ }
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal =
+ triggeringPrincipalOrErr.unwrap();
+
+ nsCOMPtr<nsIPrincipal> principalToInherit;
+ nsCOMPtr<nsIPrincipal> flattenedPrincipalToInherit;
+ if (loadInfoArgs.principalToInheritInfo().isSome()) {
+ auto principalToInheritOrErr =
+ PrincipalInfoToPrincipal(loadInfoArgs.principalToInheritInfo().ref());
+ if (NS_WARN_IF(principalToInheritOrErr.isErr())) {
+ return principalToInheritOrErr.unwrapErr();
+ }
+ flattenedPrincipalToInherit = principalToInheritOrErr.unwrap();
+ }
+
+ if (XRE_IsContentProcess()) {
+ auto targetBrowsingContextId = loadInfoArgs.frameBrowsingContextID()
+ ? loadInfoArgs.frameBrowsingContextID()
+ : loadInfoArgs.browsingContextID();
+ if (RefPtr<BrowsingContext> bc =
+ BrowsingContext::Get(targetBrowsingContextId)) {
+ auto [originalTriggeringPrincipal, originalPrincipalToInherit] =
+ bc->GetTriggeringAndInheritPrincipalsForCurrentLoad();
+
+ if (originalTriggeringPrincipal &&
+ originalTriggeringPrincipal->Equals(triggeringPrincipal)) {
+ triggeringPrincipal = originalTriggeringPrincipal;
+ }
+ if (originalPrincipalToInherit &&
+ (loadInfoArgs.securityFlags() &
+ nsILoadInfo::SEC_FORCE_INHERIT_PRINCIPAL) &&
+ originalPrincipalToInherit->Equals(flattenedPrincipalToInherit)) {
+ principalToInherit = originalPrincipalToInherit;
+ }
+ }
+ }
+ if (!principalToInherit && loadInfoArgs.principalToInheritInfo().isSome()) {
+ principalToInherit = flattenedPrincipalToInherit;
+ }
+
+ nsCOMPtr<nsIPrincipal> topLevelPrincipal;
+ if (loadInfoArgs.topLevelPrincipalInfo().isSome()) {
+ auto topLevelPrincipalOrErr =
+ PrincipalInfoToPrincipal(loadInfoArgs.topLevelPrincipalInfo().ref());
+ if (NS_WARN_IF(topLevelPrincipalOrErr.isErr())) {
+ return topLevelPrincipalOrErr.unwrapErr();
+ }
+ topLevelPrincipal = topLevelPrincipalOrErr.unwrap();
+ }
+
+ nsCOMPtr<nsIURI> resultPrincipalURI;
+ if (loadInfoArgs.resultPrincipalURI().isSome()) {
+ resultPrincipalURI = DeserializeURI(loadInfoArgs.resultPrincipalURI());
+ NS_ENSURE_TRUE(resultPrincipalURI, NS_ERROR_UNEXPECTED);
+ }
+
+ // If we received this message from a content process, reset
+ // triggeringRemoteType to the process which sent us the message. If the
+ // parent sent us the message, we trust it to provide the correct triggering
+ // remote type.
+ //
+ // This means that the triggering remote type will be reset if a LoadInfo is
+ // bounced through a content process, as the LoadInfo can no longer be
+ // validated to be coming from the originally specified remote type.
+ nsCString triggeringRemoteType = loadInfoArgs.triggeringRemoteType();
+ if (aOriginRemoteType != NOT_REMOTE_TYPE &&
+ aOriginRemoteType != triggeringRemoteType) {
+ triggeringRemoteType = aOriginRemoteType;
+ }
+
+ RedirectHistoryArray redirectChainIncludingInternalRedirects;
+ for (const RedirectHistoryEntryInfo& entryInfo :
+ loadInfoArgs.redirectChainIncludingInternalRedirects()) {
+ nsCOMPtr<nsIRedirectHistoryEntry> redirectHistoryEntry =
+ RHEntryInfoToRHEntry(entryInfo);
+ NS_ENSURE_TRUE(redirectHistoryEntry, NS_ERROR_UNEXPECTED);
+ redirectChainIncludingInternalRedirects.AppendElement(
+ redirectHistoryEntry.forget());
+ }
+
+ RedirectHistoryArray redirectChain;
+ for (const RedirectHistoryEntryInfo& entryInfo :
+ loadInfoArgs.redirectChain()) {
+ nsCOMPtr<nsIRedirectHistoryEntry> redirectHistoryEntry =
+ RHEntryInfoToRHEntry(entryInfo);
+ NS_ENSURE_TRUE(redirectHistoryEntry, NS_ERROR_UNEXPECTED);
+ redirectChain.AppendElement(redirectHistoryEntry.forget());
+ }
+ nsTArray<nsCOMPtr<nsIPrincipal>> ancestorPrincipals;
+ nsTArray<uint64_t> ancestorBrowsingContextIDs;
+ if (XRE_IsParentProcess() &&
+ (nsContentUtils::InternalContentPolicyTypeToExternal(
+ loadInfoArgs.contentPolicyType()) !=
+ ExtContentPolicy::TYPE_DOCUMENT)) {
+ // Only fill out ancestor principals and browsing context IDs when we
+ // are deserializing LoadInfoArgs to be LoadInfo for a subresource
+ RefPtr<BrowsingContext> parentBC =
+ BrowsingContext::Get(loadInfoArgs.browsingContextID());
+ if (parentBC) {
+ LoadInfo::ComputeAncestors(parentBC->Canonical(), ancestorPrincipals,
+ ancestorBrowsingContextIDs);
+ }
+ }
+
+ Maybe<ClientInfo> clientInfo;
+ if (loadInfoArgs.clientInfo().isSome()) {
+ clientInfo.emplace(ClientInfo(loadInfoArgs.clientInfo().ref()));
+ }
+
+ Maybe<ClientInfo> reservedClientInfo;
+ if (loadInfoArgs.reservedClientInfo().isSome()) {
+ reservedClientInfo.emplace(
+ ClientInfo(loadInfoArgs.reservedClientInfo().ref()));
+ }
+
+ Maybe<ClientInfo> initialClientInfo;
+ if (loadInfoArgs.initialClientInfo().isSome()) {
+ initialClientInfo.emplace(
+ ClientInfo(loadInfoArgs.initialClientInfo().ref()));
+ }
+
+ // We can have an initial client info or a reserved client info, but not both.
+ MOZ_DIAGNOSTIC_ASSERT(reservedClientInfo.isNothing() ||
+ initialClientInfo.isNothing());
+ NS_ENSURE_TRUE(
+ reservedClientInfo.isNothing() || initialClientInfo.isNothing(),
+ NS_ERROR_UNEXPECTED);
+
+ Maybe<ServiceWorkerDescriptor> controller;
+ if (loadInfoArgs.controller().isSome()) {
+ controller.emplace(
+ ServiceWorkerDescriptor(loadInfoArgs.controller().ref()));
+ }
+
+ nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
+ CookieJarSettings::Deserialize(loadInfoArgs.cookieJarSettings(),
+ getter_AddRefs(cookieJarSettings));
+
+ Maybe<RFPTarget> overriddenFingerprintingSettings;
+ if (loadInfoArgs.overriddenFingerprintingSettings().isSome()) {
+ overriddenFingerprintingSettings.emplace(
+ RFPTarget(loadInfoArgs.overriddenFingerprintingSettings().ref()));
+ }
+
+ nsCOMPtr<nsIContentSecurityPolicy> cspToInherit;
+ Maybe<mozilla::ipc::CSPInfo> cspToInheritInfo =
+ loadInfoArgs.cspToInheritInfo();
+ if (cspToInheritInfo.isSome()) {
+ nsCOMPtr<Document> doc = do_QueryInterface(aCspToInheritLoadingContext);
+ cspToInherit = CSPInfoToCSP(cspToInheritInfo.ref(), doc);
+ }
+
+ // Restore the loadingContext for frames using the BrowsingContext's
+ // embedder element. Note that this only works if the embedder is
+ // same-process, so won't be fission compatible.
+ nsCOMPtr<nsINode> loadingContext;
+ RefPtr<BrowsingContext> frameBrowsingContext =
+ BrowsingContext::Get(loadInfoArgs.frameBrowsingContextID());
+ if (frameBrowsingContext) {
+ loadingContext = frameBrowsingContext->GetEmbedderElement();
+ }
+
+ Maybe<bool> isThirdPartyContextToTopWindow;
+ if (loadInfoArgs.isThirdPartyContextToTopWindow().isSome()) {
+ isThirdPartyContextToTopWindow.emplace(
+ loadInfoArgs.isThirdPartyContextToTopWindow().ref());
+ }
+
+ nsCOMPtr<nsIInterceptionInfo> interceptionInfo;
+ if (loadInfoArgs.interceptionInfo().isSome()) {
+ const InterceptionInfoArg& interceptionInfoArg =
+ loadInfoArgs.interceptionInfo().ref();
+ nsCOMPtr<nsIPrincipal> triggeringPrincipal;
+ if (interceptionInfoArg.triggeringPrincipalInfo().isSome()) {
+ auto triggeringPrincipalOrErr = PrincipalInfoToPrincipal(
+ interceptionInfoArg.triggeringPrincipalInfo().ref());
+ if (NS_WARN_IF(triggeringPrincipalOrErr.isErr())) {
+ return triggeringPrincipalOrErr.unwrapErr();
+ }
+ triggeringPrincipal = triggeringPrincipalOrErr.unwrap();
+ }
+
+ RedirectHistoryArray redirectChain;
+ for (const RedirectHistoryEntryInfo& entryInfo :
+ interceptionInfoArg.redirectChain()) {
+ nsCOMPtr<nsIRedirectHistoryEntry> redirectHistoryEntry =
+ RHEntryInfoToRHEntry(entryInfo);
+ NS_ENSURE_TRUE(redirectHistoryEntry, NS_ERROR_UNEXPECTED);
+ redirectChain.AppendElement(redirectHistoryEntry.forget());
+ }
+
+ interceptionInfo = new InterceptionInfo(
+ triggeringPrincipal, interceptionInfoArg.contentPolicyType(),
+ redirectChain, interceptionInfoArg.fromThirdParty());
+ }
+
+ RefPtr<mozilla::net::LoadInfo> loadInfo = new mozilla::net::LoadInfo(
+ loadingPrincipal, triggeringPrincipal, principalToInherit,
+ topLevelPrincipal, resultPrincipalURI, cookieJarSettings, cspToInherit,
+ triggeringRemoteType, loadInfoArgs.sandboxedNullPrincipalID(), clientInfo,
+ reservedClientInfo, initialClientInfo, controller,
+ loadInfoArgs.securityFlags(), loadInfoArgs.sandboxFlags(),
+ loadInfoArgs.triggeringSandboxFlags(), loadInfoArgs.triggeringWindowId(),
+ loadInfoArgs.triggeringStorageAccess(), loadInfoArgs.contentPolicyType(),
+ static_cast<LoadTainting>(loadInfoArgs.tainting()),
+ loadInfoArgs.blockAllMixedContent(),
+ loadInfoArgs.upgradeInsecureRequests(),
+ loadInfoArgs.browserUpgradeInsecureRequests(),
+ loadInfoArgs.browserDidUpgradeInsecureRequests(),
+ loadInfoArgs.browserWouldUpgradeInsecureRequests(),
+ loadInfoArgs.forceAllowDataURI(),
+ loadInfoArgs.allowInsecureRedirectToDataURI(),
+ loadInfoArgs.skipContentPolicyCheckForWebRequest(),
+ loadInfoArgs.originalFrameSrcLoad(),
+ loadInfoArgs.forceInheritPrincipalDropped(), loadInfoArgs.innerWindowID(),
+ loadInfoArgs.browsingContextID(), loadInfoArgs.frameBrowsingContextID(),
+ loadInfoArgs.initialSecurityCheckDone(),
+ loadInfoArgs.isInThirdPartyContext(), isThirdPartyContextToTopWindow,
+ loadInfoArgs.isFormSubmission(), loadInfoArgs.sendCSPViolationEvents(),
+ loadInfoArgs.originAttributes(),
+ std::move(redirectChainIncludingInternalRedirects),
+ std::move(redirectChain), std::move(ancestorPrincipals),
+ ancestorBrowsingContextIDs, loadInfoArgs.corsUnsafeHeaders(),
+ loadInfoArgs.forcePreflight(), loadInfoArgs.isPreflight(),
+ loadInfoArgs.loadTriggeredFromExternal(),
+ loadInfoArgs.serviceWorkerTaintingSynthesized(),
+ loadInfoArgs.documentHasUserInteracted(),
+ loadInfoArgs.allowListFutureDocumentsCreatedFromThisRedirectChain(),
+ loadInfoArgs.needForCheckingAntiTrackingHeuristic(),
+ loadInfoArgs.cspNonce(), loadInfoArgs.integrityMetadata(),
+ loadInfoArgs.skipContentSniffing(), loadInfoArgs.httpsOnlyStatus(),
+ loadInfoArgs.hstsStatus(), loadInfoArgs.hasValidUserGestureActivation(),
+ loadInfoArgs.allowDeprecatedSystemRequests(),
+ loadInfoArgs.isInDevToolsContext(), loadInfoArgs.parserCreatedScript(),
+ loadInfoArgs.storagePermission(), overriddenFingerprintingSettings,
+ loadInfoArgs.isMetaRefresh(), loadInfoArgs.requestBlockingReason(),
+ loadingContext, loadInfoArgs.loadingEmbedderPolicy(),
+ loadInfoArgs.originTrialCoepCredentiallessEnabledForTopLevel(),
+ loadInfoArgs.unstrippedURI(), interceptionInfo,
+ loadInfoArgs.hasInjectedCookieForCookieBannerHandling(),
+ loadInfoArgs.wasSchemelessInput());
+
+ if (loadInfoArgs.isFromProcessingFrameAttributes()) {
+ loadInfo->SetIsFromProcessingFrameAttributes();
+ }
+
+ if (loadInfoArgs.isMediaRequest()) {
+ loadInfo->SetIsMediaRequest(true);
+
+ if (loadInfoArgs.isMediaInitialRequest()) {
+ loadInfo->SetIsMediaInitialRequest(true);
+ }
+ }
+
+ if (loadInfoArgs.isFromObjectOrEmbed()) {
+ loadInfo->SetIsFromObjectOrEmbed(true);
+ }
+
+ loadInfo.forget(outLoadInfo);
+ return NS_OK;
+}
+
+void LoadInfoToParentLoadInfoForwarder(
+ nsILoadInfo* aLoadInfo, ParentLoadInfoForwarderArgs* aForwarderArgsOut) {
+ Maybe<IPCServiceWorkerDescriptor> ipcController;
+ Maybe<ServiceWorkerDescriptor> controller(aLoadInfo->GetController());
+ if (controller.isSome()) {
+ ipcController.emplace(controller.ref().ToIPC());
+ }
+
+ uint32_t tainting = nsILoadInfo::TAINTING_BASIC;
+ Unused << aLoadInfo->GetTainting(&tainting);
+
+ Maybe<CookieJarSettingsArgs> cookieJarSettingsArgs;
+
+ nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
+ nsresult rv =
+ aLoadInfo->GetCookieJarSettings(getter_AddRefs(cookieJarSettings));
+ CookieJarSettings* cs =
+ static_cast<CookieJarSettings*>(cookieJarSettings.get());
+ if (NS_SUCCEEDED(rv) && cookieJarSettings && cs->HasBeenChanged()) {
+ CookieJarSettingsArgs args;
+ cs->Serialize(args);
+ cookieJarSettingsArgs = Some(args);
+ }
+
+ nsCOMPtr<nsIURI> unstrippedURI;
+ Unused << aLoadInfo->GetUnstrippedURI(getter_AddRefs(unstrippedURI));
+
+ Maybe<bool> isThirdPartyContextToTopWindow;
+ if (static_cast<LoadInfo*>(aLoadInfo)
+ ->HasIsThirdPartyContextToTopWindowSet()) {
+ isThirdPartyContextToTopWindow.emplace(
+ aLoadInfo->GetIsThirdPartyContextToTopWindow());
+ }
+
+ Maybe<uint64_t> overriddenFingerprintingSettingsArg;
+ Maybe<RFPTarget> overriddenFingerprintingSettings =
+ aLoadInfo->GetOverriddenFingerprintingSettings();
+
+ if (overriddenFingerprintingSettings) {
+ overriddenFingerprintingSettingsArg =
+ Some(uint64_t(overriddenFingerprintingSettings.ref()));
+ }
+
+ *aForwarderArgsOut = ParentLoadInfoForwarderArgs(
+ aLoadInfo->GetAllowInsecureRedirectToDataURI(), ipcController, tainting,
+ aLoadInfo->GetSkipContentSniffing(), aLoadInfo->GetHttpsOnlyStatus(),
+ aLoadInfo->GetHstsStatus(), aLoadInfo->GetHasValidUserGestureActivation(),
+ aLoadInfo->GetAllowDeprecatedSystemRequests(),
+ aLoadInfo->GetIsInDevToolsContext(), aLoadInfo->GetParserCreatedScript(),
+ aLoadInfo->GetTriggeringSandboxFlags(),
+ aLoadInfo->GetTriggeringWindowId(),
+ aLoadInfo->GetTriggeringStorageAccess(),
+ aLoadInfo->GetServiceWorkerTaintingSynthesized(),
+ aLoadInfo->GetDocumentHasUserInteracted(),
+ aLoadInfo->GetAllowListFutureDocumentsCreatedFromThisRedirectChain(),
+ cookieJarSettingsArgs, aLoadInfo->GetRequestBlockingReason(),
+ aLoadInfo->GetStoragePermission(), overriddenFingerprintingSettingsArg,
+ aLoadInfo->GetIsMetaRefresh(), isThirdPartyContextToTopWindow,
+ aLoadInfo->GetIsInThirdPartyContext(), unstrippedURI);
+}
+
+nsresult MergeParentLoadInfoForwarder(
+ ParentLoadInfoForwarderArgs const& aForwarderArgs, nsILoadInfo* aLoadInfo) {
+ nsresult rv;
+
+ rv = aLoadInfo->SetAllowInsecureRedirectToDataURI(
+ aForwarderArgs.allowInsecureRedirectToDataURI());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ aLoadInfo->ClearController();
+ auto& controller = aForwarderArgs.controller();
+ if (controller.isSome()) {
+ aLoadInfo->SetController(ServiceWorkerDescriptor(controller.ref()));
+ }
+
+ if (aForwarderArgs.serviceWorkerTaintingSynthesized()) {
+ aLoadInfo->SynthesizeServiceWorkerTainting(
+ static_cast<LoadTainting>(aForwarderArgs.tainting()));
+ } else {
+ aLoadInfo->MaybeIncreaseTainting(aForwarderArgs.tainting());
+ }
+
+ rv = aLoadInfo->SetSkipContentSniffing(aForwarderArgs.skipContentSniffing());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetHttpsOnlyStatus(aForwarderArgs.httpsOnlyStatus());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetHstsStatus(aForwarderArgs.hstsStatus());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetTriggeringSandboxFlags(
+ aForwarderArgs.triggeringSandboxFlags());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetTriggeringWindowId(aForwarderArgs.triggeringWindowId());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetTriggeringStorageAccess(
+ aForwarderArgs.triggeringStorageAccess());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetHasValidUserGestureActivation(
+ aForwarderArgs.hasValidUserGestureActivation());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetAllowDeprecatedSystemRequests(
+ aForwarderArgs.allowDeprecatedSystemRequests());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetIsInDevToolsContext(aForwarderArgs.isInDevToolsContext());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetParserCreatedScript(aForwarderArgs.parserCreatedScript());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ MOZ_ALWAYS_SUCCEEDS(aLoadInfo->SetDocumentHasUserInteracted(
+ aForwarderArgs.documentHasUserInteracted()));
+ MOZ_ALWAYS_SUCCEEDS(
+ aLoadInfo->SetAllowListFutureDocumentsCreatedFromThisRedirectChain(
+ aForwarderArgs
+ .allowListFutureDocumentsCreatedFromThisRedirectChain()));
+ MOZ_ALWAYS_SUCCEEDS(aLoadInfo->SetRequestBlockingReason(
+ aForwarderArgs.requestBlockingReason()));
+
+ const Maybe<CookieJarSettingsArgs>& cookieJarSettingsArgs =
+ aForwarderArgs.cookieJarSettings();
+ if (cookieJarSettingsArgs.isSome()) {
+ nsCOMPtr<nsICookieJarSettings> cookieJarSettings;
+ nsresult rv =
+ aLoadInfo->GetCookieJarSettings(getter_AddRefs(cookieJarSettings));
+ if (NS_SUCCEEDED(rv) && cookieJarSettings) {
+ static_cast<CookieJarSettings*>(cookieJarSettings.get())
+ ->Merge(cookieJarSettingsArgs.ref());
+ }
+ }
+
+ rv = aLoadInfo->SetStoragePermission(aForwarderArgs.storagePermission());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetIsMetaRefresh(aForwarderArgs.isMetaRefresh());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ const Maybe<uint64_t> overriddenFingerprintingSettings =
+ aForwarderArgs.overriddenFingerprintingSettings();
+ if (overriddenFingerprintingSettings.isSome()) {
+ aLoadInfo->SetOverriddenFingerprintingSettings(
+ RFPTarget(overriddenFingerprintingSettings.ref()));
+ }
+
+ static_cast<LoadInfo*>(aLoadInfo)->ClearIsThirdPartyContextToTopWindow();
+ if (aForwarderArgs.isThirdPartyContextToTopWindow().isSome()) {
+ rv = aLoadInfo->SetIsThirdPartyContextToTopWindow(
+ aForwarderArgs.isThirdPartyContextToTopWindow().ref());
+ }
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetIsInThirdPartyContext(
+ aForwarderArgs.isInThirdPartyContext());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ rv = aLoadInfo->SetUnstrippedURI(aForwarderArgs.unstrippedURI());
+ NS_ENSURE_SUCCESS(rv, rv);
+
+ return NS_OK;
+}
+
+void LoadInfoToChildLoadInfoForwarder(
+ nsILoadInfo* aLoadInfo, ChildLoadInfoForwarderArgs* aForwarderArgsOut) {
+ Maybe<IPCClientInfo> ipcReserved;
+ Maybe<ClientInfo> reserved(aLoadInfo->GetReservedClientInfo());
+ if (reserved.isSome()) {
+ ipcReserved.emplace(reserved.ref().ToIPC());
+ }
+
+ Maybe<IPCClientInfo> ipcInitial;
+ Maybe<ClientInfo> initial(aLoadInfo->GetInitialClientInfo());
+ if (initial.isSome()) {
+ ipcInitial.emplace(initial.ref().ToIPC());
+ }
+
+ Maybe<IPCServiceWorkerDescriptor> ipcController;
+ Maybe<ServiceWorkerDescriptor> controller(aLoadInfo->GetController());
+ if (controller.isSome()) {
+ ipcController.emplace(controller.ref().ToIPC());
+ }
+
+ *aForwarderArgsOut =
+ ChildLoadInfoForwarderArgs(ipcReserved, ipcInitial, ipcController,
+ aLoadInfo->GetRequestBlockingReason());
+}
+
+nsresult MergeChildLoadInfoForwarder(
+ const ChildLoadInfoForwarderArgs& aForwarderArgs, nsILoadInfo* aLoadInfo) {
+ Maybe<ClientInfo> reservedClientInfo;
+ auto& ipcReserved = aForwarderArgs.reservedClientInfo();
+ if (ipcReserved.isSome()) {
+ reservedClientInfo.emplace(ClientInfo(ipcReserved.ref()));
+ }
+
+ Maybe<ClientInfo> initialClientInfo;
+ auto& ipcInitial = aForwarderArgs.initialClientInfo();
+ if (ipcInitial.isSome()) {
+ initialClientInfo.emplace(ClientInfo(ipcInitial.ref()));
+ }
+
+ // There should only be at most one reserved or initial ClientInfo.
+ if (NS_WARN_IF(reservedClientInfo.isSome() && initialClientInfo.isSome())) {
+ return NS_ERROR_FAILURE;
+ }
+
+ // If we received no reserved or initial ClientInfo, then we must not
+ // already have one set. There are no use cases where this should
+ // happen and we don't have a way to clear the current value.
+ if (NS_WARN_IF(reservedClientInfo.isNothing() &&
+ initialClientInfo.isNothing() &&
+ (aLoadInfo->GetReservedClientInfo().isSome() ||
+ aLoadInfo->GetInitialClientInfo().isSome()))) {
+ return NS_ERROR_FAILURE;
+ }
+
+ if (reservedClientInfo.isSome()) {
+ // We need to override here instead of simply set the value. This
+ // allows us to change the reserved client. This is necessary when
+ // the ClientChannelHelper created a new reserved client in the
+ // child-side of the redirect.
+ aLoadInfo->OverrideReservedClientInfoInParent(reservedClientInfo.ref());
+ } else if (initialClientInfo.isSome()) {
+ aLoadInfo->SetInitialClientInfo(initialClientInfo.ref());
+ }
+
+ aLoadInfo->ClearController();
+ auto& controller = aForwarderArgs.controller();
+ if (controller.isSome()) {
+ aLoadInfo->SetController(ServiceWorkerDescriptor(controller.ref()));
+ }
+
+ uint32_t blockingReason = aForwarderArgs.requestBlockingReason();
+ if (blockingReason) {
+ // We only want to override when non-null, so that any earlier set non-null
+ // value is not reverted to 0.
+ aLoadInfo->SetRequestBlockingReason(blockingReason);
+ }
+
+ return NS_OK;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/BackgroundUtils.h b/ipc/glue/BackgroundUtils.h
new file mode 100644
index 0000000000..5d8f80e935
--- /dev/null
+++ b/ipc/glue/BackgroundUtils.h
@@ -0,0 +1,194 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_backgroundutils_h__
+#define mozilla_ipc_backgroundutils_h__
+
+#include "ipc/IPCMessageUtils.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/OriginAttributes.h"
+#include "nsCOMPtr.h"
+#include "nscore.h"
+
+class nsIContentSecurityPolicy;
+class nsILoadInfo;
+class nsINode;
+class nsIPrincipal;
+class nsIRedirectHistoryEntry;
+
+namespace IPC {
+
+namespace detail {
+template <class ParamType>
+struct OriginAttributesParamTraits {
+ typedef ParamType paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ nsAutoCString suffix;
+ aParam.CreateSuffix(suffix);
+ WriteParam(aWriter, suffix);
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ nsAutoCString suffix;
+ return ReadParam(aReader, &suffix) && aResult->PopulateFromSuffix(suffix);
+ }
+};
+} // namespace detail
+
+template <>
+struct ParamTraits<mozilla::OriginAttributes>
+ : public detail::OriginAttributesParamTraits<mozilla::OriginAttributes> {};
+
+} // namespace IPC
+
+namespace mozilla {
+
+namespace dom {
+class Document;
+}
+
+namespace net {
+class ChildLoadInfoForwarderArgs;
+class LoadInfoArgs;
+class LoadInfo;
+class ParentLoadInfoForwarderArgs;
+class RedirectHistoryEntryInfo;
+} // namespace net
+
+namespace ipc {
+
+class ContentSecurityPolicy;
+class CSPInfo;
+class PrincipalInfo;
+
+/**
+ * Convert a PrincipalInfo to an nsIPrincipal.
+ *
+ * MUST be called on the main thread.
+ */
+Result<nsCOMPtr<nsIPrincipal>, nsresult> PrincipalInfoToPrincipal(
+ const PrincipalInfo& aPrincipalInfo);
+
+/**
+ * Convert an nsIPrincipal to a PrincipalInfo.
+ *
+ * MUST be called on the main thread only.
+ */
+nsresult PrincipalToPrincipalInfo(nsIPrincipal* aPrincipal,
+ PrincipalInfo* aPrincipalInfo,
+ bool aSkipBaseDomain = false);
+
+/**
+ * Compare storage keys for equivalence.
+ *
+ * Only use with storage keys retrieved from nsIGlobalObject::GetStorageKey!
+ * Bug 1776271 tracks enhancing this into a proper type.
+ */
+bool StorageKeysEqual(const PrincipalInfo& aLeft, const PrincipalInfo& aRight);
+
+/**
+ * Convert a CSPInfo to an nsIContentSecurityPolicy.
+ *
+ * MUST be called on the main thread only.
+ *
+ * If possible, provide a requesting doc, so policy violation events can
+ * be dispatched correctly. If aRequestingDoc is null, then the CSPInfo holds
+ * the necessary fallback information, like a serialized requestPrincipal,
+ * to generate a valid nsIContentSecurityPolicy.
+ */
+already_AddRefed<nsIContentSecurityPolicy> CSPInfoToCSP(
+ const CSPInfo& aCSPInfo, mozilla::dom::Document* aRequestingDoc,
+ nsresult* aOptionalResult = nullptr);
+
+/**
+ * Convert an nsIContentSecurityPolicy to a CSPInfo.
+ *
+ * MUST be called on the main thread only.
+ */
+nsresult CSPToCSPInfo(nsIContentSecurityPolicy* aCSP, CSPInfo* aCSPInfo);
+
+/**
+ * Return true if this PrincipalInfo is a content principal and it has
+ * a privateBrowsing id in its OriginAttributes
+ */
+bool IsPrincipalInfoPrivate(const PrincipalInfo& aPrincipalInfo);
+
+/**
+ * Convert an RedirectHistoryEntryInfo to a nsIRedirectHistoryEntry.
+ */
+
+already_AddRefed<nsIRedirectHistoryEntry> RHEntryInfoToRHEntry(
+ const mozilla::net::RedirectHistoryEntryInfo& aRHEntryInfo);
+
+/**
+ * Convert an nsIRedirectHistoryEntry to a RedirectHistoryEntryInfo.
+ */
+
+nsresult RHEntryToRHEntryInfo(
+ nsIRedirectHistoryEntry* aRHEntry,
+ mozilla::net::RedirectHistoryEntryInfo* aRHEntryInfo);
+
+/**
+ * Convert a LoadInfo to LoadInfoArgs struct.
+ */
+nsresult LoadInfoToLoadInfoArgs(nsILoadInfo* aLoadInfo,
+ mozilla::net::LoadInfoArgs* outLoadInfoArgs);
+
+/**
+ * Convert LoadInfoArgs to a LoadInfo.
+ */
+nsresult LoadInfoArgsToLoadInfo(const mozilla::net::LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsILoadInfo** outLoadInfo);
+nsresult LoadInfoArgsToLoadInfo(const mozilla::net::LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsINode* aCspToInheritLoadingContext,
+ nsILoadInfo** outLoadInfo);
+nsresult LoadInfoArgsToLoadInfo(const net::LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ mozilla::net::LoadInfo** outLoadInfo);
+nsresult LoadInfoArgsToLoadInfo(const net::LoadInfoArgs& aLoadInfoArgs,
+ const nsACString& aOriginRemoteType,
+ nsINode* aCspToInheritLoadingContext,
+ mozilla::net::LoadInfo** outLoadInfo);
+
+/**
+ * Fills ParentLoadInfoForwarderArgs with properties we want to carry to child
+ * processes.
+ */
+void LoadInfoToParentLoadInfoForwarder(
+ nsILoadInfo* aLoadInfo,
+ mozilla::net::ParentLoadInfoForwarderArgs* aForwarderArgsOut);
+
+/**
+ * Merges (replaces) properties of an existing LoadInfo on a child process
+ * with properties carried down through ParentLoadInfoForwarderArgs.
+ */
+nsresult MergeParentLoadInfoForwarder(
+ mozilla::net::ParentLoadInfoForwarderArgs const& aForwarderArgs,
+ nsILoadInfo* aLoadInfo);
+
+/**
+ * Fills ChildLoadInfoForwarderArgs with properties we want to carry to the
+ * parent process after the initial channel creation.
+ */
+void LoadInfoToChildLoadInfoForwarder(
+ nsILoadInfo* aLoadInfo,
+ mozilla::net::ChildLoadInfoForwarderArgs* aForwarderArgsOut);
+
+/**
+ * Merges (replaces) properties of an existing LoadInfo on the parent process
+ * with properties contained in a ChildLoadInfoForwarderArgs.
+ */
+nsresult MergeChildLoadInfoForwarder(
+ const mozilla::net::ChildLoadInfoForwarderArgs& aForwardArgs,
+ nsILoadInfo* aLoadInfo);
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_backgroundutils_h__
diff --git a/ipc/glue/BigBuffer.cpp b/ipc/glue/BigBuffer.cpp
new file mode 100644
index 0000000000..822ffe20fe
--- /dev/null
+++ b/ipc/glue/BigBuffer.cpp
@@ -0,0 +1,105 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/BigBuffer.h"
+
+#include "mozilla/ipc/SharedMemoryBasic.h"
+#include "nsDebug.h"
+
+namespace mozilla::ipc {
+
+BigBuffer::BigBuffer(Adopt, SharedMemory* aSharedMemory, size_t aSize)
+ : mSize(aSize), mData(AsVariant(RefPtr{aSharedMemory})) {
+ MOZ_RELEASE_ASSERT(aSharedMemory && aSharedMemory->memory(),
+ "shared memory must be non-null and mapped");
+ MOZ_RELEASE_ASSERT(mSize <= aSharedMemory->Size(),
+ "shared memory region isn't large enough");
+}
+
+BigBuffer::BigBuffer(Adopt, uint8_t* aData, size_t aSize)
+ : mSize(aSize), mData(AsVariant(UniqueFreePtr<uint8_t[]>{aData})) {}
+
+uint8_t* BigBuffer::Data() {
+ return mData.is<0>() ? mData.as<0>().get()
+ : reinterpret_cast<uint8_t*>(mData.as<1>()->memory());
+}
+const uint8_t* BigBuffer::Data() const {
+ return mData.is<0>()
+ ? mData.as<0>().get()
+ : reinterpret_cast<const uint8_t*>(mData.as<1>()->memory());
+}
+
+auto BigBuffer::TryAllocBuffer(size_t aSize) -> Maybe<Storage> {
+ if (aSize <= kShmemThreshold) {
+ auto mem = UniqueFreePtr<uint8_t[]>{
+ reinterpret_cast<uint8_t*>(malloc(aSize))}; // Fallible!
+ if (!mem) return {};
+ return Some(AsVariant(std::move(mem)));
+ }
+
+ RefPtr<SharedMemory> shmem = new SharedMemoryBasic();
+ size_t capacity = SharedMemory::PageAlignedSize(aSize);
+ if (!shmem->Create(capacity) || !shmem->Map(capacity)) {
+ return {};
+ }
+ return Some(AsVariant(shmem));
+}
+
+} // namespace mozilla::ipc
+
+void IPC::ParamTraits<mozilla::ipc::BigBuffer>::Write(MessageWriter* aWriter,
+ paramType&& aParam) {
+ using namespace mozilla::ipc;
+ size_t size = std::exchange(aParam.mSize, 0);
+ auto data = std::exchange(aParam.mData, BigBuffer::NoData());
+
+ WriteParam(aWriter, size);
+ bool isShmem = data.is<1>();
+ WriteParam(aWriter, isShmem);
+
+ if (isShmem) {
+ if (!data.as<1>()->WriteHandle(aWriter)) {
+ aWriter->FatalError("Failed to write data shmem");
+ }
+ } else {
+ aWriter->WriteBytes(data.as<0>().get(), size);
+ }
+}
+
+bool IPC::ParamTraits<mozilla::ipc::BigBuffer>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ using namespace mozilla::ipc;
+ size_t size = 0;
+ bool isShmem = false;
+ if (!ReadParam(aReader, &size) || !ReadParam(aReader, &isShmem)) {
+ aReader->FatalError("Failed to read data size and format");
+ return false;
+ }
+
+ if (isShmem) {
+ RefPtr<SharedMemory> shmem = new SharedMemoryBasic();
+ size_t capacity = SharedMemory::PageAlignedSize(size);
+ if (!shmem->ReadHandle(aReader) || !shmem->Map(capacity)) {
+ aReader->FatalError("Failed to read data shmem");
+ return false;
+ }
+ *aResult = BigBuffer(BigBuffer::Adopt{}, shmem, size);
+ return true;
+ }
+
+ mozilla::UniqueFreePtr<uint8_t[]> buf{
+ reinterpret_cast<uint8_t*>(malloc(size))};
+ if (!buf) {
+ aReader->FatalError("Failed to allocate data buffer");
+ return false;
+ }
+ if (!aReader->ReadBytesInto(buf.get(), size)) {
+ aReader->FatalError("Failed to read data");
+ return false;
+ }
+ *aResult = BigBuffer(BigBuffer::Adopt{}, buf.release(), size);
+ return true;
+}
diff --git a/ipc/glue/BigBuffer.h b/ipc/glue/BigBuffer.h
new file mode 100644
index 0000000000..7136b6c03c
--- /dev/null
+++ b/ipc/glue/BigBuffer.h
@@ -0,0 +1,131 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_BigBuffer_h
+#define mozilla_ipc_BigBuffer_h
+
+#include <stdlib.h>
+#include <inttypes.h>
+#include "mozilla/Span.h"
+#include "mozilla/Variant.h"
+#include "mozilla/ipc/SharedMemory.h"
+
+namespace mozilla::ipc {
+
+class BigBuffer {
+ public:
+ static constexpr size_t kShmemThreshold = 64 * 1024;
+
+ static BigBuffer TryAlloc(const size_t aSize) {
+ auto ret = BigBuffer{};
+ auto data = TryAllocBuffer(aSize);
+ if (data) {
+ ret.mSize = aSize;
+ ret.mData = std::move(data.ref());
+ }
+ return ret;
+ }
+
+ // Return a new BigBuffer which wraps no data.
+ BigBuffer() : mSize(0), mData(NoData()) {}
+
+ BigBuffer(const BigBuffer&) = delete;
+ BigBuffer& operator=(const BigBuffer&) = delete;
+
+ BigBuffer(BigBuffer&& aOther) noexcept
+ : mSize(std::exchange(aOther.mSize, 0)),
+ mData(std::exchange(aOther.mData, NoData())) {}
+
+ BigBuffer& operator=(BigBuffer&& aOther) noexcept {
+ mSize = std::exchange(aOther.mSize, 0);
+ mData = std::exchange(aOther.mData, NoData());
+ return *this;
+ }
+
+ // Create a new BigBuffer with the given size.
+ // The buffer will be created uninitialized and must be fully initialized
+ // before sending over IPC to avoid leaking uninitialized memory to another
+ // process.
+ explicit BigBuffer(size_t aSize) : mSize(aSize), mData(AllocBuffer(aSize)) {}
+
+ // Create a new BigBuffer containing the data from the provided byte slice.
+ explicit BigBuffer(Span<const uint8_t> aData) : BigBuffer(aData.Length()) {
+ memcpy(Data(), aData.Elements(), aData.Length());
+ }
+
+ // Marker to indicate that a particular constructor of BigBuffer adopts
+ // ownership of the provided data.
+ struct Adopt {};
+
+ // Create a new BigBuffer from an existing shared memory region, taking
+ // ownership of that shared memory region. The shared memory region must be
+ // non-null, mapped, and large enough to fit aSize bytes.
+ BigBuffer(Adopt, SharedMemory* aSharedMemory, size_t aSize);
+
+ // Create a new BigBuffer from an existing memory buffer, taking ownership of
+ // that memory region. The region will be freed using `free()` when it is no
+ // longer needed.
+ BigBuffer(Adopt, uint8_t* aData, size_t aSize);
+
+ ~BigBuffer() = default;
+
+ // Returns a pointer to the data stored by this BigBuffer, regardless of
+ // backing storage type.
+ uint8_t* Data();
+ const uint8_t* Data() const;
+
+ // Returns the size of the data stored by this BigBuffer, regardless of
+ // backing storage type.
+ size_t Size() const { return mSize; }
+
+ // Get a view of the BigBuffer's data as a span.
+ Span<uint8_t> AsSpan() { return Span{Data(), Size()}; }
+ Span<const uint8_t> AsSpan() const { return Span{Data(), Size()}; }
+
+ // If the BigBuffer is backed by shared memory, returns a pointer to the
+ // backing SharedMemory region.
+ SharedMemory* GetSharedMemory() const {
+ return mData.is<1>() ? mData.as<1>().get() : nullptr;
+ }
+
+ private:
+ friend struct IPC::ParamTraits<mozilla::ipc::BigBuffer>;
+
+ using Storage = Variant<UniqueFreePtr<uint8_t[]>, RefPtr<SharedMemory>>;
+
+ // Empty storage which holds no data.
+ static Storage NoData() { return AsVariant(UniqueFreePtr<uint8_t[]>{}); }
+
+ // Fallibly allocate a new storage of the given size.
+ static Maybe<Storage> TryAllocBuffer(size_t aSize);
+
+ // Infallibly allocate a new storage of the given size.
+ static Storage AllocBuffer(size_t aSize) {
+ auto ret = TryAllocBuffer(aSize);
+ if (!ret) {
+ NS_ABORT_OOM(aSize);
+ }
+ return std::move(ret.ref());
+ }
+
+ size_t mSize;
+ Storage mData;
+};
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+template <>
+struct ParamTraits<mozilla::ipc::BigBuffer> {
+ using paramType = mozilla::ipc::BigBuffer;
+ static void Write(MessageWriter* aWriter, paramType&& aParam);
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+} // namespace IPC
+
+#endif // mozilla_BigBuffer_h
diff --git a/ipc/glue/BrowserProcessSubThread.cpp b/ipc/glue/BrowserProcessSubThread.cpp
new file mode 100644
index 0000000000..6c2ba6a48c
--- /dev/null
+++ b/ipc/glue/BrowserProcessSubThread.cpp
@@ -0,0 +1,83 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/BrowserProcessSubThread.h"
+#include "mozilla/ipc/NodeController.h"
+
+#if defined(XP_WIN)
+# include <objbase.h>
+#endif
+
+namespace mozilla {
+namespace ipc {
+
+//
+// BrowserProcessSubThread
+//
+
+// Friendly names for the well-known threads.
+static const char* kBrowserThreadNames[BrowserProcessSubThread::ID_COUNT] = {
+ "IPC I/O Parent", // IO
+};
+
+/* static */
+StaticMutex BrowserProcessSubThread::sLock;
+BrowserProcessSubThread* BrowserProcessSubThread::sBrowserThreads[ID_COUNT] = {
+ nullptr, // IO
+};
+
+BrowserProcessSubThread::BrowserProcessSubThread(ID aId)
+ : base::Thread(kBrowserThreadNames[aId]), mIdentifier(aId) {
+ StaticMutexAutoLock lock(sLock);
+ DCHECK(aId >= 0 && aId < ID_COUNT);
+ DCHECK(sBrowserThreads[aId] == nullptr);
+ sBrowserThreads[aId] = this;
+}
+
+BrowserProcessSubThread::~BrowserProcessSubThread() {
+ Stop();
+ {
+ StaticMutexAutoLock lock(sLock);
+ sBrowserThreads[mIdentifier] = nullptr;
+ }
+}
+
+void BrowserProcessSubThread::Init() {
+#if defined(XP_WIN)
+ // Initializes the COM library on the current thread.
+ CoInitialize(nullptr);
+#endif
+
+ // Initialize the ports library in the current thread.
+ if (mIdentifier == IO) {
+ NodeController::InitBrokerProcess();
+ }
+}
+
+void BrowserProcessSubThread::CleanUp() {
+ if (mIdentifier == IO) {
+ NodeController::CleanUp();
+ }
+
+#if defined(XP_WIN)
+ // Closes the COM library on the current thread. CoInitialize must
+ // be balanced by a corresponding call to CoUninitialize.
+ CoUninitialize();
+#endif
+}
+
+// static
+MessageLoop* BrowserProcessSubThread::GetMessageLoop(ID aId) {
+ StaticMutexAutoLock lock(sLock);
+ DCHECK(aId >= 0 && aId < ID_COUNT);
+
+ if (sBrowserThreads[aId]) return sBrowserThreads[aId]->message_loop();
+
+ return nullptr;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/BrowserProcessSubThread.h b/ipc/glue/BrowserProcessSubThread.h
new file mode 100644
index 0000000000..9be8d1ec3d
--- /dev/null
+++ b/ipc/glue/BrowserProcessSubThread.h
@@ -0,0 +1,66 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_BrowserProcessSubThread_h
+#define mozilla_ipc_BrowserProcessSubThread_h
+
+#include "base/thread.h"
+#include "mozilla/StaticMutex.h"
+
+#include "nsDebug.h"
+
+namespace mozilla {
+namespace ipc {
+
+// Copied from browser_process_impl.cc, modified slightly.
+class BrowserProcessSubThread : public base::Thread {
+ public:
+ // An enumeration of the well-known threads.
+ enum ID {
+ IO,
+
+ // This identifier does not represent a thread. Instead it counts
+ // the number of well-known threads. Insert new well-known
+ // threads before this identifier.
+ ID_COUNT
+ };
+
+ explicit BrowserProcessSubThread(ID aId);
+ ~BrowserProcessSubThread();
+
+ static MessageLoop* GetMessageLoop(ID identifier);
+
+ protected:
+ virtual void Init() override;
+ virtual void CleanUp() override;
+
+ private:
+ // The identifier of this thread. Only one thread can exist with a given
+ // identifier at a given time.
+ ID mIdentifier;
+
+ // This lock protects |browser_threads_|. Do not read or modify that array
+ // without holding this lock. Do not block while holding this lock.
+
+ static StaticMutex sLock;
+
+ // An array of the ChromeThread objects. This array is protected by |lock_|.
+ // The threads are not owned by this array. Typically, the threads are owned
+ // on the UI thread by the g_browser_process object. ChromeThreads remove
+ // themselves from this array upon destruction.
+ static BrowserProcessSubThread* sBrowserThreads[ID_COUNT] MOZ_GUARDED_BY(
+ sLock);
+};
+
+inline void AssertIOThread() {
+ NS_ASSERTION(MessageLoop::TYPE_IO == MessageLoop::current()->type(),
+ "should be on the IO thread!");
+}
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_BrowserProcessSubThread_h
diff --git a/ipc/glue/ByteBuf.h b/ipc/glue/ByteBuf.h
new file mode 100644
index 0000000000..3f3a798b89
--- /dev/null
+++ b/ipc/glue/ByteBuf.h
@@ -0,0 +1,71 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* A type that can be sent without needing to make a copy during
+ * serialization. In addition the receiver can take ownership of the
+ * data to avoid having to make an additional copy. */
+
+#ifndef mozilla_ipc_ByteBuf_h
+#define mozilla_ipc_ByteBuf_h
+
+#include "mozilla/Assertions.h"
+
+namespace IPC {
+template <typename T>
+struct ParamTraits;
+}
+
+namespace mozilla {
+
+namespace ipc {
+
+class ByteBuf final {
+ friend struct IPC::ParamTraits<mozilla::ipc::ByteBuf>;
+
+ public:
+ bool Allocate(size_t aLength) {
+ MOZ_ASSERT(mData == nullptr);
+ mData = (uint8_t*)malloc(aLength);
+ if (!mData) {
+ return false;
+ }
+ mLen = aLength;
+ mCapacity = aLength;
+ return true;
+ }
+
+ ByteBuf() : mData(nullptr), mLen(0), mCapacity(0) {}
+
+ ByteBuf(uint8_t* aData, size_t aLen, size_t aCapacity)
+ : mData(aData), mLen(aLen), mCapacity(aCapacity) {}
+
+ ByteBuf(const ByteBuf& aFrom) = delete;
+
+ ByteBuf(ByteBuf&& aFrom)
+ : mData(aFrom.mData), mLen(aFrom.mLen), mCapacity(aFrom.mCapacity) {
+ aFrom.mData = nullptr;
+ aFrom.mLen = 0;
+ aFrom.mCapacity = 0;
+ }
+
+ ByteBuf& operator=(ByteBuf&& aFrom) {
+ std::swap(mData, aFrom.mData);
+ std::swap(mLen, aFrom.mLen);
+ std::swap(mCapacity, aFrom.mCapacity);
+ return *this;
+ }
+
+ ~ByteBuf() { free(mData); }
+
+ uint8_t* mData;
+ size_t mLen;
+ size_t mCapacity;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_ByteBuf_h
diff --git a/ipc/glue/ByteBufUtils.h b/ipc/glue/ByteBufUtils.h
new file mode 100644
index 0000000000..ba19864214
--- /dev/null
+++ b/ipc/glue/ByteBufUtils.h
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* A type that can be sent without needing to make a copy during
+ * serialization. In addition the receiver can take ownership of the
+ * data to avoid having to make an additional copy. */
+
+#ifndef mozilla_ipc_ByteBufUtils_h
+#define mozilla_ipc_ByteBufUtils_h
+
+#include "mozilla/ipc/ByteBuf.h"
+#include "mozilla/CheckedInt.h"
+#include "mozilla/mozalloc_oom.h"
+#include "ipc/IPCMessageUtils.h"
+
+namespace IPC {
+
+template <>
+struct ParamTraits<mozilla::ipc::ByteBuf> {
+ typedef mozilla::ipc::ByteBuf paramType;
+
+ // this is where we transfer the memory from the ByteBuf to IPDL, avoiding a
+ // copy
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ // We need to send the length as a 32-bit value, not a size_t, because on
+ // ARM64 Windows we end up with a 32-bit GMP process sending a ByteBuf to
+ // a 64-bit parent process. WriteBytesZeroCopy takes a uint32_t as an
+ // argument, so it would end up getting truncated anyways. See bug 1757534.
+ mozilla::CheckedInt<uint32_t> length = aParam.mLen;
+ MOZ_RELEASE_ASSERT(length.isValid());
+ WriteParam(aWriter, length.value());
+ // hand over ownership of the buffer to the Message
+ aWriter->WriteBytesZeroCopy(aParam.mData, length.value(), aParam.mCapacity);
+ aParam.mData = nullptr;
+ aParam.mCapacity = 0;
+ aParam.mLen = 0;
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ // We make a copy from the BufferList so that we get a contigous result.
+ uint32_t length;
+ if (!ReadParam(aReader, &length)) return false;
+ if (!aResult->Allocate(length)) {
+ mozalloc_handle_oom(length);
+ return false;
+ }
+ return aReader->ReadBytesInto(aResult->mData, length);
+ }
+};
+
+} // namespace IPC
+
+#endif // ifndef mozilla_ipc_ByteBufUtils_h
diff --git a/ipc/glue/CrashReporterClient.cpp b/ipc/glue/CrashReporterClient.cpp
new file mode 100644
index 0000000000..7e0eabe6ca
--- /dev/null
+++ b/ipc/glue/CrashReporterClient.cpp
@@ -0,0 +1,47 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrashReporterClient.h"
+#include "nsISupportsImpl.h"
+
+namespace mozilla {
+namespace ipc {
+
+StaticMutex CrashReporterClient::sLock;
+StaticRefPtr<CrashReporterClient> CrashReporterClient::sClientSingleton;
+
+CrashReporterClient::CrashReporterClient() {
+ MOZ_COUNT_CTOR(CrashReporterClient);
+}
+
+CrashReporterClient::~CrashReporterClient() {
+ MOZ_COUNT_DTOR(CrashReporterClient);
+}
+
+/* static */
+void CrashReporterClient::InitSingleton() {
+ {
+ StaticMutexAutoLock lock(sLock);
+
+ MOZ_ASSERT(!sClientSingleton);
+ sClientSingleton = new CrashReporterClient();
+ }
+}
+
+/* static */
+void CrashReporterClient::DestroySingleton() {
+ StaticMutexAutoLock lock(sLock);
+ sClientSingleton = nullptr;
+}
+
+/* static */
+RefPtr<CrashReporterClient> CrashReporterClient::GetSingleton() {
+ StaticMutexAutoLock lock(sLock);
+ return sClientSingleton;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/CrashReporterClient.h b/ipc/glue/CrashReporterClient.h
new file mode 100644
index 0000000000..26ada18a03
--- /dev/null
+++ b/ipc/glue/CrashReporterClient.h
@@ -0,0 +1,51 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_CrashReporterClient_h
+#define mozilla_ipc_CrashReporterClient_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/Unused.h"
+#include "nsExceptionHandler.h"
+
+namespace mozilla {
+namespace ipc {
+
+class CrashReporterClient {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(CrashReporterClient);
+
+ // |aTopLevelProtocol| must have a child-to-parent message:
+ //
+ // async InitCrashReporter(NativeThreadId threadId);
+ template <typename T>
+ static void InitSingleton(T* aToplevelProtocol) {
+ InitSingleton();
+ Unused << aToplevelProtocol->SendInitCrashReporter(
+ CrashReporter::CurrentThreadId());
+ }
+
+ static void InitSingleton();
+
+ static void DestroySingleton();
+ static RefPtr<CrashReporterClient> GetSingleton();
+
+ private:
+ explicit CrashReporterClient();
+ ~CrashReporterClient();
+
+ private:
+ static StaticMutex sLock;
+ static StaticRefPtr<CrashReporterClient> sClientSingleton
+ MOZ_GUARDED_BY(sLock);
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_CrashReporterClient_h
diff --git a/ipc/glue/CrashReporterHelper.h b/ipc/glue/CrashReporterHelper.h
new file mode 100644
index 0000000000..c13901c2cc
--- /dev/null
+++ b/ipc/glue/CrashReporterHelper.h
@@ -0,0 +1,94 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_CrashReporterHelper_h
+#define mozilla_ipc_CrashReporterHelper_h
+
+#include "CrashReporterHost.h"
+#include "mozilla/UniquePtr.h"
+#include "nsIAppStartup.h"
+#include "nsExceptionHandler.h"
+#include "nsICrashService.h"
+#include "nsPrintfCString.h"
+#include "nsServiceManagerUtils.h"
+
+namespace mozilla {
+namespace ipc {
+
+/**
+ * This class encapsulates the common elements of crash report handling for
+ * toplevel protocols representing processes. To use this class, you should:
+ *
+ * 1. Declare a method to initialize the crash reporter in your IPDL:
+ * `async InitCrashReporter(NativeThreadId threadId)`
+ *
+ * 2. Inherit from this class, providing the appropriate `GeckoProcessType`
+ * enum value for the template parameter PT.
+ *
+ * 3. When your protocol actor is destroyed with a reason of `AbnormalShutdown`,
+ * you should call `GenerateCrashReport(OtherPid())`. If you need the crash
+ * report ID it will be copied in the second optional parameter upon
+ * successful crash report generation.
+ */
+template <GeckoProcessType PT>
+class CrashReporterHelper {
+ public:
+ CrashReporterHelper() : mCrashReporter(nullptr) {}
+ IPCResult RecvInitCrashReporter(const CrashReporter::ThreadId& aThreadId) {
+ mCrashReporter = MakeUnique<ipc::CrashReporterHost>(PT, aThreadId);
+ return IPC_OK();
+ }
+
+ protected:
+ void GenerateCrashReport(base::ProcessId aPid,
+ nsString* aMinidumpId = nullptr) {
+ nsAutoString minidumpId;
+ if (!mCrashReporter) {
+ HandleOrphanedMinidump(aPid, minidumpId);
+ } else if (mCrashReporter->GenerateCrashReport(aPid)) {
+ minidumpId = mCrashReporter->MinidumpID();
+ }
+
+ if (aMinidumpId) {
+ *aMinidumpId = minidumpId;
+ }
+
+ mCrashReporter = nullptr;
+ }
+
+ void MaybeTerminateProcess() {
+ if (PR_GetEnv("MOZ_CRASHREPORTER_SHUTDOWN")) {
+ NS_WARNING(nsPrintfCString("Shutting down due to %s process crash.",
+ XRE_GetProcessTypeString())
+ .get());
+ nsCOMPtr<nsIAppStartup> appService =
+ do_GetService("@mozilla.org/toolkit/app-startup;1");
+ if (appService) {
+ bool userAllowedQuit = true;
+ appService->Quit(nsIAppStartup::eForceQuit, 1, &userAllowedQuit);
+ }
+ }
+ }
+
+ private:
+ void HandleOrphanedMinidump(base::ProcessId aPid, nsString& aMinidumpId) {
+ if (CrashReporter::FinalizeOrphanedMinidump(aPid, PT, &aMinidumpId)) {
+ CrashReporterHost::RecordCrash(PT, nsICrashService::CRASH_TYPE_CRASH,
+ aMinidumpId);
+ } else {
+ NS_WARNING(nsPrintfCString("child process pid = %" PRIPID
+ " crashed without leaving a minidump behind",
+ aPid)
+ .get());
+ }
+ }
+
+ protected:
+ UniquePtr<ipc::CrashReporterHost> mCrashReporter;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_CrashReporterHelper_h
diff --git a/ipc/glue/CrashReporterHost.cpp b/ipc/glue/CrashReporterHost.cpp
new file mode 100644
index 0000000000..d4f0c0f968
--- /dev/null
+++ b/ipc/glue/CrashReporterHost.cpp
@@ -0,0 +1,181 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrashReporterHost.h"
+#include "mozilla/dom/Promise.h"
+#include "mozilla/Sprintf.h"
+#include "mozilla/SyncRunnable.h"
+#include "mozilla/Telemetry.h"
+#include "nsServiceManagerUtils.h"
+#include "nsICrashService.h"
+#include "nsXULAppAPI.h"
+#include "nsIFile.h"
+
+namespace mozilla {
+namespace ipc {
+
+CrashReporterHost::CrashReporterHost(GeckoProcessType aProcessType,
+ CrashReporter::ThreadId aThreadId)
+ : mProcessType(aProcessType),
+ mThreadId(aThreadId),
+ mStartTime(::time(nullptr)),
+ mFinalized(false) {}
+
+bool CrashReporterHost::GenerateCrashReport(base::ProcessId aPid) {
+ if (!TakeCrashedChildMinidump(aPid, nullptr)) {
+ return false;
+ }
+
+ FinalizeCrashReport();
+ RecordCrash(mProcessType, nsICrashService::CRASH_TYPE_CRASH, mDumpID);
+ return true;
+}
+
+RefPtr<nsIFile> CrashReporterHost::TakeCrashedChildMinidump(
+ base::ProcessId aPid, uint32_t* aOutSequence) {
+ CrashReporter::AnnotationTable annotations;
+ MOZ_ASSERT(!HasMinidump());
+
+ RefPtr<nsIFile> crashDump;
+ if (!CrashReporter::TakeMinidumpForChild(aPid, getter_AddRefs(crashDump),
+ annotations, aOutSequence)) {
+ return nullptr;
+ }
+ if (!AdoptMinidump(crashDump, annotations)) {
+ return nullptr;
+ }
+ return crashDump;
+}
+
+bool CrashReporterHost::AdoptMinidump(nsIFile* aFile,
+ const AnnotationTable& aAnnotations) {
+ if (!CrashReporter::GetIDFromMinidump(aFile, mDumpID)) {
+ return false;
+ }
+
+ MergeCrashAnnotations(mExtraAnnotations, aAnnotations);
+ return true;
+}
+
+void CrashReporterHost::FinalizeCrashReport() {
+ MOZ_ASSERT(!mFinalized);
+ MOZ_ASSERT(HasMinidump());
+
+ mExtraAnnotations[CrashReporter::Annotation::ProcessType] =
+ XRE_ChildProcessTypeToAnnotation(mProcessType);
+
+ char startTime[32];
+ SprintfLiteral(startTime, "%lld", static_cast<long long>(mStartTime));
+ mExtraAnnotations[CrashReporter::Annotation::StartupTime] =
+ nsDependentCString(startTime);
+
+ CrashReporter::WriteExtraFile(mDumpID, mExtraAnnotations);
+ mFinalized = true;
+}
+
+void CrashReporterHost::DeleteCrashReport() {
+ if (mFinalized && HasMinidump()) {
+ CrashReporter::DeleteMinidumpFilesForID(mDumpID, Some(u"browser"_ns));
+ }
+}
+
+/* static */
+void CrashReporterHost::RecordCrash(GeckoProcessType aProcessType,
+ int32_t aCrashType,
+ const nsString& aChildDumpID) {
+ if (!NS_IsMainThread()) {
+ RefPtr<Runnable> runnable = NS_NewRunnableFunction(
+ "ipc::CrashReporterHost::RecordCrash", [&]() -> void {
+ CrashReporterHost::RecordCrash(aProcessType, aCrashType,
+ aChildDumpID);
+ });
+ RefPtr<nsIThread> mainThread = do_GetMainThread();
+ SyncRunnable::DispatchToThread(mainThread, runnable);
+ return;
+ }
+
+ RecordCrashWithTelemetry(aProcessType, aCrashType);
+ NotifyCrashService(aProcessType, aCrashType, aChildDumpID);
+}
+
+/* static */
+void CrashReporterHost::RecordCrashWithTelemetry(GeckoProcessType aProcessType,
+ int32_t aCrashType) {
+ nsCString key;
+
+ switch (aProcessType) {
+#define GECKO_PROCESS_TYPE(enum_value, enum_name, string_name, proc_typename, \
+ process_bin_type, procinfo_typename, \
+ webidl_typename, allcaps_name) \
+ case GeckoProcessType_##enum_name: \
+ key.AssignLiteral(string_name); \
+ break;
+#include "mozilla/GeckoProcessTypes.h"
+#undef GECKO_PROCESS_TYPE
+ // We can't really hit this, thanks to the above switch, but having it
+ // here will placate the compiler.
+ default:
+ MOZ_ASSERT_UNREACHABLE("unknown process type");
+ }
+
+ Telemetry::Accumulate(Telemetry::SUBPROCESS_CRASHES_WITH_DUMP, key, 1);
+}
+
+/* static */
+void CrashReporterHost::NotifyCrashService(GeckoProcessType aProcessType,
+ int32_t aCrashType,
+ const nsString& aChildDumpID) {
+ MOZ_ASSERT(!aChildDumpID.IsEmpty());
+
+ nsCOMPtr<nsICrashService> crashService =
+ do_GetService("@mozilla.org/crashservice;1");
+ if (!crashService) {
+ return;
+ }
+
+ int32_t processType;
+
+ switch (aProcessType) {
+ case GeckoProcessType_IPDLUnitTest:
+ case GeckoProcessType_Default:
+ NS_ERROR("unknown process type");
+ return;
+ default:
+ processType = (int)aProcessType;
+ break;
+ }
+
+ RefPtr<dom::Promise> promise;
+ crashService->AddCrash(processType, aCrashType, aChildDumpID,
+ getter_AddRefs(promise));
+}
+
+void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey,
+ bool aValue) {
+ mExtraAnnotations[aKey] = aValue ? "1"_ns : "0"_ns;
+}
+
+void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey,
+ int aValue) {
+ nsAutoCString valueString;
+ valueString.AppendInt(aValue);
+ mExtraAnnotations[aKey] = valueString;
+}
+
+void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey,
+ unsigned int aValue) {
+ nsAutoCString valueString;
+ valueString.AppendInt(aValue);
+ mExtraAnnotations[aKey] = valueString;
+}
+
+void CrashReporterHost::AddAnnotation(CrashReporter::Annotation aKey,
+ const nsACString& aValue) {
+ mExtraAnnotations[aKey] = aValue;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/CrashReporterHost.h b/ipc/glue/CrashReporterHost.h
new file mode 100644
index 0000000000..7b71b64cdf
--- /dev/null
+++ b/ipc/glue/CrashReporterHost.h
@@ -0,0 +1,130 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_CrashReporterHost_h
+#define mozilla_ipc_CrashReporterHost_h
+
+#include <functional>
+
+#include "mozilla/UniquePtr.h"
+#include "base/process.h"
+#include "nsExceptionHandler.h"
+#include "nsThreadUtils.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+namespace mozilla {
+namespace ipc {
+
+// This is the newer replacement for CrashReporterParent. It is created in
+// response to a InitCrashReporter message on a top-level actor. When the
+// process terminates abnormally, the top-level should call GenerateCrashReport
+// to automatically integrate metadata.
+class CrashReporterHost {
+ typedef CrashReporter::AnnotationTable AnnotationTable;
+
+ public:
+ CrashReporterHost(GeckoProcessType aProcessType,
+ CrashReporter::ThreadId aThreadId);
+
+ // Helper function for generating a crash report for a process that probably
+ // crashed (i.e., had an AbnormalShutdown in ActorDestroy). Returns true if
+ // the process has a minidump attached and we were able to generate a report.
+ bool GenerateCrashReport(base::ProcessId aPid);
+
+ // Given an existing minidump for a crashed child process, take ownership of
+ // it from IPDL. After this, FinalizeCrashReport may be called.
+ RefPtr<nsIFile> TakeCrashedChildMinidump(base::ProcessId aPid,
+ uint32_t* aOutSequence);
+
+ // Replace the stored minidump with a new one. After this,
+ // FinalizeCrashReport may be called.
+ bool AdoptMinidump(nsIFile* aFile, const AnnotationTable& aAnnotations);
+
+ // If a minidump was already captured (e.g. via the hang reporter), this
+ // finalizes the existing report by attaching metadata, writing out the
+ // .extra file and notifying the crash service.
+ void FinalizeCrashReport();
+
+ // Delete any crash report we might have generated.
+ void DeleteCrashReport();
+
+ // Generate a paired minidump. This does not take the crash report, as
+ // GenerateCrashReport does. After this, FinalizeCrashReport may be called.
+ //
+ // This calls TakeCrashedChildMinidump and FinalizeCrashReport.
+ template <typename Toplevel>
+ bool GenerateMinidumpAndPair(Toplevel* aToplevelProtocol,
+ const nsACString& aPairName) {
+ auto childHandle = base::kInvalidProcessHandle;
+ const auto cleanup = MakeScopeExit([&]() {
+ if (childHandle && childHandle != base::kInvalidProcessHandle) {
+ base::CloseProcessHandle(childHandle);
+ }
+ });
+#ifdef XP_MACOSX
+ childHandle = aToplevelProtocol->Process()->GetChildTask();
+#else
+ if (!base::OpenPrivilegedProcessHandle(aToplevelProtocol->OtherPid(),
+ &childHandle)) {
+ NS_WARNING("Failed to open child process handle.");
+ return false;
+ }
+#endif
+
+ nsCOMPtr<nsIFile> targetDump;
+ if (!CrashReporter::CreateMinidumpsAndPair(childHandle, mThreadId,
+ aPairName, mExtraAnnotations,
+ getter_AddRefs(targetDump))) {
+ return false;
+ }
+
+ return CrashReporter::GetIDFromMinidump(targetDump, mDumpID);
+ }
+
+ void AddAnnotation(CrashReporter::Annotation aKey, bool aValue);
+ void AddAnnotation(CrashReporter::Annotation aKey, int aValue);
+ void AddAnnotation(CrashReporter::Annotation aKey, unsigned int aValue);
+ void AddAnnotation(CrashReporter::Annotation aKey, const nsACString& aValue);
+
+ bool HasMinidump() const { return !mDumpID.IsEmpty(); }
+ const nsString& MinidumpID() const {
+ MOZ_ASSERT(HasMinidump());
+ return mDumpID;
+ }
+ const nsCString& AdditionalMinidumps() const {
+ return mExtraAnnotations[CrashReporter::Annotation::additional_minidumps];
+ }
+
+ // This is a static helper function to notify the crash service that a
+ // crash has occurred and record the crash with telemetry. This can be called
+ // from any thread, and if not called from the main thread, will post a
+ // synchronous message to the main thread.
+ static void RecordCrash(GeckoProcessType aProcessType, int32_t aCrashType,
+ const nsString& aChildDumpID);
+
+ private:
+ // Get the nsICrashService crash type to use for an impending crash.
+ int32_t GetCrashType();
+
+ static void RecordCrashWithTelemetry(GeckoProcessType aProcessType,
+ int32_t aCrashType);
+ static void NotifyCrashService(GeckoProcessType aProcessType,
+ int32_t aCrashType,
+ const nsString& aChildDumpID);
+
+ private:
+ GeckoProcessType mProcessType;
+ CrashReporter::ThreadId mThreadId;
+ time_t mStartTime;
+ AnnotationTable mExtraAnnotations;
+ nsString mDumpID;
+ bool mFinalized;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_CrashReporterHost_h
diff --git a/ipc/glue/CrossProcessMutex.h b/ipc/glue/CrossProcessMutex.h
new file mode 100644
index 0000000000..3e16166c4b
--- /dev/null
+++ b/ipc/glue/CrossProcessMutex.h
@@ -0,0 +1,118 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_CrossProcessMutex_h
+#define mozilla_CrossProcessMutex_h
+
+#include "base/process.h"
+#include "mozilla/Mutex.h"
+
+#if defined(XP_WIN)
+# include "mozilla/UniquePtrExtensions.h"
+#endif
+#if !defined(XP_WIN) && !defined(XP_NETBSD) && !defined(XP_OPENBSD)
+# include <pthread.h>
+# include "mozilla/ipc/SharedMemoryBasic.h"
+# include "mozilla/Atomics.h"
+#endif
+
+namespace IPC {
+template <typename T>
+struct ParamTraits;
+} // namespace IPC
+
+//
+// Provides:
+//
+// - CrossProcessMutex, a non-recursive mutex that can be shared across
+// processes
+// - CrossProcessMutexAutoLock, an RAII class for ensuring that Mutexes are
+// properly locked and unlocked
+//
+// Using CrossProcessMutexAutoLock/CrossProcessMutexAutoUnlock is MUCH
+// preferred to making bare calls to CrossProcessMutex.Lock and Unlock.
+//
+namespace mozilla {
+#if defined(XP_WIN)
+typedef mozilla::UniqueFileHandle CrossProcessMutexHandle;
+#elif !defined(XP_NETBSD) && !defined(XP_OPENBSD)
+typedef mozilla::ipc::SharedMemoryBasic::Handle CrossProcessMutexHandle;
+#else
+// Stub for other platforms. We can't use uintptr_t here since different
+// processes could disagree on its size.
+typedef uintptr_t CrossProcessMutexHandle;
+#endif
+
+class CrossProcessMutex {
+ public:
+ /**
+ * CrossProcessMutex
+ * @param name A name which can reference this lock (currently unused)
+ **/
+ explicit CrossProcessMutex(const char* aName);
+ /**
+ * CrossProcessMutex
+ * @param handle A handle of an existing cross process mutex that can be
+ * opened.
+ */
+ explicit CrossProcessMutex(CrossProcessMutexHandle aHandle);
+
+ /**
+ * ~CrossProcessMutex
+ **/
+ ~CrossProcessMutex();
+
+ /**
+ * Lock
+ * This will lock the mutex. Any other thread in any other process that
+ * has access to this mutex calling lock will block execution until the
+ * initial caller of lock has made a call to Unlock.
+ *
+ * If the owning process is terminated unexpectedly the mutex will be
+ * released.
+ **/
+ void Lock();
+
+ /**
+ * Unlock
+ * This will unlock the mutex. A single thread currently waiting on a lock
+ * call will resume execution and aquire ownership of the lock. No
+ * guarantees are made as to the order in which waiting threads will resume
+ * execution.
+ **/
+ void Unlock();
+
+ /**
+ * CloneHandle
+ * This function is called to generate a serializable structure that can
+ * be sent to the specified process and opened on the other side.
+ *
+ * @returns A handle that can be shared to another process
+ */
+ CrossProcessMutexHandle CloneHandle();
+
+ private:
+ friend struct IPC::ParamTraits<CrossProcessMutex>;
+
+ CrossProcessMutex();
+ CrossProcessMutex(const CrossProcessMutex&);
+ CrossProcessMutex& operator=(const CrossProcessMutex&);
+
+#if defined(XP_WIN)
+ HANDLE mMutex;
+#elif !defined(XP_NETBSD) && !defined(XP_OPENBSD)
+ RefPtr<mozilla::ipc::SharedMemoryBasic> mSharedBuffer;
+ pthread_mutex_t* mMutex;
+ mozilla::Atomic<int32_t>* mCount;
+#endif
+};
+
+typedef detail::BaseAutoLock<CrossProcessMutex&> CrossProcessMutexAutoLock;
+typedef detail::BaseAutoUnlock<CrossProcessMutex&> CrossProcessMutexAutoUnlock;
+
+} // namespace mozilla
+
+#endif
diff --git a/ipc/glue/CrossProcessMutex_posix.cpp b/ipc/glue/CrossProcessMutex_posix.cpp
new file mode 100644
index 0000000000..c37fcb797d
--- /dev/null
+++ b/ipc/glue/CrossProcessMutex_posix.cpp
@@ -0,0 +1,140 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrossProcessMutex.h"
+#include "mozilla/Unused.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+
+namespace {
+
+struct MutexData {
+ pthread_mutex_t mMutex;
+ mozilla::Atomic<int32_t> mCount;
+};
+
+} // namespace
+
+namespace mozilla {
+
+static void InitMutex(pthread_mutex_t* mMutex) {
+ pthread_mutexattr_t mutexAttributes;
+ pthread_mutexattr_init(&mutexAttributes);
+ // Make the mutex reentrant so it behaves the same as a win32 mutex
+ if (pthread_mutexattr_settype(&mutexAttributes, PTHREAD_MUTEX_RECURSIVE)) {
+ MOZ_CRASH();
+ }
+ if (pthread_mutexattr_setpshared(&mutexAttributes, PTHREAD_PROCESS_SHARED)) {
+ MOZ_CRASH();
+ }
+
+ if (pthread_mutex_init(mMutex, &mutexAttributes)) {
+ MOZ_CRASH();
+ }
+}
+
+CrossProcessMutex::CrossProcessMutex(const char*)
+ : mMutex(nullptr), mCount(nullptr) {
+#if defined(MOZ_SANDBOX)
+ // POSIX mutexes in shared memory aren't guaranteed to be safe - and
+ // they specifically are not on Linux.
+ MOZ_RELEASE_ASSERT(false);
+#endif
+ mSharedBuffer = new ipc::SharedMemoryBasic;
+ if (!mSharedBuffer->Create(sizeof(MutexData))) {
+ MOZ_CRASH();
+ }
+
+ if (!mSharedBuffer->Map(sizeof(MutexData))) {
+ MOZ_CRASH();
+ }
+
+ MutexData* data = static_cast<MutexData*>(mSharedBuffer->memory());
+
+ if (!data) {
+ MOZ_CRASH();
+ }
+
+ mMutex = &(data->mMutex);
+ mCount = &(data->mCount);
+
+ *mCount = 1;
+ InitMutex(mMutex);
+
+ MOZ_COUNT_CTOR(CrossProcessMutex);
+}
+
+CrossProcessMutex::CrossProcessMutex(CrossProcessMutexHandle aHandle)
+ : mMutex(nullptr), mCount(nullptr) {
+ mSharedBuffer = new ipc::SharedMemoryBasic;
+
+ if (!mSharedBuffer->IsHandleValid(aHandle)) {
+ MOZ_CRASH();
+ }
+
+ if (!mSharedBuffer->SetHandle(std::move(aHandle),
+ ipc::SharedMemory::RightsReadWrite)) {
+ MOZ_CRASH();
+ }
+
+ if (!mSharedBuffer->Map(sizeof(MutexData))) {
+ MOZ_CRASH();
+ }
+
+ MutexData* data = static_cast<MutexData*>(mSharedBuffer->memory());
+
+ if (!data) {
+ MOZ_CRASH();
+ }
+
+ mMutex = &(data->mMutex);
+ mCount = &(data->mCount);
+ int32_t count = (*mCount)++;
+
+ if (count == 0) {
+ // The other side has already let go of their CrossProcessMutex, so now
+ // mMutex is garbage. We need to re-initialize it.
+ InitMutex(mMutex);
+ }
+
+ MOZ_COUNT_CTOR(CrossProcessMutex);
+}
+
+CrossProcessMutex::~CrossProcessMutex() {
+ int32_t count = --(*mCount);
+
+ if (count == 0) {
+ // Nothing can be done if the destroy fails so ignore return code.
+ Unused << pthread_mutex_destroy(mMutex);
+ }
+
+ MOZ_COUNT_DTOR(CrossProcessMutex);
+}
+
+void CrossProcessMutex::Lock() {
+ MOZ_ASSERT(*mCount > 0, "Attempting to lock mutex with zero ref count");
+ pthread_mutex_lock(mMutex);
+}
+
+void CrossProcessMutex::Unlock() {
+ MOZ_ASSERT(*mCount > 0, "Attempting to unlock mutex with zero ref count");
+ pthread_mutex_unlock(mMutex);
+}
+
+CrossProcessMutexHandle CrossProcessMutex::CloneHandle() {
+ CrossProcessMutexHandle result = ipc::SharedMemoryBasic::NULLHandle();
+
+ if (mSharedBuffer) {
+ result = mSharedBuffer->CloneHandle();
+ if (!result) {
+ MOZ_CRASH();
+ }
+ }
+
+ return result;
+}
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessMutex_unimplemented.cpp b/ipc/glue/CrossProcessMutex_unimplemented.cpp
new file mode 100644
index 0000000000..70b63d7ea9
--- /dev/null
+++ b/ipc/glue/CrossProcessMutex_unimplemented.cpp
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrossProcessMutex.h"
+
+#include "nsDebug.h"
+
+namespace mozilla {
+
+CrossProcessMutex::CrossProcessMutex(const char*) {
+ MOZ_CRASH("Cross-process mutices not allowed on this platform.");
+}
+
+CrossProcessMutex::CrossProcessMutex(CrossProcessMutexHandle) {
+ MOZ_CRASH("Cross-process mutices not allowed on this platform.");
+}
+
+CrossProcessMutex::~CrossProcessMutex() {
+ MOZ_CRASH(
+ "Cross-process mutices not allowed on this platform - woah! We should've "
+ "aborted by now!");
+}
+
+void CrossProcessMutex::Lock() {
+ MOZ_CRASH(
+ "Cross-process mutices not allowed on this platform - woah! We should've "
+ "aborted by now!");
+}
+
+void CrossProcessMutex::Unlock() {
+ MOZ_CRASH(
+ "Cross-process mutices not allowed on this platform - woah! We should've "
+ "aborted by now!");
+}
+
+CrossProcessMutexHandle CrossProcessMutex::CloneHandle() {
+ MOZ_CRASH(
+ "Cross-process mutices not allowed on this platform - woah! We should've "
+ "aborted by now!");
+ return 0;
+}
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessMutex_windows.cpp b/ipc/glue/CrossProcessMutex_windows.cpp
new file mode 100644
index 0000000000..d4bbe2f2ba
--- /dev/null
+++ b/ipc/glue/CrossProcessMutex_windows.cpp
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <windows.h>
+
+#include "base/process_util.h"
+#include "CrossProcessMutex.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+#include "ProtocolUtils.h"
+
+using base::GetCurrentProcessHandle;
+using base::ProcessHandle;
+
+namespace mozilla {
+
+CrossProcessMutex::CrossProcessMutex(const char*) {
+ // We explicitly share this using DuplicateHandle, we do -not- want this to
+ // be inherited by child processes by default! So no security attributes are
+ // given.
+ mMutex = ::CreateMutexA(nullptr, FALSE, nullptr);
+ if (!mMutex) {
+ MOZ_CRASH("This shouldn't happen - failed to create mutex!");
+ }
+ MOZ_COUNT_CTOR(CrossProcessMutex);
+}
+
+CrossProcessMutex::CrossProcessMutex(CrossProcessMutexHandle aHandle) {
+ DWORD flags;
+ if (!::GetHandleInformation(aHandle.get(), &flags)) {
+ MOZ_CRASH("Attempt to construct a mutex from an invalid handle!");
+ }
+ mMutex = aHandle.release();
+ MOZ_COUNT_CTOR(CrossProcessMutex);
+}
+
+CrossProcessMutex::~CrossProcessMutex() {
+ NS_ASSERTION(mMutex, "Improper construction of mutex or double free.");
+ ::CloseHandle(mMutex);
+ MOZ_COUNT_DTOR(CrossProcessMutex);
+}
+
+void CrossProcessMutex::Lock() {
+ NS_ASSERTION(mMutex, "Improper construction of mutex.");
+ ::WaitForSingleObject(mMutex, INFINITE);
+}
+
+void CrossProcessMutex::Unlock() {
+ NS_ASSERTION(mMutex, "Improper construction of mutex.");
+ ::ReleaseMutex(mMutex);
+}
+
+CrossProcessMutexHandle CrossProcessMutex::CloneHandle() {
+ HANDLE newHandle;
+ if (!::DuplicateHandle(GetCurrentProcess(), mMutex, GetCurrentProcess(),
+ &newHandle, 0, false, DUPLICATE_SAME_ACCESS)) {
+ return nullptr;
+ }
+ return mozilla::UniqueFileHandle(newHandle);
+}
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessSemaphore.h b/ipc/glue/CrossProcessSemaphore.h
new file mode 100644
index 0000000000..466f88f8c3
--- /dev/null
+++ b/ipc/glue/CrossProcessSemaphore.h
@@ -0,0 +1,119 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_CrossProcessSemaphore_h
+#define mozilla_CrossProcessSemaphore_h
+
+#include "base/process.h"
+#include "mozilla/TimeStamp.h"
+#include "mozilla/Maybe.h"
+
+#if defined(XP_WIN) || defined(XP_DARWIN)
+# include "mozilla/UniquePtrExtensions.h"
+#else
+# include <pthread.h>
+# include <semaphore.h>
+# include "mozilla/ipc/SharedMemoryBasic.h"
+# include "mozilla/Atomics.h"
+#endif
+
+namespace IPC {
+template <typename T>
+struct ParamTraits;
+} // namespace IPC
+
+//
+// Provides:
+//
+// - CrossProcessSemaphore, a semaphore that can be shared across processes
+namespace mozilla {
+
+template <typename T>
+inline bool IsHandleValid(const T& handle) {
+ return bool(handle);
+}
+
+#if defined(XP_WIN)
+typedef mozilla::UniqueFileHandle CrossProcessSemaphoreHandle;
+#elif defined(XP_DARWIN)
+typedef mozilla::UniqueMachSendRight CrossProcessSemaphoreHandle;
+#else
+typedef mozilla::ipc::SharedMemoryBasic::Handle CrossProcessSemaphoreHandle;
+
+template <>
+inline bool IsHandleValid<CrossProcessSemaphoreHandle>(
+ const CrossProcessSemaphoreHandle& handle) {
+ return !(handle == mozilla::ipc::SharedMemoryBasic::NULLHandle());
+}
+#endif
+
+class CrossProcessSemaphore {
+ public:
+ /**
+ * CrossProcessSemaphore
+ * @param name A name which can reference this lock (currently unused)
+ **/
+ static CrossProcessSemaphore* Create(const char* aName,
+ uint32_t aInitialValue);
+
+ /**
+ * CrossProcessSemaphore
+ * @param handle A handle of an existing cross process semaphore that can be
+ * opened.
+ */
+ static CrossProcessSemaphore* Create(CrossProcessSemaphoreHandle aHandle);
+
+ ~CrossProcessSemaphore();
+
+ /**
+ * Decrements the current value of the semaphore. This will block if the
+ * current value of the semaphore is 0, up to a maximum of aWaitTime (if
+ * specified).
+ * Returns true if the semaphore was succesfully decremented, false otherwise.
+ **/
+ bool Wait(const Maybe<TimeDuration>& aWaitTime = Nothing());
+
+ /**
+ * Increments the current value of the semaphore.
+ **/
+ void Signal();
+
+ /**
+ * CloneHandle
+ * This function is called to generate a serializable structure that can
+ * be sent to the specified process and opened on the other side.
+ *
+ * @returns A handle that can be shared to another process
+ */
+ CrossProcessSemaphoreHandle CloneHandle();
+
+ void CloseHandle();
+
+ private:
+ friend struct IPC::ParamTraits<CrossProcessSemaphore>;
+
+ CrossProcessSemaphore();
+ CrossProcessSemaphore(const CrossProcessSemaphore&);
+ CrossProcessSemaphore& operator=(const CrossProcessSemaphore&);
+
+#if defined(XP_WIN)
+ explicit CrossProcessSemaphore(HANDLE aSemaphore);
+
+ HANDLE mSemaphore;
+#elif defined(XP_DARWIN)
+ explicit CrossProcessSemaphore(CrossProcessSemaphoreHandle aSemaphore);
+
+ CrossProcessSemaphoreHandle mSemaphore;
+#else
+ RefPtr<mozilla::ipc::SharedMemoryBasic> mSharedBuffer;
+ sem_t* mSemaphore;
+ mozilla::Atomic<int32_t>* mRefCount;
+#endif
+};
+
+} // namespace mozilla
+
+#endif
diff --git a/ipc/glue/CrossProcessSemaphore_mach.cpp b/ipc/glue/CrossProcessSemaphore_mach.cpp
new file mode 100644
index 0000000000..d7cccee2a0
--- /dev/null
+++ b/ipc/glue/CrossProcessSemaphore_mach.cpp
@@ -0,0 +1,92 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrossProcessSemaphore.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+#include <mach/mach_time.h>
+
+static const uint64_t kNsPerUs = 1000;
+static const uint64_t kNsPerSec = 1000000000;
+
+namespace mozilla {
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(const char*,
+ uint32_t aInitialValue) {
+ semaphore_t sem = SEMAPHORE_NULL;
+ if (semaphore_create(mach_task_self(), &sem, SYNC_POLICY_FIFO,
+ aInitialValue) == KERN_SUCCESS &&
+ sem != SEMAPHORE_NULL) {
+ return new CrossProcessSemaphore(CrossProcessSemaphoreHandle(sem));
+ }
+ return nullptr;
+}
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(
+ CrossProcessSemaphoreHandle aHandle) {
+ if (!aHandle) {
+ return nullptr;
+ }
+ return new CrossProcessSemaphore(std::move(aHandle));
+}
+
+CrossProcessSemaphore::CrossProcessSemaphore(
+ CrossProcessSemaphoreHandle aSemaphore)
+ : mSemaphore(std::move(aSemaphore)) {
+ MOZ_COUNT_CTOR(CrossProcessSemaphore);
+}
+
+CrossProcessSemaphore::~CrossProcessSemaphore() {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore or double free.");
+ MOZ_COUNT_DTOR(CrossProcessSemaphore);
+}
+
+bool CrossProcessSemaphore::Wait(const Maybe<TimeDuration>& aWaitTime) {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore.");
+ int kr = KERN_OPERATION_TIMED_OUT;
+ // semaphore_(timed)wait may be interrupted by KERN_ABORTED. Carefully restart
+ // the wait until it either succeeds or times out.
+ if (aWaitTime.isNothing()) {
+ do {
+ kr = semaphore_wait(mSemaphore.get());
+ } while (kr == KERN_ABORTED);
+ } else {
+ mach_timebase_info_data_t tb;
+ if (mach_timebase_info(&tb) != KERN_SUCCESS) {
+ return false;
+ }
+ uint64_t now = (mach_absolute_time() * tb.numer) / tb.denom;
+ uint64_t deadline = now + uint64_t(kNsPerUs * aWaitTime->ToMicroseconds());
+ while (now <= deadline) {
+ uint64_t ns = deadline - now;
+ mach_timespec_t ts;
+ ts.tv_sec = ns / kNsPerSec;
+ ts.tv_nsec = ns % kNsPerSec;
+ kr = semaphore_timedwait(mSemaphore.get(), ts);
+ if (kr != KERN_ABORTED) {
+ break;
+ }
+ now = (mach_absolute_time() * tb.numer) / tb.denom;
+ }
+ }
+ return kr == KERN_SUCCESS;
+}
+
+void CrossProcessSemaphore::Signal() {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore.");
+ semaphore_signal(mSemaphore.get());
+}
+
+CrossProcessSemaphoreHandle CrossProcessSemaphore::CloneHandle() {
+ // Transfer the mach port backing the semaphore.
+ return mozilla::RetainMachSendRight(mSemaphore.get());
+}
+
+void CrossProcessSemaphore::CloseHandle() {}
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessSemaphore_posix.cpp b/ipc/glue/CrossProcessSemaphore_posix.cpp
new file mode 100644
index 0000000000..3b32a897ee
--- /dev/null
+++ b/ipc/glue/CrossProcessSemaphore_posix.cpp
@@ -0,0 +1,164 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrossProcessSemaphore.h"
+#include "mozilla/Unused.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+#include <errno.h>
+
+static const uint64_t kNsPerMs = 1000000;
+static const uint64_t kNsPerSec = 1000000000;
+
+namespace {
+
+struct SemaphoreData {
+ sem_t mSemaphore;
+ mozilla::Atomic<int32_t> mRefCount;
+ uint32_t mInitialValue;
+};
+
+} // namespace
+
+namespace mozilla {
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(const char*,
+ uint32_t aInitialValue) {
+ RefPtr<ipc::SharedMemoryBasic> sharedBuffer = new ipc::SharedMemoryBasic;
+ if (!sharedBuffer->Create(sizeof(SemaphoreData))) {
+ return nullptr;
+ }
+
+ if (!sharedBuffer->Map(sizeof(SemaphoreData))) {
+ return nullptr;
+ }
+
+ SemaphoreData* data = static_cast<SemaphoreData*>(sharedBuffer->memory());
+
+ if (!data) {
+ return nullptr;
+ }
+
+ if (sem_init(&data->mSemaphore, 1, aInitialValue)) {
+ return nullptr;
+ }
+
+ CrossProcessSemaphore* sem = new CrossProcessSemaphore;
+ sem->mSharedBuffer = sharedBuffer;
+ sem->mSemaphore = &data->mSemaphore;
+ sem->mRefCount = &data->mRefCount;
+ *sem->mRefCount = 1;
+
+ data->mInitialValue = aInitialValue;
+
+ return sem;
+}
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(
+ CrossProcessSemaphoreHandle aHandle) {
+ RefPtr<ipc::SharedMemoryBasic> sharedBuffer = new ipc::SharedMemoryBasic;
+
+ if (!sharedBuffer->IsHandleValid(aHandle)) {
+ return nullptr;
+ }
+
+ if (!sharedBuffer->SetHandle(std::move(aHandle),
+ ipc::SharedMemory::RightsReadWrite)) {
+ return nullptr;
+ }
+
+ if (!sharedBuffer->Map(sizeof(SemaphoreData))) {
+ return nullptr;
+ }
+
+ sharedBuffer->CloseHandle();
+
+ SemaphoreData* data = static_cast<SemaphoreData*>(sharedBuffer->memory());
+
+ if (!data) {
+ return nullptr;
+ }
+
+ int32_t oldCount = data->mRefCount++;
+ if (oldCount == 0) {
+ // The other side has already let go of their CrossProcessSemaphore, so now
+ // mSemaphore is garbage. We need to re-initialize it.
+ if (sem_init(&data->mSemaphore, 1, data->mInitialValue)) {
+ data->mRefCount--;
+ return nullptr;
+ }
+ }
+
+ CrossProcessSemaphore* sem = new CrossProcessSemaphore;
+ sem->mSharedBuffer = sharedBuffer;
+ sem->mSemaphore = &data->mSemaphore;
+ sem->mRefCount = &data->mRefCount;
+ return sem;
+}
+
+CrossProcessSemaphore::CrossProcessSemaphore()
+ : mSemaphore(nullptr), mRefCount(nullptr) {
+ MOZ_COUNT_CTOR(CrossProcessSemaphore);
+}
+
+CrossProcessSemaphore::~CrossProcessSemaphore() {
+ int32_t oldCount = --(*mRefCount);
+
+ if (oldCount == 0) {
+ // Nothing can be done if the destroy fails so ignore return code.
+ Unused << sem_destroy(mSemaphore);
+ }
+
+ MOZ_COUNT_DTOR(CrossProcessSemaphore);
+}
+
+bool CrossProcessSemaphore::Wait(const Maybe<TimeDuration>& aWaitTime) {
+ MOZ_ASSERT(*mRefCount > 0,
+ "Attempting to wait on a semaphore with zero ref count");
+ int ret;
+ if (aWaitTime.isSome()) {
+ struct timespec ts;
+ if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
+ return false;
+ }
+
+ uint64_t ns = uint64_t(kNsPerMs * aWaitTime->ToMilliseconds()) + ts.tv_nsec;
+ ts.tv_sec += ns / kNsPerSec;
+ ts.tv_nsec = ns % kNsPerSec;
+
+ while ((ret = sem_timedwait(mSemaphore, &ts)) == -1 && errno == EINTR) {
+ }
+ } else {
+ while ((ret = sem_wait(mSemaphore)) == -1 && errno == EINTR) {
+ }
+ }
+ return ret == 0;
+}
+
+void CrossProcessSemaphore::Signal() {
+ MOZ_ASSERT(*mRefCount > 0,
+ "Attempting to signal a semaphore with zero ref count");
+ sem_post(mSemaphore);
+}
+
+CrossProcessSemaphoreHandle CrossProcessSemaphore::CloneHandle() {
+ CrossProcessSemaphoreHandle result = ipc::SharedMemoryBasic::NULLHandle();
+
+ if (mSharedBuffer) {
+ result = mSharedBuffer->CloneHandle();
+ if (!result) {
+ MOZ_CRASH();
+ }
+ }
+
+ return result;
+}
+
+void CrossProcessSemaphore::CloseHandle() { mSharedBuffer->CloseHandle(); }
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessSemaphore_unimplemented.cpp b/ipc/glue/CrossProcessSemaphore_unimplemented.cpp
new file mode 100644
index 0000000000..822aeb76eb
--- /dev/null
+++ b/ipc/glue/CrossProcessSemaphore_unimplemented.cpp
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "CrossProcessSemaphore.h"
+
+#include "nsDebug.h"
+
+namespace mozilla {
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(const char*, uint32_t) {
+ MOZ_CRASH("Cross-process semaphores not allowed on this platform.");
+ return nullptr;
+}
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(
+ CrossProcessSemaphoreHandle) {
+ MOZ_CRASH("Cross-process semaphores not allowed on this platform.");
+ return nullptr;
+}
+
+CrossProcessSemaphore::CrossProcessSemaphore() {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+}
+
+CrossProcessSemaphore::~CrossProcessSemaphore() {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+}
+
+bool CrossProcessSemaphore::Wait(const Maybe<TimeDuration>& aWaitTime) {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+ return false;
+}
+
+void CrossProcessSemaphore::Signal() {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+}
+
+CrossProcessSemaphoreHandle CrossProcessSemaphore::CloneHandle() {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+ return 0;
+}
+
+void CrossProcessSemaphore::CloseHandle() {
+ MOZ_CRASH(
+ "Cross-process semaphores not allowed on this platform - woah! We "
+ "should've aborted by now!");
+}
+
+} // namespace mozilla
diff --git a/ipc/glue/CrossProcessSemaphore_windows.cpp b/ipc/glue/CrossProcessSemaphore_windows.cpp
new file mode 100644
index 0000000000..70644b7d51
--- /dev/null
+++ b/ipc/glue/CrossProcessSemaphore_windows.cpp
@@ -0,0 +1,83 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <windows.h>
+
+#include "base/process_util.h"
+#include "CrossProcessSemaphore.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+#include "ProtocolUtils.h"
+
+using base::GetCurrentProcessHandle;
+using base::ProcessHandle;
+
+namespace mozilla {
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(const char*,
+ uint32_t aInitialValue) {
+ // We explicitly share this using DuplicateHandle, we do -not- want this to
+ // be inherited by child processes by default! So no security attributes are
+ // given.
+ HANDLE semaphore =
+ ::CreateSemaphoreA(nullptr, aInitialValue, 0x7fffffff, nullptr);
+ if (!semaphore) {
+ return nullptr;
+ }
+ return new CrossProcessSemaphore(semaphore);
+}
+
+/* static */
+CrossProcessSemaphore* CrossProcessSemaphore::Create(
+ CrossProcessSemaphoreHandle aHandle) {
+ DWORD flags;
+ if (!::GetHandleInformation(aHandle.get(), &flags)) {
+ return nullptr;
+ }
+
+ return new CrossProcessSemaphore(aHandle.release());
+}
+
+CrossProcessSemaphore::CrossProcessSemaphore(HANDLE aSemaphore)
+ : mSemaphore(aSemaphore) {
+ MOZ_COUNT_CTOR(CrossProcessSemaphore);
+}
+
+CrossProcessSemaphore::~CrossProcessSemaphore() {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore or double free.");
+ ::CloseHandle(mSemaphore);
+ MOZ_COUNT_DTOR(CrossProcessSemaphore);
+}
+
+bool CrossProcessSemaphore::Wait(const Maybe<TimeDuration>& aWaitTime) {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore.");
+ HRESULT hr = ::WaitForSingleObject(
+ mSemaphore, aWaitTime.isSome() ? aWaitTime->ToMilliseconds() : INFINITE);
+ return hr == WAIT_OBJECT_0;
+}
+
+void CrossProcessSemaphore::Signal() {
+ MOZ_ASSERT(mSemaphore, "Improper construction of semaphore.");
+ ::ReleaseSemaphore(mSemaphore, 1, nullptr);
+}
+
+CrossProcessSemaphoreHandle CrossProcessSemaphore::CloneHandle() {
+ HANDLE newHandle;
+ bool succeeded =
+ ::DuplicateHandle(GetCurrentProcess(), mSemaphore, GetCurrentProcess(),
+ &newHandle, 0, false, DUPLICATE_SAME_ACCESS);
+
+ if (!succeeded) {
+ return nullptr;
+ }
+
+ return UniqueFileHandle(newHandle);
+}
+
+void CrossProcessSemaphore::CloseHandle() {}
+
+} // namespace mozilla
diff --git a/ipc/glue/DataPipe.cpp b/ipc/glue/DataPipe.cpp
new file mode 100644
index 0000000000..bc1af11515
--- /dev/null
+++ b/ipc/glue/DataPipe.cpp
@@ -0,0 +1,767 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "DataPipe.h"
+#include "mozilla/AlreadyAddRefed.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/CheckedInt.h"
+#include "mozilla/ErrorNames.h"
+#include "mozilla/Logging.h"
+#include "mozilla/MoveOnlyFunction.h"
+#include "mozilla/ipc/InputStreamParams.h"
+#include "nsIAsyncInputStream.h"
+#include "nsStreamUtils.h"
+#include "nsThreadUtils.h"
+
+namespace mozilla {
+namespace ipc {
+
+LazyLogModule gDataPipeLog("DataPipe");
+
+namespace data_pipe_detail {
+
+// Helper for queueing up actions to be run once the mutex has been unlocked.
+// Actions will be run in-order.
+class MOZ_SCOPED_CAPABILITY DataPipeAutoLock {
+ public:
+ explicit DataPipeAutoLock(Mutex& aMutex) MOZ_CAPABILITY_ACQUIRE(aMutex)
+ : mMutex(aMutex) {
+ mMutex.Lock();
+ }
+ DataPipeAutoLock(const DataPipeAutoLock&) = delete;
+ DataPipeAutoLock& operator=(const DataPipeAutoLock&) = delete;
+
+ template <typename F>
+ void AddUnlockAction(F aAction) {
+ mActions.AppendElement(std::move(aAction));
+ }
+
+ ~DataPipeAutoLock() MOZ_CAPABILITY_RELEASE() {
+ mMutex.Unlock();
+ for (auto& action : mActions) {
+ action();
+ }
+ }
+
+ private:
+ Mutex& mMutex;
+ AutoTArray<MoveOnlyFunction<void()>, 4> mActions;
+};
+
+static void DoNotifyOnUnlock(DataPipeAutoLock& aLock,
+ already_AddRefed<nsIRunnable> aCallback,
+ already_AddRefed<nsIEventTarget> aTarget) {
+ nsCOMPtr<nsIRunnable> callback{std::move(aCallback)};
+ nsCOMPtr<nsIEventTarget> target{std::move(aTarget)};
+ if (callback) {
+ aLock.AddUnlockAction(
+ [callback = std::move(callback), target = std::move(target)]() mutable {
+ if (target) {
+ target->Dispatch(callback.forget());
+ } else {
+ NS_DispatchBackgroundTask(callback.forget());
+ }
+ });
+ }
+}
+
+class DataPipeLink : public NodeController::PortObserver {
+ public:
+ DataPipeLink(bool aReceiverSide, std::shared_ptr<Mutex> aMutex,
+ ScopedPort aPort, SharedMemoryBasic::Handle aShmemHandle,
+ SharedMemory* aShmem, uint32_t aCapacity, nsresult aPeerStatus,
+ uint32_t aOffset, uint32_t aAvailable)
+ : mMutex(std::move(aMutex)),
+ mPort(std::move(aPort)),
+ mShmemHandle(std::move(aShmemHandle)),
+ mShmem(aShmem),
+ mCapacity(aCapacity),
+ mReceiverSide(aReceiverSide),
+ mPeerStatus(aPeerStatus),
+ mOffset(aOffset),
+ mAvailable(aAvailable) {}
+
+ void Init() MOZ_EXCLUDES(*mMutex) {
+ {
+ DataPipeAutoLock lock(*mMutex);
+ if (NS_FAILED(mPeerStatus)) {
+ return;
+ }
+ MOZ_ASSERT(mPort.IsValid());
+ mPort.Controller()->SetPortObserver(mPort.Port(), this);
+ }
+ OnPortStatusChanged();
+ }
+
+ void OnPortStatusChanged() final MOZ_EXCLUDES(*mMutex);
+
+ // Add a task to notify the callback after `aLock` is unlocked.
+ //
+ // This method is safe to call multiple times, as after the first time it is
+ // called, `mCallback` will be cleared.
+ void NotifyOnUnlock(DataPipeAutoLock& aLock) MOZ_REQUIRES(*mMutex) {
+ DoNotifyOnUnlock(aLock, mCallback.forget(), mCallbackTarget.forget());
+ }
+
+ void SendBytesConsumedOnUnlock(DataPipeAutoLock& aLock, uint32_t aBytes)
+ MOZ_REQUIRES(*mMutex) {
+ MOZ_LOG(gDataPipeLog, LogLevel::Verbose,
+ ("SendOnUnlock CONSUMED(%u) %s", aBytes, Describe(aLock).get()));
+ if (NS_FAILED(mPeerStatus)) {
+ return;
+ }
+
+ // `mPort` may be destroyed by `SetPeerError` after the DataPipe is unlocked
+ // but before we send the message. The strong controller and port references
+ // will allow us to try to send the message anyway, and it will be safely
+ // dropped if the port has already been closed. CONSUMED messages are safe
+ // to deliver out-of-order, so we don't need to worry about ordering here.
+ aLock.AddUnlockAction([controller = RefPtr{mPort.Controller()},
+ port = mPort.Port(), aBytes]() mutable {
+ auto message = MakeUnique<IPC::Message>(
+ MSG_ROUTING_NONE, DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE);
+ IPC::MessageWriter writer(*message);
+ WriteParam(&writer, aBytes);
+ controller->SendUserMessage(port, std::move(message));
+ });
+ }
+
+ void SetPeerError(DataPipeAutoLock& aLock, nsresult aStatus,
+ bool aSendClosed = false) MOZ_REQUIRES(*mMutex) {
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("SetPeerError(%s%s) %s", GetStaticErrorName(aStatus),
+ aSendClosed ? ", send" : "", Describe(aLock).get()));
+ // The pipe was closed or errored. Clear the observer reference back
+ // to this type from the port layer, and ensure we notify waiters.
+ MOZ_ASSERT(NS_SUCCEEDED(mPeerStatus));
+ mPeerStatus = NS_SUCCEEDED(aStatus) ? NS_BASE_STREAM_CLOSED : aStatus;
+ aLock.AddUnlockAction([port = std::move(mPort), aStatus, aSendClosed] {
+ if (aSendClosed) {
+ auto message = MakeUnique<IPC::Message>(MSG_ROUTING_NONE,
+ DATA_PIPE_CLOSED_MESSAGE_TYPE);
+ IPC::MessageWriter writer(*message);
+ WriteParam(&writer, aStatus);
+ port.Controller()->SendUserMessage(port.Port(), std::move(message));
+ }
+ // The `ScopedPort` being destroyed with this action will close it,
+ // clearing the observer reference from the ports layer.
+ });
+ NotifyOnUnlock(aLock);
+ }
+
+ nsCString Describe(DataPipeAutoLock& aLock) const MOZ_REQUIRES(*mMutex) {
+ return nsPrintfCString(
+ "[%s(%p) c=%u e=%s o=%u a=%u, cb=%s]",
+ mReceiverSide ? "Receiver" : "Sender", this, mCapacity,
+ GetStaticErrorName(mPeerStatus), mOffset, mAvailable,
+ mCallback ? (mCallbackClosureOnly ? "clo" : "yes") : "no");
+ }
+
+ // This mutex is shared with the `DataPipeBase` which owns this
+ // `DataPipeLink`.
+ std::shared_ptr<Mutex> mMutex;
+
+ ScopedPort mPort MOZ_GUARDED_BY(*mMutex);
+ SharedMemoryBasic::Handle mShmemHandle MOZ_GUARDED_BY(*mMutex);
+ const RefPtr<SharedMemory> mShmem;
+ const uint32_t mCapacity;
+ const bool mReceiverSide;
+
+ bool mProcessingSegment MOZ_GUARDED_BY(*mMutex) = false;
+
+ nsresult mPeerStatus MOZ_GUARDED_BY(*mMutex) = NS_OK;
+ uint32_t mOffset MOZ_GUARDED_BY(*mMutex) = 0;
+ uint32_t mAvailable MOZ_GUARDED_BY(*mMutex) = 0;
+
+ bool mCallbackClosureOnly MOZ_GUARDED_BY(*mMutex) = false;
+ nsCOMPtr<nsIRunnable> mCallback MOZ_GUARDED_BY(*mMutex);
+ nsCOMPtr<nsIEventTarget> mCallbackTarget MOZ_GUARDED_BY(*mMutex);
+};
+
+void DataPipeLink::OnPortStatusChanged() {
+ DataPipeAutoLock lock(*mMutex);
+
+ while (NS_SUCCEEDED(mPeerStatus)) {
+ UniquePtr<IPC::Message> message;
+ if (!mPort.Controller()->GetMessage(mPort.Port(), &message)) {
+ SetPeerError(lock, NS_BASE_STREAM_CLOSED);
+ return;
+ }
+ if (!message) {
+ return; // no more messages
+ }
+
+ IPC::MessageReader reader(*message);
+ switch (message->type()) {
+ case DATA_PIPE_CLOSED_MESSAGE_TYPE: {
+ nsresult status = NS_OK;
+ if (!ReadParam(&reader, &status)) {
+ NS_WARNING("Unable to parse nsresult error from peer");
+ status = NS_ERROR_UNEXPECTED;
+ }
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("Got CLOSED(%s) %s", GetStaticErrorName(status),
+ Describe(lock).get()));
+ SetPeerError(lock, status);
+ return;
+ }
+ case DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE: {
+ uint32_t consumed = 0;
+ if (!ReadParam(&reader, &consumed)) {
+ NS_WARNING("Unable to parse bytes consumed from peer");
+ SetPeerError(lock, NS_ERROR_UNEXPECTED);
+ return;
+ }
+
+ MOZ_LOG(gDataPipeLog, LogLevel::Verbose,
+ ("Got CONSUMED(%u) %s", consumed, Describe(lock).get()));
+ auto newAvailable = CheckedUint32{mAvailable} + consumed;
+ if (!newAvailable.isValid() || newAvailable.value() > mCapacity) {
+ NS_WARNING("Illegal bytes consumed message received from peer");
+ SetPeerError(lock, NS_ERROR_UNEXPECTED);
+ return;
+ }
+ mAvailable = newAvailable.value();
+ if (!mCallbackClosureOnly) {
+ NotifyOnUnlock(lock);
+ }
+ break;
+ }
+ default: {
+ NS_WARNING("Illegal message type received from peer");
+ SetPeerError(lock, NS_ERROR_UNEXPECTED);
+ return;
+ }
+ }
+ }
+}
+
+DataPipeBase::DataPipeBase(bool aReceiverSide, nsresult aError)
+ : mMutex(std::make_shared<Mutex>(aReceiverSide ? "DataPipeReceiver"
+ : "DataPipeSender")),
+ mStatus(NS_SUCCEEDED(aError) ? NS_BASE_STREAM_CLOSED : aError) {}
+
+DataPipeBase::DataPipeBase(bool aReceiverSide, ScopedPort aPort,
+ SharedMemoryBasic::Handle aShmemHandle,
+ SharedMemory* aShmem, uint32_t aCapacity,
+ nsresult aPeerStatus, uint32_t aOffset,
+ uint32_t aAvailable)
+ : mMutex(std::make_shared<Mutex>(aReceiverSide ? "DataPipeReceiver"
+ : "DataPipeSender")),
+ mStatus(NS_OK),
+ mLink(new DataPipeLink(aReceiverSide, mMutex, std::move(aPort),
+ std::move(aShmemHandle), aShmem, aCapacity,
+ aPeerStatus, aOffset, aAvailable)) {
+ mLink->Init();
+}
+
+DataPipeBase::~DataPipeBase() {
+ DataPipeAutoLock lock(*mMutex);
+ CloseInternal(lock, NS_BASE_STREAM_CLOSED);
+}
+
+void DataPipeBase::CloseInternal(DataPipeAutoLock& aLock, nsresult aStatus) {
+ if (NS_FAILED(mStatus)) {
+ return;
+ }
+
+ MOZ_LOG(
+ gDataPipeLog, LogLevel::Debug,
+ ("Closing(%s) %s", GetStaticErrorName(aStatus), Describe(aLock).get()));
+
+ // Set our status to an errored status.
+ mStatus = NS_SUCCEEDED(aStatus) ? NS_BASE_STREAM_CLOSED : aStatus;
+ RefPtr<DataPipeLink> link = mLink.forget();
+ AssertSameMutex(link->mMutex);
+ link->NotifyOnUnlock(aLock);
+
+ // If our peer hasn't disappeared yet, clean up our connection to it.
+ if (NS_SUCCEEDED(link->mPeerStatus)) {
+ link->SetPeerError(aLock, mStatus, /* aSendClosed */ true);
+ }
+}
+
+nsresult DataPipeBase::ProcessSegmentsInternal(
+ uint32_t aCount, ProcessSegmentFun aProcessSegment,
+ uint32_t* aProcessedCount) {
+ *aProcessedCount = 0;
+
+ while (*aProcessedCount < aCount) {
+ DataPipeAutoLock lock(*mMutex);
+ mMutex->AssertCurrentThreadOwns();
+
+ MOZ_LOG(gDataPipeLog, LogLevel::Verbose,
+ ("ProcessSegments(%u of %u) %s", *aProcessedCount, aCount,
+ Describe(lock).get()));
+
+ nsresult status = CheckStatus(lock);
+ if (NS_FAILED(status)) {
+ if (*aProcessedCount > 0) {
+ return NS_OK;
+ }
+ return status == NS_BASE_STREAM_CLOSED ? NS_OK : status;
+ }
+
+ RefPtr<DataPipeLink> link = mLink;
+ AssertSameMutex(link->mMutex);
+ if (!link->mAvailable) {
+ MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(link->mPeerStatus),
+ "CheckStatus will have returned an error");
+ return *aProcessedCount > 0 ? NS_OK : NS_BASE_STREAM_WOULD_BLOCK;
+ }
+
+ MOZ_RELEASE_ASSERT(!link->mProcessingSegment,
+ "Only one thread may be processing a segment at a time");
+
+ // Extract an iterator over the next contiguous region of the shared memory
+ // buffer which will be used .
+ char* start = static_cast<char*>(link->mShmem->memory()) + link->mOffset;
+ char* iter = start;
+ char* end = start + std::min({aCount - *aProcessedCount, link->mAvailable,
+ link->mCapacity - link->mOffset});
+
+ // Record the consumed region from our segment when exiting this scope,
+ // telling our peer how many bytes were consumed. Hold on to `mLink` to keep
+ // the shmem mapped and make sure we can clean up even if we're closed while
+ // processing the shmem region.
+ link->mProcessingSegment = true;
+ auto scopeExit = MakeScopeExit([&] {
+ mMutex->AssertCurrentThreadOwns(); // should still be held
+ AssertSameMutex(link->mMutex);
+
+ MOZ_RELEASE_ASSERT(link->mProcessingSegment);
+ link->mProcessingSegment = false;
+ uint32_t totalProcessed = iter - start;
+ if (totalProcessed > 0) {
+ link->mOffset += totalProcessed;
+ MOZ_RELEASE_ASSERT(link->mOffset <= link->mCapacity);
+ if (link->mOffset == link->mCapacity) {
+ link->mOffset = 0;
+ }
+ link->mAvailable -= totalProcessed;
+ link->SendBytesConsumedOnUnlock(lock, totalProcessed);
+ }
+ MOZ_LOG(gDataPipeLog, LogLevel::Verbose,
+ ("Processed Segment(%u of %zu) %s", totalProcessed, end - start,
+ Describe(lock).get()));
+ });
+
+ {
+ MutexAutoUnlock unlock(*mMutex);
+ while (iter < end) {
+ uint32_t processed = 0;
+ Span segment{iter, end};
+ nsresult rv = aProcessSegment(segment, *aProcessedCount, &processed);
+ if (NS_FAILED(rv) || processed == 0) {
+ return NS_OK;
+ }
+
+ MOZ_RELEASE_ASSERT(processed <= segment.Length());
+ iter += processed;
+ *aProcessedCount += processed;
+ }
+ }
+ }
+ MOZ_DIAGNOSTIC_ASSERT(*aProcessedCount == aCount,
+ "Must have processed exactly aCount");
+ return NS_OK;
+}
+
+void DataPipeBase::AsyncWaitInternal(already_AddRefed<nsIRunnable> aCallback,
+ already_AddRefed<nsIEventTarget> aTarget,
+ bool aClosureOnly) {
+ RefPtr<nsIRunnable> callback = std::move(aCallback);
+ RefPtr<nsIEventTarget> target = std::move(aTarget);
+
+ DataPipeAutoLock lock(*mMutex);
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("AsyncWait %s %p %s", aClosureOnly ? "(closure)" : "(ready)",
+ callback.get(), Describe(lock).get()));
+
+ if (NS_FAILED(CheckStatus(lock))) {
+#ifdef DEBUG
+ if (mLink) {
+ AssertSameMutex(mLink->mMutex);
+ MOZ_ASSERT(!mLink->mCallback);
+ }
+#endif
+ DoNotifyOnUnlock(lock, callback.forget(), target.forget());
+ return;
+ }
+
+ AssertSameMutex(mLink->mMutex);
+
+ // NOTE: After this point, `mLink` may have previously had a callback which is
+ // now being cancelled, make sure we clear `mCallback` even if we're going to
+ // call `aCallback` immediately.
+ mLink->mCallback = callback.forget();
+ mLink->mCallbackTarget = target.forget();
+ mLink->mCallbackClosureOnly = aClosureOnly;
+ if (!aClosureOnly && mLink->mAvailable) {
+ mLink->NotifyOnUnlock(lock);
+ }
+}
+
+nsresult DataPipeBase::CheckStatus(DataPipeAutoLock& aLock) {
+ // If our peer has closed or errored, we may need to close our local side to
+ // reflect the error code our peer provided. If we're a sender, we want to
+ // become closed immediately, whereas if we're a receiver we want to wait
+ // until our available buffer has been exhausted.
+ //
+ // NOTE: There may still be 2-stage writes/reads ongoing at this point, which
+ // will continue due to `mLink` being kept alive by the
+ // `ProcessSegmentsInternal` function.
+ if (NS_FAILED(mStatus)) {
+ return mStatus;
+ }
+ AssertSameMutex(mLink->mMutex);
+ if (NS_FAILED(mLink->mPeerStatus) &&
+ (!mLink->mReceiverSide || !mLink->mAvailable)) {
+ CloseInternal(aLock, mLink->mPeerStatus);
+ }
+ return mStatus;
+}
+
+nsCString DataPipeBase::Describe(DataPipeAutoLock& aLock) {
+ if (mLink) {
+ AssertSameMutex(mLink->mMutex);
+ return mLink->Describe(aLock);
+ }
+ return nsPrintfCString("[status=%s]", GetStaticErrorName(mStatus));
+}
+
+template <typename T>
+void DataPipeWrite(IPC::MessageWriter* aWriter, T* aParam) {
+ DataPipeAutoLock lock(*aParam->mMutex);
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("IPC Write: %s", aParam->Describe(lock).get()));
+
+ WriteParam(aWriter, aParam->mStatus);
+ if (NS_FAILED(aParam->mStatus)) {
+ return;
+ }
+
+ aParam->AssertSameMutex(aParam->mLink->mMutex);
+ MOZ_RELEASE_ASSERT(!aParam->mLink->mProcessingSegment,
+ "cannot transfer while processing a segment");
+
+ // Serialize relevant parameters to our peer.
+ WriteParam(aWriter, std::move(aParam->mLink->mPort));
+ WriteParam(aWriter, std::move(aParam->mLink->mShmemHandle));
+ WriteParam(aWriter, aParam->mLink->mCapacity);
+ WriteParam(aWriter, aParam->mLink->mPeerStatus);
+ WriteParam(aWriter, aParam->mLink->mOffset);
+ WriteParam(aWriter, aParam->mLink->mAvailable);
+
+ // Mark our peer as closed so we don't try to send to it when closing.
+ aParam->mLink->mPeerStatus = NS_ERROR_NOT_INITIALIZED;
+ aParam->CloseInternal(lock, NS_ERROR_NOT_INITIALIZED);
+}
+
+template <typename T>
+bool DataPipeRead(IPC::MessageReader* aReader, RefPtr<T>* aResult) {
+ nsresult rv = NS_OK;
+ if (!ReadParam(aReader, &rv)) {
+ aReader->FatalError("failed to read DataPipe status");
+ return false;
+ }
+ if (NS_FAILED(rv)) {
+ *aResult = new T(rv);
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("IPC Read: [status=%s]", GetStaticErrorName(rv)));
+ return true;
+ }
+
+ ScopedPort port;
+ if (!ReadParam(aReader, &port)) {
+ aReader->FatalError("failed to read DataPipe port");
+ return false;
+ }
+ SharedMemoryBasic::Handle shmemHandle;
+ if (!ReadParam(aReader, &shmemHandle)) {
+ aReader->FatalError("failed to read DataPipe shmem");
+ return false;
+ }
+ // Due to the awkward shared memory API provided by SharedMemoryBasic, we need
+ // to transfer ownership into the `shmem` here, then steal it back later in
+ // the function. Bug 1797039 tracks potential changes to the RawShmem API
+ // which could improve this situation.
+ RefPtr shmem = new SharedMemoryBasic();
+ if (!shmem->SetHandle(std::move(shmemHandle),
+ SharedMemory::RightsReadWrite)) {
+ aReader->FatalError("failed to create DataPipe shmem from handle");
+ return false;
+ }
+ uint32_t capacity = 0;
+ nsresult peerStatus = NS_OK;
+ uint32_t offset = 0;
+ uint32_t available = 0;
+ if (!ReadParam(aReader, &capacity) || !ReadParam(aReader, &peerStatus) ||
+ !ReadParam(aReader, &offset) || !ReadParam(aReader, &available)) {
+ aReader->FatalError("failed to read DataPipe fields");
+ return false;
+ }
+ if (!capacity || offset >= capacity || available > capacity) {
+ aReader->FatalError("received DataPipe state values are inconsistent");
+ return false;
+ }
+ if (!shmem->Map(SharedMemory::PageAlignedSize(capacity))) {
+ aReader->FatalError("failed to map DataPipe shared memory region");
+ return false;
+ }
+
+ *aResult = new T(std::move(port), shmem->TakeHandle(), shmem, capacity,
+ peerStatus, offset, available);
+ if (MOZ_LOG_TEST(gDataPipeLog, LogLevel::Debug)) {
+ DataPipeAutoLock lock(*(*aResult)->mMutex);
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("IPC Read: %s", (*aResult)->Describe(lock).get()));
+ }
+ return true;
+}
+
+} // namespace data_pipe_detail
+
+//-----------------------------------------------------------------------------
+// DataPipeSender
+//-----------------------------------------------------------------------------
+
+NS_IMPL_ISUPPORTS(DataPipeSender, nsIOutputStream, nsIAsyncOutputStream,
+ DataPipeSender)
+
+// nsIOutputStream
+
+NS_IMETHODIMP DataPipeSender::Close() {
+ return CloseWithStatus(NS_BASE_STREAM_CLOSED);
+}
+
+NS_IMETHODIMP DataPipeSender::Flush() { return NS_OK; }
+
+NS_IMETHODIMP DataPipeSender::StreamStatus() {
+ data_pipe_detail::DataPipeAutoLock lock(*mMutex);
+ return CheckStatus(lock);
+}
+
+NS_IMETHODIMP DataPipeSender::Write(const char* aBuf, uint32_t aCount,
+ uint32_t* aWriteCount) {
+ return WriteSegments(NS_CopyBufferToSegment, (void*)aBuf, aCount,
+ aWriteCount);
+}
+
+NS_IMETHODIMP DataPipeSender::WriteFrom(nsIInputStream* aFromStream,
+ uint32_t aCount,
+ uint32_t* aWriteCount) {
+ return WriteSegments(NS_CopyStreamToSegment, aFromStream, aCount,
+ aWriteCount);
+}
+
+NS_IMETHODIMP DataPipeSender::WriteSegments(nsReadSegmentFun aReader,
+ void* aClosure, uint32_t aCount,
+ uint32_t* aWriteCount) {
+ auto processSegment = [&](Span<char> aSpan, uint32_t aToOffset,
+ uint32_t* aReadCount) -> nsresult {
+ return aReader(this, aClosure, aSpan.data(), aToOffset, aSpan.Length(),
+ aReadCount);
+ };
+ return ProcessSegmentsInternal(aCount, processSegment, aWriteCount);
+}
+
+NS_IMETHODIMP DataPipeSender::IsNonBlocking(bool* _retval) {
+ *_retval = true;
+ return NS_OK;
+}
+
+// nsIAsyncOutputStream
+
+NS_IMETHODIMP DataPipeSender::CloseWithStatus(nsresult reason) {
+ data_pipe_detail::DataPipeAutoLock lock(*mMutex);
+ CloseInternal(lock, reason);
+ return NS_OK;
+}
+
+NS_IMETHODIMP DataPipeSender::AsyncWait(nsIOutputStreamCallback* aCallback,
+ uint32_t aFlags,
+ uint32_t aRequestedCount,
+ nsIEventTarget* aTarget) {
+ AsyncWaitInternal(
+ aCallback ? NS_NewCancelableRunnableFunction(
+ "DataPipeReceiver::AsyncWait",
+ [self = RefPtr{this}, callback = RefPtr{aCallback}] {
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("Calling OnOutputStreamReady(%p, %p)",
+ callback.get(), self.get()));
+ callback->OnOutputStreamReady(self);
+ })
+ : nullptr,
+ do_AddRef(aTarget), aFlags & WAIT_CLOSURE_ONLY);
+ return NS_OK;
+}
+
+//-----------------------------------------------------------------------------
+// DataPipeReceiver
+//-----------------------------------------------------------------------------
+
+NS_IMPL_ISUPPORTS(DataPipeReceiver, nsIInputStream, nsIAsyncInputStream,
+ nsIIPCSerializableInputStream, DataPipeReceiver)
+
+// nsIInputStream
+
+NS_IMETHODIMP DataPipeReceiver::Close() {
+ return CloseWithStatus(NS_BASE_STREAM_CLOSED);
+}
+
+NS_IMETHODIMP DataPipeReceiver::Available(uint64_t* _retval) {
+ data_pipe_detail::DataPipeAutoLock lock(*mMutex);
+ nsresult rv = CheckStatus(lock);
+ if (NS_FAILED(rv)) {
+ return rv;
+ }
+ AssertSameMutex(mLink->mMutex);
+ *_retval = mLink->mAvailable;
+ return NS_OK;
+}
+
+NS_IMETHODIMP DataPipeReceiver::StreamStatus() {
+ data_pipe_detail::DataPipeAutoLock lock(*mMutex);
+ return CheckStatus(lock);
+}
+
+NS_IMETHODIMP DataPipeReceiver::Read(char* aBuf, uint32_t aCount,
+ uint32_t* aReadCount) {
+ return ReadSegments(NS_CopySegmentToBuffer, aBuf, aCount, aReadCount);
+}
+
+NS_IMETHODIMP DataPipeReceiver::ReadSegments(nsWriteSegmentFun aWriter,
+ void* aClosure, uint32_t aCount,
+ uint32_t* aReadCount) {
+ auto processSegment = [&](Span<char> aSpan, uint32_t aToOffset,
+ uint32_t* aWriteCount) -> nsresult {
+ return aWriter(this, aClosure, aSpan.data(), aToOffset, aSpan.Length(),
+ aWriteCount);
+ };
+ return ProcessSegmentsInternal(aCount, processSegment, aReadCount);
+}
+
+NS_IMETHODIMP DataPipeReceiver::IsNonBlocking(bool* _retval) {
+ *_retval = true;
+ return NS_OK;
+}
+
+// nsIAsyncInputStream
+
+NS_IMETHODIMP DataPipeReceiver::CloseWithStatus(nsresult aStatus) {
+ data_pipe_detail::DataPipeAutoLock lock(*mMutex);
+ CloseInternal(lock, aStatus);
+ return NS_OK;
+}
+
+NS_IMETHODIMP DataPipeReceiver::AsyncWait(nsIInputStreamCallback* aCallback,
+ uint32_t aFlags,
+ uint32_t aRequestedCount,
+ nsIEventTarget* aTarget) {
+ AsyncWaitInternal(
+ aCallback ? NS_NewCancelableRunnableFunction(
+ "DataPipeReceiver::AsyncWait",
+ [self = RefPtr{this}, callback = RefPtr{aCallback}] {
+ MOZ_LOG(gDataPipeLog, LogLevel::Debug,
+ ("Calling OnInputStreamReady(%p, %p)",
+ callback.get(), self.get()));
+ callback->OnInputStreamReady(self);
+ })
+ : nullptr,
+ do_AddRef(aTarget), aFlags & WAIT_CLOSURE_ONLY);
+ return NS_OK;
+}
+
+// nsIIPCSerializableInputStream
+
+void DataPipeReceiver::SerializedComplexity(uint32_t aMaxSize,
+ uint32_t* aSizeUsed,
+ uint32_t* aPipes,
+ uint32_t* aTransferables) {
+ // We report DataPipeReceiver as taking one transferrable to serialize, rather
+ // than one pipe, as we aren't starting a new pipe for this purpose, and are
+ // instead transferring an existing pipe.
+ *aTransferables = 1;
+}
+
+void DataPipeReceiver::Serialize(InputStreamParams& aParams, uint32_t aMaxSize,
+ uint32_t* aSizeUsed) {
+ *aSizeUsed = 0;
+ aParams = DataPipeReceiverStreamParams(WrapNotNull(this));
+}
+
+bool DataPipeReceiver::Deserialize(const InputStreamParams& aParams) {
+ MOZ_CRASH("Handled directly in `DeserializeInputStream`");
+}
+
+//-----------------------------------------------------------------------------
+// NewDataPipe
+//-----------------------------------------------------------------------------
+
+nsresult NewDataPipe(uint32_t aCapacity, DataPipeSender** aSender,
+ DataPipeReceiver** aReceiver) {
+ if (!aCapacity) {
+ aCapacity = kDefaultDataPipeCapacity;
+ }
+
+ RefPtr<NodeController> controller = NodeController::GetSingleton();
+ if (!controller) {
+ return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
+ }
+
+ // Allocate a pair of ports for messaging between the sender & receiver.
+ auto [senderPort, receiverPort] = controller->CreatePortPair();
+
+ // Create and allocate the shared memory region.
+ auto shmem = MakeRefPtr<SharedMemoryBasic>();
+ size_t alignedCapacity = SharedMemory::PageAlignedSize(aCapacity);
+ if (!shmem->Create(alignedCapacity) || !shmem->Map(alignedCapacity)) {
+ return NS_ERROR_OUT_OF_MEMORY;
+ }
+
+ // We'll first clone then take the handle from the region so that the sender &
+ // receiver each have a handle. This avoids the need to duplicate the handle
+ // when serializing, when errors are non-recoverable.
+ SharedMemoryBasic::Handle senderShmemHandle = shmem->CloneHandle();
+ SharedMemoryBasic::Handle receiverShmemHandle = shmem->TakeHandle();
+ if (!senderShmemHandle || !receiverShmemHandle) {
+ return NS_ERROR_OUT_OF_MEMORY;
+ }
+
+ RefPtr sender =
+ new DataPipeSender(std::move(senderPort), std::move(senderShmemHandle),
+ shmem, aCapacity, NS_OK, 0, aCapacity);
+ RefPtr receiver = new DataPipeReceiver(std::move(receiverPort),
+ std::move(receiverShmemHandle), shmem,
+ aCapacity, NS_OK, 0, 0);
+ sender.forget(aSender);
+ receiver.forget(aReceiver);
+ return NS_OK;
+}
+
+} // namespace ipc
+} // namespace mozilla
+
+void IPC::ParamTraits<mozilla::ipc::DataPipeSender*>::Write(
+ MessageWriter* aWriter, mozilla::ipc::DataPipeSender* aParam) {
+ mozilla::ipc::data_pipe_detail::DataPipeWrite(aWriter, aParam);
+}
+
+bool IPC::ParamTraits<mozilla::ipc::DataPipeSender*>::Read(
+ MessageReader* aReader, RefPtr<mozilla::ipc::DataPipeSender>* aResult) {
+ return mozilla::ipc::data_pipe_detail::DataPipeRead(aReader, aResult);
+}
+
+void IPC::ParamTraits<mozilla::ipc::DataPipeReceiver*>::Write(
+ MessageWriter* aWriter, mozilla::ipc::DataPipeReceiver* aParam) {
+ mozilla::ipc::data_pipe_detail::DataPipeWrite(aWriter, aParam);
+}
+
+bool IPC::ParamTraits<mozilla::ipc::DataPipeReceiver*>::Read(
+ MessageReader* aReader, RefPtr<mozilla::ipc::DataPipeReceiver>* aResult) {
+ return mozilla::ipc::data_pipe_detail::DataPipeRead(aReader, aResult);
+}
diff --git a/ipc/glue/DataPipe.h b/ipc/glue/DataPipe.h
new file mode 100644
index 0000000000..f339b1c72d
--- /dev/null
+++ b/ipc/glue/DataPipe.h
@@ -0,0 +1,192 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_DataPipe_h
+#define mozilla_ipc_DataPipe_h
+
+#include "mozilla/ipc/SharedMemoryBasic.h"
+#include "mozilla/ipc/NodeController.h"
+#include "nsIAsyncInputStream.h"
+#include "nsIAsyncOutputStream.h"
+#include "nsIIPCSerializableInputStream.h"
+#include "nsISupports.h"
+
+namespace mozilla {
+namespace ipc {
+
+namespace data_pipe_detail {
+
+class DataPipeAutoLock;
+class DataPipeLink;
+
+class DataPipeBase {
+ public:
+ DataPipeBase(const DataPipeBase&) = delete;
+ DataPipeBase& operator=(const DataPipeBase&) = delete;
+
+ protected:
+ explicit DataPipeBase(bool aReceiverSide, nsresult aError);
+ DataPipeBase(bool aReceiverSide, ScopedPort aPort,
+ SharedMemoryBasic::Handle aShmemHandle, SharedMemory* aShmem,
+ uint32_t aCapacity, nsresult aPeerStatus, uint32_t aOffset,
+ uint32_t aAvailable);
+
+ void CloseInternal(DataPipeAutoLock&, nsresult aStatus) MOZ_REQUIRES(*mMutex);
+
+ void AsyncWaitInternal(already_AddRefed<nsIRunnable> aCallback,
+ already_AddRefed<nsIEventTarget> aTarget,
+ bool aClosureOnly) MOZ_EXCLUDES(*mMutex);
+
+ // Like `nsWriteSegmentFun` or `nsReadSegmentFun`.
+ using ProcessSegmentFun =
+ FunctionRef<nsresult(Span<char> aSpan, uint32_t aProcessedThisCall,
+ uint32_t* aProcessedCount)>;
+ nsresult ProcessSegmentsInternal(uint32_t aCount,
+ ProcessSegmentFun aProcessSegment,
+ uint32_t* aProcessedCount)
+ MOZ_EXCLUDES(*mMutex);
+
+ nsresult CheckStatus(DataPipeAutoLock&) MOZ_REQUIRES(*mMutex);
+
+ nsCString Describe(DataPipeAutoLock&) MOZ_REQUIRES(*mMutex);
+
+ // Thread safety helper to tell the analysis that `mLink->mMutex` is held when
+ // `mMutex` is held.
+ void AssertSameMutex(const std::shared_ptr<Mutex>& aMutex)
+ MOZ_REQUIRES(*mMutex) MOZ_ASSERT_CAPABILITY(*aMutex) {
+ MOZ_ASSERT(mMutex == aMutex);
+ }
+
+ virtual ~DataPipeBase();
+
+ const std::shared_ptr<Mutex> mMutex;
+ nsresult mStatus MOZ_GUARDED_BY(*mMutex) = NS_OK;
+ RefPtr<DataPipeLink> mLink MOZ_GUARDED_BY(*mMutex);
+};
+
+template <typename T>
+void DataPipeWrite(IPC::MessageWriter* aWriter, T* aParam);
+
+template <typename T>
+bool DataPipeRead(IPC::MessageReader* aReader, RefPtr<T>* aResult);
+
+} // namespace data_pipe_detail
+
+class DataPipeSender;
+class DataPipeReceiver;
+
+#define NS_DATAPIPESENDER_IID \
+ { \
+ 0x6698ed77, 0x9fff, 0x425d, { \
+ 0xb0, 0xa6, 0x1d, 0x30, 0x66, 0xee, 0xb8, 0x16 \
+ } \
+ }
+
+// Helper class for streaming data to another process.
+class DataPipeSender final : public nsIAsyncOutputStream,
+ public data_pipe_detail::DataPipeBase {
+ public:
+ NS_DECLARE_STATIC_IID_ACCESSOR(NS_DATAPIPESENDER_IID)
+ NS_DECL_THREADSAFE_ISUPPORTS
+ NS_DECL_NSIOUTPUTSTREAM
+ NS_DECL_NSIASYNCOUTPUTSTREAM
+
+ private:
+ friend nsresult NewDataPipe(uint32_t, DataPipeSender**, DataPipeReceiver**);
+ friend void data_pipe_detail::DataPipeWrite<DataPipeSender>(
+ IPC::MessageWriter* aWriter, DataPipeSender* aParam);
+ friend bool data_pipe_detail::DataPipeRead<DataPipeSender>(
+ IPC::MessageReader* aReader, RefPtr<DataPipeSender>* aResult);
+
+ explicit DataPipeSender(nsresult aError)
+ : data_pipe_detail::DataPipeBase(/* aReceiverSide */ false, aError) {}
+ DataPipeSender(ScopedPort aPort, SharedMemoryBasic::Handle aShmemHandle,
+ SharedMemory* aShmem, uint32_t aCapacity, nsresult aPeerStatus,
+ uint32_t aOffset, uint32_t aAvailable)
+ : data_pipe_detail::DataPipeBase(
+ /* aReceiverSide */ false, std::move(aPort),
+ std::move(aShmemHandle), aShmem, aCapacity, aPeerStatus, aOffset,
+ aAvailable) {}
+
+ ~DataPipeSender() = default;
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(DataPipeSender, NS_DATAPIPESENDER_IID)
+
+#define NS_DATAPIPERECEIVER_IID \
+ { \
+ 0x0a185f83, 0x499e, 0x450c, { \
+ 0x95, 0x82, 0x27, 0x67, 0xad, 0x6d, 0x64, 0xb5 \
+ } \
+ }
+
+// Helper class for streaming data from another process.
+class DataPipeReceiver final : public nsIAsyncInputStream,
+ public nsIIPCSerializableInputStream,
+ public data_pipe_detail::DataPipeBase {
+ public:
+ NS_DECLARE_STATIC_IID_ACCESSOR(NS_DATAPIPERECEIVER_IID)
+ NS_DECL_THREADSAFE_ISUPPORTS
+ NS_DECL_NSIINPUTSTREAM
+ NS_DECL_NSIASYNCINPUTSTREAM
+ NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM
+
+ private:
+ friend nsresult NewDataPipe(uint32_t, DataPipeSender**, DataPipeReceiver**);
+ friend void data_pipe_detail::DataPipeWrite<DataPipeReceiver>(
+ IPC::MessageWriter* aWriter, DataPipeReceiver* aParam);
+ friend bool data_pipe_detail::DataPipeRead<DataPipeReceiver>(
+ IPC::MessageReader* aReader, RefPtr<DataPipeReceiver>* aResult);
+
+ explicit DataPipeReceiver(nsresult aError)
+ : data_pipe_detail::DataPipeBase(/* aReceiverSide */ true, aError) {}
+ DataPipeReceiver(ScopedPort aPort, SharedMemoryBasic::Handle aShmemHandle,
+ SharedMemory* aShmem, uint32_t aCapacity,
+ nsresult aPeerStatus, uint32_t aOffset, uint32_t aAvailable)
+ : data_pipe_detail::DataPipeBase(
+ /* aReceiverSide */ true, std::move(aPort), std::move(aShmemHandle),
+ aShmem, aCapacity, aPeerStatus, aOffset, aAvailable) {}
+
+ ~DataPipeReceiver() = default;
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(DataPipeReceiver, NS_DATAPIPERECEIVER_IID)
+
+constexpr uint32_t kDefaultDataPipeCapacity = 64 * 1024;
+
+/**
+ * Create a new DataPipe pair. The sender and receiver ends of the pipe may be
+ * used to transfer data between processes. |aCapacity| is the capacity of the
+ * underlying ring buffer. If `0` is passed, `kDefaultDataPipeCapacity` will be
+ * used.
+ */
+nsresult NewDataPipe(uint32_t aCapacity, DataPipeSender** aSender,
+ DataPipeReceiver** aReceiver);
+
+} // namespace ipc
+} // namespace mozilla
+
+namespace IPC {
+
+template <>
+struct ParamTraits<mozilla::ipc::DataPipeSender*> {
+ static void Write(MessageWriter* aWriter,
+ mozilla::ipc::DataPipeSender* aParam);
+ static bool Read(MessageReader* aReader,
+ RefPtr<mozilla::ipc::DataPipeSender>* aResult);
+};
+
+template <>
+struct ParamTraits<mozilla::ipc::DataPipeReceiver*> {
+ static void Write(MessageWriter* aWriter,
+ mozilla::ipc::DataPipeReceiver* aParam);
+ static bool Read(MessageReader* aReader,
+ RefPtr<mozilla::ipc::DataPipeReceiver>* aResult);
+};
+
+} // namespace IPC
+
+#endif // mozilla_ipc_DataPipe_h
diff --git a/ipc/glue/Endpoint.cpp b/ipc/glue/Endpoint.cpp
new file mode 100644
index 0000000000..3391f8b359
--- /dev/null
+++ b/ipc/glue/Endpoint.cpp
@@ -0,0 +1,167 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/Endpoint.h"
+#include "chrome/common/ipc_message.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "nsThreadUtils.h"
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+
+namespace mozilla::ipc {
+
+UntypedManagedEndpoint::UntypedManagedEndpoint(IProtocol* aActor)
+ : mInner(Some(Inner{
+ /* mOtherSide */ aActor->GetWeakLifecycleProxy(),
+ /* mToplevel */ nullptr,
+ aActor->Id(),
+ aActor->GetProtocolId(),
+ aActor->Manager()->Id(),
+ aActor->Manager()->GetProtocolId(),
+ })) {}
+
+UntypedManagedEndpoint::~UntypedManagedEndpoint() {
+ if (!IsValid()) {
+ return;
+ }
+
+ if (mInner->mOtherSide) {
+ // If this ManagedEndpoint was never sent over IPC, deliver a fake
+ // MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE message directly to the other side
+ // actor.
+ mInner->mOtherSide->ActorEventTarget()->Dispatch(NS_NewRunnableFunction(
+ "~ManagedEndpoint (Local)",
+ [otherSide = mInner->mOtherSide, id = mInner->mId] {
+ if (IProtocol* actor = otherSide->Get(); actor && actor->CanRecv()) {
+ MOZ_DIAGNOSTIC_ASSERT(actor->Id() == id, "Wrong Actor?");
+ RefPtr<ActorLifecycleProxy> strongProxy(actor->GetLifecycleProxy());
+ strongProxy->Get()->OnMessageReceived(
+ IPC::Message(id, MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE));
+ }
+ }));
+ } else if (mInner->mToplevel) {
+ // If it was sent over IPC, we'll need to send the message to the sending
+ // side. Let's send the message async.
+ mInner->mToplevel->ActorEventTarget()->Dispatch(NS_NewRunnableFunction(
+ "~ManagedEndpoint (Remote)",
+ [toplevel = mInner->mToplevel, id = mInner->mId] {
+ if (IProtocol* actor = toplevel->Get();
+ actor && actor->CanSend() && actor->GetIPCChannel()) {
+ actor->GetIPCChannel()->Send(MakeUnique<IPC::Message>(
+ id, MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE));
+ }
+ }));
+ }
+}
+
+bool UntypedManagedEndpoint::BindCommon(IProtocol* aActor,
+ IProtocol* aManager) {
+ MOZ_ASSERT(aManager);
+ if (!mInner) {
+ NS_WARNING("Cannot bind to invalid endpoint");
+ return false;
+ }
+
+ // Perform thread assertions.
+ if (mInner->mToplevel) {
+ MOZ_DIAGNOSTIC_ASSERT(
+ mInner->mToplevel->ActorEventTarget()->IsOnCurrentThread());
+ MOZ_DIAGNOSTIC_ASSERT(aManager->ToplevelProtocol() ==
+ mInner->mToplevel->Get());
+ }
+
+ if (NS_WARN_IF(aManager->Id() != mInner->mManagerId) ||
+ NS_WARN_IF(aManager->GetProtocolId() != mInner->mManagerType) ||
+ NS_WARN_IF(aActor->GetProtocolId() != mInner->mType)) {
+ MOZ_ASSERT_UNREACHABLE("Actor and manager do not match Endpoint");
+ return false;
+ }
+
+ if (!aManager->CanSend() || !aManager->GetIPCChannel()) {
+ NS_WARNING("Manager cannot send");
+ return false;
+ }
+
+ int32_t id = mInner->mId;
+ mInner.reset();
+
+ // Our typed caller will insert the actor into the managed container.
+ aActor->SetManagerAndRegister(aManager, id);
+
+ aManager->GetIPCChannel()->Send(
+ MakeUnique<IPC::Message>(id, MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE));
+ return true;
+}
+
+/* static */
+void IPDLParamTraits<UntypedManagedEndpoint>::Write(IPC::MessageWriter* aWriter,
+ IProtocol* aActor,
+ paramType&& aParam) {
+ bool isValid = aParam.mInner.isSome();
+ WriteIPDLParam(aWriter, aActor, isValid);
+ if (!isValid) {
+ return;
+ }
+
+ auto inner = std::move(*aParam.mInner);
+ aParam.mInner.reset();
+
+ MOZ_RELEASE_ASSERT(inner.mOtherSide, "Has not been sent over IPC yet");
+ MOZ_RELEASE_ASSERT(inner.mOtherSide->ActorEventTarget()->IsOnCurrentThread(),
+ "Must be being sent from the correct thread");
+ MOZ_RELEASE_ASSERT(
+ inner.mOtherSide->Get() && inner.mOtherSide->Get()->ToplevelProtocol() ==
+ aActor->ToplevelProtocol(),
+ "Must be being sent over the same toplevel protocol");
+
+ WriteIPDLParam(aWriter, aActor, inner.mId);
+ WriteIPDLParam(aWriter, aActor, inner.mType);
+ WriteIPDLParam(aWriter, aActor, inner.mManagerId);
+ WriteIPDLParam(aWriter, aActor, inner.mManagerType);
+}
+
+/* static */
+bool IPDLParamTraits<UntypedManagedEndpoint>::Read(IPC::MessageReader* aReader,
+ IProtocol* aActor,
+ paramType* aResult) {
+ *aResult = UntypedManagedEndpoint{};
+ bool isValid = false;
+ if (!aActor || !ReadIPDLParam(aReader, aActor, &isValid)) {
+ return false;
+ }
+ if (!isValid) {
+ return true;
+ }
+
+ aResult->mInner.emplace();
+ auto& inner = *aResult->mInner;
+ inner.mToplevel = aActor->ToplevelProtocol()->GetWeakLifecycleProxy();
+ return ReadIPDLParam(aReader, aActor, &inner.mId) &&
+ ReadIPDLParam(aReader, aActor, &inner.mType) &&
+ ReadIPDLParam(aReader, aActor, &inner.mManagerId) &&
+ ReadIPDLParam(aReader, aActor, &inner.mManagerType);
+}
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+void ParamTraits<mozilla::ipc::UntypedEndpoint>::Write(MessageWriter* aWriter,
+ paramType&& aParam) {
+ IPC::WriteParam(aWriter, std::move(aParam.mPort));
+ IPC::WriteParam(aWriter, aParam.mMessageChannelId);
+ IPC::WriteParam(aWriter, aParam.mMyPid);
+ IPC::WriteParam(aWriter, aParam.mOtherPid);
+}
+
+bool ParamTraits<mozilla::ipc::UntypedEndpoint>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ return IPC::ReadParam(aReader, &aResult->mPort) &&
+ IPC::ReadParam(aReader, &aResult->mMessageChannelId) &&
+ IPC::ReadParam(aReader, &aResult->mMyPid) &&
+ IPC::ReadParam(aReader, &aResult->mOtherPid);
+}
+
+} // namespace IPC
diff --git a/ipc/glue/Endpoint.h b/ipc/glue/Endpoint.h
new file mode 100644
index 0000000000..d7eea94dfc
--- /dev/null
+++ b/ipc/glue/Endpoint.h
@@ -0,0 +1,288 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef IPC_GLUE_ENDPOINT_H_
+#define IPC_GLUE_ENDPOINT_H_
+
+#include <utility>
+#include "CrashAnnotations.h"
+#include "base/process.h"
+#include "base/process_util.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/MessageLink.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/ipc/NodeController.h"
+#include "mozilla/ipc/ScopedPort.h"
+#include "nsXULAppAPI.h"
+#include "nscore.h"
+
+namespace IPC {
+template <class P>
+struct ParamTraits;
+}
+
+namespace mozilla {
+namespace ipc {
+
+namespace endpoint_detail {
+
+template <class T>
+static auto ActorNeedsOtherPidHelper(int)
+ -> decltype(std::declval<T>().OtherPid(), std::true_type{});
+template <class>
+static auto ActorNeedsOtherPidHelper(long) -> std::false_type;
+
+template <typename T>
+constexpr bool ActorNeedsOtherPid =
+ decltype(ActorNeedsOtherPidHelper<T>(0))::value;
+
+} // namespace endpoint_detail
+
+struct PrivateIPDLInterface {};
+
+class UntypedEndpoint {
+ public:
+ using ProcessId = base::ProcessId;
+
+ UntypedEndpoint() = default;
+
+ UntypedEndpoint(const PrivateIPDLInterface&, ScopedPort aPort,
+ const nsID& aMessageChannelId,
+ ProcessId aMyPid = base::kInvalidProcessId,
+ ProcessId aOtherPid = base::kInvalidProcessId)
+ : mPort(std::move(aPort)),
+ mMessageChannelId(aMessageChannelId),
+ mMyPid(aMyPid),
+ mOtherPid(aOtherPid) {}
+
+ UntypedEndpoint(const UntypedEndpoint&) = delete;
+ UntypedEndpoint(UntypedEndpoint&& aOther) = default;
+
+ UntypedEndpoint& operator=(const UntypedEndpoint&) = delete;
+ UntypedEndpoint& operator=(UntypedEndpoint&& aOther) = default;
+
+ // This method binds aActor to this endpoint. After this call, the actor can
+ // be used to send and receive messages. The endpoint becomes invalid.
+ //
+ // If specified, aEventTarget is the target the actor will be bound to, and
+ // must be on the current thread. Otherwise, GetCurrentSerialEventTarget() is
+ // used.
+ bool Bind(IToplevelProtocol* aActor,
+ nsISerialEventTarget* aEventTarget = nullptr) {
+ MOZ_RELEASE_ASSERT(IsValid());
+ MOZ_RELEASE_ASSERT(mMyPid == base::kInvalidProcessId ||
+ mMyPid == base::GetCurrentProcId());
+ MOZ_RELEASE_ASSERT(!aEventTarget || aEventTarget->IsOnCurrentThread());
+ return aActor->Open(std::move(mPort), mMessageChannelId, mOtherPid,
+ aEventTarget);
+ }
+
+ bool IsValid() const { return mPort.IsValid(); }
+
+ protected:
+ friend struct IPC::ParamTraits<UntypedEndpoint>;
+
+ ScopedPort mPort;
+ nsID mMessageChannelId{};
+ ProcessId mMyPid = base::kInvalidProcessId;
+ ProcessId mOtherPid = base::kInvalidProcessId;
+};
+
+/**
+ * An endpoint represents one end of a partially initialized IPDL channel. To
+ * set up a new top-level protocol:
+ *
+ * Endpoint<PFooParent> parentEp;
+ * Endpoint<PFooChild> childEp;
+ * nsresult rv;
+ * rv = PFoo::CreateEndpoints(&parentEp, &childEp);
+ *
+ * Endpoints can be passed in IPDL messages or sent to other threads using
+ * PostTask. Once an Endpoint has arrived at its destination process and thread,
+ * you need to create the top-level actor and bind it to the endpoint:
+ *
+ * FooParent* parent = new FooParent();
+ * bool rv1 = parentEp.Bind(parent, processActor);
+ * bool rv2 = parent->SendBar(...);
+ *
+ * (See Bind below for an explanation of processActor.) Once the actor is bound
+ * to the endpoint, it can send and receive messages.
+ *
+ * If creating endpoints for a [NeedsOtherPid] actor, you're required to also
+ * pass in parentPid and childPid, which are the pids of the processes in which
+ * the parent and child endpoints will be used.
+ */
+template <class PFooSide>
+class Endpoint final : public UntypedEndpoint {
+ public:
+ using UntypedEndpoint::IsValid;
+ using UntypedEndpoint::UntypedEndpoint;
+
+ base::ProcessId OtherPid() const {
+ static_assert(
+ endpoint_detail::ActorNeedsOtherPid<PFooSide>,
+ "OtherPid may only be called on Endpoints for actors which are "
+ "[NeedsOtherPid]");
+ MOZ_RELEASE_ASSERT(mOtherPid != base::kInvalidProcessId);
+ return mOtherPid;
+ }
+
+ // This method binds aActor to this endpoint. After this call, the actor can
+ // be used to send and receive messages. The endpoint becomes invalid.
+ //
+ // If specified, aEventTarget is the target the actor will be bound to, and
+ // must be on the current thread. Otherwise, GetCurrentSerialEventTarget() is
+ // used.
+ bool Bind(PFooSide* aActor, nsISerialEventTarget* aEventTarget = nullptr) {
+ return UntypedEndpoint::Bind(aActor, aEventTarget);
+ }
+};
+
+#if defined(XP_MACOSX)
+void AnnotateCrashReportWithErrno(CrashReporter::Annotation tag, int error);
+#else
+inline void AnnotateCrashReportWithErrno(CrashReporter::Annotation tag,
+ int error) {}
+#endif
+
+// This function is used internally to create a pair of Endpoints. See the
+// comment above Endpoint for a description of how it might be used.
+template <class PFooParent, class PFooChild>
+nsresult CreateEndpoints(const PrivateIPDLInterface& aPrivate,
+ Endpoint<PFooParent>* aParentEndpoint,
+ Endpoint<PFooChild>* aChildEndpoint) {
+ static_assert(
+ !endpoint_detail::ActorNeedsOtherPid<PFooParent> &&
+ !endpoint_detail::ActorNeedsOtherPid<PFooChild>,
+ "Pids are required when creating endpoints for [NeedsOtherPid] actors");
+
+ auto [parentPort, childPort] =
+ NodeController::GetSingleton()->CreatePortPair();
+ nsID channelId = nsID::GenerateUUID();
+ *aParentEndpoint =
+ Endpoint<PFooParent>(aPrivate, std::move(parentPort), channelId);
+ *aChildEndpoint =
+ Endpoint<PFooChild>(aPrivate, std::move(childPort), channelId);
+ return NS_OK;
+}
+
+template <class PFooParent, class PFooChild>
+nsresult CreateEndpoints(const PrivateIPDLInterface& aPrivate,
+ base::ProcessId aParentDestPid,
+ base::ProcessId aChildDestPid,
+ Endpoint<PFooParent>* aParentEndpoint,
+ Endpoint<PFooChild>* aChildEndpoint) {
+ MOZ_RELEASE_ASSERT(aParentDestPid != base::kInvalidProcessId);
+ MOZ_RELEASE_ASSERT(aChildDestPid != base::kInvalidProcessId);
+
+ auto [parentPort, childPort] =
+ NodeController::GetSingleton()->CreatePortPair();
+ nsID channelId = nsID::GenerateUUID();
+ *aParentEndpoint =
+ Endpoint<PFooParent>(aPrivate, std::move(parentPort), channelId,
+ aParentDestPid, aChildDestPid);
+ *aChildEndpoint = Endpoint<PFooChild>(
+ aPrivate, std::move(childPort), channelId, aChildDestPid, aParentDestPid);
+ return NS_OK;
+}
+
+class UntypedManagedEndpoint {
+ public:
+ bool IsValid() const { return mInner.isSome(); }
+
+ UntypedManagedEndpoint(const UntypedManagedEndpoint&) = delete;
+ UntypedManagedEndpoint& operator=(const UntypedManagedEndpoint&) = delete;
+
+ protected:
+ UntypedManagedEndpoint() = default;
+ explicit UntypedManagedEndpoint(IProtocol* aActor);
+
+ UntypedManagedEndpoint(UntypedManagedEndpoint&& aOther) noexcept
+ : mInner(std::move(aOther.mInner)) {
+ aOther.mInner = Nothing();
+ }
+ UntypedManagedEndpoint& operator=(UntypedManagedEndpoint&& aOther) noexcept {
+ this->~UntypedManagedEndpoint();
+ new (this) UntypedManagedEndpoint(std::move(aOther));
+ return *this;
+ }
+
+ ~UntypedManagedEndpoint() noexcept;
+
+ bool BindCommon(IProtocol* aActor, IProtocol* aManager);
+
+ private:
+ friend struct IPDLParamTraits<UntypedManagedEndpoint>;
+
+ struct Inner {
+ // Pointers to the toplevel actor which will manage this connection. When
+ // created, only `mOtherSide` will be set, and will reference the
+ // toplevel actor which the other side is managed by. After being sent over
+ // IPC, only `mToplevel` will be set, and will be the toplevel actor for the
+ // channel which received the IPC message.
+ RefPtr<WeakActorLifecycleProxy> mOtherSide;
+ RefPtr<WeakActorLifecycleProxy> mToplevel;
+
+ int32_t mId = 0;
+ ProtocolId mType = LastMsgIndex;
+ int32_t mManagerId = 0;
+ ProtocolId mManagerType = LastMsgIndex;
+ };
+ Maybe<Inner> mInner;
+};
+
+/**
+ * A managed endpoint represents one end of a partially initialized managed
+ * IPDL actor. It is used for situations where the usual IPDL Constructor
+ * methods do not give sufficient control over the construction of actors, such
+ * as when constructing actors within replies, or constructing multiple related
+ * actors simultaneously.
+ *
+ * FooParent* parent = new FooParent();
+ * ManagedEndpoint<PFooChild> childEp = parentMgr->OpenPFooEndpoint(parent);
+ *
+ * ManagedEndpoints should be sent using IPDL messages or other mechanisms to
+ * the other side of the manager channel. Once the ManagedEndpoint has arrived
+ * at its destination, you can create the actor, and bind it to the endpoint.
+ *
+ * FooChild* child = new FooChild();
+ * childMgr->BindPFooEndpoint(childEp, child);
+ *
+ * WARNING: If the remote side of an endpoint has not been bound before it
+ * begins to receive messages, an IPC routing error will occur, likely causing
+ * a browser crash.
+ */
+template <class PFooSide>
+class ManagedEndpoint : public UntypedManagedEndpoint {
+ public:
+ ManagedEndpoint() = default;
+ ManagedEndpoint(ManagedEndpoint&&) noexcept = default;
+ ManagedEndpoint& operator=(ManagedEndpoint&&) noexcept = default;
+
+ ManagedEndpoint(const PrivateIPDLInterface&, IProtocol* aActor)
+ : UntypedManagedEndpoint(aActor) {}
+
+ bool Bind(const PrivateIPDLInterface&, PFooSide* aActor, IProtocol* aManager,
+ ManagedContainer<PFooSide>& aContainer) {
+ if (!BindCommon(aActor, aManager)) {
+ return false;
+ }
+ aContainer.Insert(aActor);
+ return true;
+ }
+
+ // Only invalid ManagedEndpoints can be equal, as valid endpoints are unique.
+ bool operator==(const ManagedEndpoint& _o) const {
+ return !IsValid() && !_o.IsValid();
+ }
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // IPC_GLUE_ENDPOINT_H_
diff --git a/ipc/glue/EnumSerializer.h b/ipc/glue/EnumSerializer.h
new file mode 100644
index 0000000000..13c1de3841
--- /dev/null
+++ b/ipc/glue/EnumSerializer.h
@@ -0,0 +1,187 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_ENUMSERIALIZER_H__
+#define __IPC_GLUE_ENUMSERIALIZER_H__
+
+#include "CrashAnnotations.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/IntegerTypeTraits.h"
+#include "nsExceptionHandler.h"
+#include "nsLiteralString.h"
+#include "nsString.h"
+#include "nsTLiteralString.h"
+
+class PickleIterator;
+
+namespace IPC {
+class Message;
+class MessageReader;
+class MessageWriter;
+} // namespace IPC
+
+#ifdef _MSC_VER
+# pragma warning(disable : 4800)
+#endif
+
+namespace IPC {
+
+/**
+ * Generic enum serializer.
+ *
+ * Consider using the specializations below, such as ContiguousEnumSerializer.
+ *
+ * This is a generic serializer for any enum type used in IPDL.
+ * Programmers can define ParamTraits<E> for enum type E by deriving
+ * EnumSerializer<E, MyEnumValidator> where MyEnumValidator is a struct
+ * that has to define a static IsLegalValue function returning whether
+ * a given value is a legal value of the enum type at hand.
+ *
+ * \sa https://developer.mozilla.org/en/IPDL/Type_Serialization
+ */
+template <typename E, typename EnumValidator>
+struct EnumSerializer {
+ typedef E paramType;
+
+ // XXX(Bug 1690343) Should this be changed to
+ // std::make_unsigned_t<std::underlying_type_t<paramType>>, to make this more
+ // consistent with the type used for validating values?
+ typedef typename mozilla::UnsignedStdintTypeForSize<sizeof(paramType)>::Type
+ uintParamType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aValue) {
+ // XXX This assertion is somewhat meaningless at least for E that don't have
+ // a fixed underlying type: if aValue weren't a legal value, we would
+ // already have UB where this function is called.
+ MOZ_RELEASE_ASSERT(EnumValidator::IsLegalValue(
+ static_cast<std::underlying_type_t<paramType>>(aValue)));
+ WriteParam(aWriter, uintParamType(aValue));
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ uintParamType value;
+ if (!ReadParam(aReader, &value)) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCReadErrorReason, "Bad iter"_ns);
+ return false;
+ } else if (!EnumValidator::IsLegalValue(value)) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCReadErrorReason, "Illegal value"_ns);
+ return false;
+ }
+ *aResult = paramType(value);
+ return true;
+ }
+};
+
+template <typename E, E MinLegal, E HighBound>
+class ContiguousEnumValidator {
+ // Silence overzealous -Wtype-limits bug in GCC fixed in GCC 4.8:
+ // "comparison of unsigned expression >= 0 is always true"
+ // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11856
+ template <typename T>
+ static bool IsLessThanOrEqual(T a, T b) {
+ return a <= b;
+ }
+
+ public:
+ using IntegralType = std::underlying_type_t<E>;
+ static constexpr auto kMinLegalIntegral = static_cast<IntegralType>(MinLegal);
+ static constexpr auto kHighBoundIntegral =
+ static_cast<IntegralType>(HighBound);
+
+ static bool IsLegalValue(const IntegralType e) {
+ return IsLessThanOrEqual(kMinLegalIntegral, e) && e < kHighBoundIntegral;
+ }
+};
+
+template <typename E, E MinLegal, E MaxLegal>
+class ContiguousEnumValidatorInclusive {
+ // Silence overzealous -Wtype-limits bug in GCC fixed in GCC 4.8:
+ // "comparison of unsigned expression >= 0 is always true"
+ // http://gcc.gnu.org/bugzilla/show_bug.cgi?id=11856
+ template <typename T>
+ static bool IsLessThanOrEqual(T a, T b) {
+ return a <= b;
+ }
+
+ public:
+ using IntegralType = std::underlying_type_t<E>;
+ static constexpr auto kMinLegalIntegral = static_cast<IntegralType>(MinLegal);
+ static constexpr auto kMaxLegalIntegral = static_cast<IntegralType>(MaxLegal);
+
+ static bool IsLegalValue(const IntegralType e) {
+ return IsLessThanOrEqual(kMinLegalIntegral, e) && e <= kMaxLegalIntegral;
+ }
+};
+
+template <typename E, E AllBits>
+struct BitFlagsEnumValidator {
+ static bool IsLegalValue(const std::underlying_type_t<E> e) {
+ return (e & static_cast<std::underlying_type_t<E>>(AllBits)) == e;
+ }
+};
+
+/**
+ * Specialization of EnumSerializer for enums with contiguous enum values.
+ *
+ * Provide two values: MinLegal, HighBound. An enum value x will be
+ * considered legal if MinLegal <= x < HighBound.
+ *
+ * For example, following is definition of serializer for enum type FOO.
+ * \code
+ * enum FOO { FOO_FIRST, FOO_SECOND, FOO_LAST, NUM_FOO };
+ *
+ * template <>
+ * struct ParamTraits<FOO>:
+ * public ContiguousEnumSerializer<FOO, FOO_FIRST, NUM_FOO> {};
+ * \endcode
+ * FOO_FIRST, FOO_SECOND, and FOO_LAST are valid value.
+ */
+template <typename E, E MinLegal, E HighBound>
+struct ContiguousEnumSerializer
+ : EnumSerializer<E, ContiguousEnumValidator<E, MinLegal, HighBound>> {};
+
+/**
+ * This is similar to ContiguousEnumSerializer, but the last template
+ * parameter is expected to be the highest legal value, rather than a
+ * sentinel value. This is intended to support enumerations that don't
+ * have sentinel values.
+ */
+template <typename E, E MinLegal, E MaxLegal>
+struct ContiguousEnumSerializerInclusive
+ : EnumSerializer<E,
+ ContiguousEnumValidatorInclusive<E, MinLegal, MaxLegal>> {
+};
+
+/**
+ * Specialization of EnumSerializer for enums representing bit flags.
+ *
+ * Provide one value: AllBits. An enum value x will be
+ * considered legal if (x & AllBits) == x;
+ *
+ * Example:
+ * \code
+ * enum FOO {
+ * FOO_FIRST = 1 << 0,
+ * FOO_SECOND = 1 << 1,
+ * FOO_LAST = 1 << 2,
+ * ALL_BITS = (1 << 3) - 1
+ * };
+ *
+ * template <>
+ * struct ParamTraits<FOO>:
+ * public BitFlagsEnumSerializer<FOO, FOO::ALL_BITS> {};
+ * \endcode
+ */
+template <typename E, E AllBits>
+struct BitFlagsEnumSerializer
+ : EnumSerializer<E, BitFlagsEnumValidator<E, AllBits>> {};
+
+} /* namespace IPC */
+
+#endif /* __IPC_GLUE_ENUMSERIALIZER_H__ */
diff --git a/ipc/glue/EnvironmentMap.h b/ipc/glue/EnvironmentMap.h
new file mode 100644
index 0000000000..61dcc1b7d2
--- /dev/null
+++ b/ipc/glue/EnvironmentMap.h
@@ -0,0 +1,62 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+// Copyright (c) 2011 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.
+
+#ifndef SANDBOXING_COMMON_ENVIRONMENTMAP_H_
+#define SANDBOXING_COMMON_ENVIRONMENTMAP_H_
+
+#include <map>
+#include <memory>
+#include <string>
+
+namespace base {
+
+#if defined(XP_WIN)
+
+typedef std::wstring NativeEnvironmentString;
+typedef std::map<NativeEnvironmentString, NativeEnvironmentString>
+ EnvironmentMap;
+
+# define ENVIRONMENT_LITERAL(x) L##x
+# define ENVIRONMENT_STRING(x) \
+ ((std::wstring)(NS_ConvertUTF8toUTF16((x)).get()))
+
+// Returns a modified environment vector constructed from the given environment
+// and the list of changes given in |changes|. Each key in the environment is
+// matched against the first element of the pairs. In the event of a match, the
+// value is replaced by the second of the pair, unless the second is empty, in
+// which case the key-value is removed.
+//
+// This Windows version takes and returns a Windows-style environment block
+// which is a concatenated list of null-terminated 16-bit strings. The end is
+// marked by a double-null terminator. The size of the returned string will
+// include the terminators.
+NativeEnvironmentString AlterEnvironment(const wchar_t* env,
+ const EnvironmentMap& changes);
+
+#else
+
+typedef std::string NativeEnvironmentString;
+typedef std::map<NativeEnvironmentString, NativeEnvironmentString>
+ EnvironmentMap;
+
+# define ENVIRONMENT_LITERAL(x) x
+# define ENVIRONMENT_STRING(x) x
+
+// See general comments for the Windows version above.
+//
+// This Posix version takes and returns a Posix-style environment block, which
+// is a null-terminated list of pointers to null-terminated strings. The
+// returned array will have appended to it the storage for the array itself so
+// there is only one pointer to manage, but this means that you can't copy the
+// array without keeping the original around.
+std::unique_ptr<char*[]> AlterEnvironment(const char* const* env,
+ const EnvironmentMap& changes);
+
+#endif
+
+} // namespace base
+
+#endif // SANDBOXING_COMMON_ENVIRONMENTMAP_H_
diff --git a/ipc/glue/FileDescriptor.cpp b/ipc/glue/FileDescriptor.cpp
new file mode 100644
index 0000000000..697de4cc63
--- /dev/null
+++ b/ipc/glue/FileDescriptor.cpp
@@ -0,0 +1,117 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "FileDescriptor.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+#include "nsDebug.h"
+
+#ifdef XP_WIN
+# include <windows.h>
+# include "ProtocolUtils.h"
+#else // XP_WIN
+# include <unistd.h>
+#endif // XP_WIN
+
+namespace mozilla {
+namespace ipc {
+
+FileDescriptor::FileDescriptor() = default;
+
+FileDescriptor::FileDescriptor(const FileDescriptor& aOther)
+ : mHandle(Clone(aOther.mHandle.get())) {}
+
+FileDescriptor::FileDescriptor(FileDescriptor&& aOther)
+ : mHandle(std::move(aOther.mHandle)) {}
+
+FileDescriptor::FileDescriptor(PlatformHandleType aHandle)
+ : mHandle(Clone(aHandle)) {}
+
+FileDescriptor::FileDescriptor(UniquePlatformHandle&& aHandle)
+ : mHandle(std::move(aHandle)) {}
+
+FileDescriptor::~FileDescriptor() = default;
+
+FileDescriptor& FileDescriptor::operator=(const FileDescriptor& aOther) {
+ if (this != &aOther) {
+ mHandle = Clone(aOther.mHandle.get());
+ }
+ return *this;
+}
+
+FileDescriptor& FileDescriptor::operator=(FileDescriptor&& aOther) {
+ if (this != &aOther) {
+ mHandle = std::move(aOther.mHandle);
+ }
+ return *this;
+}
+
+bool FileDescriptor::IsValid() const { return mHandle != nullptr; }
+
+FileDescriptor::UniquePlatformHandle FileDescriptor::ClonePlatformHandle()
+ const {
+ return Clone(mHandle.get());
+}
+
+FileDescriptor::UniquePlatformHandle FileDescriptor::TakePlatformHandle() {
+ return UniquePlatformHandle(mHandle.release());
+}
+
+bool FileDescriptor::operator==(const FileDescriptor& aOther) const {
+ return mHandle == aOther.mHandle;
+}
+
+// static
+FileDescriptor::UniquePlatformHandle FileDescriptor::Clone(
+ PlatformHandleType aHandle) {
+ FileDescriptor::PlatformHandleType newHandle;
+
+#ifdef XP_WIN
+ if (aHandle == INVALID_HANDLE_VALUE || aHandle == nullptr) {
+ return UniqueFileHandle();
+ }
+ if (::DuplicateHandle(GetCurrentProcess(), aHandle, GetCurrentProcess(),
+ &newHandle, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
+ return UniqueFileHandle(newHandle);
+ }
+#else // XP_WIN
+ if (aHandle < 0) {
+ return UniqueFileHandle();
+ }
+ newHandle = dup(aHandle);
+ if (newHandle >= 0) {
+ return UniqueFileHandle(newHandle);
+ }
+#endif
+ NS_WARNING("Failed to duplicate file handle for current process!");
+ return UniqueFileHandle();
+}
+
+void IPDLParamTraits<FileDescriptor>::Write(IPC::MessageWriter* aWriter,
+ IProtocol* aActor,
+ const FileDescriptor& aParam) {
+ WriteIPDLParam(aWriter, aActor, aParam.ClonePlatformHandle());
+}
+
+bool IPDLParamTraits<FileDescriptor>::Read(IPC::MessageReader* aReader,
+ IProtocol* aActor,
+ FileDescriptor* aResult) {
+ UniqueFileHandle handle;
+ if (!ReadIPDLParam(aReader, aActor, &handle)) {
+ return false;
+ }
+
+ *aResult = FileDescriptor(std::move(handle));
+ if (!aResult->IsValid()) {
+ printf_stderr("IPDL protocol Error: Received an invalid file descriptor\n");
+ }
+ return true;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/FileDescriptor.h b/ipc/glue/FileDescriptor.h
new file mode 100644
index 0000000000..15160624da
--- /dev/null
+++ b/ipc/glue/FileDescriptor.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_FileDescriptor_h
+#define mozilla_ipc_FileDescriptor_h
+
+#include "base/basictypes.h"
+#include "base/process.h"
+#include "mozilla/UniquePtrExtensions.h"
+
+namespace mozilla {
+namespace ipc {
+
+// This class is used by IPDL to share file descriptors across processes. When
+// sending a FileDescriptor, IPDL will transfer a duplicate of the handle into
+// the remote process.
+//
+// To use this class add 'FileDescriptor' as an argument in the IPDL protocol
+// and then pass a file descriptor from C++ to the Send method. The Recv method
+// will receive a FileDescriptor& on which PlatformHandle() can be called to
+// return the platform file handle.
+class FileDescriptor {
+ public:
+ typedef base::ProcessId ProcessId;
+
+ using UniquePlatformHandle = mozilla::UniqueFileHandle;
+ using PlatformHandleType = UniquePlatformHandle::ElementType;
+
+ // This should only ever be created by IPDL.
+ struct IPDLPrivate {};
+
+ // Represents an invalid handle.
+ FileDescriptor();
+
+ // Copy constructor will duplicate a new handle.
+ FileDescriptor(const FileDescriptor& aOther);
+
+ FileDescriptor(FileDescriptor&& aOther);
+
+ // This constructor will duplicate a new handle.
+ // The caller still have to close aHandle.
+ explicit FileDescriptor(PlatformHandleType aHandle);
+
+ explicit FileDescriptor(UniquePlatformHandle&& aHandle);
+
+ ~FileDescriptor();
+
+ FileDescriptor& operator=(const FileDescriptor& aOther);
+
+ FileDescriptor& operator=(FileDescriptor&& aOther);
+
+ // Tests mHandle against a well-known invalid platform-specific file handle
+ // (e.g. -1 on POSIX, INVALID_HANDLE_VALUE on Windows).
+ bool IsValid() const;
+
+ // Returns a duplicated handle, it is caller's responsibility to close the
+ // handle.
+ UniquePlatformHandle ClonePlatformHandle() const;
+
+ // Extracts the underlying handle and makes this object an invalid handle.
+ // (Compare UniquePtr::release.)
+ UniquePlatformHandle TakePlatformHandle();
+
+ // Only used in nsTArray.
+ bool operator==(const FileDescriptor& aOther) const;
+
+ private:
+ static UniqueFileHandle Clone(PlatformHandleType aHandle);
+
+ UniquePlatformHandle mHandle;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_FileDescriptor_h
diff --git a/ipc/glue/FileDescriptorShuffle.cpp b/ipc/glue/FileDescriptorShuffle.cpp
new file mode 100644
index 0000000000..7ce89e1b16
--- /dev/null
+++ b/ipc/glue/FileDescriptorShuffle.cpp
@@ -0,0 +1,113 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "FileDescriptorShuffle.h"
+
+#include "base/eintr_wrapper.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/DebugOnly.h"
+
+#include <algorithm>
+#include <unistd.h>
+#include <fcntl.h>
+
+namespace mozilla {
+namespace ipc {
+
+// F_DUPFD_CLOEXEC is like F_DUPFD (see below) but atomically makes
+// the new fd close-on-exec. This is useful to prevent accidental fd
+// leaks into processes created by plain fork/exec, but IPC uses
+// CloseSuperfluousFds so it's not essential.
+//
+// F_DUPFD_CLOEXEC is in POSIX 2008, but as of 2018 there are still
+// some OSes that don't support it. (Specifically: Solaris 10 doesn't
+// have it, and Android should have kernel support but doesn't define
+// the constant until API 21 (Lollipop). We also don't use this for
+// IPC child launching on Android, so there's no point in hard-coding
+// the definitions like we do for Android in some other cases.)
+#ifdef F_DUPFD_CLOEXEC
+static const int kDupFdCmd = F_DUPFD_CLOEXEC;
+#else
+static const int kDupFdCmd = F_DUPFD;
+#endif
+
+// This implementation ensures that the *ranges* of the source and
+// destination fds don't overlap, which is unnecessary but sufficient
+// to avoid conflicts or identity mappings.
+//
+// In practice, the source fds will usually be large and the
+// destination fds will all be relatively small, so there mostly won't
+// be temporary fds. This approach has the advantage of being simple
+// (and linear-time, but hopefully there aren't enough fds for that to
+// matter).
+bool FileDescriptorShuffle::Init(MappingRef aMapping) {
+ MOZ_ASSERT(mMapping.IsEmpty());
+
+ // Find the maximum destination fd; any source fds not greater than
+ // this will be duplicated.
+ int maxDst = STDERR_FILENO;
+ for (const auto& elem : aMapping) {
+ maxDst = std::max(maxDst, elem.second);
+ }
+ mMaxDst = maxDst;
+
+#ifdef DEBUG
+ // Increase the limit to make sure the F_DUPFD case gets test coverage.
+ if (!aMapping.IsEmpty()) {
+ // Try to find a value that will create a nontrivial partition.
+ int fd0 = aMapping[0].first;
+ int fdn = aMapping.rbegin()->first;
+ maxDst = std::max(maxDst, (fd0 + fdn) / 2);
+ }
+#endif
+
+ for (const auto& elem : aMapping) {
+ int src = elem.first;
+ // F_DUPFD is like dup() but allows placing a lower bound
+ // on the new fd, which is exactly what we want.
+ if (src <= maxDst) {
+ src = fcntl(src, kDupFdCmd, maxDst + 1);
+ if (src < 0) {
+ return false;
+ }
+ mTempFds.AppendElement(src);
+ }
+ MOZ_ASSERT(src > maxDst);
+#ifdef DEBUG
+ // Check for accidentally mapping two different fds to the same
+ // destination. (This is O(n^2) time, but it shouldn't matter.)
+ for (const auto& otherElem : mMapping) {
+ MOZ_ASSERT(elem.second != otherElem.second);
+ }
+#endif
+ mMapping.AppendElement(std::make_pair(src, elem.second));
+ }
+ return true;
+}
+
+bool FileDescriptorShuffle::MapsTo(int aFd) const {
+ // Prune fds that are too large to be a destination, rather than
+ // searching; this should be the common case.
+ if (aFd > mMaxDst) {
+ return false;
+ }
+ for (const auto& elem : mMapping) {
+ if (elem.second == aFd) {
+ return true;
+ }
+ }
+ return false;
+}
+
+FileDescriptorShuffle::~FileDescriptorShuffle() {
+ for (const auto& fd : mTempFds) {
+ mozilla::DebugOnly<int> rv = IGNORE_EINTR(close(fd));
+ MOZ_ASSERT(rv == 0);
+ }
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/FileDescriptorShuffle.h b/ipc/glue/FileDescriptorShuffle.h
new file mode 100644
index 0000000000..4afa8e0474
--- /dev/null
+++ b/ipc/glue/FileDescriptorShuffle.h
@@ -0,0 +1,68 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_FileDescriptorShuffle_h
+#define mozilla_ipc_FileDescriptorShuffle_h
+
+#include "mozilla/Span.h"
+#include "nsTArray.h"
+
+#include <functional>
+#include <utility>
+
+// This class converts a set of file descriptor mapping, which may
+// contain conflicts (like {a->b, b->c} or {a->b, b->a}) into a
+// sequence of dup2() operations that can be performed between fork
+// and exec, or with posix_spawn_file_actions_adddup2. It may create
+// temporary duplicates of fds to use as the source of a dup2; they
+// are closed on destruction.
+//
+// The dup2 sequence is guaranteed to not contain dup2(x, x) for any
+// x; if such an element is present in the input, it will be dup2()ed
+// from a temporary fd to ensure that the close-on-exec bit is cleared.
+//
+// In general, this is *not* guaranteed to minimize the use of
+// temporary fds.
+
+namespace mozilla {
+namespace ipc {
+
+class FileDescriptorShuffle {
+ public:
+ FileDescriptorShuffle() = default;
+ ~FileDescriptorShuffle();
+
+ using MappingRef = mozilla::Span<const std::pair<int, int>>;
+
+ // Translate the given mapping, creating temporary fds as needed.
+ // Can fail (return false) on failure to duplicate fds.
+ bool Init(MappingRef aMapping);
+
+ // Accessor for the dup2() sequence. Do not use the returned value
+ // or the fds contained in it after this object is destroyed.
+ MappingRef Dup2Sequence() const { return mMapping; }
+
+ // Tests whether the given fd is used as a destination in this mapping.
+ // Can be used to close other fds after performing the dup2()s.
+ bool MapsTo(int aFd) const;
+
+ // Forget the information, so that it's destructor will not try to
+ // delete FDs duped by itself.
+ void Forget() { mTempFds.Clear(); }
+
+ private:
+ nsTArray<std::pair<int, int>> mMapping;
+ nsTArray<int> mTempFds;
+ int mMaxDst;
+
+ FileDescriptorShuffle(const FileDescriptorShuffle&) = delete;
+ void operator=(const FileDescriptorShuffle&) = delete;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_FileDescriptorShuffle_h
diff --git a/ipc/glue/FileDescriptorUtils.cpp b/ipc/glue/FileDescriptorUtils.cpp
new file mode 100644
index 0000000000..e4af78e79e
--- /dev/null
+++ b/ipc/glue/FileDescriptorUtils.cpp
@@ -0,0 +1,109 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "FileDescriptorUtils.h"
+
+#include "nsIEventTarget.h"
+
+#include "nsCOMPtr.h"
+#include "nsDebug.h"
+#include "nsNetCID.h"
+#include "nsServiceManagerUtils.h"
+#include "prio.h"
+#include "private/pprio.h"
+
+#include <errno.h>
+#ifdef XP_WIN
+# include <io.h>
+#else
+# include <unistd.h>
+#endif
+
+using mozilla::ipc::CloseFileRunnable;
+
+CloseFileRunnable::CloseFileRunnable(const FileDescriptor& aFileDescriptor)
+ : Runnable("CloseFileRunnable"), mFileDescriptor(aFileDescriptor) {
+ MOZ_ASSERT(aFileDescriptor.IsValid());
+}
+
+CloseFileRunnable::~CloseFileRunnable() {
+ if (mFileDescriptor.IsValid()) {
+ // It's probably safer to take the main thread IO hit here rather than leak
+ // the file descriptor.
+ CloseFile();
+ }
+}
+
+NS_IMPL_ISUPPORTS_INHERITED0(CloseFileRunnable, Runnable)
+
+void CloseFileRunnable::Dispatch() {
+ nsCOMPtr<nsIEventTarget> eventTarget =
+ do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
+ NS_ENSURE_TRUE_VOID(eventTarget);
+
+ nsresult rv = eventTarget->Dispatch(this, NS_DISPATCH_NORMAL);
+ NS_ENSURE_SUCCESS_VOID(rv);
+}
+
+void CloseFileRunnable::CloseFile() {
+ // It's possible for this to happen on the main thread if the dispatch to the
+ // stream service fails so we can't assert the thread on which we're running.
+ mFileDescriptor = FileDescriptor();
+}
+
+NS_IMETHODIMP
+CloseFileRunnable::Run() {
+ MOZ_ASSERT(!NS_IsMainThread());
+
+ CloseFile();
+ return NS_OK;
+}
+
+namespace mozilla {
+namespace ipc {
+
+FILE* FileDescriptorToFILE(const FileDescriptor& aDesc, const char* aOpenMode) {
+ if (!aDesc.IsValid()) {
+ errno = EBADF;
+ return nullptr;
+ }
+ auto handle = aDesc.ClonePlatformHandle();
+#ifdef XP_WIN
+ int fd = _open_osfhandle(static_cast<intptr_t>(handle.get()), 0);
+ if (fd == -1) {
+ return nullptr;
+ }
+ Unused << handle.release();
+#else
+ int fd = handle.release();
+#endif
+ FILE* file = fdopen(fd, aOpenMode);
+ if (!file) {
+ int saved_errno = errno;
+ close(fd);
+ errno = saved_errno;
+ }
+ return file;
+}
+
+FileDescriptor FILEToFileDescriptor(FILE* aStream) {
+ if (!aStream) {
+ errno = EBADF;
+ return FileDescriptor();
+ }
+#ifdef XP_WIN
+ int fd = _fileno(aStream);
+ if (fd == -1) {
+ return FileDescriptor();
+ }
+ return FileDescriptor(reinterpret_cast<HANDLE>(_get_osfhandle(fd)));
+#else
+ return FileDescriptor(fileno(aStream));
+#endif
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/FileDescriptorUtils.h b/ipc/glue/FileDescriptorUtils.h
new file mode 100644
index 0000000000..e8aab0639e
--- /dev/null
+++ b/ipc/glue/FileDescriptorUtils.h
@@ -0,0 +1,53 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_FileDescriptorUtils_h
+#define mozilla_ipc_FileDescriptorUtils_h
+
+#include "mozilla/Attributes.h"
+#include "mozilla/ipc/FileDescriptor.h"
+#include "nsThreadUtils.h"
+#include <stdio.h>
+
+namespace mozilla {
+namespace ipc {
+
+// When Dispatch() is called (from main thread) this class arranges to close the
+// provided FileDescriptor on one of the socket transport service threads (to
+// avoid main thread I/O).
+class CloseFileRunnable final : public Runnable {
+ typedef mozilla::ipc::FileDescriptor FileDescriptor;
+
+ FileDescriptor mFileDescriptor;
+
+ public:
+ explicit CloseFileRunnable(const FileDescriptor& aFileDescriptor);
+
+ NS_DECL_ISUPPORTS_INHERITED
+ NS_DECL_NSIRUNNABLE
+
+ void Dispatch();
+
+ private:
+ ~CloseFileRunnable();
+
+ void CloseFile();
+};
+
+// On failure, FileDescriptorToFILE returns nullptr; on success,
+// returns duplicated FILE*.
+// This is meant for use with FileDescriptors received over IPC.
+FILE* FileDescriptorToFILE(const FileDescriptor& aDesc, const char* aOpenMode);
+
+// FILEToFileDescriptor does not consume the given FILE*; it must be
+// fclose()d as normal, and this does not invalidate the returned
+// FileDescriptor.
+FileDescriptor FILEToFileDescriptor(FILE* aStream);
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_FileDescriptorUtils_h
diff --git a/ipc/glue/ForkServer.cpp b/ipc/glue/ForkServer.cpp
new file mode 100644
index 0000000000..b70fdbf2c0
--- /dev/null
+++ b/ipc/glue/ForkServer.cpp
@@ -0,0 +1,316 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/ForkServer.h"
+
+#include "chrome/common/chrome_switches.h"
+#include "ipc/IPCMessageUtilsSpecializations.h"
+#include "mozilla/BlockingResourceBase.h"
+#include "mozilla/Logging.h"
+#include "mozilla/Omnijar.h"
+#include "mozilla/ipc/FileDescriptor.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+#include "mozilla/ipc/SetProcessTitle.h"
+#include "nsTraceRefcnt.h"
+
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxLaunch.h"
+#endif
+
+#include <algorithm>
+
+namespace mozilla {
+namespace ipc {
+
+LazyLogModule gForkServiceLog("ForkService");
+
+ForkServer::ForkServer() {}
+
+/**
+ * Prepare an environment for running a fork server.
+ */
+void ForkServer::InitProcess(int* aArgc, char*** aArgv) {
+ base::InitForkServerProcess();
+
+ mTcver = MakeUnique<MiniTransceiver>(kClientPipeFd,
+ DataBufferClear::AfterReceiving);
+}
+
+/**
+ * Preload any resources that the forked child processes might need,
+ * and which might change incompatibly or become unavailable by the
+ * time they're started. For example: the omnijar files, or certain
+ * shared libraries.
+ */
+static void ForkServerPreload(int& aArgc, char** aArgv) {
+ Omnijar::ChildProcessInit(aArgc, aArgv);
+}
+
+/**
+ * Start providing the service at the IPC channel.
+ */
+bool ForkServer::HandleMessages() {
+ while (true) {
+ UniquePtr<IPC::Message> msg;
+ if (!mTcver->Recv(msg)) {
+ break;
+ }
+
+ OnMessageReceived(std::move(msg));
+
+ if (mAppProcBuilder) {
+ // New process - child
+ return false;
+ }
+ }
+ // Stop the server
+ return true;
+}
+
+inline void CleanCString(nsCString& str) {
+ char* data;
+ int sz = str.GetMutableData(&data);
+
+ memset(data, ' ', sz);
+}
+
+inline void CleanString(std::string& str) {
+ const char deadbeef[] =
+ "\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef"
+ "\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef\xde\xad\xbe\xef";
+ int pos = 0;
+ size_t sz = str.size();
+ while (sz > 0) {
+ int toclean = std::min(sz, sizeof(deadbeef) - 1);
+ str.replace(pos, toclean, deadbeef);
+ sz -= toclean;
+ pos += toclean;
+ }
+}
+
+inline void PrepareArguments(std::vector<std::string>& aArgv,
+ nsTArray<nsCString>& aArgvArray) {
+ for (auto& elt : aArgvArray) {
+ aArgv.push_back(elt.get());
+ CleanCString(elt);
+ }
+}
+
+// Prepare aOptions->env_map
+inline void PrepareEnv(base::LaunchOptions* aOptions,
+ nsTArray<EnvVar>& aEnvMap) {
+ for (auto& elt : aEnvMap) {
+ nsCString& var = std::get<0>(elt);
+ nsCString& val = std::get<1>(elt);
+ aOptions->env_map[var.get()] = val.get();
+ CleanCString(var);
+ CleanCString(val);
+ }
+}
+
+// Prepare aOptions->fds_to_remap
+inline void PrepareFdsRemap(base::LaunchOptions* aOptions,
+ nsTArray<FdMapping>& aFdsRemap) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("fds mapping:"));
+ for (auto& elt : aFdsRemap) {
+ // FDs are duplicated here.
+ int fd = std::get<0>(elt).ClonePlatformHandle().release();
+ std::pair<int, int> fdmap(fd, std::get<1>(elt));
+ aOptions->fds_to_remap.push_back(fdmap);
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("\t%d => %d", fdmap.first, fdmap.second));
+ }
+}
+
+template <class P>
+static void ReadParamInfallible(IPC::MessageReader* aReader, P* aResult,
+ const char* aCrashMessage) {
+ if (!IPC::ReadParam(aReader, aResult)) {
+ MOZ_CRASH_UNSAFE(aCrashMessage);
+ }
+}
+
+/**
+ * Parse a Message to get a list of arguments and fill a LaunchOptions.
+ */
+inline bool ParseForkNewSubprocess(IPC::Message& aMsg,
+ std::vector<std::string>& aArgv,
+ base::LaunchOptions* aOptions) {
+ if (aMsg.type() != Msg_ForkNewSubprocess__ID) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("unknown message type %d\n", aMsg.type()));
+ return false;
+ }
+
+ IPC::MessageReader reader(aMsg);
+ nsTArray<nsCString> argv_array;
+ nsTArray<EnvVar> env_map;
+ nsTArray<FdMapping> fds_remap;
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ ReadParamInfallible(&reader, &aOptions->fork_flags,
+ "Error deserializing 'int'");
+ ReadParamInfallible(&reader, &aOptions->sandbox_chroot,
+ "Error deserializing 'bool'");
+#endif
+ ReadParamInfallible(&reader, &argv_array,
+ "Error deserializing 'nsCString[]'");
+ ReadParamInfallible(&reader, &env_map, "Error deserializing 'EnvVar[]'");
+ ReadParamInfallible(&reader, &fds_remap, "Error deserializing 'FdMapping[]'");
+ reader.EndRead();
+
+ PrepareArguments(aArgv, argv_array);
+ PrepareEnv(aOptions, env_map);
+ PrepareFdsRemap(aOptions, fds_remap);
+
+ return true;
+}
+
+inline void SanitizeBuffers(IPC::Message& aMsg, std::vector<std::string>& aArgv,
+ base::LaunchOptions& aOptions) {
+ // Clean all buffers in the message to make sure content processes
+ // not peeking others.
+ auto& blist = aMsg.Buffers();
+ for (auto itr = blist.Iter(); !itr.Done();
+ itr.Advance(blist, itr.RemainingInSegment())) {
+ memset(itr.Data(), 0, itr.RemainingInSegment());
+ }
+
+ // clean all data string made from the message.
+ for (auto& var : aOptions.env_map) {
+ // Do it anyway since it is not going to be used anymore.
+ CleanString(*const_cast<std::string*>(&var.first));
+ CleanString(var.second);
+ }
+ for (auto& arg : aArgv) {
+ CleanString(arg);
+ }
+}
+
+/**
+ * Extract parameters from the |Message| to create a
+ * |base::AppProcessBuilder| as |mAppProcBuilder|.
+ *
+ * It will return in both the fork server process and the new content
+ * process. |mAppProcBuilder| is null for the fork server.
+ */
+void ForkServer::OnMessageReceived(UniquePtr<IPC::Message> message) {
+ std::vector<std::string> argv;
+ base::LaunchOptions options;
+ if (!ParseForkNewSubprocess(*message, argv, &options)) {
+ return;
+ }
+
+ base::ProcessHandle child_pid = -1;
+ mAppProcBuilder = MakeUnique<base::AppProcessBuilder>();
+ if (!mAppProcBuilder->ForkProcess(argv, std::move(options), &child_pid)) {
+ MOZ_CRASH("fail to fork");
+ }
+ MOZ_ASSERT(child_pid >= 0);
+
+ if (child_pid == 0) {
+ // Content process
+ return;
+ }
+
+ // Fork server process
+
+ mAppProcBuilder = nullptr;
+
+ IPC::Message reply(MSG_ROUTING_CONTROL, Reply_ForkNewSubprocess__ID);
+ IPC::MessageWriter writer(reply);
+ WriteIPDLParam(&writer, nullptr, child_pid);
+ mTcver->SendInfallible(reply, "failed to send a reply message");
+
+ // Without this, the content processes that is forked later are
+ // able to read the content of buffers even the buffers have been
+ // released.
+ SanitizeBuffers(*message, argv, options);
+}
+
+/**
+ * Setup and run a fork server at the main thread.
+ *
+ * This function returns for two reasons:
+ * - the fork server is stopped normally, or
+ * - a new process is forked from the fork server and this function
+ * returned in the child, the new process.
+ *
+ * For the later case, aArgc and aArgv are modified to pass the
+ * arguments from the chrome process.
+ */
+bool ForkServer::RunForkServer(int* aArgc, char*** aArgv) {
+#ifdef DEBUG
+ if (getenv("MOZ_FORKSERVER_WAIT_GDB")) {
+ printf(
+ "Waiting for 30 seconds."
+ " Attach the fork server with gdb %s %d\n",
+ (*aArgv)[0], base::GetCurrentProcId());
+ sleep(30);
+ }
+ bool sleep_newproc = !!getenv("MOZ_FORKSERVER_WAIT_GDB_NEWPROC");
+#endif
+
+ SetProcessTitleInit(*aArgv);
+
+ // Do this before NS_LogInit() to avoid log files taking lower
+ // FDs.
+ ForkServer forkserver;
+ forkserver.InitProcess(aArgc, aArgv);
+
+ XRE_SetProcessType("forkserver");
+ NS_LogInit();
+ mozilla::LogModule::Init(0, nullptr);
+ ForkServerPreload(*aArgc, *aArgv);
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("Start a fork server"));
+ {
+ DebugOnly<base::ProcessHandle> forkserver_pid = base::GetCurrentProcId();
+ if (forkserver.HandleMessages()) {
+ // In the fork server process
+ // The server has stopped.
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("Terminate the fork server"));
+ Omnijar::CleanUp();
+ NS_LogTerm();
+ return true;
+ }
+ // Now, we are running in a content process just forked from
+ // the fork server process.
+ MOZ_ASSERT(base::GetCurrentProcId() != forkserver_pid);
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose, ("Fork a new content process"));
+ }
+#ifdef DEBUG
+ if (sleep_newproc) {
+ printf(
+ "Waiting for 30 seconds."
+ " Attach the new process with gdb %s %d\n",
+ (*aArgv)[0], base::GetCurrentProcId());
+ sleep(30);
+ }
+#endif
+ NS_LogTerm();
+
+ MOZ_ASSERT(forkserver.mAppProcBuilder);
+ // |messageloop| has been destroyed. So, we can intialized the
+ // process safely. Message loops may allocates some file
+ // descriptors. If it is destroyed later, it may mess up this
+ // content process by closing wrong file descriptors.
+ forkserver.mAppProcBuilder->InitAppProcess(aArgc, aArgv);
+ forkserver.mAppProcBuilder.reset();
+
+ // Open log files again with right names and the new PID.
+ nsTraceRefcnt::ResetLogFiles((*aArgv)[*aArgc - 1]);
+
+ return false;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ForkServer.h b/ipc/glue/ForkServer.h
new file mode 100644
index 0000000000..ba4ed9d44e
--- /dev/null
+++ b/ipc/glue/ForkServer.h
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set ts=8 sts=4 et sw=4 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef __FORKSERVER_H_
+#define __FORKSERVER_H_
+
+#include "mozilla/UniquePtr.h"
+#include "base/process_util.h"
+#include "mozilla/ipc/MiniTransceiver.h"
+
+namespace mozilla {
+namespace ipc {
+
+class ForkServer {
+ public:
+ // NOTE: This can re-use the same ID as the initial IPC::Channel, as the
+ // initial IPC::Channel will not be used by the fork server.
+ static constexpr int kClientPipeFd = 3;
+
+ ForkServer();
+ ~ForkServer(){};
+
+ void InitProcess(int* aArgc, char*** aArgv);
+ bool HandleMessages();
+
+ // Called when a message is received.
+ void OnMessageReceived(UniquePtr<IPC::Message> message);
+
+ static bool RunForkServer(int* aArgc, char*** aArgv);
+
+ private:
+ UniquePtr<MiniTransceiver> mTcver;
+ UniquePtr<base::AppProcessBuilder> mAppProcBuilder;
+};
+
+enum {
+ Msg_ForkNewSubprocess__ID = 0x7f0, // a random picked number
+ Reply_ForkNewSubprocess__ID,
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // __FORKSERVER_H_
diff --git a/ipc/glue/ForkServiceChild.cpp b/ipc/glue/ForkServiceChild.cpp
new file mode 100644
index 0000000000..65560dfaea
--- /dev/null
+++ b/ipc/glue/ForkServiceChild.cpp
@@ -0,0 +1,193 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "ForkServiceChild.h"
+#include "ForkServer.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "mozilla/Logging.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+#include "mozilla/StaticPrefs_dom.h"
+#include "mozilla/Services.h"
+#include "ipc/IPCMessageUtilsSpecializations.h"
+#include "nsIObserverService.h"
+
+#include <unistd.h>
+#include <fcntl.h>
+
+namespace mozilla {
+namespace ipc {
+
+extern LazyLogModule gForkServiceLog;
+
+mozilla::UniquePtr<ForkServiceChild> ForkServiceChild::sForkServiceChild;
+
+static bool ConfigurePipeFd(int aFd) {
+ int flags = fcntl(aFd, F_GETFD, 0);
+ return flags != -1 && fcntl(aFd, F_SETFD, flags | FD_CLOEXEC) != -1;
+}
+
+void ForkServiceChild::StartForkServer() {
+ // Create the socket to use for communication, and mark both ends as
+ // FD_CLOEXEC.
+ int fds[2];
+ if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) < 0) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Error,
+ ("failed to create fork server socket"));
+ return;
+ }
+ UniqueFileHandle server(fds[0]);
+ UniqueFileHandle client(fds[1]);
+
+ if (!ConfigurePipeFd(server.get()) || !ConfigurePipeFd(client.get())) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Error,
+ ("failed to configure fork server socket"));
+ return;
+ }
+
+ GeckoChildProcessHost* subprocess =
+ new GeckoChildProcessHost(GeckoProcessType_ForkServer, false);
+ subprocess->AddFdToRemap(client.get(), ForkServer::kClientPipeFd);
+ if (!subprocess->LaunchAndWaitForProcessHandle(std::vector<std::string>{})) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Error, ("failed to launch fork server"));
+ return;
+ }
+
+ sForkServiceChild =
+ mozilla::MakeUnique<ForkServiceChild>(server.release(), subprocess);
+}
+
+void ForkServiceChild::StopForkServer() { sForkServiceChild = nullptr; }
+
+ForkServiceChild::ForkServiceChild(int aFd, GeckoChildProcessHost* aProcess)
+ : mFailed(false), mProcess(aProcess) {
+ mTcver = MakeUnique<MiniTransceiver>(aFd);
+}
+
+ForkServiceChild::~ForkServiceChild() {
+ mProcess->Destroy();
+ close(mTcver->GetFD());
+}
+
+Result<Ok, LaunchError> ForkServiceChild::SendForkNewSubprocess(
+ const Args& aArgs, pid_t* aPid) {
+ mRecvPid = -1;
+ IPC::Message msg(MSG_ROUTING_CONTROL, Msg_ForkNewSubprocess__ID);
+
+ IPC::MessageWriter writer(msg);
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ WriteIPDLParam(&writer, nullptr, aArgs.mForkFlags);
+ WriteIPDLParam(&writer, nullptr, aArgs.mChroot);
+#endif
+ WriteIPDLParam(&writer, nullptr, aArgs.mArgv);
+ WriteIPDLParam(&writer, nullptr, aArgs.mEnv);
+ WriteIPDLParam(&writer, nullptr, aArgs.mFdsRemap);
+ if (!mTcver->Send(msg)) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("the pipe to the fork server is closed or having errors"));
+ OnError();
+ return Err(LaunchError("FSC::SFNS::Send"));
+ }
+
+ UniquePtr<IPC::Message> reply;
+ if (!mTcver->Recv(reply)) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("the pipe to the fork server is closed or having errors"));
+ OnError();
+ return Err(LaunchError("FSC::SFNS::Recv"));
+ }
+ OnMessageReceived(std::move(reply));
+
+ MOZ_ASSERT(mRecvPid != -1);
+ *aPid = mRecvPid;
+ return Ok();
+}
+
+void ForkServiceChild::OnMessageReceived(UniquePtr<IPC::Message> message) {
+ if (message->type() != Reply_ForkNewSubprocess__ID) {
+ MOZ_LOG(gForkServiceLog, LogLevel::Verbose,
+ ("unknown reply type %d", message->type()));
+ return;
+ }
+ IPC::MessageReader reader(*message);
+
+ if (!ReadIPDLParam(&reader, nullptr, &mRecvPid)) {
+ MOZ_CRASH("Error deserializing 'pid_t'");
+ }
+ reader.EndRead();
+}
+
+void ForkServiceChild::OnError() {
+ mFailed = true;
+ ForkServerLauncher::RestartForkServer();
+}
+
+NS_IMPL_ISUPPORTS(ForkServerLauncher, nsIObserver)
+
+bool ForkServerLauncher::mHaveStartedClient = false;
+StaticRefPtr<ForkServerLauncher> ForkServerLauncher::mSingleton;
+
+ForkServerLauncher::ForkServerLauncher() {}
+
+ForkServerLauncher::~ForkServerLauncher() {}
+
+already_AddRefed<ForkServerLauncher> ForkServerLauncher::Create() {
+ if (mSingleton == nullptr) {
+ mSingleton = new ForkServerLauncher();
+ }
+ RefPtr<ForkServerLauncher> launcher = mSingleton;
+ return launcher.forget();
+}
+
+NS_IMETHODIMP
+ForkServerLauncher::Observe(nsISupports* aSubject, const char* aTopic,
+ const char16_t* aData) {
+ if (strcmp(aTopic, NS_XPCOM_STARTUP_CATEGORY) == 0) {
+ nsCOMPtr<nsIObserverService> obsSvc =
+ mozilla::services::GetObserverService();
+ MOZ_ASSERT(obsSvc != nullptr);
+ // preferences are not available until final-ui-startup
+ obsSvc->AddObserver(this, "final-ui-startup", false);
+ } else if (!mHaveStartedClient && strcmp(aTopic, "final-ui-startup") == 0) {
+ if (StaticPrefs::dom_ipc_forkserver_enable_AtStartup()) {
+ mHaveStartedClient = true;
+ ForkServiceChild::StartForkServer();
+
+ nsCOMPtr<nsIObserverService> obsSvc =
+ mozilla::services::GetObserverService();
+ MOZ_ASSERT(obsSvc != nullptr);
+ obsSvc->AddObserver(this, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
+ } else {
+ mSingleton = nullptr;
+ }
+ }
+
+ if (strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0) {
+ if (mHaveStartedClient) {
+ mHaveStartedClient = false;
+ ForkServiceChild::StopForkServer();
+ }
+
+ // To make leak checker happy!
+ mSingleton = nullptr;
+ }
+ return NS_OK;
+}
+
+void ForkServerLauncher::RestartForkServer() {
+ // Restart fork server
+ NS_SUCCEEDED(NS_DispatchToMainThreadQueue(
+ NS_NewRunnableFunction("OnForkServerError",
+ [] {
+ if (mSingleton) {
+ ForkServiceChild::StopForkServer();
+ ForkServiceChild::StartForkServer();
+ }
+ }),
+ EventQueuePriority::Idle));
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ForkServiceChild.h b/ipc/glue/ForkServiceChild.h
new file mode 100644
index 0000000000..73d090d556
--- /dev/null
+++ b/ipc/glue/ForkServiceChild.h
@@ -0,0 +1,113 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef __FORKSERVICE_CHILD_H_
+#define __FORKSERVICE_CHILD_H_
+
+#include "base/process_util.h"
+#include "nsIObserver.h"
+#include "nsString.h"
+#include "mozilla/ipc/MiniTransceiver.h"
+#include "mozilla/ipc/LaunchError.h"
+#include "mozilla/Result.h"
+
+#include <sys/types.h>
+#include <poll.h>
+
+namespace mozilla {
+namespace ipc {
+
+class GeckoChildProcessHost;
+
+/**
+ * This is the interface to the fork server.
+ *
+ * When the chrome process calls |ForkServiceChild| to create a new
+ * process, this class send a message to the fork server through a
+ * pipe and get the PID of the new process from the reply.
+ */
+class ForkServiceChild {
+ public:
+ ForkServiceChild(int aFd, GeckoChildProcessHost* aProcess);
+ virtual ~ForkServiceChild();
+
+ struct Args {
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ int mForkFlags = 0;
+ bool mChroot = false;
+#endif
+ nsTArray<nsCString> mArgv;
+ nsTArray<EnvVar> mEnv;
+ nsTArray<FdMapping> mFdsRemap;
+ };
+
+ /**
+ * Ask the fork server to create a new process with given parameters.
+ *
+ * The fork server uses |base::LaunchApp()| to create a new
+ * content process with the following parameters.
+ *
+ * \param aArgv assigns |argv| of the content process.
+ * \param aEnvMap sets |LaunchOptions::env_map|.
+ * \param aFdsRemap sets |LaunchOptions::fd_to_remap|.
+ * \param aPid returns the PID of the content process created.
+ * \return true if success.
+ */
+ Result<Ok, LaunchError> SendForkNewSubprocess(const Args& aArgs, pid_t* aPid);
+
+ /**
+ * Create a fork server process and the singleton of this class.
+ *
+ * This function uses |GeckoChildProcessHost| to launch the fork
+ * server, getting the fd of a pipe/socket to the fork server from
+ * it's |IPC::Channel|.
+ */
+ static void StartForkServer();
+ static void StopForkServer();
+ /**
+ * Return the singleton.
+ */
+ static ForkServiceChild* Get() {
+ auto child = sForkServiceChild.get();
+ return child == nullptr || child->mFailed ? nullptr : child;
+ }
+
+ private:
+ // Called when a message is received.
+ void OnMessageReceived(UniquePtr<IPC::Message> message);
+ void OnError();
+
+ UniquePtr<MiniTransceiver> mTcver;
+ static UniquePtr<ForkServiceChild> sForkServiceChild;
+ pid_t mRecvPid;
+ bool mFailed; // The forkserver has crashed or disconnected.
+ GeckoChildProcessHost* mProcess;
+};
+
+/**
+ * Start a fork server at |xpcom-startup| from the chrome process.
+ */
+class ForkServerLauncher : public nsIObserver {
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+
+ ForkServerLauncher();
+ static already_AddRefed<ForkServerLauncher> Create();
+
+ private:
+ friend class ForkServiceChild;
+ virtual ~ForkServerLauncher();
+
+ static void RestartForkServer();
+
+ static bool mHaveStartedClient;
+ static StaticRefPtr<ForkServerLauncher> mSingleton;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif /* __FORKSERVICE_CHILD_H_ */
diff --git a/ipc/glue/GeckoChildProcessHost.cpp b/ipc/glue/GeckoChildProcessHost.cpp
new file mode 100644
index 0000000000..bde3a9a389
--- /dev/null
+++ b/ipc/glue/GeckoChildProcessHost.cpp
@@ -0,0 +1,1801 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "GeckoChildProcessHost.h"
+
+#include "base/command_line.h"
+#include "base/process.h"
+#include "base/process_util.h"
+#include "base/string_util.h"
+#include "base/task.h"
+#include "chrome/common/chrome_switches.h"
+#include "chrome/common/process_watcher.h"
+#ifdef MOZ_WIDGET_COCOA
+# include <bsm/libbsm.h>
+# include <mach/mach_traps.h>
+# include <servers/bootstrap.h>
+# include "SharedMemoryBasic.h"
+# include "base/rand_util.h"
+# include "chrome/common/mach_ipc_mac.h"
+# include "mozilla/StaticPrefs_media.h"
+# include "nsILocalFileMac.h"
+#endif
+
+#include "GeckoProfiler.h"
+#include "MainThreadUtils.h"
+#include "mozilla/Preferences.h"
+#include "mozilla/Sprintf.h"
+#include "nsXPCOMPrivate.h"
+#include "prenv.h"
+#include "prerror.h"
+
+#if defined(MOZ_SANDBOX)
+# include "mozilla/SandboxSettings.h"
+# include "nsAppDirectoryServiceDefs.h"
+#endif
+
+#include <sys/stat.h>
+
+#include "ProtocolUtils.h"
+#include "mozilla/LinkedList.h"
+#include "mozilla/Logging.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/GeckoArgs.h"
+#include "mozilla/Omnijar.h"
+#include "mozilla/RDDProcessHost.h"
+#include "mozilla/Services.h"
+#include "mozilla/SharedThreadPool.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/TaskQueue.h"
+#include "mozilla/Telemetry.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/ipc/BrowserProcessSubThread.h"
+#include "mozilla/ipc/EnvironmentMap.h"
+#include "mozilla/ipc/NodeController.h"
+#include "mozilla/net/SocketProcessHost.h"
+#include "nsDirectoryService.h"
+#include "nsDirectoryServiceDefs.h"
+#include "nsExceptionHandler.h"
+#include "nsIFile.h"
+#include "nsIObserverService.h"
+#include "nsPrintfCString.h"
+
+#ifdef XP_WIN
+# include <stdlib.h>
+
+# include "nsIWinTaskbar.h"
+# define NS_TASKBAR_CONTRACTID "@mozilla.org/windows-taskbar;1"
+
+# if defined(MOZ_SANDBOX)
+# include "WinUtils.h"
+# include "mozilla/Preferences.h"
+# include "mozilla/sandboxing/sandboxLogging.h"
+# if defined(_ARM64_)
+# include "mozilla/remoteSandboxBroker.h"
+# endif
+# endif
+
+# include "mozilla/NativeNt.h"
+# include "mozilla/CacheNtDllThunk.h"
+#endif
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxLaunch.h"
+#endif
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+# include "GMPProcessParent.h"
+# include "nsMacUtilsImpl.h"
+#endif
+
+#include "mozilla/ipc/UtilityProcessHost.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+
+#include "nsClassHashtable.h"
+#include "nsHashKeys.h"
+#include "nsNativeCharsetUtils.h"
+#include "nsTArray.h"
+#include "nscore.h" // for NS_FREE_PERMANENT_DATA
+#include "nsIThread.h"
+
+using mozilla::MonitorAutoLock;
+using mozilla::Preferences;
+using mozilla::StaticMutexAutoLock;
+
+#ifdef MOZ_WIDGET_ANDROID
+# include "AndroidBridge.h"
+# include "mozilla/java/GeckoProcessManagerWrappers.h"
+# include "mozilla/java/GeckoProcessTypeWrappers.h"
+# include "mozilla/java/GeckoResultWrappers.h"
+# include "mozilla/jni/Refs.h"
+# include "mozilla/jni/Utils.h"
+#endif
+
+#ifdef MOZ_ENABLE_FORKSERVER
+# include "mozilla/ipc/ForkServiceChild.h"
+#endif
+
+static bool ShouldHaveDirectoryService() {
+ return GeckoProcessType_Default == XRE_GetProcessType();
+}
+
+namespace mozilla {
+namespace ipc {
+
+struct LaunchResults {
+ base::ProcessHandle mHandle = 0;
+#ifdef XP_MACOSX
+ task_t mChildTask = MACH_PORT_NULL;
+#endif
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ RefPtr<AbstractSandboxBroker> mSandboxBroker;
+#endif
+};
+typedef mozilla::MozPromise<LaunchResults, LaunchError, true>
+ ProcessLaunchPromise;
+
+static Atomic<int32_t> gChildCounter;
+
+static inline nsISerialEventTarget* IOThread() {
+ return XRE_GetIOMessageLoop()->SerialEventTarget();
+}
+
+class BaseProcessLauncher {
+ public:
+ BaseProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : mProcessType(aHost->mProcessType),
+ mLaunchOptions(std::move(aHost->mLaunchOptions)),
+ mExtraOpts(std::move(aExtraOpts)),
+#ifdef XP_WIN
+ mGroupId(aHost->mGroupId),
+#endif
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ mAllowedFilesRead(aHost->mAllowedFilesRead),
+ mSandboxLevel(aHost->mSandboxLevel),
+ mSandbox(aHost->mSandbox),
+ mIsFileContent(aHost->mIsFileContent),
+ mEnableSandboxLogging(aHost->mEnableSandboxLogging),
+#endif
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ mDisableOSActivityMode(aHost->mDisableOSActivityMode),
+#endif
+ mTmpDirName(aHost->mTmpDirName),
+ mChildId(++gChildCounter) {
+ SprintfLiteral(mPidString, "%" PRIPID, base::GetCurrentProcId());
+ aHost->mInitialChannelId.ToProvidedString(mInitialChannelIdString);
+
+ // Compute the serial event target we'll use for launching.
+ nsCOMPtr<nsIEventTarget> threadOrPool = GetIPCLauncher();
+ mLaunchThread =
+ TaskQueue::Create(threadOrPool.forget(), "BaseProcessLauncher");
+
+ if (ShouldHaveDirectoryService()) {
+ // "Current process directory" means the app dir, not the current
+ // working dir or similar.
+ mozilla::Unused
+ << nsDirectoryService::gService->GetCurrentProcessDirectory(
+ getter_AddRefs(mAppDir));
+ }
+ }
+
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(BaseProcessLauncher);
+
+#ifdef ALLOW_GECKO_CHILD_PROCESS_ARCH
+ void SetLaunchArchitecture(uint32_t aLaunchArch) {
+ mLaunchArch = aLaunchArch;
+ }
+#endif
+
+ RefPtr<ProcessLaunchPromise> Launch(GeckoChildProcessHost*);
+
+ protected:
+ virtual ~BaseProcessLauncher() = default;
+
+ RefPtr<ProcessLaunchPromise> PerformAsyncLaunch();
+ RefPtr<ProcessLaunchPromise> FinishLaunch();
+
+ // Overrideable hooks. If superclass behavior is invoked, it's always at the
+ // top of the override.
+ virtual Result<Ok, LaunchError> DoSetup();
+ virtual RefPtr<ProcessHandlePromise> DoLaunch() = 0;
+ virtual Result<Ok, LaunchError> DoFinishLaunch();
+
+ void MapChildLogging();
+
+ static BinPathType GetPathToBinary(FilePath&, GeckoProcessType);
+
+ void GetChildLogName(const char* origLogName, nsACString& buffer);
+
+ const char* ChildProcessType() {
+ return XRE_GeckoProcessTypeToString(mProcessType);
+ }
+
+ nsCOMPtr<nsISerialEventTarget> mLaunchThread;
+ GeckoProcessType mProcessType;
+ UniquePtr<base::LaunchOptions> mLaunchOptions;
+#ifdef ALLOW_GECKO_CHILD_PROCESS_ARCH
+ uint32_t mLaunchArch = base::PROCESS_ARCH_INVALID;
+#endif
+ std::vector<std::string> mExtraOpts;
+#ifdef XP_WIN
+ nsString mGroupId;
+#endif
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ std::vector<std::wstring> mAllowedFilesRead;
+ int32_t mSandboxLevel;
+ SandboxingKind mSandbox;
+ bool mIsFileContent;
+ bool mEnableSandboxLogging;
+#endif
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ // Controls whether or not the process will be launched with
+ // environment variable OS_ACTIVITY_MODE set to "disabled".
+ bool mDisableOSActivityMode;
+#endif
+ nsCString mTmpDirName;
+ LaunchResults mResults = LaunchResults();
+ int32_t mChildId;
+ TimeStamp mStartTimeStamp = TimeStamp::Now();
+ char mPidString[32];
+ char mInitialChannelIdString[NSID_LENGTH];
+
+ // Set during launch.
+ IPC::Channel::ChannelHandle mClientChannelHandle;
+ nsCOMPtr<nsIFile> mAppDir;
+};
+
+#ifdef XP_WIN
+class WindowsProcessLauncher : public BaseProcessLauncher {
+ public:
+ WindowsProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : BaseProcessLauncher(aHost, std::move(aExtraOpts)),
+ mCachedNtdllThunk(GetCachedNtDllThunk()) {}
+
+ protected:
+ virtual Result<Ok, LaunchError> DoSetup() override;
+ virtual RefPtr<ProcessHandlePromise> DoLaunch() override;
+ virtual Result<Ok, LaunchError> DoFinishLaunch() override;
+
+ mozilla::Maybe<CommandLine> mCmdLine;
+ bool mUseSandbox = false;
+
+ const Buffer<IMAGE_THUNK_DATA>* mCachedNtdllThunk;
+};
+typedef WindowsProcessLauncher ProcessLauncher;
+#endif // XP_WIN
+
+#ifdef XP_UNIX
+class PosixProcessLauncher : public BaseProcessLauncher {
+ public:
+ PosixProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : BaseProcessLauncher(aHost, std::move(aExtraOpts)),
+ mProfileDir(aHost->mProfileDir),
+ mChannelDstFd(IPC::Channel::GetClientChannelHandle()) {}
+
+ protected:
+ virtual Result<Ok, LaunchError> DoSetup() override;
+ virtual RefPtr<ProcessHandlePromise> DoLaunch() override;
+
+ nsCOMPtr<nsIFile> mProfileDir;
+
+ std::vector<std::string> mChildArgv;
+ int mChannelDstFd;
+};
+
+# if defined(XP_MACOSX)
+class MacProcessLauncher : public PosixProcessLauncher {
+ public:
+ MacProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : PosixProcessLauncher(aHost, std::move(aExtraOpts)),
+ // Put a random number into the channel name, so that
+ // a compromised renderer can't pretend being the child
+ // that's forked off.
+ mMachConnectionName(
+ StringPrintf("org.mozilla.machname.%d",
+ base::RandInt(0, std::numeric_limits<int>::max()))) {
+ MOZ_ASSERT(mMachConnectionName.size() < BOOTSTRAP_MAX_NAME_LEN);
+ }
+
+ protected:
+ virtual Result<Ok, LaunchError> DoFinishLaunch() override;
+
+ std::string mMachConnectionName;
+ // We add a mach port to the command line so the child can communicate its
+ // 'task_t' back to the parent.
+ mozilla::UniqueMachReceiveRight mParentRecvPort;
+
+ friend class PosixProcessLauncher;
+};
+typedef MacProcessLauncher ProcessLauncher;
+# elif defined(MOZ_WIDGET_ANDROID)
+class AndroidProcessLauncher : public PosixProcessLauncher {
+ public:
+ AndroidProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : PosixProcessLauncher(aHost, std::move(aExtraOpts)) {}
+
+ protected:
+ virtual RefPtr<ProcessHandlePromise> DoLaunch() override;
+ RefPtr<ProcessHandlePromise> LaunchAndroidService(
+ const GeckoProcessType aType, const std::vector<std::string>& argv,
+ const base::file_handle_mapping_vector& fds_to_remap);
+};
+typedef AndroidProcessLauncher ProcessLauncher;
+// NB: Technically Android is linux (i.e. XP_LINUX is defined), but we want
+// orthogonal IPC machinery there. Conversely, there are tier-3 non-Linux
+// platforms (BSD and Solaris) where we want the "linux" IPC machinery. So
+// we use MOZ_WIDGET_* to choose the platform backend.
+# elif defined(MOZ_WIDGET_GTK)
+class LinuxProcessLauncher : public PosixProcessLauncher {
+ public:
+ LinuxProcessLauncher(GeckoChildProcessHost* aHost,
+ std::vector<std::string>&& aExtraOpts)
+ : PosixProcessLauncher(aHost, std::move(aExtraOpts)) {}
+
+ protected:
+ virtual Result<Ok, LaunchError> DoSetup() override;
+};
+typedef LinuxProcessLauncher ProcessLauncher;
+# elif
+# error "Unknown platform"
+# endif
+#endif // XP_UNIX
+
+using base::ProcessHandle;
+using mozilla::ipc::BaseProcessLauncher;
+using mozilla::ipc::ProcessLauncher;
+
+mozilla::StaticAutoPtr<mozilla::LinkedList<GeckoChildProcessHost>>
+ GeckoChildProcessHost::sGeckoChildProcessHosts;
+
+mozilla::StaticMutex GeckoChildProcessHost::sMutex;
+
+GeckoChildProcessHost::GeckoChildProcessHost(GeckoProcessType aProcessType,
+ bool aIsFileContent)
+ : mProcessType(aProcessType),
+ mIsFileContent(aIsFileContent),
+ mMonitor("mozilla.ipc.GeckoChildProcessHost.mMonitor"),
+ mLaunchOptions(MakeUnique<base::LaunchOptions>()),
+ mInitialChannelId(nsID::GenerateUUID()),
+ mProcessState(CREATING_CHANNEL),
+#ifdef XP_WIN
+ mGroupId(u"-"),
+#endif
+#if defined(MOZ_SANDBOX) && defined(XP_WIN)
+ mEnableSandboxLogging(false),
+ mSandboxLevel(0),
+#endif
+ mHandleLock("mozilla.ipc.GeckoChildProcessHost.mHandleLock"),
+ mChildProcessHandle(0),
+#if defined(MOZ_WIDGET_COCOA)
+ mChildTask(MACH_PORT_NULL),
+#endif
+#if defined(MOZ_SANDBOX) && defined(XP_MACOSX)
+ mDisableOSActivityMode(false),
+#endif
+ mDestroying(false) {
+ MOZ_COUNT_CTOR(GeckoChildProcessHost);
+ StaticMutexAutoLock lock(sMutex);
+ if (!sGeckoChildProcessHosts) {
+ sGeckoChildProcessHosts = new mozilla::LinkedList<GeckoChildProcessHost>();
+ }
+ sGeckoChildProcessHosts->insertBack(this);
+#if defined(MOZ_SANDBOX) && defined(XP_LINUX)
+ if (aProcessType == GeckoProcessType_Content) {
+# if defined(MOZ_CONTENT_TEMP_DIR)
+ // The content process needs the content temp dir:
+ nsCOMPtr<nsIFile> contentTempDir;
+ nsresult rv = NS_GetSpecialDirectory(NS_APP_CONTENT_PROCESS_TEMP_DIR,
+ getter_AddRefs(contentTempDir));
+ if (NS_SUCCEEDED(rv)) {
+ contentTempDir->GetNativePath(mTmpDirName);
+ }
+# endif
+ } else if (aProcessType == GeckoProcessType_RDD) {
+ // The RDD process makes limited use of EGL. If Mesa's shader
+ // cache is enabled and the directory isn't explicitly set, then
+ // it will try to getpwuid() the user which can cause problems
+ // with sandboxing. Because we shouldn't need shader caching in
+ // this process, we just disable the cache to prevent that.
+ mLaunchOptions->env_map["MESA_GLSL_CACHE_DISABLE"] = "true";
+ mLaunchOptions->env_map["MESA_SHADER_CACHE_DISABLE"] = "true";
+ // In case the nvidia driver is also loaded:
+ mLaunchOptions->env_map["__GL_SHADER_DISK_CACHE"] = "0";
+ }
+#endif
+#if defined(MOZ_ENABLE_FORKSERVER)
+ if (aProcessType != GeckoProcessType_ForkServer && ForkServiceChild::Get()) {
+ mLaunchOptions->use_forkserver = true;
+ }
+#endif
+}
+
+GeckoChildProcessHost::~GeckoChildProcessHost()
+
+{
+ AssertIOThread();
+ MOZ_RELEASE_ASSERT(mDestroying);
+
+ MOZ_COUNT_DTOR(GeckoChildProcessHost);
+
+ {
+ mozilla::AutoWriteLock hLock(mHandleLock);
+#if defined(MOZ_WIDGET_COCOA)
+ if (mChildTask != MACH_PORT_NULL) {
+ mach_port_deallocate(mach_task_self(), mChildTask);
+ }
+#endif
+
+ if (mChildProcessHandle != 0) {
+ ProcessWatcher::EnsureProcessTerminated(
+ mChildProcessHandle
+#ifdef NS_FREE_PERMANENT_DATA
+ // If we're doing leak logging, shutdown can be slow.
+ ,
+ false // don't "force"
+#endif
+ );
+ mChildProcessHandle = 0;
+ }
+ }
+
+#if defined(MOZ_SANDBOX) && defined(XP_WIN)
+ if (mSandboxBroker) {
+ mSandboxBroker->Shutdown();
+ mSandboxBroker = nullptr;
+ }
+#endif
+}
+
+base::ProcessHandle GeckoChildProcessHost::GetChildProcessHandle() {
+ mozilla::AutoReadLock handleLock(mHandleLock);
+ return mChildProcessHandle;
+}
+
+base::ProcessId GeckoChildProcessHost::GetChildProcessId() {
+ mozilla::AutoReadLock handleLock(mHandleLock);
+ if (!mChildProcessHandle) {
+ return 0;
+ }
+ return base::GetProcId(mChildProcessHandle);
+}
+
+#ifdef XP_MACOSX
+task_t GeckoChildProcessHost::GetChildTask() {
+ mozilla::AutoReadLock handleLock(mHandleLock);
+ return mChildTask;
+}
+#endif
+
+void GeckoChildProcessHost::RemoveFromProcessList() {
+ StaticMutexAutoLock lock(sMutex);
+ if (!sGeckoChildProcessHosts) {
+ return;
+ }
+ LinkedListElement<GeckoChildProcessHost>::removeFrom(
+ *sGeckoChildProcessHosts);
+}
+
+void GeckoChildProcessHost::Destroy() {
+ MOZ_RELEASE_ASSERT(!mDestroying);
+ // We can remove from the list before it's really destroyed
+ RemoveFromProcessList();
+ RefPtr<ProcessHandlePromise> whenReady = mHandlePromise;
+
+ if (!whenReady) {
+ // AsyncLaunch not called yet, so dispatch immediately.
+ whenReady = ProcessHandlePromise::CreateAndReject(
+ LaunchError("DestroyEarly"), __func__);
+ }
+
+ using Value = ProcessHandlePromise::ResolveOrRejectValue;
+ mDestroying = true;
+ whenReady->Then(XRE_GetIOMessageLoop()->SerialEventTarget(), __func__,
+ [this](const Value&) { delete this; });
+}
+
+// static
+mozilla::BinPathType BaseProcessLauncher::GetPathToBinary(
+ FilePath& exePath, GeckoProcessType processType) {
+ BinPathType pathType = XRE_GetChildProcBinPathType(processType);
+
+ if (pathType == BinPathType::Self) {
+#if defined(XP_WIN)
+ wchar_t exePathBuf[MAXPATHLEN];
+ if (!::GetModuleFileNameW(nullptr, exePathBuf, MAXPATHLEN)) {
+ MOZ_CRASH("GetModuleFileNameW failed (FIXME)");
+ }
+ exePath = FilePath::FromWStringHack(exePathBuf);
+#else
+ exePath = FilePath(CommandLine::ForCurrentProcess()->argv()[0]);
+#endif
+ return pathType;
+ }
+
+#ifdef MOZ_WIDGET_COCOA
+ // The GMP child process runs via the Media Plugin Helper executable
+ // which is a clone of plugin-container allowing for GMP-specific
+ // codesigning entitlements.
+ nsCString bundleName;
+ std::string executableLeafName;
+ if (processType == GeckoProcessType_GMPlugin &&
+ mozilla::StaticPrefs::media_plugin_helper_process_enabled()) {
+ bundleName = MOZ_EME_PROCESS_BUNDLENAME;
+ executableLeafName = MOZ_EME_PROCESS_NAME_BRANDED;
+ } else {
+ bundleName = MOZ_CHILD_PROCESS_BUNDLENAME;
+ executableLeafName = MOZ_CHILD_PROCESS_NAME;
+ }
+#endif
+
+ if (ShouldHaveDirectoryService()) {
+ MOZ_ASSERT(gGREBinPath);
+#ifdef XP_WIN
+ exePath = FilePath(char16ptr_t(gGREBinPath));
+#elif MOZ_WIDGET_COCOA
+ nsCOMPtr<nsIFile> childProcPath;
+ NS_NewLocalFile(nsDependentString(gGREBinPath), false,
+ getter_AddRefs(childProcPath));
+
+ // We need to use an App Bundle on OS X so that we can hide
+ // the dock icon. See Bug 557225.
+ childProcPath->AppendNative(bundleName);
+ childProcPath->AppendNative("Contents"_ns);
+ childProcPath->AppendNative("MacOS"_ns);
+ nsCString tempCPath;
+ childProcPath->GetNativePath(tempCPath);
+ exePath = FilePath(tempCPath.get());
+#else
+ nsCString path;
+ NS_CopyUnicodeToNative(nsDependentString(gGREBinPath), path);
+ exePath = FilePath(path.get());
+#endif
+ }
+
+ if (exePath.empty()) {
+#ifdef XP_WIN
+ exePath =
+ FilePath::FromWStringHack(CommandLine::ForCurrentProcess()->program());
+#else
+ exePath = FilePath(CommandLine::ForCurrentProcess()->argv()[0]);
+#endif
+ exePath = exePath.DirName();
+ }
+
+#ifdef MOZ_WIDGET_COCOA
+ exePath = exePath.Append(executableLeafName);
+#else
+ exePath = exePath.AppendASCII(MOZ_CHILD_PROCESS_NAME);
+#endif
+
+ return pathType;
+}
+
+#ifdef MOZ_WIDGET_COCOA
+class AutoCFTypeObject {
+ public:
+ explicit AutoCFTypeObject(CFTypeRef object) { mObject = object; }
+ ~AutoCFTypeObject() { ::CFRelease(mObject); }
+
+ private:
+ CFTypeRef mObject;
+};
+#endif
+
+// We start the unique IDs at 1 so that 0 can be used to mean that
+// a component has no unique ID assigned to it.
+uint32_t GeckoChildProcessHost::sNextUniqueID = 1;
+
+/* static */
+uint32_t GeckoChildProcessHost::GetUniqueID() { return sNextUniqueID++; }
+
+/* static */
+void GeckoChildProcessHost::SetEnv(const char* aKey, const char* aValue) {
+ MOZ_ASSERT(mLaunchOptions);
+ mLaunchOptions->env_map[ENVIRONMENT_STRING(aKey)] =
+ ENVIRONMENT_STRING(aValue);
+}
+
+void GeckoChildProcessHost::PrepareLaunch() {
+ if (CrashReporter::GetEnabled()) {
+ CrashReporter::OOPInit();
+ }
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ SandboxLaunch::Configure(mProcessType, mSandbox, mLaunchOptions.get());
+#endif
+
+#ifdef XP_WIN
+
+# if defined(MOZ_SANDBOX)
+ // We need to get the pref here as the process is launched off main thread.
+ if (mProcessType == GeckoProcessType_Content) {
+ // Win32k Lockdown state must be initialized on the main thread.
+ // This is our last chance to do it before it is read on the IPC Launch
+ // thread
+ GetWin32kLockdownState();
+ mSandboxLevel = GetEffectiveContentSandboxLevel();
+ mEnableSandboxLogging =
+ Preferences::GetBool("security.sandbox.logging.enabled");
+
+ // We currently have to whitelist certain paths for tests to work in some
+ // development configurations.
+ nsAutoString readPaths;
+ nsresult rv = Preferences::GetString(
+ "security.sandbox.content.read_path_whitelist", readPaths);
+ if (NS_SUCCEEDED(rv)) {
+ for (const nsAString& readPath : readPaths.Split(',')) {
+ nsString trimmedPath(readPath);
+ trimmedPath.Trim(" ", true, true);
+ std::wstring resolvedPath(trimmedPath.Data());
+ // Check if path ends with '\' as this indicates we want to give read
+ // access to a directory and so it needs a wildcard.
+ if (resolvedPath.back() == L'\\') {
+ resolvedPath.append(L"*");
+ }
+ mAllowedFilesRead.push_back(resolvedPath);
+ }
+ }
+ }
+# endif
+
+# if defined(MOZ_SANDBOX)
+ // For other process types we can't rely on them being launched on main
+ // thread and they may not have access to prefs in the child process, so allow
+ // them to turn on logging via an environment variable.
+ mEnableSandboxLogging =
+ mEnableSandboxLogging || !!PR_GetEnv("MOZ_SANDBOX_LOGGING");
+
+# endif
+#elif defined(XP_MACOSX)
+# if defined(MOZ_SANDBOX)
+ if (ShouldHaveDirectoryService() &&
+ mProcessType != GeckoProcessType_GMPlugin) {
+ mozilla::Unused << NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
+ getter_AddRefs(mProfileDir));
+ }
+# endif
+#endif
+}
+
+#ifdef XP_WIN
+void GeckoChildProcessHost::InitWindowsGroupID() {
+ // On Win7+, pass the application user model to the child, so it can
+ // register with it. This insures windows created by the container
+ // properly group with the parent app on the Win7 taskbar.
+ nsCOMPtr<nsIWinTaskbar> taskbarInfo = do_GetService(NS_TASKBAR_CONTRACTID);
+ if (taskbarInfo) {
+ bool isSupported = false;
+ taskbarInfo->GetAvailable(&isSupported);
+ nsAutoString appId;
+ if (isSupported && NS_SUCCEEDED(taskbarInfo->GetDefaultGroupId(appId))) {
+ MOZ_ASSERT(mGroupId.EqualsLiteral("-"));
+ mGroupId.Assign(appId);
+ }
+ }
+}
+#endif
+
+bool GeckoChildProcessHost::SyncLaunch(std::vector<std::string> aExtraOpts,
+ int aTimeoutMs) {
+ if (!AsyncLaunch(std::move(aExtraOpts))) {
+ return false;
+ }
+ return WaitUntilConnected(aTimeoutMs);
+}
+
+// Note: for most process types, we currently call AsyncLaunch, and therefore
+// the *ProcessLauncher constructor, on the main thread, while the
+// ProcessLauncher methods to actually execute the launch are called on the IO
+// or IPC launcher thread. GMP processes are an exception - the GMP code
+// invokes GeckoChildProcessHost from non-main-threads, and therefore we cannot
+// rely on having access to mainthread-only services (like the directory
+// service) from this code if we're launching that type of process.
+bool GeckoChildProcessHost::AsyncLaunch(std::vector<std::string> aExtraOpts) {
+ PrepareLaunch();
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ if (IsMacSandboxLaunchEnabled() && !AppendMacSandboxParams(aExtraOpts)) {
+ return false;
+ }
+#endif
+
+ RefPtr<BaseProcessLauncher> launcher =
+ new ProcessLauncher(this, std::move(aExtraOpts));
+#ifdef ALLOW_GECKO_CHILD_PROCESS_ARCH
+ launcher->SetLaunchArchitecture(mLaunchArch);
+#endif
+
+ // Note: Destroy() waits on mHandlePromise to delete |this|. As such, we want
+ // to be sure that all of our post-launch processing on |this| happens before
+ // mHandlePromise notifies.
+ MOZ_ASSERT(mHandlePromise == nullptr);
+ mHandlePromise =
+ mozilla::InvokeAsync<GeckoChildProcessHost*>(
+ IOThread(), launcher.get(), __func__, &BaseProcessLauncher::Launch,
+ this)
+ ->Then(
+ IOThread(), __func__,
+ [this](LaunchResults&& aResults) {
+ {
+ {
+ mozilla::AutoWriteLock handleLock(mHandleLock);
+ if (!OpenPrivilegedHandle(base::GetProcId(aResults.mHandle))
+#ifdef XP_WIN
+ // If we failed in opening the process handle, try
+ // harder by duplicating one.
+ && !::DuplicateHandle(
+ ::GetCurrentProcess(), aResults.mHandle,
+ ::GetCurrentProcess(), &mChildProcessHandle,
+ PROCESS_DUP_HANDLE | PROCESS_TERMINATE |
+ PROCESS_QUERY_INFORMATION | PROCESS_VM_READ |
+ SYNCHRONIZE,
+ FALSE, 0)
+#endif // XP_WIN
+ ) {
+ MOZ_CRASH("cannot open handle to child process");
+ }
+ // The original handle is no longer needed; it must
+ // be closed to prevent a resource leak.
+ base::CloseProcessHandle(aResults.mHandle);
+ // FIXME (bug 1720523): define a cross-platform
+ // "safe" invalid value to use in places like this.
+ aResults.mHandle = 0;
+
+#ifdef XP_MACOSX
+ this->mChildTask = aResults.mChildTask;
+#endif
+
+ if (mNodeChannel) {
+ mNodeChannel->SetOtherPid(
+ base::GetProcId(this->mChildProcessHandle));
+#ifdef XP_MACOSX
+ mNodeChannel->SetMachTaskPort(this->mChildTask);
+#endif
+ }
+ }
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ this->mSandboxBroker = std::move(aResults.mSandboxBroker);
+#endif
+
+ MonitorAutoLock lock(mMonitor);
+ // The OnChannel{Connected,Error} may have already advanced
+ // the state.
+ if (mProcessState < PROCESS_CREATED) {
+ mProcessState = PROCESS_CREATED;
+ }
+ lock.Notify();
+ }
+ return ProcessHandlePromise::CreateAndResolve(
+ GetChildProcessHandle(), __func__);
+ },
+ [this](const LaunchError aError) {
+ // WaitUntilConnected might be waiting for us to signal.
+ // If something failed let's set the error state and notify.
+ CHROMIUM_LOG(ERROR)
+ << "Failed to launch "
+ << XRE_GeckoProcessTypeToString(mProcessType)
+ << " subprocess";
+ Telemetry::Accumulate(
+ Telemetry::SUBPROCESS_LAUNCH_FAILURE,
+ nsDependentCString(
+ XRE_GeckoProcessTypeToString(mProcessType)));
+ nsCString telemetryKey = nsPrintfCString(
+#if defined(XP_WIN)
+ "%s,0x%lx,%s",
+#else
+ "%s,%d,%s",
+#endif
+ aError.FunctionName(), aError.ErrorCode(),
+ XRE_GeckoProcessTypeToString(mProcessType));
+ // Max telemetry key is 72 chars
+ // https://searchfox.org/mozilla-central/rev/c244b16815d1fc827d141472b9faac5610f250e7/toolkit/components/telemetry/core/TelemetryScalar.cpp#105
+ if (telemetryKey.Length() > 72) {
+ NS_WARNING(nsPrintfCString("Truncating telemetry key: %s",
+ telemetryKey.get())
+ .get());
+ telemetryKey.Truncate(72);
+ }
+ Telemetry::ScalarAdd(
+ Telemetry::ScalarID::
+ DOM_PARENTPROCESS_PROCESS_LAUNCH_ERRORS,
+ NS_ConvertUTF8toUTF16(telemetryKey), 1);
+ {
+ MonitorAutoLock lock(mMonitor);
+ mProcessState = PROCESS_ERROR;
+ lock.Notify();
+ }
+ return ProcessHandlePromise::CreateAndReject(aError, __func__);
+ });
+ return true;
+}
+
+bool GeckoChildProcessHost::WaitUntilConnected(int32_t aTimeoutMs) {
+ AUTO_PROFILER_LABEL("GeckoChildProcessHost::WaitUntilConnected", OTHER);
+
+ // NB: this uses a different mechanism than the chromium parent
+ // class.
+ TimeDuration timeout = (aTimeoutMs > 0)
+ ? TimeDuration::FromMilliseconds(aTimeoutMs)
+ : TimeDuration::Forever();
+
+ MonitorAutoLock lock(mMonitor);
+ TimeStamp waitStart = TimeStamp::Now();
+ TimeStamp current;
+
+ // We'll receive several notifications, we need to exit when we
+ // have either successfully launched or have timed out.
+ while (mProcessState != PROCESS_CONNECTED) {
+ // If there was an error then return it, don't wait out the timeout.
+ if (mProcessState == PROCESS_ERROR) {
+ break;
+ }
+
+ CVStatus status = lock.Wait(timeout);
+ if (status == CVStatus::Timeout) {
+ break;
+ }
+
+ if (timeout != TimeDuration::Forever()) {
+ current = TimeStamp::Now();
+ timeout -= current - waitStart;
+ waitStart = current;
+ }
+ }
+
+ return mProcessState == PROCESS_CONNECTED;
+}
+
+bool GeckoChildProcessHost::WaitForProcessHandle() {
+ MonitorAutoLock lock(mMonitor);
+ while (mProcessState < PROCESS_CREATED) {
+ lock.Wait();
+ }
+ MOZ_ASSERT(mProcessState == PROCESS_ERROR || GetChildProcessHandle());
+
+ return mProcessState < PROCESS_ERROR;
+}
+
+bool GeckoChildProcessHost::LaunchAndWaitForProcessHandle(
+ StringVector aExtraOpts) {
+ if (!AsyncLaunch(std::move(aExtraOpts))) {
+ return false;
+ }
+ return WaitForProcessHandle();
+}
+
+void GeckoChildProcessHost::InitializeChannel(
+ IPC::Channel::ChannelHandle&& aServerHandle) {
+ // Create the IPC channel which will be used for communication with this
+ // process.
+ mozilla::UniquePtr<IPC::Channel> channel = MakeUnique<IPC::Channel>(
+ std::move(aServerHandle), IPC::Channel::MODE_SERVER,
+ base::kInvalidProcessId);
+#if defined(XP_WIN)
+ channel->StartAcceptingHandles(IPC::Channel::MODE_SERVER);
+#elif defined(XP_DARWIN)
+ channel->StartAcceptingMachPorts(IPC::Channel::MODE_SERVER);
+#endif
+
+ mNodeController = NodeController::GetSingleton();
+ std::tie(mInitialPort, mNodeChannel) =
+ mNodeController->InviteChildProcess(std::move(channel), this);
+
+ MonitorAutoLock lock(mMonitor);
+ mProcessState = CHANNEL_INITIALIZED;
+ lock.Notify();
+}
+
+void GeckoChildProcessHost::SetAlreadyDead() {
+ mozilla::AutoWriteLock handleLock(mHandleLock);
+ if (mChildProcessHandle &&
+ mChildProcessHandle != base::kInvalidProcessHandle) {
+ base::CloseProcessHandle(mChildProcessHandle);
+ }
+
+ mChildProcessHandle = 0;
+}
+
+void BaseProcessLauncher::GetChildLogName(const char* origLogName,
+ nsACString& buffer) {
+#ifdef XP_WIN
+ // On Windows we must expand relative paths because sandboxing rules
+ // bound only to full paths. fopen fowards to NtCreateFile which checks
+ // the path against the sanboxing rules as passed to fopen (left relative).
+ char absPath[MAX_PATH + 2];
+ if (_fullpath(absPath, origLogName, sizeof(absPath))) {
+ buffer.Append(absPath);
+ } else
+#endif
+ {
+ buffer.Append(origLogName);
+ }
+
+ // Remove .moz_log extension to avoid its duplication, it will be added
+ // automatically by the logging backend
+ static constexpr auto kMozLogExt = nsLiteralCString{MOZ_LOG_FILE_EXTENSION};
+ if (StringEndsWith(buffer, kMozLogExt)) {
+ buffer.Truncate(buffer.Length() - kMozLogExt.Length());
+ }
+
+ // Append child-specific postfix to name
+ buffer.AppendLiteral(".child-");
+ buffer.AppendInt(mChildId);
+}
+
+// Windows needs a single dedicated thread for process launching,
+// because of thread-safety restrictions/assertions in the sandbox
+// code.
+//
+// Android also needs a single dedicated thread to simplify thread
+// safety in java.
+//
+// Fork server needs a dedicated thread for accessing
+// |ForkServiceChild|.
+#if defined(XP_WIN) || defined(MOZ_WIDGET_ANDROID) || \
+ defined(MOZ_ENABLE_FORKSERVER)
+
+static mozilla::StaticMutex gIPCLaunchThreadMutex;
+static mozilla::StaticRefPtr<nsIThread> gIPCLaunchThread
+ MOZ_GUARDED_BY(gIPCLaunchThreadMutex);
+
+class IPCLaunchThreadObserver final : public nsIObserver {
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+ protected:
+ virtual ~IPCLaunchThreadObserver() = default;
+};
+
+NS_IMPL_ISUPPORTS(IPCLaunchThreadObserver, nsIObserver, nsISupports)
+
+NS_IMETHODIMP
+IPCLaunchThreadObserver::Observe(nsISupports* aSubject, const char* aTopic,
+ const char16_t* aData) {
+ MOZ_RELEASE_ASSERT(strcmp(aTopic, "xpcom-shutdown-threads") == 0);
+ StaticMutexAutoLock lock(gIPCLaunchThreadMutex);
+
+ nsresult rv = NS_OK;
+ if (gIPCLaunchThread) {
+ rv = gIPCLaunchThread->Shutdown();
+ gIPCLaunchThread = nullptr;
+ }
+ mozilla::Unused << NS_WARN_IF(NS_FAILED(rv));
+ return rv;
+}
+
+nsCOMPtr<nsIEventTarget> GetIPCLauncher() {
+ StaticMutexAutoLock lock(gIPCLaunchThreadMutex);
+ if (!gIPCLaunchThread) {
+ nsCOMPtr<nsIThread> thread;
+ nsresult rv = NS_NewNamedThread("IPC Launch"_ns, getter_AddRefs(thread));
+ if (!NS_WARN_IF(NS_FAILED(rv))) {
+ NS_DispatchToMainThread(
+ NS_NewRunnableFunction("GeckoChildProcessHost::GetIPCLauncher", [] {
+ nsCOMPtr<nsIObserverService> obsService =
+ mozilla::services::GetObserverService();
+ nsCOMPtr<nsIObserver> obs = new IPCLaunchThreadObserver();
+ obsService->AddObserver(obs, "xpcom-shutdown-threads", false);
+ }));
+ gIPCLaunchThread = thread.forget();
+ }
+ }
+
+ nsCOMPtr<nsIEventTarget> thread = gIPCLaunchThread.get();
+ MOZ_DIAGNOSTIC_ASSERT(thread);
+ return thread;
+}
+
+#else // defined(XP_WIN) || defined(MOZ_WIDGET_ANDROID) ||
+ // defined(MOZ_ENABLE_FORKSERVER)
+
+// Other platforms use an on-demand thread pool.
+
+nsCOMPtr<nsIEventTarget> GetIPCLauncher() {
+ nsCOMPtr<nsIEventTarget> pool =
+ mozilla::SharedThreadPool::Get("IPC Launch"_ns);
+ MOZ_DIAGNOSTIC_ASSERT(pool);
+ return pool;
+}
+
+#endif // XP_WIN || MOZ_WIDGET_ANDROID || MOZ_ENABLE_FORKSERVER
+
+void
+#if defined(XP_WIN)
+AddAppDirToCommandLine(CommandLine& aCmdLine, nsIFile* aAppDir)
+#else
+AddAppDirToCommandLine(std::vector<std::string>& aCmdLine, nsIFile* aAppDir,
+ nsIFile* aProfileDir)
+#endif
+{
+ // Content processes need access to application resources, so pass
+ // the full application directory path to the child process.
+ if (aAppDir) {
+#if defined(XP_WIN)
+ nsString path;
+ MOZ_ALWAYS_SUCCEEDS(aAppDir->GetPath(path));
+ aCmdLine.AppendLooseValue(UTF8ToWide(geckoargs::sAppDir.Name()));
+ std::wstring wpath(path.get());
+ aCmdLine.AppendLooseValue(wpath);
+#else
+ nsAutoCString path;
+ MOZ_ALWAYS_SUCCEEDS(aAppDir->GetNativePath(path));
+ geckoargs::sAppDir.Put(path.get(), aCmdLine);
+#endif
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ // Full path to the profile dir
+ if (aProfileDir) {
+ // If the profile doesn't exist, normalization will
+ // fail. But we don't return an error here because some
+ // tests require startup with a missing profile dir.
+ // For users, almost universally, the profile will be in
+ // the home directory and normalization isn't required.
+ mozilla::Unused << aProfileDir->Normalize();
+ nsAutoCString path;
+ MOZ_ALWAYS_SUCCEEDS(aProfileDir->GetNativePath(path));
+ geckoargs::sProfile.Put(path.get(), aCmdLine);
+ }
+#endif
+ }
+}
+
+#if defined(XP_WIN) && (defined(MOZ_SANDBOX) || defined(_ARM64_))
+static bool Contains(const std::vector<std::string>& aExtraOpts,
+ const char* aValue) {
+ return std::any_of(aExtraOpts.begin(), aExtraOpts.end(),
+ [&](const std::string arg) {
+ return arg.find(aValue) != std::string::npos;
+ });
+}
+#endif // defined(XP_WIN) && (defined(MOZ_SANDBOX) || defined(_ARM64_))
+
+RefPtr<ProcessLaunchPromise> BaseProcessLauncher::PerformAsyncLaunch() {
+ Result<Ok, LaunchError> aError = DoSetup();
+ if (aError.isErr()) {
+ return ProcessLaunchPromise::CreateAndReject(aError.unwrapErr(), __func__);
+ }
+ RefPtr<BaseProcessLauncher> self = this;
+ return DoLaunch()->Then(
+ mLaunchThread, __func__,
+ [self](base::ProcessHandle aHandle) {
+ self->mResults.mHandle = aHandle;
+ return self->FinishLaunch();
+ },
+ [](LaunchError aError) {
+ return ProcessLaunchPromise::CreateAndReject(aError, __func__);
+ });
+}
+
+Result<Ok, LaunchError> BaseProcessLauncher::DoSetup() {
+ RefPtr<BaseProcessLauncher> self = this;
+ GetProfilerEnvVarsForChildProcess([self](const char* key, const char* value) {
+ self->mLaunchOptions->env_map[ENVIRONMENT_STRING(key)] =
+ ENVIRONMENT_STRING(value);
+ });
+#ifdef MOZ_MEMORY
+ if (mProcessType == GeckoProcessType_Content) {
+ nsAutoCString mallocOpts(PR_GetEnv("MALLOC_OPTIONS"));
+ // Disable randomization of small arenas in content.
+ mallocOpts.Append("r");
+ self->mLaunchOptions->env_map[ENVIRONMENT_LITERAL("MALLOC_OPTIONS")] =
+ ENVIRONMENT_STRING(mallocOpts.get());
+ }
+#endif
+
+ MapChildLogging();
+
+ return Ok();
+}
+
+void BaseProcessLauncher::MapChildLogging() {
+ const char* origNSPRLogName = PR_GetEnv("NSPR_LOG_FILE");
+ const char* origMozLogName = PR_GetEnv("MOZ_LOG_FILE");
+
+ if (origNSPRLogName) {
+ nsAutoCString nsprLogName;
+ GetChildLogName(origNSPRLogName, nsprLogName);
+ mLaunchOptions->env_map[ENVIRONMENT_LITERAL("NSPR_LOG_FILE")] =
+ ENVIRONMENT_STRING(nsprLogName.get());
+ }
+ if (origMozLogName) {
+ nsAutoCString mozLogName;
+ GetChildLogName(origMozLogName, mozLogName);
+ mLaunchOptions->env_map[ENVIRONMENT_LITERAL("MOZ_LOG_FILE")] =
+ ENVIRONMENT_STRING(mozLogName.get());
+ }
+
+ // `RUST_LOG_CHILD` is meant for logging child processes only.
+ nsAutoCString childRustLog(PR_GetEnv("RUST_LOG_CHILD"));
+ if (!childRustLog.IsEmpty()) {
+ mLaunchOptions->env_map[ENVIRONMENT_LITERAL("RUST_LOG")] =
+ ENVIRONMENT_STRING(childRustLog.get());
+ }
+}
+
+Result<Ok, LaunchError> BaseProcessLauncher::DoFinishLaunch() {
+ // We're in the parent and the child was launched. Close the child channel
+ // handle in the parent as soon as possible, which will allow the parent to
+ // detect when the child closes its handle (either due to normal exit or due
+ // to crash).
+ mClientChannelHandle = nullptr;
+
+ return Ok();
+}
+
+#if defined(MOZ_WIDGET_GTK)
+Result<Ok, LaunchError> LinuxProcessLauncher::DoSetup() {
+ Result<Ok, LaunchError> aError = PosixProcessLauncher::DoSetup();
+ if (aError.isErr()) {
+ return aError;
+ }
+
+ if (mProcessType == GeckoProcessType_Content) {
+ // disable IM module to avoid sandbox violation
+ mLaunchOptions->env_map["GTK_IM_MODULE"] = "gtk-im-context-simple";
+
+ // Disable ATK accessibility code in content processes because it conflicts
+ // with the sandbox, and we proxy that information through the main process
+ // anyway.
+ mLaunchOptions->env_map["NO_AT_BRIDGE"] = "1";
+ }
+
+# ifdef MOZ_SANDBOX
+ if (!mTmpDirName.IsEmpty()) {
+ // Point a bunch of things that might want to write from content to our
+ // shiny new content-process specific tmpdir
+ mLaunchOptions->env_map[ENVIRONMENT_LITERAL("TMPDIR")] =
+ ENVIRONMENT_STRING(mTmpDirName.get());
+ // Partial fix for bug 1380051 (not persistent - should be)
+ mLaunchOptions->env_map[ENVIRONMENT_LITERAL("MESA_GLSL_CACHE_DIR")] =
+ ENVIRONMENT_STRING(mTmpDirName.get());
+ }
+# endif // MOZ_SANDBOX
+
+ return Ok();
+}
+#endif // MOZ_WIDGET_GTK
+
+#ifdef XP_UNIX
+Result<Ok, LaunchError> PosixProcessLauncher::DoSetup() {
+ Result<Ok, LaunchError> aError = BaseProcessLauncher::DoSetup();
+ if (aError.isErr()) {
+ return aError;
+ }
+
+ // XPCOM may not be initialized in some subprocesses. We don't want
+ // to initialize XPCOM just for the directory service, especially
+ // since LD_LIBRARY_PATH is already set correctly in subprocesses
+ // (meaning that we don't need to set that up in the environment).
+ if (ShouldHaveDirectoryService()) {
+ MOZ_ASSERT(gGREBinPath);
+ nsCString path;
+ NS_CopyUnicodeToNative(nsDependentString(gGREBinPath), path);
+# if defined(XP_LINUX) || defined(__DragonFly__) || defined(XP_FREEBSD) || \
+ defined(XP_NETBSD) || defined(XP_OPENBSD)
+ const char* ld_library_path = PR_GetEnv("LD_LIBRARY_PATH");
+ nsCString new_ld_lib_path(path.get());
+
+ if (ld_library_path && *ld_library_path) {
+ new_ld_lib_path.Append(':');
+ new_ld_lib_path.Append(ld_library_path);
+ }
+ mLaunchOptions->env_map["LD_LIBRARY_PATH"] = new_ld_lib_path.get();
+
+# elif XP_DARWIN
+ // With signed production Mac builds, the dynamic linker (dyld) will
+ // ignore dyld environment variables preventing the use of variables
+ // such as DYLD_LIBRARY_PATH and DYLD_INSERT_LIBRARIES.
+
+ // If we're running with gtests, add the gtest XUL ahead of normal XUL on
+ // the DYLD_LIBRARY_PATH so that plugin-container.app loads it instead.
+ nsCString new_dyld_lib_path(path.get());
+ if (PR_GetEnv("MOZ_RUN_GTEST")) {
+ new_dyld_lib_path = path + "/gtest:"_ns + new_dyld_lib_path;
+ mLaunchOptions->env_map["DYLD_LIBRARY_PATH"] = new_dyld_lib_path.get();
+ }
+
+ // DYLD_INSERT_LIBRARIES is currently unused by default but we allow
+ // it to be set by the external environment.
+ const char* interpose = PR_GetEnv("DYLD_INSERT_LIBRARIES");
+ if (interpose && strlen(interpose) > 0) {
+ mLaunchOptions->env_map["DYLD_INSERT_LIBRARIES"] = interpose;
+ }
+
+ // Prevent connection attempts to diagnosticd(8) to save cycles. Log
+ // messages can trigger these connection attempts, but access to
+ // diagnosticd is blocked in sandboxed child processes.
+# ifdef MOZ_SANDBOX
+ if (mDisableOSActivityMode) {
+ mLaunchOptions->env_map["OS_ACTIVITY_MODE"] = "disable";
+ }
+# endif // defined(MOZ_SANDBOX)
+# endif
+ }
+
+ FilePath exePath;
+ BinPathType pathType = GetPathToBinary(exePath, mProcessType);
+
+ // remap the IPC socket fd to a well-known int, as the OS does for
+ // STDOUT_FILENO, for example
+ // The fork server doesn't use IPC::Channel, so can skip this step.
+ if (mProcessType != GeckoProcessType_ForkServer) {
+# ifdef MOZ_WIDGET_ANDROID
+ // On Android mChannelDstFd is uninitialised and the launching code uses
+ // only the first of each pair.
+ mLaunchOptions->fds_to_remap.push_back(
+ std::pair<int, int>(mClientChannelHandle.get(), -1));
+# else
+ MOZ_ASSERT(mChannelDstFd >= 0);
+ mLaunchOptions->fds_to_remap.push_back(
+ std::pair<int, int>(mClientChannelHandle.get(), mChannelDstFd));
+# endif
+ }
+
+ // no need for kProcessChannelID, the child process inherits the
+ // other end of the socketpair() from us
+
+ mChildArgv.push_back(exePath.value());
+
+ if (pathType == BinPathType::Self) {
+ mChildArgv.push_back("-contentproc");
+ }
+
+ mChildArgv.insert(mChildArgv.end(), mExtraOpts.begin(), mExtraOpts.end());
+
+ if ((mProcessType == GeckoProcessType_Content ||
+ mProcessType == GeckoProcessType_ForkServer) &&
+ Omnijar::IsInitialized()) {
+ // Make sure that child processes can find the omnijar, if they
+ // use full XPCOM. See Omnijar::ChildProcessInit and its callers.
+ nsAutoCString path;
+ nsCOMPtr<nsIFile> greFile = Omnijar::GetPath(Omnijar::GRE);
+ if (greFile && NS_SUCCEEDED(greFile->GetNativePath(path))) {
+ geckoargs::sGREOmni.Put(path.get(), mChildArgv);
+ }
+ nsCOMPtr<nsIFile> appFile = Omnijar::GetPath(Omnijar::APP);
+ if (appFile && NS_SUCCEEDED(appFile->GetNativePath(path))) {
+ geckoargs::sAppOmni.Put(path.get(), mChildArgv);
+ }
+ }
+
+ if (mProcessType != GeckoProcessType_GMPlugin) {
+ // Add the application directory path (-appdir path)
+# ifdef XP_MACOSX
+ AddAppDirToCommandLine(mChildArgv, mAppDir, mProfileDir);
+# else
+ AddAppDirToCommandLine(mChildArgv, mAppDir, nullptr);
+# endif
+ }
+
+ mChildArgv.push_back(mInitialChannelIdString);
+
+ mChildArgv.push_back(mPidString);
+
+ if (!CrashReporter::IsDummy()) {
+# if defined(MOZ_WIDGET_COCOA)
+ mChildArgv.push_back(CrashReporter::GetChildNotificationPipe());
+# elif defined(XP_UNIX)
+ int childCrashFd, childCrashRemapFd;
+ if (NS_WARN_IF(!CrashReporter::CreateNotificationPipeForChild(
+ &childCrashFd, &childCrashRemapFd))) {
+ return Err(LaunchError("CR::CreateNotificationPipeForChild"));
+ }
+
+ if (0 <= childCrashFd) {
+ mLaunchOptions->fds_to_remap.push_back(
+ std::pair<int, int>(childCrashFd, childCrashRemapFd));
+ // "true" == crash reporting enabled
+ mChildArgv.push_back("true");
+ } else {
+ // "false" == crash reporting disabled
+ mChildArgv.push_back("false");
+ }
+# endif
+ }
+
+# ifdef MOZ_WIDGET_COCOA
+ {
+ auto* thisMac = static_cast<MacProcessLauncher*>(this);
+ kern_return_t kr =
+ bootstrap_check_in(bootstrap_port, thisMac->mMachConnectionName.c_str(),
+ getter_Transfers(thisMac->mParentRecvPort));
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR) << "parent bootstrap_check_in failed: "
+ << mach_error_string(kr);
+ return Err(LaunchError("bootstrap_check_in", kr));
+ }
+ mChildArgv.push_back(thisMac->mMachConnectionName.c_str());
+ }
+# endif // MOZ_WIDGET_COCOA
+
+ mChildArgv.push_back(ChildProcessType());
+ return Ok();
+}
+#endif // XP_UNIX
+
+#if defined(MOZ_WIDGET_ANDROID)
+RefPtr<ProcessHandlePromise> AndroidProcessLauncher::DoLaunch() {
+ return LaunchAndroidService(mProcessType, mChildArgv,
+ mLaunchOptions->fds_to_remap);
+}
+#endif // MOZ_WIDGET_ANDROID
+
+#ifdef XP_UNIX
+RefPtr<ProcessHandlePromise> PosixProcessLauncher::DoLaunch() {
+ ProcessHandle handle = 0;
+ Result<Ok, LaunchError> aError =
+ base::LaunchApp(mChildArgv, std::move(*mLaunchOptions), &handle);
+ if (aError.isErr()) {
+ return ProcessHandlePromise::CreateAndReject(aError.unwrapErr(), __func__);
+ }
+ return ProcessHandlePromise::CreateAndResolve(handle, __func__);
+}
+#endif // XP_UNIX
+
+#ifdef XP_MACOSX
+Result<Ok, LaunchError> MacProcessLauncher::DoFinishLaunch() {
+ Result<Ok, LaunchError> aError = PosixProcessLauncher::DoFinishLaunch();
+ if (aError.isErr()) {
+ return aError;
+ }
+
+ MOZ_ASSERT(mParentRecvPort, "should have been configured during DoSetup()");
+
+ // Wait for the child process to send us its 'task_t' data.
+ const int kTimeoutMs = 10000;
+
+ mozilla::UniqueMachSendRight child_task;
+ audit_token_t audit_token{};
+ kern_return_t kr = MachReceivePortSendRight(
+ mParentRecvPort, mozilla::Some(kTimeoutMs), &child_task, &audit_token);
+ if (kr != KERN_SUCCESS) {
+ std::string errString = StringPrintf("0x%x %s", kr, mach_error_string(kr));
+ CHROMIUM_LOG(ERROR) << "parent MachReceivePortSendRight failed: "
+ << errString;
+ return Err(LaunchError("MachReceivePortSendRight", kr));
+ }
+
+ // Ensure the message was sent by the newly spawned child process.
+ if (audit_token_to_pid(audit_token) != base::GetProcId(mResults.mHandle)) {
+ CHROMIUM_LOG(ERROR) << "task_t was not sent by child process";
+ return Err(LaunchError("audit_token_to_pid"));
+ }
+
+ // Ensure the task_t corresponds to the newly spawned child process.
+ pid_t task_pid = -1;
+ kr = pid_for_task(child_task.get(), &task_pid);
+ if (kr != KERN_SUCCESS) {
+ CHROMIUM_LOG(ERROR) << "pid_for_task failed: " << mach_error_string(kr);
+ return Err(LaunchError("pid_for_task", kr));
+ }
+ if (task_pid != base::GetProcId(mResults.mHandle)) {
+ CHROMIUM_LOG(ERROR) << "task_t is not for child process";
+ return Err(LaunchError("task_pid"));
+ }
+
+ mResults.mChildTask = child_task.release();
+
+ return Ok();
+}
+#endif // XP_MACOSX
+
+#ifdef XP_WIN
+Result<Ok, LaunchError> WindowsProcessLauncher::DoSetup() {
+ Result<Ok, LaunchError> aError = BaseProcessLauncher::DoSetup();
+ if (aError.isErr()) {
+ return aError;
+ }
+
+ FilePath exePath;
+ BinPathType pathType = GetPathToBinary(exePath, mProcessType);
+
+# if defined(MOZ_SANDBOX) || defined(_ARM64_)
+ const bool isGMP = mProcessType == GeckoProcessType_GMPlugin;
+ const bool isWidevine = isGMP && Contains(mExtraOpts, "gmp-widevinecdm");
+# if defined(_ARM64_)
+ bool useRemoteSandboxBroker = false;
+ if (mLaunchArch & (base::PROCESS_ARCH_I386 | base::PROCESS_ARCH_X86_64)) {
+ // On Windows on ARM64 for ClearKey and Widevine, and for the sandbox
+ // launcher process, we want to run the x86 plugin-container.exe in
+ // the "i686" subdirectory, instead of the aarch64 plugin-container.exe.
+ // So insert "i686" into the exePath.
+ exePath = exePath.DirName().AppendASCII("i686").Append(exePath.BaseName());
+ useRemoteSandboxBroker =
+ mProcessType != GeckoProcessType_RemoteSandboxBroker;
+ }
+# endif // if defined(_ARM64_)
+# endif // defined(MOZ_SANDBOX) || defined(_ARM64_)
+
+ mCmdLine.emplace(exePath.ToWStringHack());
+
+ if (pathType == BinPathType::Self) {
+ mCmdLine->AppendLooseValue(UTF8ToWide("-contentproc"));
+ }
+
+# ifdef HAS_DLL_BLOCKLIST
+ if (IsDynamicBlocklistDisabled(
+ gSafeMode,
+ CommandLine::ForCurrentProcess()->HasSwitch(UTF8ToWide(
+ mozilla::geckoargs::sDisableDynamicDllBlocklist.sMatch)))) {
+ mCmdLine->AppendLooseValue(
+ UTF8ToWide(mozilla::geckoargs::sDisableDynamicDllBlocklist.sMatch));
+ }
+# endif // HAS_DLL_BLOCKLIST
+
+ // Inherit the initial client channel handle into the child process.
+ std::wstring processChannelID =
+ std::to_wstring(uint32_t(uintptr_t(mClientChannelHandle.get())));
+ mLaunchOptions->handles_to_inherit.push_back(mClientChannelHandle.get());
+ mCmdLine->AppendSwitchWithValue(switches::kProcessChannelID,
+ processChannelID);
+
+ for (std::vector<std::string>::iterator it = mExtraOpts.begin();
+ it != mExtraOpts.end(); ++it) {
+ mCmdLine->AppendLooseValue(UTF8ToWide(*it));
+ }
+
+# if defined(MOZ_SANDBOX)
+# if defined(_ARM64_)
+ if (useRemoteSandboxBroker)
+ mResults.mSandboxBroker = new RemoteSandboxBroker(mLaunchArch);
+ else
+# endif // if defined(_ARM64_)
+ mResults.mSandboxBroker = new SandboxBroker();
+
+ // XXX: Bug 1124167: We should get rid of the process specific logic for
+ // sandboxing in this class at some point. Unfortunately it will take a bit
+ // of reorganizing so I don't think this patch is the right time.
+ switch (mProcessType) {
+ case GeckoProcessType_Content:
+ if (mSandboxLevel > 0) {
+ // For now we treat every failure as fatal in
+ // SetSecurityLevelForContentProcess and just crash there right away.
+ // Should this change in the future then we should also handle the error
+ // here.
+ mResults.mSandboxBroker->SetSecurityLevelForContentProcess(
+ mSandboxLevel, mIsFileContent);
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_IPDLUnitTest:
+ // XXX: We don't sandbox this process type yet
+ break;
+ case GeckoProcessType_GMPlugin:
+ if (!PR_GetEnv("MOZ_DISABLE_GMP_SANDBOX")) {
+ // The Widevine CDM on Windows can only load at USER_RESTRICTED,
+ // not at USER_LOCKDOWN. So look in the command line arguments
+ // to see if we're loading the path to the Widevine CDM, and if
+ // so use sandbox level USER_RESTRICTED instead of USER_LOCKDOWN.
+ auto level =
+ isWidevine ? SandboxBroker::Restricted : SandboxBroker::LockDown;
+ if (NS_WARN_IF(
+ !mResults.mSandboxBroker->SetSecurityLevelForGMPlugin(level))) {
+ return Err(LaunchError("SetSecurityLevelForGMPlugin"));
+ }
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_GPU:
+ if (mSandboxLevel > 0 && !PR_GetEnv("MOZ_DISABLE_GPU_SANDBOX")) {
+ // For now we treat every failure as fatal in
+ // SetSecurityLevelForGPUProcess and just crash there right away. Should
+ // this change in the future then we should also handle the error here.
+ mResults.mSandboxBroker->SetSecurityLevelForGPUProcess(mSandboxLevel);
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_VR:
+ if (mSandboxLevel > 0 && !PR_GetEnv("MOZ_DISABLE_VR_SANDBOX")) {
+ // TODO: Implement sandbox for VR process, Bug 1430043.
+ }
+ break;
+ case GeckoProcessType_RDD:
+ if (!PR_GetEnv("MOZ_DISABLE_RDD_SANDBOX")) {
+ if (NS_WARN_IF(
+ !mResults.mSandboxBroker->SetSecurityLevelForRDDProcess())) {
+ return Err(LaunchError("SetSecurityLevelForRDDProcess"));
+ }
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_Socket:
+ if (!PR_GetEnv("MOZ_DISABLE_SOCKET_PROCESS_SANDBOX")) {
+ if (NS_WARN_IF(
+ !mResults.mSandboxBroker->SetSecurityLevelForSocketProcess())) {
+ return Err(LaunchError("SetSecurityLevelForSocketProcess"));
+ }
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_Utility:
+ if (IsUtilitySandboxEnabled(mSandbox)) {
+ if (!mResults.mSandboxBroker->SetSecurityLevelForUtilityProcess(
+ mSandbox)) {
+ return Err(LaunchError("SetSecurityLevelForUtilityProcess"));
+ }
+ mUseSandbox = true;
+ }
+ break;
+ case GeckoProcessType_RemoteSandboxBroker:
+ // We don't sandbox the sandbox launcher...
+ break;
+ case GeckoProcessType_Default:
+ default:
+ MOZ_CRASH("Bad process type in GeckoChildProcessHost");
+ break;
+ };
+
+ if (mUseSandbox) {
+ for (auto it = mAllowedFilesRead.begin(); it != mAllowedFilesRead.end();
+ ++it) {
+ mResults.mSandboxBroker->AllowReadFile(it->c_str());
+ }
+
+ if (mResults.mSandboxBroker->IsWin32kLockedDown()) {
+ mCmdLine->AppendLooseValue(
+ UTF8ToWide(geckoargs::sWin32kLockedDown.Name()));
+ }
+ }
+# endif // defined(MOZ_SANDBOX)
+
+ // Add the application directory path (-appdir path)
+ AddAppDirToCommandLine(mCmdLine.ref(), mAppDir);
+
+ // XXX Command line params past this point are expected to be at
+ // the end of the command line string, and in a specific order.
+ // See XRE_InitChildProcess in nsEmbedFunction.
+
+ // Win app model id
+ mCmdLine->AppendLooseValue(mGroupId.get());
+
+ // Initial MessageChannel id
+ mCmdLine->AppendLooseValue(UTF8ToWide(mInitialChannelIdString));
+
+ // Process id
+ mCmdLine->AppendLooseValue(UTF8ToWide(mPidString));
+
+ mCmdLine->AppendLooseValue(
+ UTF8ToWide(CrashReporter::GetChildNotificationPipe()));
+
+ // Process type
+ mCmdLine->AppendLooseValue(UTF8ToWide(ChildProcessType()));
+
+# ifdef MOZ_SANDBOX
+ if (mUseSandbox) {
+ // Mark the handles to inherit as inheritable.
+ for (HANDLE h : mLaunchOptions->handles_to_inherit) {
+ mResults.mSandboxBroker->AddHandleToShare(h);
+ }
+ }
+# endif // MOZ_SANDBOX
+
+ return Ok();
+}
+
+RefPtr<ProcessHandlePromise> WindowsProcessLauncher::DoLaunch() {
+ ProcessHandle handle = 0;
+# ifdef MOZ_SANDBOX
+ if (mUseSandbox) {
+ const IMAGE_THUNK_DATA* cachedNtdllThunk =
+ mCachedNtdllThunk ? mCachedNtdllThunk->begin() : nullptr;
+ Result<Ok, LaunchError> err = mResults.mSandboxBroker->LaunchApp(
+ mCmdLine->program().c_str(), mCmdLine->command_line_string().c_str(),
+ mLaunchOptions->env_map, mProcessType, mEnableSandboxLogging,
+ cachedNtdllThunk, &handle);
+ if (err.isOk()) {
+ EnvironmentLog("MOZ_PROCESS_LOG")
+ .print("==> process %d launched child process %d (%S)\n",
+ base::GetCurrentProcId(), base::GetProcId(handle),
+ mCmdLine->command_line_string().c_str());
+ return ProcessHandlePromise::CreateAndResolve(handle, __func__);
+ }
+ return ProcessHandlePromise::CreateAndReject(err.unwrapErr(), __func__);
+ }
+# endif // defined(MOZ_SANDBOX)
+
+ Result<Ok, LaunchError> launchErr =
+ base::LaunchApp(mCmdLine.ref(), *mLaunchOptions, &handle);
+ if (launchErr.isErr()) {
+ return ProcessHandlePromise::CreateAndReject(launchErr.unwrapErr(),
+ __func__);
+ }
+ return ProcessHandlePromise::CreateAndResolve(handle, __func__);
+}
+
+Result<Ok, LaunchError> WindowsProcessLauncher::DoFinishLaunch() {
+ Result<Ok, LaunchError> err = BaseProcessLauncher::DoFinishLaunch();
+ if (err.isErr()) {
+ return err;
+ }
+
+ return Ok();
+}
+#endif // XP_WIN
+
+RefPtr<ProcessLaunchPromise> BaseProcessLauncher::FinishLaunch() {
+ Result<Ok, LaunchError> aError = DoFinishLaunch();
+ if (aError.isErr()) {
+ return ProcessLaunchPromise::CreateAndReject(aError.unwrapErr(), __func__);
+ }
+
+ MOZ_DIAGNOSTIC_ASSERT(mResults.mHandle);
+
+ Telemetry::AccumulateTimeDelta(Telemetry::CHILD_PROCESS_LAUNCH_MS,
+ mStartTimeStamp);
+
+ return ProcessLaunchPromise::CreateAndResolve(mResults, __func__);
+}
+
+bool GeckoChildProcessHost::OpenPrivilegedHandle(base::ProcessId aPid) {
+ if (mChildProcessHandle) {
+ MOZ_ASSERT(aPid == base::GetProcId(mChildProcessHandle));
+ return true;
+ }
+
+ return base::OpenPrivilegedProcessHandle(aPid, &mChildProcessHandle);
+}
+
+void GeckoChildProcessHost::OnChannelConnected(base::ProcessId peer_pid) {
+ {
+ mozilla::AutoWriteLock hLock(mHandleLock);
+ if (!OpenPrivilegedHandle(peer_pid)) {
+ MOZ_CRASH("can't open handle to child process");
+ }
+ }
+ MonitorAutoLock lock(mMonitor);
+ mProcessState = PROCESS_CONNECTED;
+ lock.Notify();
+}
+
+RefPtr<ProcessHandlePromise> GeckoChildProcessHost::WhenProcessHandleReady() {
+ MOZ_ASSERT(mHandlePromise != nullptr);
+ return mHandlePromise;
+}
+
+#ifdef MOZ_WIDGET_ANDROID
+RefPtr<ProcessHandlePromise> AndroidProcessLauncher::LaunchAndroidService(
+ const GeckoProcessType aType, const std::vector<std::string>& argv,
+ const base::file_handle_mapping_vector& fds_to_remap) {
+ MOZ_RELEASE_ASSERT((2 <= fds_to_remap.size()) && (fds_to_remap.size() <= 5));
+ JNIEnv* const env = mozilla::jni::GetEnvForThread();
+ MOZ_ASSERT(env);
+
+ const int argvSize = argv.size();
+ jni::ObjectArray::LocalRef jargs =
+ jni::ObjectArray::New<jni::String>(argvSize);
+ for (int ix = 0; ix < argvSize; ix++) {
+ jargs->SetElement(ix, jni::StringParam(argv[ix].c_str(), env));
+ }
+
+ // XXX: this processing depends entirely on the internals of
+ // ContentParent::LaunchSubprocess()
+ // GeckoChildProcessHost::PerformAsyncLaunch(), and the order in
+ // which they append to fds_to_remap. There must be a better way to do it.
+ // See bug 1440207.
+ int32_t prefsFd = fds_to_remap[0].first;
+ int32_t prefMapFd = fds_to_remap[1].first;
+ int32_t ipcFd = fds_to_remap[2].first;
+ int32_t crashFd = -1;
+ if (fds_to_remap.size() == 4) {
+ crashFd = fds_to_remap[3].first;
+ }
+
+ auto type = java::GeckoProcessType::FromInt(aType);
+ auto genericResult = java::GeckoProcessManager::Start(
+ type, jargs, prefsFd, prefMapFd, ipcFd, crashFd);
+ auto typedResult = java::GeckoResult::LocalRef(std::move(genericResult));
+ return ProcessHandlePromise::FromGeckoResult(typedResult);
+}
+#endif
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+bool GeckoChildProcessHost::AppendMacSandboxParams(StringVector& aArgs) {
+ MacSandboxInfo info;
+ if (NS_WARN_IF(!FillMacSandboxInfo(info))) {
+ return false;
+ }
+ info.AppendAsParams(aArgs);
+ return true;
+}
+
+// Fill |aInfo| with the flags needed to launch the utility sandbox
+bool GeckoChildProcessHost::FillMacSandboxInfo(MacSandboxInfo& aInfo) {
+ aInfo.type = GetDefaultMacSandboxType();
+ aInfo.shouldLog = Preferences::GetBool("security.sandbox.logging.enabled") ||
+ PR_GetEnv("MOZ_SANDBOX_LOGGING");
+
+ nsAutoCString appPath;
+ if (!nsMacUtilsImpl::GetAppPath(appPath)) {
+ MOZ_CRASH("Failed to get app path");
+ }
+ aInfo.appPath.assign(appPath.get());
+ return true;
+}
+
+void GeckoChildProcessHost::DisableOSActivityMode() {
+ mDisableOSActivityMode = true;
+}
+
+//
+// If early sandbox startup is enabled for this process type, map the
+// process type to the sandbox type and enable the sandbox. Returns true
+// if no errors were encountered or if early sandbox startup is not
+// enabled for this process. Returns false if an error was encountered.
+//
+/* static */
+bool GeckoChildProcessHost::StartMacSandbox(int aArgc, char** aArgv,
+ std::string& aErrorMessage) {
+ MacSandboxType sandboxType = MacSandboxType_Invalid;
+ switch (XRE_GetProcessType()) {
+ // For now, only support early sandbox startup for content,
+ // RDD, and GMP processes. Add case statements for the additional
+ // process types once early sandbox startup is implemented for them.
+ case GeckoProcessType_Content:
+ // Content processes don't use GeckoChildProcessHost
+ // to configure sandboxing so hard code the sandbox type.
+ sandboxType = MacSandboxType_Content;
+ break;
+ case GeckoProcessType_RDD:
+ sandboxType = RDDProcessHost::GetMacSandboxType();
+ break;
+ case GeckoProcessType_Socket:
+ sandboxType = net::SocketProcessHost::GetMacSandboxType();
+ break;
+ case GeckoProcessType_GMPlugin:
+ sandboxType = gmp::GMPProcessParent::GetMacSandboxType();
+ break;
+ case GeckoProcessType_Utility:
+ sandboxType = ipc::UtilityProcessHost::GetMacSandboxType();
+ break;
+ default:
+ return true;
+ }
+
+ return mozilla::StartMacSandboxIfEnabled(sandboxType, aArgc, aArgv,
+ aErrorMessage);
+}
+
+#endif /* XP_MACOSX && MOZ_SANDBOX */
+
+/* static */
+void GeckoChildProcessHost::GetAll(const GeckoProcessCallback& aCallback) {
+ StaticMutexAutoLock lock(sMutex);
+ if (!sGeckoChildProcessHosts) {
+ return;
+ }
+ for (GeckoChildProcessHost* gp = sGeckoChildProcessHosts->getFirst(); gp;
+ gp = static_cast<mozilla::LinkedListElement<GeckoChildProcessHost>*>(gp)
+ ->getNext()) {
+ aCallback(gp);
+ }
+}
+
+RefPtr<ProcessLaunchPromise> BaseProcessLauncher::Launch(
+ GeckoChildProcessHost* aHost) {
+ AssertIOThread();
+
+ // The ForkServer doesn't use IPC::Channel for communication, so we can skip
+ // initializing it.
+ if (mProcessType != GeckoProcessType_ForkServer) {
+ IPC::Channel::ChannelHandle serverHandle;
+ if (!IPC::Channel::CreateRawPipe(&serverHandle, &mClientChannelHandle)) {
+ return ProcessLaunchPromise::CreateAndReject(LaunchError("CreateRawPipe"),
+ __func__);
+ }
+ aHost->InitializeChannel(std::move(serverHandle));
+ }
+
+ return InvokeAsync(mLaunchThread, this, __func__,
+ &BaseProcessLauncher::PerformAsyncLaunch);
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/GeckoChildProcessHost.h b/ipc/glue/GeckoChildProcessHost.h
new file mode 100644
index 0000000000..89ed399fea
--- /dev/null
+++ b/ipc/glue/GeckoChildProcessHost.h
@@ -0,0 +1,316 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_GECKOCHILDPROCESSHOST_H__
+#define __IPC_GLUE_GECKOCHILDPROCESSHOST_H__
+
+#include "base/file_path.h"
+#include "base/process_util.h"
+#include "base/waitable_event.h"
+#include "chrome/common/ipc_message.h"
+#include "mojo/core/ports/port_ref.h"
+
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/FileDescriptor.h"
+#include "mozilla/ipc/NodeChannel.h"
+#include "mozilla/ipc/LaunchError.h"
+#include "mozilla/ipc/ScopedPort.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/Buffer.h"
+#include "mozilla/LinkedList.h"
+#include "mozilla/Monitor.h"
+#include "mozilla/MozPromise.h"
+#include "mozilla/RWLock.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/UniquePtr.h"
+
+#include "nsCOMPtr.h"
+#include "nsExceptionHandler.h"
+#include "nsXULAppAPI.h" // for GeckoProcessType
+#include "nsString.h"
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+# include "sandboxBroker.h"
+#endif
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+# include "mozilla/Sandbox.h"
+#endif
+
+#if defined(MOZ_SANDBOX)
+# include "mozilla/ipc/UtilityProcessSandboxing.h"
+#endif
+
+#if (defined(XP_WIN) && defined(_ARM64_)) || \
+ (defined(XP_MACOSX) && defined(__aarch64__))
+# define ALLOW_GECKO_CHILD_PROCESS_ARCH
+#endif
+
+struct _MacSandboxInfo;
+typedef _MacSandboxInfo MacSandboxInfo;
+
+namespace mozilla {
+namespace ipc {
+
+typedef mozilla::MozPromise<base::ProcessHandle, LaunchError, false>
+ ProcessHandlePromise;
+
+class GeckoChildProcessHost : public SupportsWeakPtr,
+ public LinkedListElement<GeckoChildProcessHost> {
+ protected:
+ typedef mozilla::Monitor Monitor;
+ typedef std::vector<std::string> StringVector;
+
+ public:
+ using ProcessId = base::ProcessId;
+ using ProcessHandle = base::ProcessHandle;
+
+ explicit GeckoChildProcessHost(GeckoProcessType aProcessType,
+ bool aIsFileContent = false);
+
+ // Causes the object to be deleted, on the I/O thread, after any
+ // pending asynchronous work (like launching) is complete. This
+ // method can be called from any thread. If called from the I/O
+ // thread itself, deletion won't happen until the event loop spins;
+ // otherwise, it could happen immediately.
+ //
+ // GeckoChildProcessHost instances must not be deleted except
+ // through this method.
+ void Destroy();
+
+ static uint32_t GetUniqueID();
+
+ // Call this before launching to set an environment variable for the
+ // child process. The arguments must be UTF-8.
+ void SetEnv(const char* aKey, const char* aValue);
+
+ // Does not block. The IPC channel may not be initialized yet, and
+ // the child process may or may not have been created when this
+ // method returns.
+ bool AsyncLaunch(StringVector aExtraOpts = StringVector());
+
+ virtual bool WaitUntilConnected(int32_t aTimeoutMs = 0);
+
+ // Block until the IPC channel for our subprocess is initialized and
+ // the OS process is created. The subprocess may or may not have
+ // connected back to us when this method returns.
+ //
+ // NB: on POSIX, this method is relatively cheap, and doesn't
+ // require disk IO. On win32 however, it requires at least the
+ // analogue of stat(). This difference induces a semantic
+ // difference in this method: on POSIX, when we return, we know the
+ // subprocess has been created, but we don't know whether its
+ // executable image can be loaded. On win32, we do know that when
+ // we return. But we don't know if dynamic linking succeeded on
+ // either platform.
+ bool LaunchAndWaitForProcessHandle(StringVector aExtraOpts = StringVector());
+ bool WaitForProcessHandle();
+
+ // Block until the child process has been created and it connects to
+ // the IPC channel, meaning it's fully initialized. (Or until an
+ // error occurs.)
+ bool SyncLaunch(StringVector aExtraOpts = StringVector(),
+ int32_t timeoutMs = 0);
+
+ virtual void OnChannelConnected(base::ProcessId peer_pid);
+
+ // Resolves to the process handle when it's available (see
+ // LaunchAndWaitForProcessHandle); use with AsyncLaunch.
+ RefPtr<ProcessHandlePromise> WhenProcessHandleReady();
+
+ void InitializeChannel(IPC::Channel::ChannelHandle&& aServerHandle);
+
+ virtual bool CanShutdown() { return true; }
+
+ UntypedEndpoint TakeInitialEndpoint() {
+ return UntypedEndpoint{PrivateIPDLInterface{}, std::move(mInitialPort),
+ mInitialChannelId, base::GetCurrentProcId(),
+ GetChildProcessId()};
+ }
+
+ // Returns a "borrowed" handle to the child process - the handle returned
+ // by this function must not be closed by the caller. The handle is also
+ // not guaranteed to remain valid; if the caller is using it for anything
+ // more than logging or asserting non-null, it will need to deal with
+ // synchronization.
+ //
+ // Warning: the null value here is 0, not kInvalidProcessHandle.
+ ProcessHandle GetChildProcessHandle();
+
+ // Returns the child's process ID; as for GetChildProcessHandle, there is
+ // no inherent guarantee that it will remain valid or continue to
+ // reference the same process.
+ //
+ // The null value here is also 0; this matches the result of
+ // GetProcId on a zero or (on Windows) invalid handle.
+ ProcessId GetChildProcessId();
+
+ GeckoProcessType GetProcessType() { return mProcessType; }
+
+#ifdef XP_MACOSX
+ task_t GetChildTask();
+#endif
+
+#ifdef XP_WIN
+
+ void AddHandleToShare(HANDLE aHandle) {
+ mLaunchOptions->handles_to_inherit.push_back(aHandle);
+ }
+#else
+ void AddFdToRemap(int aSrcFd, int aDstFd) {
+ mLaunchOptions->fds_to_remap.push_back(std::make_pair(aSrcFd, aDstFd));
+ }
+#endif
+
+#ifdef ALLOW_GECKO_CHILD_PROCESS_ARCH
+ void SetLaunchArchitecture(uint32_t aArch) { mLaunchArch = aArch; }
+#endif
+
+ // For bug 943174: Skip the EnsureProcessTerminated call in the destructor.
+ void SetAlreadyDead();
+
+#if defined(MOZ_SANDBOX) && defined(XP_MACOSX)
+ // Start the sandbox from the child process.
+ static bool StartMacSandbox(int aArgc, char** aArgv,
+ std::string& aErrorMessage);
+
+ // The sandbox type that will be use when sandboxing is
+ // enabled in the derived class and FillMacSandboxInfo
+ // has not been overridden.
+ static MacSandboxType GetDefaultMacSandboxType() {
+ return MacSandboxType_Utility;
+ };
+
+ // Must be called before the process is launched. Determines if
+ // child processes will be launched with OS_ACTIVITY_MODE set to
+ // "disabled" or not. When |mDisableOSActivityMode| is set to true,
+ // child processes will be launched with OS_ACTIVITY_MODE
+ // disabled to avoid connection attempts to diagnosticd(8) which are
+ // blocked in child processes due to sandboxing.
+ void DisableOSActivityMode();
+#endif // defined(MOZ_SANDBOX) && defined(XP_MACOSX)
+ typedef std::function<void(GeckoChildProcessHost*)> GeckoProcessCallback;
+
+ // Iterates over all instances and calls aCallback with each one of them.
+ // This method will lock any addition/removal of new processes
+ // so you need to make sure the callback is as fast as possible.
+ //
+ // To reiterate: the callbacks are executed synchronously.
+ static void GetAll(const GeckoProcessCallback& aCallback);
+
+ friend class BaseProcessLauncher;
+ friend class PosixProcessLauncher;
+ friend class WindowsProcessLauncher;
+
+ protected:
+ virtual ~GeckoChildProcessHost();
+ GeckoProcessType mProcessType;
+ bool mIsFileContent;
+ Monitor mMonitor;
+ FilePath mProcessPath;
+#ifdef ALLOW_GECKO_CHILD_PROCESS_ARCH
+ // Used on platforms where we may launch a child process with a different
+ // architecture than the parent process.
+ uint32_t mLaunchArch = base::PROCESS_ARCH_INVALID;
+#endif
+ // GeckoChildProcessHost holds the launch options so they can be set
+ // up on the main thread using main-thread-only APIs like prefs, and
+ // then used for the actual launch on another thread. This pointer
+ // is set to null to free the options after the child is launched.
+ UniquePtr<base::LaunchOptions> mLaunchOptions;
+ ScopedPort mInitialPort;
+ nsID mInitialChannelId;
+ RefPtr<NodeController> mNodeController;
+ RefPtr<NodeChannel> mNodeChannel;
+
+ // This value must be accessed while holding mMonitor.
+ enum {
+ // This object has been constructed, but the OS process has not
+ // yet.
+ CREATING_CHANNEL = 0,
+ // The IPC channel for our subprocess has been created, but the OS
+ // process has still not been created.
+ CHANNEL_INITIALIZED,
+ // The OS process has been created, but it hasn't yet connected to
+ // our IPC channel.
+ PROCESS_CREATED,
+ // The process is launched and connected to our IPC channel. All
+ // is well.
+ PROCESS_CONNECTED,
+ PROCESS_ERROR
+ } mProcessState MOZ_GUARDED_BY(mMonitor);
+
+ void PrepareLaunch();
+
+#ifdef XP_WIN
+ void InitWindowsGroupID();
+ nsString mGroupId;
+# ifdef MOZ_SANDBOX
+ RefPtr<AbstractSandboxBroker> mSandboxBroker;
+ std::vector<std::wstring> mAllowedFilesRead;
+ bool mEnableSandboxLogging;
+ int32_t mSandboxLevel;
+# endif
+#endif // XP_WIN
+
+#if defined(MOZ_SANDBOX)
+ SandboxingKind mSandbox;
+#endif
+
+ mozilla::RWLock mHandleLock;
+ ProcessHandle mChildProcessHandle MOZ_GUARDED_BY(mHandleLock);
+#if defined(XP_DARWIN)
+ task_t mChildTask MOZ_GUARDED_BY(mHandleLock);
+#endif
+ RefPtr<ProcessHandlePromise> mHandlePromise;
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ bool mDisableOSActivityMode;
+#endif
+
+ bool OpenPrivilegedHandle(base::ProcessId aPid) MOZ_REQUIRES(mHandleLock);
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ // Override this method to return true to launch the child process
+ // using the Mac utility (by default) sandbox. Override
+ // FillMacSandboxInfo() to change the sandbox type and settings.
+ virtual bool IsMacSandboxLaunchEnabled() { return false; }
+
+ // Fill a MacSandboxInfo to configure the sandbox
+ virtual bool FillMacSandboxInfo(MacSandboxInfo& aInfo);
+
+ // Adds the command line arguments needed to enable
+ // sandboxing of the child process at startup before
+ // the child event loop is up.
+ virtual bool AppendMacSandboxParams(StringVector& aArgs);
+#endif
+
+ private:
+ DISALLOW_EVIL_CONSTRUCTORS(GeckoChildProcessHost);
+
+ // Removes the instance from sGeckoChildProcessHosts
+ void RemoveFromProcessList();
+
+ // Linux-Only. Set this up before we're called from a different thread.
+ nsCString mTmpDirName;
+ // Mac and Windows. Set this up before we're called from a different thread.
+ nsCOMPtr<nsIFile> mProfileDir;
+
+ mozilla::Atomic<bool> mDestroying;
+
+ static uint32_t sNextUniqueID;
+ static StaticAutoPtr<LinkedList<GeckoChildProcessHost>>
+ sGeckoChildProcessHosts MOZ_GUARDED_BY(sMutex);
+ static StaticMutex sMutex;
+};
+
+nsCOMPtr<nsIEventTarget> GetIPCLauncher();
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* __IPC_GLUE_GECKOCHILDPROCESSHOST_H__ */
diff --git a/ipc/glue/IOThreadChild.h b/ipc/glue/IOThreadChild.h
new file mode 100644
index 0000000000..d4e877e67c
--- /dev/null
+++ b/ipc/glue/IOThreadChild.h
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef dom_plugins_IOThreadChild_h
+#define dom_plugins_IOThreadChild_h
+
+#include "chrome/common/child_thread.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/NodeController.h"
+#include "mozilla/ipc/ProcessChild.h"
+
+namespace mozilla {
+namespace ipc {
+//-----------------------------------------------------------------------------
+
+// The IOThreadChild class represents a background thread where the
+// IPC IO MessageLoop lives.
+class IOThreadChild : public ChildThread {
+ public:
+ explicit IOThreadChild(base::ProcessId aParentPid)
+ : ChildThread(base::Thread::Options(MessageLoop::TYPE_IO,
+ /* stack size */ 0),
+ aParentPid) {}
+
+ ~IOThreadChild() = default;
+
+ static MessageLoop* message_loop() {
+ return IOThreadChild::current()->Thread::message_loop();
+ }
+
+ protected:
+ static IOThreadChild* current() {
+ return static_cast<IOThreadChild*>(ChildThread::current());
+ }
+
+ private:
+ DISALLOW_EVIL_CONSTRUCTORS(IOThreadChild);
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef dom_plugins_IOThreadChild_h
diff --git a/ipc/glue/IPCCore.h b/ipc/glue/IPCCore.h
new file mode 100644
index 0000000000..bb6b725c35
--- /dev/null
+++ b/ipc/glue/IPCCore.h
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef IPC_GLUE_IPCCORE_H_
+#define IPC_GLUE_IPCCORE_H_
+
+namespace mozilla {
+
+struct void_t {
+ constexpr bool operator==(const void_t&) const { return true; }
+};
+
+struct null_t {
+ constexpr bool operator==(const null_t&) const { return true; }
+};
+
+} // namespace mozilla
+
+#endif // IPC_GLUE_IPCCORE_H_
diff --git a/ipc/glue/IPCForwards.h b/ipc/glue/IPCForwards.h
new file mode 100644
index 0000000000..8aef885257
--- /dev/null
+++ b/ipc/glue/IPCForwards.h
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IPCForwards_h
+#define mozilla_ipc_IPCForwards_h
+
+// A few helpers to avoid having to include lots of stuff in headers.
+
+namespace mozilla {
+template <typename T>
+class Maybe;
+
+namespace ipc {
+class IProtocol;
+}
+} // namespace mozilla
+
+namespace IPC {
+class Message;
+class MessageReader;
+class MessageWriter;
+template <typename T, bool>
+class ReadResult;
+} // namespace IPC
+
+// TODO(bug 1812271): Remove users of this macro.
+#define ALLOW_DEPRECATED_READPARAM \
+ public: \
+ enum { kHasDeprecatedReadParamPrivateConstructor = true }; \
+ template <typename, bool> \
+ friend class IPC::ReadResult; \
+ \
+ private:
+
+#endif
diff --git a/ipc/glue/IPCMessageUtils.h b/ipc/glue/IPCMessageUtils.h
new file mode 100644
index 0000000000..cdcd3c574a
--- /dev/null
+++ b/ipc/glue/IPCMessageUtils.h
@@ -0,0 +1,237 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_IPCMESSAGEUTILS_H__
+#define __IPC_GLUE_IPCMESSAGEUTILS_H__
+
+#include <cstdint>
+#include <string>
+#include <type_traits>
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/ipc/IPCCore.h"
+#include "mozilla/MacroForEach.h"
+
+class PickleIterator;
+
+// XXX Things that are not necessary if moving implementations to the cpp file
+#include "base/string_util.h"
+
+#ifdef _MSC_VER
+# pragma warning(disable : 4800)
+#endif
+
+#if !defined(XP_UNIX)
+// This condition must be kept in sync with the one in
+// ipc_message_utils.h, but this dummy definition of
+// base::FileDescriptor acts as a static assert that we only get one
+// def or the other (or neither, in which case code using
+// FileDescriptor fails to build)
+namespace base {
+struct FileDescriptor {};
+} // namespace base
+#endif
+
+namespace mozilla {
+template <typename...>
+class Variant;
+
+namespace detail {
+template <typename...>
+struct VariantTag;
+}
+} // namespace mozilla
+
+namespace IPC {
+
+/**
+ * A helper class for serializing plain-old data (POD) structures.
+ * The memory representation of the structure is written to and read from
+ * the serialized stream directly, without individual processing of the
+ * structure's members.
+ *
+ * Derive ParamTraits<T> from PlainOldDataSerializer<T> if T is POD.
+ *
+ * Note: For POD structures with enumeration fields, this will not do
+ * validation of the enum values the way serializing the fields
+ * individually would. Prefer serializing the fields individually
+ * in such cases.
+ */
+template <typename T>
+struct PlainOldDataSerializer {
+ static_assert(
+ std::is_trivially_copyable<T>::value,
+ "PlainOldDataSerializer can only be used with trivially copyable types!");
+
+ typedef T paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ aWriter->WriteBytes(&aParam, sizeof(aParam));
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return aReader->ReadBytesInto(aResult, sizeof(paramType));
+ }
+};
+
+/**
+ * A helper class for serializing empty structs. Since the struct is empty there
+ * is nothing to write, and a priori we know the result of the read.
+ */
+template <typename T>
+struct EmptyStructSerializer {
+ typedef T paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {}
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ *aResult = {};
+ return true;
+ }
+};
+
+template <>
+struct ParamTraits<int8_t> {
+ typedef int8_t paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ aWriter->WriteBytes(&aParam, sizeof(aParam));
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return aReader->ReadBytesInto(aResult, sizeof(*aResult));
+ }
+};
+
+template <>
+struct ParamTraits<uint8_t> {
+ typedef uint8_t paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ aWriter->WriteBytes(&aParam, sizeof(aParam));
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return aReader->ReadBytesInto(aResult, sizeof(*aResult));
+ }
+};
+
+#if !defined(XP_UNIX)
+// See above re: keeping definitions in sync
+template <>
+struct ParamTraits<base::FileDescriptor> {
+ typedef base::FileDescriptor paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ MOZ_CRASH("FileDescriptor isn't meaningful on this platform");
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ MOZ_CRASH("FileDescriptor isn't meaningful on this platform");
+ return false;
+ }
+};
+#endif // !defined(XP_UNIX)
+
+template <>
+struct ParamTraits<mozilla::void_t> {
+ typedef mozilla::void_t paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {}
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ *aResult = paramType();
+ return true;
+ }
+};
+
+template <>
+struct ParamTraits<mozilla::null_t> {
+ typedef mozilla::null_t paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {}
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ *aResult = paramType();
+ return true;
+ }
+};
+
+// Helper class for reading bitfields.
+// If T has bitfields members, derive ParamTraits<T> from BitfieldHelper<T>.
+template <typename ParamType>
+struct BitfieldHelper {
+ // We need this helper because we can't get the address of a bitfield to
+ // pass directly to ReadParam. So instead we read it into a temporary bool
+ // and set the bitfield using a setter function
+ static bool ReadBoolForBitfield(MessageReader* aReader, ParamType* aResult,
+ void (ParamType::*aSetter)(bool)) {
+ bool value;
+ if (ReadParam(aReader, &value)) {
+ (aResult->*aSetter)(value);
+ return true;
+ }
+ return false;
+ }
+};
+
+// A couple of recursive helper functions, allows syntax like:
+// WriteParams(aMsg, aParam.foo, aParam.bar, aParam.baz)
+// ReadParams(aMsg, aIter, aParam.foo, aParam.bar, aParam.baz)
+
+template <typename... Ts>
+static void WriteParams(MessageWriter* aWriter, const Ts&... aArgs) {
+ (WriteParam(aWriter, aArgs), ...);
+}
+
+template <typename... Ts>
+static bool ReadParams(MessageReader* aReader, Ts&... aArgs) {
+ return (ReadParam(aReader, &aArgs) && ...);
+}
+
+// Macros that allow syntax like:
+// DEFINE_IPC_SERIALIZER_WITH_FIELDS(SomeType, member1, member2, member3)
+// Makes sure that serialize/deserialize code do the same members in the same
+// order.
+#define ACCESS_PARAM_FIELD(Field) aParam.Field
+
+#define DEFINE_IPC_SERIALIZER_WITH_FIELDS(Type, ...) \
+ template <> \
+ struct ParamTraits<Type> { \
+ typedef Type paramType; \
+ static void Write(MessageWriter* aWriter, const paramType& aParam) { \
+ WriteParams(aWriter, MOZ_FOR_EACH_SEPARATED(ACCESS_PARAM_FIELD, (, ), \
+ (), (__VA_ARGS__))); \
+ } \
+ \
+ static bool Read(MessageReader* aReader, paramType* aResult) { \
+ paramType& aParam = *aResult; \
+ return ReadParams(aReader, \
+ MOZ_FOR_EACH_SEPARATED(ACCESS_PARAM_FIELD, (, ), (), \
+ (__VA_ARGS__))); \
+ } \
+ };
+
+#define DEFINE_IPC_SERIALIZER_WITHOUT_FIELDS(Type) \
+ template <> \
+ struct ParamTraits<Type> : public EmptyStructSerializer<Type> {};
+
+} /* namespace IPC */
+
+#define DEFINE_IPC_SERIALIZER_WITH_SUPER_CLASS_AND_FIELDS(Type, Super, ...) \
+ template <> \
+ struct ParamTraits<Type> { \
+ typedef Type paramType; \
+ static void Write(MessageWriter* aWriter, const paramType& aParam) { \
+ WriteParam(aWriter, static_cast<const Super&>(aParam)); \
+ WriteParams(aWriter, MOZ_FOR_EACH_SEPARATED(ACCESS_PARAM_FIELD, (, ), \
+ (), (__VA_ARGS__))); \
+ } \
+ \
+ static bool Read(MessageReader* aReader, paramType* aResult) { \
+ paramType& aParam = *aResult; \
+ return ReadParam(aReader, static_cast<Super*>(aResult)) && \
+ ReadParams(aReader, \
+ MOZ_FOR_EACH_SEPARATED(ACCESS_PARAM_FIELD, (, ), (), \
+ (__VA_ARGS__))); \
+ } \
+ };
+
+#endif /* __IPC_GLUE_IPCMESSAGEUTILS_H__ */
diff --git a/ipc/glue/IPCMessageUtilsSpecializations.cpp b/ipc/glue/IPCMessageUtilsSpecializations.cpp
new file mode 100644
index 0000000000..410b1e730f
--- /dev/null
+++ b/ipc/glue/IPCMessageUtilsSpecializations.cpp
@@ -0,0 +1,67 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "IPCMessageUtilsSpecializations.h"
+#include "nsGkAtoms.h"
+
+namespace IPC {
+
+static const uint16_t kDynamicAtomToken = 0xffff;
+static const uint16_t kAtomsCount =
+ static_cast<uint16_t>(mozilla::detail::GkAtoms::Atoms::AtomsCount);
+
+static_assert(static_cast<size_t>(
+ mozilla::detail::GkAtoms::Atoms::AtomsCount) == kAtomsCount,
+ "Number of static atoms must fit in a uint16_t");
+
+static_assert(kDynamicAtomToken >= kAtomsCount,
+ "Exceeded supported number of static atoms");
+
+/* static */
+void ParamTraits<nsAtom*>::Write(MessageWriter* aWriter, const nsAtom* aParam) {
+ MOZ_ASSERT(aParam);
+
+ if (aParam->IsStatic()) {
+ const nsStaticAtom* atom = aParam->AsStatic();
+ uint16_t index = static_cast<uint16_t>(nsGkAtoms::IndexOf(atom));
+ MOZ_ASSERT(index < kAtomsCount);
+ WriteParam(aWriter, index);
+ return;
+ }
+ WriteParam(aWriter, kDynamicAtomToken);
+ nsDependentAtomString atomStr(aParam);
+ // nsDependentAtomString is serialized as its base, nsString, but we
+ // can be explicit about it.
+ nsString& str = atomStr;
+ WriteParam(aWriter, str);
+}
+
+/* static */
+bool ParamTraits<nsAtom*>::Read(MessageReader* aReader,
+ RefPtr<nsAtom>* aResult) {
+ uint16_t token;
+ if (!ReadParam(aReader, &token)) {
+ return false;
+ }
+ if (token != kDynamicAtomToken) {
+ if (token >= kAtomsCount) {
+ return false;
+ }
+ *aResult = nsGkAtoms::GetAtomByIndex(token);
+ return true;
+ }
+
+ nsAutoString str;
+ if (!ReadParam(aReader, static_cast<nsString*>(&str))) {
+ return false;
+ }
+
+ *aResult = NS_Atomize(str);
+ MOZ_ASSERT(*aResult);
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/glue/IPCMessageUtilsSpecializations.h b/ipc/glue/IPCMessageUtilsSpecializations.h
new file mode 100644
index 0000000000..e9742c5c74
--- /dev/null
+++ b/ipc/glue/IPCMessageUtilsSpecializations.h
@@ -0,0 +1,841 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H__
+#define __IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H__
+
+#include <cstdint>
+#include <cstdlib>
+#include <limits>
+#include <string>
+#include <type_traits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "ipc/EnumSerializer.h"
+#include "ipc/IPCMessageUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/BitSet.h"
+#include "mozilla/EnumSet.h"
+#include "mozilla/EnumTypeTraits.h"
+#include "mozilla/IntegerRange.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/TimeStamp.h"
+#ifdef XP_WIN
+# include "mozilla/TimeStamp_windows.h"
+#endif
+
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Unused.h"
+#include "mozilla/Vector.h"
+#include "mozilla/dom/ipc/StructuredCloneData.h"
+#include "mozilla/dom/UserActivation.h"
+#include "nsCSSPropertyID.h"
+#include "nsDebug.h"
+#include "nsIContentPolicy.h"
+#include "nsID.h"
+#include "nsILoadInfo.h"
+#include "nsIThread.h"
+#include "nsLiteralString.h"
+#include "nsNetUtil.h"
+#include "nsString.h"
+#include "nsTArray.h"
+#include "nsTHashSet.h"
+
+// XXX Includes that are only required by implementations which could be moved
+// to the cpp file.
+#include "base/string_util.h" // for StringPrintf
+#include "mozilla/ArrayUtils.h" // for ArrayLength
+#include "mozilla/CheckedInt.h"
+
+#ifdef _MSC_VER
+# pragma warning(disable : 4800)
+#endif
+
+namespace mozilla {
+template <typename... Ts>
+class Variant;
+
+namespace detail {
+template <typename... Ts>
+struct VariantTag;
+}
+} // namespace mozilla
+
+namespace mozilla::dom {
+template <typename T>
+class Optional;
+}
+
+class nsAtom;
+
+namespace IPC {
+
+template <class T>
+struct ParamTraits<nsTSubstring<T>> {
+ typedef nsTSubstring<T> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ bool isVoid = aParam.IsVoid();
+ aWriter->WriteBool(isVoid);
+
+ if (isVoid) {
+ // represents a nullptr pointer
+ return;
+ }
+
+ WriteSequenceParam<const T&>(aWriter, aParam.BeginReading(),
+ aParam.Length());
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ bool isVoid;
+ if (!aReader->ReadBool(&isVoid)) {
+ return false;
+ }
+
+ if (isVoid) {
+ aResult->SetIsVoid(true);
+ return true;
+ }
+
+ return ReadSequenceParam<T>(aReader, [&](uint32_t aLength) -> T* {
+ T* data = nullptr;
+ aResult->GetMutableData(&data, aLength);
+ return data;
+ });
+ }
+};
+
+template <class T>
+struct ParamTraits<nsTString<T>> : ParamTraits<nsTSubstring<T>> {};
+
+template <class T>
+struct ParamTraits<nsTLiteralString<T>> : ParamTraits<nsTSubstring<T>> {};
+
+template <class T, size_t N>
+struct ParamTraits<nsTAutoStringN<T, N>> : ParamTraits<nsTSubstring<T>> {};
+
+template <class T>
+struct ParamTraits<nsTDependentString<T>> : ParamTraits<nsTSubstring<T>> {};
+
+// XXX While this has no special dependencies, it's currently only used in
+// GfxMessageUtils and could be moved there, or generalized to potentially work
+// with any nsTHashSet.
+template <>
+struct ParamTraits<nsTHashSet<uint64_t>> {
+ typedef nsTHashSet<uint64_t> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ uint32_t count = aParam.Count();
+ WriteParam(aWriter, count);
+ for (const auto& key : aParam) {
+ WriteParam(aWriter, key);
+ }
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ uint32_t count;
+ if (!ReadParam(aReader, &count)) {
+ return false;
+ }
+ paramType table(count);
+ for (uint32_t i = 0; i < count; ++i) {
+ uint64_t key;
+ if (!ReadParam(aReader, &key)) {
+ return false;
+ }
+ table.Insert(key);
+ }
+ *aResult = std::move(table);
+ return true;
+ }
+};
+
+template <typename E>
+struct ParamTraits<nsTArray<E>> {
+ typedef nsTArray<E> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) {
+ if constexpr (std::is_trivially_default_constructible_v<E>) {
+ return aResult->AppendElements(aLength);
+ } else {
+ aResult->SetCapacity(aLength);
+ return mozilla::Some(MakeBackInserter(*aResult));
+ }
+ });
+ }
+};
+
+template <typename E>
+struct ParamTraits<CopyableTArray<E>> : ParamTraits<nsTArray<E>> {};
+
+template <typename E>
+struct ParamTraits<FallibleTArray<E>> {
+ typedef FallibleTArray<E> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) {
+ if constexpr (std::is_trivially_default_constructible_v<E>) {
+ return aResult->AppendElements(aLength, mozilla::fallible);
+ } else {
+ if (!aResult->SetCapacity(aLength, mozilla::fallible)) {
+ return mozilla::Maybe<BackInserter>{};
+ }
+ return mozilla::Some(BackInserter{.mArray = aResult});
+ }
+ });
+ }
+
+ private:
+ struct BackInserter {
+ using iterator_category = std::output_iterator_tag;
+ using value_type = void;
+ using difference_type = void;
+ using pointer = void;
+ using reference = void;
+
+ struct Proxy {
+ paramType& mArray;
+
+ template <typename U>
+ void operator=(U&& aValue) {
+ // This won't fail because we've reserved capacity earlier.
+ MOZ_ALWAYS_TRUE(mArray.AppendElement(aValue, mozilla::fallible));
+ }
+ };
+ Proxy operator*() { return Proxy{.mArray = *mArray}; }
+
+ BackInserter& operator++() { return *this; }
+ BackInserter& operator++(int) { return *this; }
+
+ paramType* mArray = nullptr;
+ };
+};
+
+template <typename E, size_t N>
+struct ParamTraits<AutoTArray<E, N>> : ParamTraits<nsTArray<E>> {
+ typedef AutoTArray<E, N> paramType;
+};
+
+template <typename E, size_t N>
+struct ParamTraits<CopyableAutoTArray<E, N>> : ParamTraits<AutoTArray<E, N>> {};
+
+template <typename T>
+struct ParamTraits<mozilla::dom::Sequence<T>> : ParamTraits<FallibleTArray<T>> {
+};
+
+template <typename E, size_t N, typename AP>
+struct ParamTraits<mozilla::Vector<E, N, AP>> {
+ typedef mozilla::Vector<E, N, AP> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteSequenceParam<const E&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ WriteSequenceParam<E&&>(aWriter, aParam.Elements(), aParam.Length());
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) -> E* {
+ if (!aResult->resize(aLength)) {
+ // So that OOM failure shows up as OOM crash instead of IPC FatalError.
+ NS_ABORT_OOM(aLength * sizeof(E));
+ }
+ return aResult->begin();
+ });
+ }
+};
+
+template <typename E>
+struct ParamTraits<std::vector<E>> {
+ typedef std::vector<E> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteSequenceParam<const E&>(aWriter, aParam.data(), aParam.size());
+ }
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ WriteSequenceParam<E&&>(aWriter, aParam.data(), aParam.size());
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadSequenceParam<E>(aReader, [&](uint32_t aLength) {
+ if constexpr (std::is_trivially_default_constructible_v<E>) {
+ aResult->resize(aLength);
+ return aResult->data();
+ } else {
+ aResult->reserve(aLength);
+ return mozilla::Some(std::back_inserter(*aResult));
+ }
+ });
+ }
+};
+
+template <typename K, typename V>
+struct ParamTraits<std::unordered_map<K, V>> final {
+ using T = std::unordered_map<K, V>;
+
+ static void Write(MessageWriter* const writer, const T& in) {
+ WriteParam(writer, in.size());
+ for (const auto& pair : in) {
+ WriteParam(writer, pair.first);
+ WriteParam(writer, pair.second);
+ }
+ }
+
+ static bool Read(MessageReader* const reader, T* const out) {
+ size_t size = 0;
+ if (!ReadParam(reader, &size)) return false;
+ T map;
+ map.reserve(size);
+ for (const auto i : mozilla::IntegerRange(size)) {
+ std::pair<K, V> pair;
+ mozilla::Unused << i;
+ if (!ReadParam(reader, &(pair.first)) ||
+ !ReadParam(reader, &(pair.second))) {
+ return false;
+ }
+ map.insert(std::move(pair));
+ }
+ *out = std::move(map);
+ return true;
+ }
+};
+
+template <>
+struct ParamTraits<float> {
+ typedef float paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ aWriter->WriteBytes(&aParam, sizeof(paramType));
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return aReader->ReadBytesInto(aResult, sizeof(*aResult));
+ }
+};
+
+template <>
+struct ParamTraits<nsCSSPropertyID>
+ : public ContiguousEnumSerializer<nsCSSPropertyID, eCSSProperty_UNKNOWN,
+ eCSSProperty_COUNT> {};
+
+template <>
+struct ParamTraits<nsID> {
+ typedef nsID paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.m0);
+ WriteParam(aWriter, aParam.m1);
+ WriteParam(aWriter, aParam.m2);
+ for (unsigned int i = 0; i < mozilla::ArrayLength(aParam.m3); i++) {
+ WriteParam(aWriter, aParam.m3[i]);
+ }
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ if (!ReadParam(aReader, &(aResult->m0)) ||
+ !ReadParam(aReader, &(aResult->m1)) ||
+ !ReadParam(aReader, &(aResult->m2)))
+ return false;
+
+ for (unsigned int i = 0; i < mozilla::ArrayLength(aResult->m3); i++)
+ if (!ReadParam(aReader, &(aResult->m3[i]))) return false;
+
+ return true;
+ }
+};
+
+template <>
+struct ParamTraits<nsContentPolicyType>
+ : public ContiguousEnumSerializer<nsContentPolicyType,
+ nsIContentPolicy::TYPE_INVALID,
+ nsIContentPolicy::TYPE_END> {};
+
+template <>
+struct ParamTraits<mozilla::TimeDuration> {
+ typedef mozilla::TimeDuration paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.mValue);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadParam(aReader, &aResult->mValue);
+ };
+};
+
+template <>
+struct ParamTraits<mozilla::TimeStamp> {
+ typedef mozilla::TimeStamp paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.mValue);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadParam(aReader, &aResult->mValue);
+ };
+};
+
+#ifdef XP_WIN
+
+template <>
+struct ParamTraits<mozilla::TimeStampValue> {
+ typedef mozilla::TimeStampValue paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.mGTC);
+ WriteParam(aWriter, aParam.mQPC);
+ WriteParam(aWriter, aParam.mIsNull);
+ WriteParam(aWriter, aParam.mHasQPC);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return (ReadParam(aReader, &aResult->mGTC) &&
+ ReadParam(aReader, &aResult->mQPC) &&
+ ReadParam(aReader, &aResult->mIsNull) &&
+ ReadParam(aReader, &aResult->mHasQPC));
+ }
+};
+
+#endif
+
+template <>
+struct ParamTraits<mozilla::dom::ipc::StructuredCloneData> {
+ typedef mozilla::dom::ipc::StructuredCloneData paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ aParam.WriteIPCParams(aWriter);
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return aResult->ReadIPCParams(aReader);
+ }
+};
+
+template <class T>
+struct ParamTraits<mozilla::Maybe<T>> {
+ typedef mozilla::Maybe<T> paramType;
+
+ static void Write(MessageWriter* writer, const paramType& param) {
+ if (param.isSome()) {
+ WriteParam(writer, true);
+ WriteParam(writer, param.ref());
+ } else {
+ WriteParam(writer, false);
+ }
+ }
+
+ static void Write(MessageWriter* writer, paramType&& param) {
+ if (param.isSome()) {
+ WriteParam(writer, true);
+ WriteParam(writer, std::move(param.ref()));
+ } else {
+ WriteParam(writer, false);
+ }
+ }
+
+ static bool Read(MessageReader* reader, paramType* result) {
+ bool isSome;
+ if (!ReadParam(reader, &isSome)) {
+ return false;
+ }
+ if (isSome) {
+ mozilla::Maybe<T> tmp = ReadParam<T>(reader).TakeMaybe();
+ if (!tmp) {
+ return false;
+ }
+ *result = std::move(tmp);
+ } else {
+ *result = mozilla::Nothing();
+ }
+ return true;
+ }
+};
+
+template <typename T, typename U>
+struct ParamTraits<mozilla::EnumSet<T, U>> {
+ typedef mozilla::EnumSet<T, U> paramType;
+ typedef U serializedType;
+
+ static void Write(MessageWriter* writer, const paramType& param) {
+ MOZ_RELEASE_ASSERT(IsLegalValue(param.serialize()));
+ WriteParam(writer, param.serialize());
+ }
+
+ static bool Read(MessageReader* reader, paramType* result) {
+ serializedType tmp;
+
+ if (ReadParam(reader, &tmp)) {
+ if (IsLegalValue(tmp)) {
+ result->deserialize(tmp);
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ static constexpr serializedType AllEnumBits() {
+ return ~serializedType(0) >> (std::numeric_limits<serializedType>::digits -
+ (mozilla::MaxEnumValue<T>::value + 1));
+ }
+
+ static constexpr bool IsLegalValue(const serializedType value) {
+ static_assert(mozilla::MaxEnumValue<T>::value <
+ std::numeric_limits<serializedType>::digits,
+ "Enum max value is not in the range!");
+ static_assert(
+ std::is_unsigned<decltype(mozilla::MaxEnumValue<T>::value)>::value,
+ "Type of MaxEnumValue<T>::value specialization should be unsigned!");
+
+ return (value & AllEnumBits()) == value;
+ }
+};
+
+template <class... Ts>
+struct ParamTraits<mozilla::Variant<Ts...>> {
+ typedef mozilla::Variant<Ts...> paramType;
+ using Tag = typename mozilla::detail::VariantTag<Ts...>::Type;
+
+ static void Write(MessageWriter* writer, const paramType& param) {
+ WriteParam(writer, param.tag);
+ param.match([writer](const auto& t) { WriteParam(writer, t); });
+ }
+
+ // Because VariantReader is a nested struct, we need the dummy template
+ // parameter to avoid making VariantReader<0> an explicit specialization,
+ // which is not allowed for a nested class template
+ template <size_t N, typename dummy = void>
+ struct VariantReader {
+ using Next = VariantReader<N - 1>;
+
+ static bool Read(MessageReader* reader, Tag tag, paramType* result) {
+ // Since the VariantReader specializations start at N , we need to
+ // subtract one to look at N - 1, the first valid tag. This means our
+ // comparisons are off by 1. If we get to N = 0 then we have failed to
+ // find a match to the tag.
+ if (tag == N - 1) {
+ // Recall, even though the template parameter is N, we are
+ // actually interested in the N - 1 tag.
+ // Default construct our field within the result outparameter and
+ // directly deserialize into the variant. Note that this means that
+ // every type in Ts needs to be default constructible
+ return ReadParam(reader, &result->template emplace<N - 1>());
+ } else {
+ return Next::Read(reader, tag, result);
+ }
+ }
+
+ }; // VariantReader<N>
+
+ // Since we are conditioning on tag = N - 1 in the preceding specialization,
+ // if we get to `VariantReader<0, dummy>` we have failed to find
+ // a matching tag.
+ template <typename dummy>
+ struct VariantReader<0, dummy> {
+ static bool Read(MessageReader* reader, Tag tag, paramType* result) {
+ return false;
+ }
+ };
+
+ static bool Read(MessageReader* reader, paramType* result) {
+ Tag tag;
+ if (ReadParam(reader, &tag)) {
+ return VariantReader<sizeof...(Ts)>::Read(reader, tag, result);
+ }
+ return false;
+ }
+};
+
+template <typename T>
+struct ParamTraits<mozilla::dom::Optional<T>> {
+ typedef mozilla::dom::Optional<T> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ if (aParam.WasPassed()) {
+ WriteParam(aWriter, true);
+ WriteParam(aWriter, aParam.Value());
+ return;
+ }
+
+ WriteParam(aWriter, false);
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ bool wasPassed = false;
+
+ if (!ReadParam(aReader, &wasPassed)) {
+ return false;
+ }
+
+ aResult->Reset();
+
+ if (wasPassed) {
+ if (!ReadParam(aReader, &aResult->Construct())) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+};
+
+template <>
+struct ParamTraits<nsAtom*> {
+ typedef nsAtom paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType* aParam);
+ static bool Read(MessageReader* aReader, RefPtr<paramType>* aResult);
+};
+
+struct CrossOriginOpenerPolicyValidator {
+ using IntegralType =
+ std::underlying_type_t<nsILoadInfo::CrossOriginOpenerPolicy>;
+
+ static bool IsLegalValue(const IntegralType e) {
+ return AreIntegralValuesEqual(e, nsILoadInfo::OPENER_POLICY_UNSAFE_NONE) ||
+ AreIntegralValuesEqual(e, nsILoadInfo::OPENER_POLICY_SAME_ORIGIN) ||
+ AreIntegralValuesEqual(
+ e, nsILoadInfo::OPENER_POLICY_SAME_ORIGIN_ALLOW_POPUPS) ||
+ AreIntegralValuesEqual(
+ e, nsILoadInfo::
+ OPENER_POLICY_SAME_ORIGIN_EMBEDDER_POLICY_REQUIRE_CORP);
+ }
+
+ private:
+ static bool AreIntegralValuesEqual(
+ const IntegralType aLhs,
+ const nsILoadInfo::CrossOriginOpenerPolicy aRhs) {
+ return aLhs == static_cast<IntegralType>(aRhs);
+ }
+};
+
+template <>
+struct ParamTraits<nsILoadInfo::CrossOriginOpenerPolicy>
+ : EnumSerializer<nsILoadInfo::CrossOriginOpenerPolicy,
+ CrossOriginOpenerPolicyValidator> {};
+
+struct CrossOriginEmbedderPolicyValidator {
+ using IntegralType =
+ std::underlying_type_t<nsILoadInfo::CrossOriginEmbedderPolicy>;
+
+ static bool IsLegalValue(const IntegralType e) {
+ return AreIntegralValuesEqual(e, nsILoadInfo::EMBEDDER_POLICY_NULL) ||
+ AreIntegralValuesEqual(e,
+ nsILoadInfo::EMBEDDER_POLICY_REQUIRE_CORP) ||
+ AreIntegralValuesEqual(e,
+ nsILoadInfo::EMBEDDER_POLICY_CREDENTIALLESS);
+ }
+
+ private:
+ static bool AreIntegralValuesEqual(
+ const IntegralType aLhs,
+ const nsILoadInfo::CrossOriginEmbedderPolicy aRhs) {
+ return aLhs == static_cast<IntegralType>(aRhs);
+ }
+};
+
+template <>
+struct ParamTraits<nsILoadInfo::CrossOriginEmbedderPolicy>
+ : EnumSerializer<nsILoadInfo::CrossOriginEmbedderPolicy,
+ CrossOriginEmbedderPolicyValidator> {};
+
+template <>
+struct ParamTraits<nsIThread::QoSPriority>
+ : public ContiguousEnumSerializerInclusive<nsIThread::QoSPriority,
+ nsIThread::QOS_PRIORITY_NORMAL,
+ nsIThread::QOS_PRIORITY_LOW> {};
+
+template <size_t N, typename Word>
+struct ParamTraits<mozilla::BitSet<N, Word>> {
+ typedef mozilla::BitSet<N, Word> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ for (Word word : aParam.Storage()) {
+ WriteParam(aWriter, word);
+ }
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ for (Word& word : aResult->Storage()) {
+ if (!ReadParam(aReader, &word)) {
+ return false;
+ }
+ }
+ return true;
+ }
+};
+
+template <typename T>
+struct ParamTraits<mozilla::UniquePtr<T>> {
+ typedef mozilla::UniquePtr<T> paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ bool isNull = aParam == nullptr;
+ WriteParam(aWriter, isNull);
+
+ if (!isNull) {
+ WriteParam(aWriter, *aParam.get());
+ }
+ }
+
+ static bool Read(IPC::MessageReader* aReader, paramType* aResult) {
+ bool isNull = true;
+ if (!ReadParam(aReader, &isNull)) {
+ return false;
+ }
+
+ if (isNull) {
+ aResult->reset();
+ } else {
+ *aResult = mozilla::MakeUnique<T>();
+ if (!ReadParam(aReader, aResult->get())) {
+ return false;
+ }
+ }
+ return true;
+ }
+};
+
+template <typename... Ts>
+struct ParamTraits<std::tuple<Ts...>> {
+ typedef std::tuple<Ts...> paramType;
+
+ template <typename U>
+ static void Write(IPC::MessageWriter* aWriter, U&& aParam) {
+ WriteInternal(aWriter, std::forward<U>(aParam),
+ std::index_sequence_for<Ts...>{});
+ }
+
+ static bool Read(IPC::MessageReader* aReader, std::tuple<Ts...>* aResult) {
+ return ReadInternal(aReader, *aResult, std::index_sequence_for<Ts...>{});
+ }
+
+ private:
+ template <size_t... Is>
+ static void WriteInternal(IPC::MessageWriter* aWriter,
+ const std::tuple<Ts...>& aParam,
+ std::index_sequence<Is...>) {
+ WriteParams(aWriter, std::get<Is>(aParam)...);
+ }
+
+ template <size_t... Is>
+ static void WriteInternal(IPC::MessageWriter* aWriter,
+ std::tuple<Ts...>&& aParam,
+ std::index_sequence<Is...>) {
+ WriteParams(aWriter, std::move(std::get<Is>(aParam))...);
+ }
+
+ template <size_t... Is>
+ static bool ReadInternal(IPC::MessageReader* aReader,
+ std::tuple<Ts...>& aResult,
+ std::index_sequence<Is...>) {
+ return ReadParams(aReader, std::get<Is>(aResult)...);
+ }
+};
+
+template <>
+struct ParamTraits<mozilla::net::LinkHeader> {
+ typedef mozilla::net::LinkHeader paramType;
+ constexpr static int kNumberOfMembers = 14;
+ constexpr static int kSizeOfEachMember = sizeof(nsString);
+ constexpr static int kExpectedSizeOfParamType =
+ kNumberOfMembers * kSizeOfEachMember;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ static_assert(sizeof(paramType) == kExpectedSizeOfParamType,
+ "All members of should be written below.");
+ // Bug 1860565: `aParam.mAnchor` is not written.
+
+ WriteParam(aWriter, aParam.mHref);
+ WriteParam(aWriter, aParam.mRel);
+ WriteParam(aWriter, aParam.mTitle);
+ WriteParam(aWriter, aParam.mNonce);
+ WriteParam(aWriter, aParam.mIntegrity);
+ WriteParam(aWriter, aParam.mSrcset);
+ WriteParam(aWriter, aParam.mSizes);
+ WriteParam(aWriter, aParam.mType);
+ WriteParam(aWriter, aParam.mMedia);
+ WriteParam(aWriter, aParam.mCrossOrigin);
+ WriteParam(aWriter, aParam.mReferrerPolicy);
+ WriteParam(aWriter, aParam.mAs);
+ WriteParam(aWriter, aParam.mFetchPriority);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ static_assert(sizeof(paramType) == kExpectedSizeOfParamType,
+ "All members of should be handled below.");
+ // Bug 1860565: `aParam.mAnchor` is not handled.
+
+ if (!ReadParam(aReader, &aResult->mHref)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mRel)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mTitle)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mNonce)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mIntegrity)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mSrcset)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mSizes)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mType)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mMedia)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mCrossOrigin)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mReferrerPolicy)) {
+ return false;
+ }
+ if (!ReadParam(aReader, &aResult->mAs)) {
+ return false;
+ }
+ return ReadParam(aReader, &aResult->mFetchPriority);
+ };
+};
+
+template <>
+struct ParamTraits<mozilla::dom::UserActivation::Modifiers> {
+ typedef mozilla::dom::UserActivation::Modifiers paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.mModifiers);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadParam(aReader, &aResult->mModifiers);
+ };
+};
+
+} /* namespace IPC */
+
+#endif /* __IPC_GLUE_IPCMESSAGEUTILSSPECIALIZATIONS_H__ */
diff --git a/ipc/glue/IPCStream.ipdlh b/ipc/glue/IPCStream.ipdlh
new file mode 100644
index 0000000000..abf7ef7714
--- /dev/null
+++ b/ipc/glue/IPCStream.ipdlh
@@ -0,0 +1,22 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include InputStreamParams;
+include ProtocolTypes;
+
+namespace mozilla {
+namespace ipc {
+
+// Use IPCStream in your ipdl to represent serialized nsIInputStreams. Then use
+// SerializeIPCStream from IPCStreamUtils.h to perform the serialization.
+//
+// NOTE: If you don't need to handle nsIInputStream serialization failure,
+// `nsIInputStream` may be used directly by IPDL protocols.
+struct IPCStream
+{
+ InputStreamParams stream;
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/IPCStreamUtils.cpp b/ipc/glue/IPCStreamUtils.cpp
new file mode 100644
index 0000000000..b884bf5d5d
--- /dev/null
+++ b/ipc/glue/IPCStreamUtils.cpp
@@ -0,0 +1,191 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "IPCStreamUtils.h"
+
+#include "ipc/IPCMessageUtilsSpecializations.h"
+
+#include "nsIHttpHeaderVisitor.h"
+#include "nsIIPCSerializableInputStream.h"
+#include "mozIRemoteLazyInputStream.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/dom/File.h"
+#include "mozilla/ipc/IPCStream.h"
+#include "mozilla/ipc/InputStreamUtils.h"
+#include "mozilla/InputStreamLengthHelper.h"
+#include "mozilla/RemoteLazyInputStreamParent.h"
+#include "mozilla/Unused.h"
+#include "nsIMIMEInputStream.h"
+#include "nsNetCID.h"
+
+using namespace mozilla::dom;
+
+namespace mozilla::ipc {
+
+namespace {
+
+class MIMEStreamHeaderVisitor final : public nsIHttpHeaderVisitor {
+ public:
+ explicit MIMEStreamHeaderVisitor(
+ nsTArray<mozilla::ipc::HeaderEntry>& aHeaders)
+ : mHeaders(aHeaders) {}
+
+ NS_DECL_ISUPPORTS
+ NS_IMETHOD VisitHeader(const nsACString& aName,
+ const nsACString& aValue) override {
+ auto el = mHeaders.AppendElement();
+ el->name() = aName;
+ el->value() = aValue;
+ return NS_OK;
+ }
+
+ private:
+ ~MIMEStreamHeaderVisitor() = default;
+
+ nsTArray<mozilla::ipc::HeaderEntry>& mHeaders;
+};
+
+NS_IMPL_ISUPPORTS(MIMEStreamHeaderVisitor, nsIHttpHeaderVisitor)
+
+static bool SerializeLazyInputStream(nsIInputStream* aStream,
+ IPCStream& aValue) {
+ MOZ_ASSERT(aStream);
+ MOZ_ASSERT(XRE_IsParentProcess());
+
+ // If we're serializing a MIME stream, ensure we preserve header data which
+ // would not be preserved by a RemoteLazyInputStream wrapper.
+ if (nsCOMPtr<nsIMIMEInputStream> mimeStream = do_QueryInterface(aStream)) {
+ MIMEInputStreamParams params;
+ params.startedReading() = false;
+
+ nsCOMPtr<nsIHttpHeaderVisitor> visitor =
+ new MIMEStreamHeaderVisitor(params.headers());
+ if (NS_WARN_IF(NS_FAILED(mimeStream->VisitHeaders(visitor)))) {
+ return false;
+ }
+
+ nsCOMPtr<nsIInputStream> dataStream;
+ if (NS_FAILED(mimeStream->GetData(getter_AddRefs(dataStream)))) {
+ return false;
+ }
+ if (dataStream) {
+ IPCStream data;
+ if (!SerializeLazyInputStream(dataStream, data)) {
+ return false;
+ }
+ params.optionalStream().emplace(std::move(data.stream()));
+ }
+
+ aValue.stream() = std::move(params);
+ return true;
+ }
+
+ RefPtr<RemoteLazyInputStream> lazyStream =
+ RemoteLazyInputStream::WrapStream(aStream);
+ if (NS_WARN_IF(!lazyStream)) {
+ return false;
+ }
+
+ aValue.stream() = RemoteLazyInputStreamParams(WrapNotNull(lazyStream));
+
+ return true;
+}
+
+} // anonymous namespace
+
+bool SerializeIPCStream(already_AddRefed<nsIInputStream> aInputStream,
+ IPCStream& aValue, bool aAllowLazy) {
+ nsCOMPtr<nsIInputStream> stream(std::move(aInputStream));
+ if (!stream) {
+ MOZ_ASSERT_UNREACHABLE(
+ "Use the Maybe<...> overload to serialize optional nsIInputStreams");
+ return false;
+ }
+
+ // When requesting a delayed start stream from the parent process, serialize
+ // it as a remote lazy stream to avoid bloating payloads.
+ if (aAllowLazy && XRE_IsParentProcess()) {
+ return SerializeLazyInputStream(stream, aValue);
+ }
+
+ if (nsCOMPtr<nsIIPCSerializableInputStream> serializable =
+ do_QueryInterface(stream)) {
+ // If you change this size, please also update the payload size in
+ // test_reload_large_postdata.html.
+ const uint64_t kTooLargeStream = 1024 * 1024;
+
+ uint32_t sizeUsed = 0;
+ serializable->Serialize(aValue.stream(), kTooLargeStream, &sizeUsed);
+
+ MOZ_ASSERT(sizeUsed <= kTooLargeStream);
+
+ if (aValue.stream().type() == InputStreamParams::T__None) {
+ MOZ_CRASH("Serialize failed!");
+ }
+ return true;
+ }
+
+ InputStreamHelper::SerializeInputStreamAsPipe(stream, aValue.stream());
+ if (aValue.stream().type() == InputStreamParams::T__None) {
+ MOZ_ASSERT_UNREACHABLE("Serializing as a pipe failed");
+ return false;
+ }
+ return true;
+}
+
+bool SerializeIPCStream(already_AddRefed<nsIInputStream> aInputStream,
+ Maybe<IPCStream>& aValue, bool aAllowLazy) {
+ nsCOMPtr<nsIInputStream> stream(std::move(aInputStream));
+ if (!stream) {
+ aValue.reset();
+ return true;
+ }
+
+ IPCStream value;
+ if (SerializeIPCStream(stream.forget(), value, aAllowLazy)) {
+ aValue = Some(value);
+ return true;
+ }
+ return false;
+}
+
+already_AddRefed<nsIInputStream> DeserializeIPCStream(const IPCStream& aValue) {
+ return InputStreamHelper::DeserializeInputStream(aValue.stream());
+}
+
+already_AddRefed<nsIInputStream> DeserializeIPCStream(
+ const Maybe<IPCStream>& aValue) {
+ if (aValue.isNothing()) {
+ return nullptr;
+ }
+
+ return DeserializeIPCStream(aValue.ref());
+}
+
+} // namespace mozilla::ipc
+
+void IPC::ParamTraits<nsIInputStream*>::Write(IPC::MessageWriter* aWriter,
+ nsIInputStream* aParam) {
+ mozilla::Maybe<mozilla::ipc::IPCStream> stream;
+ if (!mozilla::ipc::SerializeIPCStream(do_AddRef(aParam), stream,
+ /* aAllowLazy */ true)) {
+ MOZ_CRASH("Failed to serialize nsIInputStream");
+ }
+
+ WriteParam(aWriter, stream);
+}
+
+bool IPC::ParamTraits<nsIInputStream*>::Read(IPC::MessageReader* aReader,
+ RefPtr<nsIInputStream>* aResult) {
+ mozilla::Maybe<mozilla::ipc::IPCStream> ipcStream;
+ if (!ReadParam(aReader, &ipcStream)) {
+ return false;
+ }
+
+ *aResult = mozilla::ipc::DeserializeIPCStream(ipcStream);
+ return true;
+}
diff --git a/ipc/glue/IPCStreamUtils.h b/ipc/glue/IPCStreamUtils.h
new file mode 100644
index 0000000000..c681f7cf1a
--- /dev/null
+++ b/ipc/glue/IPCStreamUtils.h
@@ -0,0 +1,51 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IPCStreamUtils_h
+#define mozilla_ipc_IPCStreamUtils_h
+
+#include "mozilla/ipc/IPCStream.h"
+#include "nsCOMPtr.h"
+#include "nsIInputStream.h"
+
+namespace mozilla::ipc {
+
+// Serialize an IPCStream to be sent over IPC fallibly.
+//
+// If |aAllowLazy| is true the stream may be serialized as a
+// RemoteLazyInputStream when being sent from child to parent.
+//
+// ParamTraits<nsIInputStream> may be used instead if serialization cannot be
+// fallible.
+[[nodiscard]] bool SerializeIPCStream(
+ already_AddRefed<nsIInputStream> aInputStream, IPCStream& aValue,
+ bool aAllowLazy);
+
+// If serialization fails, `aValue` will be initialized to `Nothing()`, so this
+// return value is safe to ignore.
+bool SerializeIPCStream(already_AddRefed<nsIInputStream> aInputStream,
+ Maybe<IPCStream>& aValue, bool aAllowLazy);
+
+// Deserialize an IPCStream received from an actor call. These methods
+// work in both the child and parent.
+already_AddRefed<nsIInputStream> DeserializeIPCStream(const IPCStream& aValue);
+
+already_AddRefed<nsIInputStream> DeserializeIPCStream(
+ const Maybe<IPCStream>& aValue);
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+template <>
+struct ParamTraits<nsIInputStream*> {
+ static void Write(MessageWriter* aWriter, nsIInputStream* aParam);
+ static bool Read(MessageReader* aReader, RefPtr<nsIInputStream>* aResult);
+};
+
+} // namespace IPC
+
+#endif // mozilla_ipc_IPCStreamUtils_h
diff --git a/ipc/glue/IPCTypes.h b/ipc/glue/IPCTypes.h
new file mode 100644
index 0000000000..fc6bf765e2
--- /dev/null
+++ b/ipc/glue/IPCTypes.h
@@ -0,0 +1,20 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef IPC_GLUE_IPCTYPES_H_
+#define IPC_GLUE_IPCTYPES_H_
+
+#include <cstdint>
+
+namespace mozilla {
+
+// This is a cross-platform approximation to HANDLE, which we expect
+// to be typedef'd to void* or thereabouts.
+typedef uintptr_t WindowsHandle;
+
+} // namespace mozilla
+
+#endif // IPC_GLUE_IPCTYPES_H_
diff --git a/ipc/glue/IPDLParamTraits.h b/ipc/glue/IPDLParamTraits.h
new file mode 100644
index 0000000000..48649d92de
--- /dev/null
+++ b/ipc/glue/IPDLParamTraits.h
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IPDLParamTraits_h
+#define mozilla_ipc_IPDLParamTraits_h
+
+#include "chrome/common/ipc_message_utils.h"
+#include "ipc/IPCMessageUtilsSpecializations.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Variant.h"
+
+#include "nsTArray.h"
+
+#include <type_traits>
+
+namespace mozilla {
+namespace ipc {
+
+class IProtocol;
+
+//
+// IPDLParamTraits was an extended version of ParamTraits. Unlike ParamTraits,
+// IPDLParamTraits passes an additional IProtocol* argument to the
+// write and read methods.
+//
+// Previously this was required for serializing and deserializing types which
+// require knowledge of which protocol they're being sent over, however the
+// actor is now available through `IPC::Message{Writer,Reader}::GetActor()` so
+// the extra argument is no longer necessary. Please use `IPC::ParamTraits` in
+// the future.
+//
+// Types which implement IPDLParamTraits are also supported by ParamTraits.
+//
+template <typename P>
+struct IPDLParamTraits {};
+
+//
+// WriteIPDLParam and ReadIPDLParam are like IPC::WriteParam and IPC::ReadParam,
+// however, they also accept a redundant extra actor argument.
+//
+// NOTE: WriteIPDLParam takes a universal reference, so that it can support
+// whatever reference type is supported by the underlying ParamTraits::Write
+// implementation.
+//
+template <typename P>
+static MOZ_NEVER_INLINE void WriteIPDLParam(IPC::MessageWriter* aWriter,
+ IProtocol* aActor, P&& aParam) {
+ MOZ_ASSERT(aActor == aWriter->GetActor());
+ IPC::WriteParam(aWriter, std::forward<P>(aParam));
+}
+
+template <typename P>
+static MOZ_NEVER_INLINE bool ReadIPDLParam(IPC::MessageReader* aReader,
+ IProtocol* aActor, P* aResult) {
+ MOZ_ASSERT(aActor == aReader->GetActor());
+ return IPC::ReadParam(aReader, aResult);
+}
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // defined(mozilla_ipc_IPDLParamTraits_h)
diff --git a/ipc/glue/IPDLStructMember.h b/ipc/glue/IPDLStructMember.h
new file mode 100644
index 0000000000..d2e3636054
--- /dev/null
+++ b/ipc/glue/IPDLStructMember.h
@@ -0,0 +1,37 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IPDLStructMember_h
+#define mozilla_ipc_IPDLStructMember_h
+
+#include <type_traits>
+#include <utility>
+#include "mozilla/Attributes.h"
+
+namespace mozilla::ipc {
+
+// For types which are trivially default constructible, like `int`, force the
+// value constructor by wrapping the type in this struct. This is an
+// implementation detail which will be hidden by the generated IPDL compiler
+// code.
+template <typename T>
+struct IPDLStructMemberWrapper {
+ template <typename... Args>
+ MOZ_IMPLICIT IPDLStructMemberWrapper(Args&&... aArgs)
+ : mVal(std::forward<Args>(aArgs)...) {}
+ MOZ_IMPLICIT operator T&() { return mVal; }
+ MOZ_IMPLICIT operator const T&() const { return mVal; }
+ T mVal{};
+};
+
+template <typename T>
+using IPDLStructMember =
+ std::conditional_t<std::is_trivially_default_constructible_v<T>,
+ IPDLStructMemberWrapper<T>, T>;
+
+} // namespace mozilla::ipc
+
+#endif // mozilla_ipc_IPDLStructMember_h
diff --git a/ipc/glue/IdleSchedulerChild.cpp b/ipc/glue/IdleSchedulerChild.cpp
new file mode 100644
index 0000000000..31cfb5457d
--- /dev/null
+++ b/ipc/glue/IdleSchedulerChild.cpp
@@ -0,0 +1,151 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/IdleSchedulerChild.h"
+#include "mozilla/ipc/IdleSchedulerParent.h"
+#include "mozilla/ipc/PBackgroundChild.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/IdlePeriodState.h"
+#include "mozilla/Telemetry.h"
+#include "BackgroundChild.h"
+
+namespace mozilla::ipc {
+
+static IdleSchedulerChild* sMainThreadIdleScheduler = nullptr;
+static bool sIdleSchedulerDestroyed = false;
+
+IdleSchedulerChild::~IdleSchedulerChild() {
+ if (sMainThreadIdleScheduler == this) {
+ sMainThreadIdleScheduler = nullptr;
+ sIdleSchedulerDestroyed = true;
+ }
+ MOZ_ASSERT(!mIdlePeriodState);
+}
+
+void IdleSchedulerChild::Init(IdlePeriodState* aIdlePeriodState) {
+ mIdlePeriodState = aIdlePeriodState;
+
+ RefPtr<IdleSchedulerChild> scheduler = this;
+ auto resolve =
+ [&](std::tuple<mozilla::Maybe<SharedMemoryHandle>, uint32_t>&& aResult) {
+ if (std::get<0>(aResult)) {
+ mActiveCounter.SetHandle(std::move(*std::get<0>(aResult)), false);
+ mActiveCounter.Map(sizeof(int32_t));
+ mChildId = std::get<1>(aResult);
+ if (mChildId && mIdlePeriodState && mIdlePeriodState->IsActive()) {
+ SetActive();
+ }
+ }
+ };
+
+ auto reject = [&](ResponseRejectReason) {};
+ SendInitForIdleUse(std::move(resolve), std::move(reject));
+}
+
+IPCResult IdleSchedulerChild::RecvIdleTime(uint64_t aId, TimeDuration aBudget) {
+ if (mIdlePeriodState) {
+ mIdlePeriodState->SetIdleToken(aId, aBudget);
+ }
+ return IPC_OK();
+}
+
+void IdleSchedulerChild::SetActive() {
+ if (mChildId && CanSend() && mActiveCounter.memory()) {
+ ++(static_cast<Atomic<int32_t>*>(
+ mActiveCounter.memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER]);
+ ++(static_cast<Atomic<int32_t>*>(mActiveCounter.memory())[mChildId]);
+ }
+}
+
+bool IdleSchedulerChild::SetPaused() {
+ if (mChildId && CanSend() && mActiveCounter.memory()) {
+ --(static_cast<Atomic<int32_t>*>(mActiveCounter.memory())[mChildId]);
+ // The following expression reduces the global activity count and checks if
+ // it drops below the cpu counter limit.
+ return (static_cast<Atomic<int32_t>*>(
+ mActiveCounter
+ .memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER])-- ==
+ static_cast<Atomic<int32_t>*>(
+ mActiveCounter.memory())[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER];
+ }
+
+ return false;
+}
+
+RefPtr<IdleSchedulerChild::MayGCPromise> IdleSchedulerChild::MayGCNow() {
+ if (mIsRequestingGC || mIsDoingGC) {
+ return MayGCPromise::CreateAndResolve(false, __func__);
+ }
+
+ mIsRequestingGC = true;
+ return SendRequestGC()->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [self = RefPtr(this)](bool aIgnored) {
+ // Only one of these may be true at a time.
+ MOZ_ASSERT(!(self->mIsRequestingGC && self->mIsDoingGC));
+
+ // The parent process always says yes, sometimes after a delay.
+ if (self->mIsRequestingGC) {
+ self->mIsRequestingGC = false;
+ self->mIsDoingGC = true;
+ return MayGCPromise::CreateAndResolve(true, __func__);
+ }
+ return MayGCPromise::CreateAndResolve(false, __func__);
+ },
+ [self = RefPtr(this)](ResponseRejectReason reason) {
+ self->mIsRequestingGC = false;
+ return MayGCPromise::CreateAndReject(reason, __func__);
+ });
+}
+
+void IdleSchedulerChild::StartedGC() {
+ // Only one of these may be true at a time.
+ MOZ_ASSERT(!(mIsRequestingGC && mIsDoingGC));
+
+ // If mRequestingGC was true then when the outstanding GC request returns
+ // it'll see that the GC has already started.
+ mIsRequestingGC = false;
+
+ if (!mIsDoingGC) {
+ if (CanSend()) {
+ SendStartedGC();
+ }
+ mIsDoingGC = true;
+ }
+}
+
+void IdleSchedulerChild::DoneGC() {
+ if (mIsDoingGC) {
+ if (CanSend()) {
+ SendDoneGC();
+ }
+ mIsDoingGC = false;
+ }
+}
+
+IdleSchedulerChild* IdleSchedulerChild::GetMainThreadIdleScheduler() {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ if (sMainThreadIdleScheduler) {
+ return sMainThreadIdleScheduler;
+ }
+
+ if (sIdleSchedulerDestroyed) {
+ return nullptr;
+ }
+
+ ipc::PBackgroundChild* background =
+ ipc::BackgroundChild::GetOrCreateForCurrentThread();
+ if (background) {
+ // this is nulled out on our destruction, so we don't need to worry
+ sMainThreadIdleScheduler = new ipc::IdleSchedulerChild();
+ MOZ_ALWAYS_TRUE(
+ background->SendPIdleSchedulerConstructor(sMainThreadIdleScheduler));
+ }
+ return sMainThreadIdleScheduler;
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/IdleSchedulerChild.h b/ipc/glue/IdleSchedulerChild.h
new file mode 100644
index 0000000000..cf93084bfc
--- /dev/null
+++ b/ipc/glue/IdleSchedulerChild.h
@@ -0,0 +1,75 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IdleSchedulerChild_h__
+#define mozilla_ipc_IdleSchedulerChild_h__
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/ipc/PIdleSchedulerChild.h"
+
+class nsIIdlePeriod;
+
+namespace mozilla {
+class IdlePeriodState;
+
+namespace ipc {
+
+class BackgroundChildImpl;
+
+class IdleSchedulerChild final : public PIdleSchedulerChild {
+ public:
+ IdleSchedulerChild() = default;
+
+ NS_INLINE_DECL_REFCOUNTING(IdleSchedulerChild)
+
+ IPCResult RecvIdleTime(uint64_t aId, TimeDuration aBudget);
+
+ void Init(IdlePeriodState* aIdlePeriodState);
+
+ void Disconnect() { mIdlePeriodState = nullptr; }
+
+ // See similar methods on PrioritizedEventQueue.
+ void SetActive();
+ // Returns true if activity state dropped below cpu count.
+ bool SetPaused();
+
+ typedef MozPromise<bool, ResponseRejectReason, true> MayGCPromise;
+
+ // Returns null if a GC or GC request is already in progress.
+ RefPtr<MayGCPromise> MayGCNow();
+
+ // Regardless of how a GC is started we get informed via these.
+ void StartedGC();
+ void DoneGC();
+
+ // Returns nullptr if this is the parent process or the IdleSchedulerChild has
+ // already been destroyed, eg if IPC is shutting down.
+ static IdleSchedulerChild* GetMainThreadIdleScheduler();
+
+ private:
+ ~IdleSchedulerChild();
+
+ friend class BackgroundChildImpl;
+
+ // See IdleScheduleParent::sActiveChildCounter
+ base::SharedMemory mActiveCounter;
+
+ IdlePeriodState* mIdlePeriodState = nullptr;
+
+ uint32_t mChildId = 0;
+
+ // These fields replicate those in IdleSchedulerParent. Tracking them here
+ // ensures we don't send confusing information to the parent, while
+ // nsJSEnvironment is free to tell us about any GCs.
+ bool mIsRequestingGC = false;
+ bool mIsDoingGC = false;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_IdleSchedulerChild_h__
diff --git a/ipc/glue/IdleSchedulerParent.cpp b/ipc/glue/IdleSchedulerParent.cpp
new file mode 100644
index 0000000000..7f91e9e754
--- /dev/null
+++ b/ipc/glue/IdleSchedulerParent.cpp
@@ -0,0 +1,452 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/StaticPrefs_page_load.h"
+#include "mozilla/StaticPrefs_javascript.h"
+#include "mozilla/Unused.h"
+#include "mozilla/ipc/IdleSchedulerParent.h"
+#include "mozilla/AppShutdown.h"
+#include "mozilla/Telemetry.h"
+#include "nsSystemInfo.h"
+#include "nsThreadUtils.h"
+#include "nsITimer.h"
+#include "nsIThread.h"
+
+namespace mozilla::ipc {
+
+base::SharedMemory* IdleSchedulerParent::sActiveChildCounter = nullptr;
+std::bitset<NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT>
+ IdleSchedulerParent::sInUseChildCounters;
+LinkedList<IdleSchedulerParent> IdleSchedulerParent::sIdleAndGCRequests;
+int32_t IdleSchedulerParent::sMaxConcurrentIdleTasksInChildProcesses = 1;
+uint32_t IdleSchedulerParent::sMaxConcurrentGCs = 1;
+uint32_t IdleSchedulerParent::sActiveGCs = 0;
+uint32_t IdleSchedulerParent::sChildProcessesRunningPrioritizedOperation = 0;
+uint32_t IdleSchedulerParent::sChildProcessesAlive = 0;
+nsITimer* IdleSchedulerParent::sStarvationPreventer = nullptr;
+
+uint32_t IdleSchedulerParent::sNumCPUs = 0;
+uint32_t IdleSchedulerParent::sPrefConcurrentGCsMax = 0;
+uint32_t IdleSchedulerParent::sPrefConcurrentGCsCPUDivisor = 0;
+
+IdleSchedulerParent::IdleSchedulerParent() {
+ MOZ_ASSERT(!AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownThreads));
+
+ sChildProcessesAlive++;
+
+ uint32_t max_gcs_pref =
+ StaticPrefs::javascript_options_concurrent_multiprocess_gcs_max();
+ uint32_t cpu_divisor_pref =
+ StaticPrefs::javascript_options_concurrent_multiprocess_gcs_cpu_divisor();
+ if (!max_gcs_pref) {
+ max_gcs_pref = UINT32_MAX;
+ }
+ if (!cpu_divisor_pref) {
+ cpu_divisor_pref = 4;
+ }
+
+ if (!sNumCPUs) {
+ // While waiting for the real logical core count behave as if there was
+ // just one core.
+ sNumCPUs = 1;
+
+ // nsISystemInfo can be initialized only on the main thread.
+ nsCOMPtr<nsIThread> thread = do_GetCurrentThread();
+ nsCOMPtr<nsIRunnable> runnable =
+ NS_NewRunnableFunction("cpucount getter", [thread]() {
+ ProcessInfo processInfo = {};
+ if (NS_SUCCEEDED(CollectProcessInfo(processInfo))) {
+ uint32_t num_cpus = processInfo.cpuCount;
+ // We have a new cpu count, Update the number of idle tasks.
+ if (MOZ_LIKELY(!AppShutdown::IsInOrBeyond(
+ ShutdownPhase::XPCOMShutdownThreads))) {
+ nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableFunction(
+ "IdleSchedulerParent::CalculateNumIdleTasks", [num_cpus]() {
+ // We're setting this within this lambda because it's run on
+ // the correct thread and avoids a race.
+ sNumCPUs = num_cpus;
+
+ // This reads the sPrefConcurrentGCsMax and
+ // sPrefConcurrentGCsCPUDivisor values set below, it will
+ // run after the code that sets those.
+ CalculateNumIdleTasks();
+ });
+
+ thread->Dispatch(runnable, NS_DISPATCH_NORMAL);
+ }
+ }
+ });
+ NS_DispatchBackgroundTask(runnable.forget(), NS_DISPATCH_EVENT_MAY_BLOCK);
+ }
+
+ if (sPrefConcurrentGCsMax != max_gcs_pref ||
+ sPrefConcurrentGCsCPUDivisor != cpu_divisor_pref) {
+ // We execute this if these preferences have changed. We also want to make
+ // sure it executes for the first IdleSchedulerParent, which it does because
+ // sPrefConcurrentGCsMax and sPrefConcurrentGCsCPUDivisor are initially
+ // zero.
+ sPrefConcurrentGCsMax = max_gcs_pref;
+ sPrefConcurrentGCsCPUDivisor = cpu_divisor_pref;
+
+ CalculateNumIdleTasks();
+ }
+}
+
+void IdleSchedulerParent::CalculateNumIdleTasks() {
+ MOZ_ASSERT(sNumCPUs);
+ MOZ_ASSERT(sPrefConcurrentGCsMax);
+ MOZ_ASSERT(sPrefConcurrentGCsCPUDivisor);
+
+ // On one and two processor (or hardware thread) systems this will
+ // allow one concurrent idle task.
+ sMaxConcurrentIdleTasksInChildProcesses = int32_t(std::max(sNumCPUs, 1u));
+ sMaxConcurrentGCs =
+ std::min(std::max(sNumCPUs / sPrefConcurrentGCsCPUDivisor, 1u),
+ sPrefConcurrentGCsMax);
+
+ if (sActiveChildCounter && sActiveChildCounter->memory()) {
+ static_cast<Atomic<int32_t>*>(
+ sActiveChildCounter->memory())[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] =
+ static_cast<int32_t>(sMaxConcurrentIdleTasksInChildProcesses);
+ }
+ IdleSchedulerParent::Schedule(nullptr);
+}
+
+IdleSchedulerParent::~IdleSchedulerParent() {
+ // We can't know if an active process just crashed, so we just always expect
+ // that is the case.
+ if (mChildId) {
+ sInUseChildCounters[mChildId] = false;
+ if (sActiveChildCounter && sActiveChildCounter->memory() &&
+ static_cast<Atomic<int32_t>*>(
+ sActiveChildCounter->memory())[mChildId]) {
+ --static_cast<Atomic<int32_t>*>(
+ sActiveChildCounter
+ ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER];
+ static_cast<Atomic<int32_t>*>(sActiveChildCounter->memory())[mChildId] =
+ 0;
+ }
+ }
+
+ if (mRunningPrioritizedOperation) {
+ --sChildProcessesRunningPrioritizedOperation;
+ }
+
+ if (mDoingGC) {
+ // Give back our GC token.
+ sActiveGCs--;
+ }
+
+ if (mRequestingGC) {
+ mRequestingGC.value()(false);
+ mRequestingGC = Nothing();
+ }
+
+ // Remove from the scheduler's queue.
+ if (isInList()) {
+ remove();
+ }
+
+ MOZ_ASSERT(sChildProcessesAlive > 0);
+ sChildProcessesAlive--;
+ if (sChildProcessesAlive == 0) {
+ MOZ_ASSERT(sIdleAndGCRequests.isEmpty());
+ delete sActiveChildCounter;
+ sActiveChildCounter = nullptr;
+
+ if (sStarvationPreventer) {
+ sStarvationPreventer->Cancel();
+ NS_RELEASE(sStarvationPreventer);
+ }
+ }
+
+ Schedule(nullptr);
+}
+
+IPCResult IdleSchedulerParent::RecvInitForIdleUse(
+ InitForIdleUseResolver&& aResolve) {
+ // This must already be non-zero, if it is zero then the cleanup code for the
+ // shared memory (initialised below) will never run. The invariant is that if
+ // the shared memory is initialsed, then this is non-zero.
+ MOZ_ASSERT(sChildProcessesAlive > 0);
+
+ MOZ_ASSERT(IsNotDoingIdleTask());
+
+ // Create a shared memory object which is shared across all the relevant
+ // processes.
+ if (!sActiveChildCounter) {
+ sActiveChildCounter = new base::SharedMemory();
+ size_t shmemSize = NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT * sizeof(int32_t);
+ if (sActiveChildCounter->Create(shmemSize) &&
+ sActiveChildCounter->Map(shmemSize)) {
+ memset(sActiveChildCounter->memory(), 0, shmemSize);
+ sInUseChildCounters[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER] = true;
+ sInUseChildCounters[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] = true;
+ static_cast<Atomic<int32_t>*>(
+ sActiveChildCounter
+ ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER] =
+ static_cast<int32_t>(sMaxConcurrentIdleTasksInChildProcesses);
+ } else {
+ delete sActiveChildCounter;
+ sActiveChildCounter = nullptr;
+ }
+ }
+ Maybe<SharedMemoryHandle> activeCounter;
+ if (SharedMemoryHandle handle =
+ sActiveChildCounter ? sActiveChildCounter->CloneHandle() : nullptr) {
+ activeCounter.emplace(std::move(handle));
+ }
+
+ uint32_t unusedId = 0;
+ for (uint32_t i = 0; i < NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT; ++i) {
+ if (!sInUseChildCounters[i]) {
+ sInUseChildCounters[i] = true;
+ unusedId = i;
+ break;
+ }
+ }
+
+ // If there wasn't an empty item, we'll fallback to 0.
+ mChildId = unusedId;
+
+ aResolve(std::tuple<mozilla::Maybe<SharedMemoryHandle>&&, const uint32_t&>(
+ std::move(activeCounter), mChildId));
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvRequestIdleTime(uint64_t aId,
+ TimeDuration aBudget) {
+ MOZ_ASSERT(aBudget);
+ MOZ_ASSERT(IsNotDoingIdleTask());
+
+ mCurrentRequestId = aId;
+ mRequestedIdleBudget = aBudget;
+
+ if (!isInList()) {
+ sIdleAndGCRequests.insertBack(this);
+ }
+
+ Schedule(this);
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvIdleTimeUsed(uint64_t aId) {
+ // The client can either signal that they've used the idle time or they're
+ // canceling the request. We cannot use a seperate cancel message because it
+ // could arrive after the parent has granted the request.
+ MOZ_ASSERT(IsWaitingForIdle() || IsDoingIdleTask());
+
+ // The parent process will always know the ID of the current request (since
+ // the IPC channel is reliable). The IDs are provided so that the client can
+ // check them (it's possible for the client to race ahead of the server).
+ MOZ_ASSERT(mCurrentRequestId == aId);
+
+ if (IsWaitingForIdle() && !mRequestingGC) {
+ remove();
+ }
+ mRequestedIdleBudget = TimeDuration();
+ Schedule(nullptr);
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvSchedule() {
+ Schedule(nullptr);
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvRunningPrioritizedOperation() {
+ ++mRunningPrioritizedOperation;
+ if (mRunningPrioritizedOperation == 1) {
+ ++sChildProcessesRunningPrioritizedOperation;
+ }
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvPrioritizedOperationDone() {
+ MOZ_ASSERT(mRunningPrioritizedOperation);
+
+ --mRunningPrioritizedOperation;
+ if (mRunningPrioritizedOperation == 0) {
+ --sChildProcessesRunningPrioritizedOperation;
+ Schedule(nullptr);
+ }
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvRequestGC(RequestGCResolver&& aResolver) {
+ MOZ_ASSERT(!mDoingGC);
+ MOZ_ASSERT(!mRequestingGC);
+
+ mRequestingGC = Some(aResolver);
+ if (!isInList()) {
+ sIdleAndGCRequests.insertBack(this);
+ }
+
+ Schedule(nullptr);
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvStartedGC() {
+ if (mDoingGC) {
+ return IPC_OK();
+ }
+
+ mDoingGC = true;
+ sActiveGCs++;
+
+ if (mRequestingGC) {
+ // We have to respond to the request before dropping it, even though the
+ // content process is already doing the GC.
+ mRequestingGC.value()(true);
+ mRequestingGC = Nothing();
+ if (!IsWaitingForIdle()) {
+ remove();
+ }
+ }
+
+ return IPC_OK();
+}
+
+IPCResult IdleSchedulerParent::RecvDoneGC() {
+ MOZ_ASSERT(mDoingGC);
+ sActiveGCs--;
+ mDoingGC = false;
+ Schedule(nullptr);
+ return IPC_OK();
+}
+
+int32_t IdleSchedulerParent::ActiveCount() {
+ if (sActiveChildCounter) {
+ return (static_cast<Atomic<int32_t>*>(
+ sActiveChildCounter
+ ->memory())[NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER]);
+ }
+ return 0;
+}
+
+bool IdleSchedulerParent::HasSpareCycles(int32_t aActiveCount) {
+ // We can run a new task if we have a spare core. If we're running a
+ // prioritised operation we halve the number of regular spare cores.
+ //
+ // sMaxConcurrentIdleTasksInChildProcesses will always be >0 so on 1 and 2
+ // core systems this will allow 1 idle tasks (0 if running a prioritized
+ // operation).
+ MOZ_ASSERT(sMaxConcurrentIdleTasksInChildProcesses > 0);
+ return sChildProcessesRunningPrioritizedOperation
+ ? sMaxConcurrentIdleTasksInChildProcesses / 2 > aActiveCount
+ : sMaxConcurrentIdleTasksInChildProcesses > aActiveCount;
+}
+
+bool IdleSchedulerParent::HasSpareGCCycles() {
+ return sMaxConcurrentGCs > sActiveGCs;
+}
+
+void IdleSchedulerParent::SendIdleTime() {
+ // We would assert that IsWaitingForIdle() except after potentially removing
+ // the task from it's list this will return false. Instead check
+ // mRequestedIdleBudget.
+ MOZ_ASSERT(mRequestedIdleBudget);
+ Unused << SendIdleTime(mCurrentRequestId, mRequestedIdleBudget);
+}
+
+void IdleSchedulerParent::SendMayGC() {
+ MOZ_ASSERT(mRequestingGC);
+ mRequestingGC.value()(true);
+ mRequestingGC = Nothing();
+ mDoingGC = true;
+ sActiveGCs++;
+}
+
+void IdleSchedulerParent::Schedule(IdleSchedulerParent* aRequester) {
+ // Tasks won't update the active count until after they receive their message
+ // and start to run, so make a copy of it here and increment it for every task
+ // we schedule. It will become an estimate of how many tasks will be active
+ // shortly.
+ int32_t activeCount = ActiveCount();
+
+ if (aRequester && aRequester->mRunningPrioritizedOperation) {
+ // Prioritised operations are requested only for idle time requests, so this
+ // must be an idle time request.
+ MOZ_ASSERT(aRequester->IsWaitingForIdle());
+
+ // If the requester is prioritized, just let it run itself.
+ if (aRequester->isInList() && !aRequester->mRequestingGC) {
+ aRequester->remove();
+ }
+ aRequester->SendIdleTime();
+ activeCount++;
+ }
+
+ RefPtr<IdleSchedulerParent> idleRequester = sIdleAndGCRequests.getFirst();
+
+ bool has_spare_cycles = HasSpareCycles(activeCount);
+ bool has_spare_gc_cycles = HasSpareGCCycles();
+
+ while (idleRequester && (has_spare_cycles || has_spare_gc_cycles)) {
+ // Get the next element before potentially removing the current one from the
+ // list.
+ RefPtr<IdleSchedulerParent> next = idleRequester->getNext();
+
+ if (has_spare_cycles && idleRequester->IsWaitingForIdle()) {
+ // We can run an idle task.
+ activeCount++;
+ if (!idleRequester->mRequestingGC) {
+ idleRequester->remove();
+ }
+ idleRequester->SendIdleTime();
+ has_spare_cycles = HasSpareCycles(activeCount);
+ }
+
+ if (has_spare_gc_cycles && idleRequester->mRequestingGC) {
+ if (!idleRequester->IsWaitingForIdle()) {
+ idleRequester->remove();
+ }
+ idleRequester->SendMayGC();
+ has_spare_gc_cycles = HasSpareGCCycles();
+ }
+
+ idleRequester = next;
+ }
+
+ if (!sIdleAndGCRequests.isEmpty() && HasSpareCycles(activeCount)) {
+ EnsureStarvationTimer();
+ }
+}
+
+void IdleSchedulerParent::EnsureStarvationTimer() {
+ // Even though idle runnables aren't really guaranteed to get run ever (which
+ // is why most of them have the timer fallback), try to not let any child
+ // process' idle handling to starve forever in case other processes are busy
+ if (!sStarvationPreventer) {
+ // Reuse StaticPrefs::page_load_deprioritization_period(), since that
+ // is used on child side when deciding the minimum idle period.
+ NS_NewTimerWithFuncCallback(
+ &sStarvationPreventer, StarvationCallback, nullptr,
+ StaticPrefs::page_load_deprioritization_period(),
+ nsITimer::TYPE_ONE_SHOT_LOW_PRIORITY, "StarvationCallback");
+ }
+}
+
+void IdleSchedulerParent::StarvationCallback(nsITimer* aTimer, void* aData) {
+ RefPtr<IdleSchedulerParent> idleRequester = sIdleAndGCRequests.getFirst();
+ while (idleRequester) {
+ if (idleRequester->IsWaitingForIdle()) {
+ // Treat the first process waiting for idle time as running prioritized
+ // operation so that it gets run.
+ ++idleRequester->mRunningPrioritizedOperation;
+ ++sChildProcessesRunningPrioritizedOperation;
+ Schedule(idleRequester);
+ --idleRequester->mRunningPrioritizedOperation;
+ --sChildProcessesRunningPrioritizedOperation;
+ break;
+ }
+
+ idleRequester = idleRequester->getNext();
+ }
+ NS_RELEASE(sStarvationPreventer);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/IdleSchedulerParent.h b/ipc/glue/IdleSchedulerParent.h
new file mode 100644
index 0000000000..a4ae130e28
--- /dev/null
+++ b/ipc/glue/IdleSchedulerParent.h
@@ -0,0 +1,131 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_IdleSchedulerParent_h__
+#define mozilla_ipc_IdleSchedulerParent_h__
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/LinkedList.h"
+#include "mozilla/ipc/PIdleSchedulerParent.h"
+#include "base/shared_memory.h"
+#include <bitset>
+
+#define NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT 1024
+#define NS_IDLE_SCHEDULER_INDEX_OF_ACTIVITY_COUNTER 0
+#define NS_IDLE_SCHEDULER_INDEX_OF_CPU_COUNTER 1
+
+class nsITimer;
+
+namespace mozilla {
+
+namespace ipc {
+
+class BackgroundParentImpl;
+
+class IdleSchedulerParent final
+ : public PIdleSchedulerParent,
+ public LinkedListElement<IdleSchedulerParent> {
+ public:
+ NS_INLINE_DECL_REFCOUNTING(IdleSchedulerParent)
+
+ IPCResult RecvInitForIdleUse(InitForIdleUseResolver&& aResolve);
+ IPCResult RecvRequestIdleTime(uint64_t aId, TimeDuration aBudget);
+ IPCResult RecvIdleTimeUsed(uint64_t aId);
+ IPCResult RecvSchedule();
+ IPCResult RecvRunningPrioritizedOperation();
+ IPCResult RecvPrioritizedOperationDone();
+ IPCResult RecvRequestGC(RequestGCResolver&& aResolve);
+ IPCResult RecvStartedGC();
+ IPCResult RecvDoneGC();
+
+ private:
+ friend class BackgroundParentImpl;
+ IdleSchedulerParent();
+ ~IdleSchedulerParent();
+
+ static void CalculateNumIdleTasks();
+
+ static int32_t ActiveCount();
+ static void Schedule(IdleSchedulerParent* aRequester);
+ static bool HasSpareCycles(int32_t aActiveCount);
+ static bool HasSpareGCCycles();
+ using PIdleSchedulerParent::SendIdleTime;
+ void SendIdleTime();
+ void SendMayGC();
+
+ static void EnsureStarvationTimer();
+ static void StarvationCallback(nsITimer* aTimer, void* aData);
+
+ uint64_t mCurrentRequestId = 0;
+ // For now we don't really use idle budget for scheduling. Zero if the
+ // process isn't requestiong or running an idle task.
+ TimeDuration mRequestedIdleBudget;
+
+ // Counting all the prioritized operations the process is doing.
+ uint32_t mRunningPrioritizedOperation = 0;
+
+ // Only one of these may be true at a time, giving three states:
+ // No active GC request, A pending GC request, or a granted GC request.
+ Maybe<RequestGCResolver> mRequestingGC;
+ bool mDoingGC = false;
+
+ uint32_t mChildId = 0;
+
+ // Current state, only one of these may be true at a time.
+ bool IsWaitingForIdle() const { return isInList() && mRequestedIdleBudget; }
+ bool IsDoingIdleTask() const { return !isInList() && mRequestedIdleBudget; }
+ bool IsNotDoingIdleTask() const { return !mRequestedIdleBudget; }
+
+ // Shared memory for counting how many child processes are running
+ // tasks. This memory is shared across all the child processes.
+ // The [0] is used for counting all the processes and
+ // [childId] is for counting per process activity.
+ // This way the global activity can be checked in a fast way by just looking
+ // at [0] value.
+ // [1] is used for cpu count for child processes.
+ static base::SharedMemory* sActiveChildCounter;
+ // A bit is set if there is a child with child Id as the offset.
+ // The bit is used to check per child specific activity counters in
+ // sActiveChildCounter.
+ static std::bitset<NS_IDLE_SCHEDULER_COUNTER_ARRAY_LENGHT>
+ sInUseChildCounters;
+
+ // Processes on this list have requested (but the request hasn't yet been
+ // granted) idle time or to start a GC or both.
+ //
+ // Either or both their mRequestedIdleBudget or mRequestingGC fields are
+ // non-zero. Child processes not on this list have either been granted all
+ // their requests not made a request ever or since they last finished an idle
+ // or GC task.
+ //
+ // Use the methods above to determine a process' idle time state, or check the
+ // mRequestingGC and mDoingGC fields for the GC state.
+ static LinkedList<IdleSchedulerParent> sIdleAndGCRequests;
+
+ static int32_t sMaxConcurrentIdleTasksInChildProcesses;
+ static uint32_t sMaxConcurrentGCs;
+ static uint32_t sActiveGCs;
+
+ // Counting all the child processes which have at least one prioritized
+ // operation.
+ static uint32_t sChildProcessesRunningPrioritizedOperation;
+
+ // When this hits zero, it's time to free the shared memory and pack up.
+ static uint32_t sChildProcessesAlive;
+
+ static nsITimer* sStarvationPreventer;
+
+ static uint32_t sNumCPUs;
+ static uint32_t sPrefConcurrentGCsMax;
+ static uint32_t sPrefConcurrentGCsCPUDivisor;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_IdleSchedulerParent_h__
diff --git a/ipc/glue/InputStreamParams.ipdlh b/ipc/glue/InputStreamParams.ipdlh
new file mode 100644
index 0000000000..2491c477af
--- /dev/null
+++ b/ipc/glue/InputStreamParams.ipdlh
@@ -0,0 +1,101 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include ProtocolTypes;
+
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+[RefCounted] using mozilla::ipc::DataPipeReceiver from "mozilla/ipc/DataPipe.h";
+[RefCounted] using mozilla::RemoteLazyInputStream from "mozilla/RemoteLazyInputStream.h";
+
+namespace mozilla {
+namespace ipc {
+
+struct HeaderEntry
+{
+ nsCString name;
+ nsCString value;
+};
+
+struct StringInputStreamParams
+{
+ nsCString data;
+};
+
+struct FileInputStreamParams
+{
+ FileDescriptor fileDescriptor;
+ int32_t behaviorFlags;
+ int32_t ioFlags;
+};
+
+struct MultiplexInputStreamParams
+{
+ InputStreamParams[] streams;
+ uint32_t currentStream;
+ nsresult status;
+ bool startedReadingCurrent;
+};
+
+struct SlicedInputStreamParams
+{
+ InputStreamParams stream;
+ uint64_t start;
+ uint64_t length;
+ uint64_t curPos;
+ bool closed;
+};
+
+struct RemoteLazyInputStreamParams
+{
+ RemoteLazyInputStream stream;
+};
+
+struct DataPipeReceiverStreamParams
+{
+ DataPipeReceiver pipe;
+};
+
+union InputStreamParams
+{
+ StringInputStreamParams;
+ FileInputStreamParams;
+ BufferedInputStreamParams;
+ MIMEInputStreamParams;
+ MultiplexInputStreamParams;
+ SlicedInputStreamParams;
+ RemoteLazyInputStreamParams;
+ InputStreamLengthWrapperParams;
+ EncryptedFileInputStreamParams;
+ DataPipeReceiverStreamParams;
+};
+
+struct EncryptedFileInputStreamParams
+{
+ FileInputStreamParams fileInputStreamParams;
+ uint8_t[] key;
+ uint32_t blockSize;
+};
+
+struct BufferedInputStreamParams
+{
+ InputStreamParams? optionalStream;
+ uint32_t bufferSize;
+};
+
+struct MIMEInputStreamParams
+{
+ InputStreamParams? optionalStream;
+ HeaderEntry[] headers;
+ bool startedReading;
+};
+
+struct InputStreamLengthWrapperParams
+{
+ InputStreamParams stream;
+ int64_t length;
+ bool consumed;
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/InputStreamUtils.cpp b/ipc/glue/InputStreamUtils.cpp
new file mode 100644
index 0000000000..039582c94a
--- /dev/null
+++ b/ipc/glue/InputStreamUtils.cpp
@@ -0,0 +1,211 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "InputStreamUtils.h"
+
+#include "nsIIPCSerializableInputStream.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/dom/File.h"
+#include "mozilla/dom/quota/DecryptingInputStream_impl.h"
+#include "mozilla/dom/quota/IPCStreamCipherStrategy.h"
+#include "mozilla/ipc/DataPipe.h"
+#include "mozilla/InputStreamLengthHelper.h"
+#include "mozilla/RemoteLazyInputStream.h"
+#include "mozilla/RemoteLazyInputStreamChild.h"
+#include "mozilla/RemoteLazyInputStreamStorage.h"
+#include "mozilla/SlicedInputStream.h"
+#include "mozilla/InputStreamLengthWrapper.h"
+#include "nsBufferedStreams.h"
+#include "nsComponentManagerUtils.h"
+#include "nsDebug.h"
+#include "nsFileStreams.h"
+#include "nsIAsyncInputStream.h"
+#include "nsIAsyncOutputStream.h"
+#include "nsID.h"
+#include "nsIMIMEInputStream.h"
+#include "nsIMultiplexInputStream.h"
+#include "nsIPipe.h"
+#include "nsMIMEInputStream.h"
+#include "nsMultiplexInputStream.h"
+#include "nsNetCID.h"
+#include "nsStreamUtils.h"
+#include "nsStringStream.h"
+#include "nsXULAppAPI.h"
+
+using namespace mozilla;
+using namespace mozilla::dom;
+
+namespace mozilla {
+namespace ipc {
+
+void InputStreamHelper::SerializedComplexity(nsIInputStream* aInputStream,
+ uint32_t aMaxSize,
+ uint32_t* aSizeUsed,
+ uint32_t* aPipes,
+ uint32_t* aTransferables) {
+ MOZ_ASSERT(aInputStream);
+
+ nsCOMPtr<nsIIPCSerializableInputStream> serializable =
+ do_QueryInterface(aInputStream);
+ if (!serializable) {
+ MOZ_CRASH("Input stream is not serializable!");
+ }
+
+ serializable->SerializedComplexity(aMaxSize, aSizeUsed, aPipes,
+ aTransferables);
+}
+
+void InputStreamHelper::SerializeInputStream(nsIInputStream* aInputStream,
+ InputStreamParams& aParams,
+ uint32_t aMaxSize,
+ uint32_t* aSizeUsed) {
+ MOZ_ASSERT(aInputStream);
+
+ nsCOMPtr<nsIIPCSerializableInputStream> serializable =
+ do_QueryInterface(aInputStream);
+ if (!serializable) {
+ MOZ_CRASH("Input stream is not serializable!");
+ }
+
+ serializable->Serialize(aParams, aMaxSize, aSizeUsed);
+
+ if (aParams.type() == InputStreamParams::T__None) {
+ MOZ_CRASH("Serialize failed!");
+ }
+}
+
+void InputStreamHelper::SerializeInputStreamAsPipe(nsIInputStream* aInputStream,
+ InputStreamParams& aParams) {
+ MOZ_ASSERT(aInputStream);
+
+ // Let's try to take the length using InputStreamLengthHelper. If the length
+ // cannot be taken synchronously, and its length is needed, the stream needs
+ // to be fully copied in memory on the deserialization side.
+ int64_t length;
+ if (!InputStreamLengthHelper::GetSyncLength(aInputStream, &length)) {
+ length = -1;
+ }
+
+ RefPtr<DataPipeSender> sender;
+ RefPtr<DataPipeReceiver> receiver;
+ nsresult rv = NewDataPipe(kDefaultDataPipeCapacity, getter_AddRefs(sender),
+ getter_AddRefs(receiver));
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return;
+ }
+
+ nsCOMPtr<nsIEventTarget> target =
+ do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
+
+ rv =
+ NS_AsyncCopy(aInputStream, sender, target, NS_ASYNCCOPY_VIA_WRITESEGMENTS,
+ kDefaultDataPipeCapacity, nullptr, nullptr);
+ if (NS_WARN_IF(NS_FAILED(rv))) {
+ return;
+ }
+
+ aParams = DataPipeReceiverStreamParams(WrapNotNull(receiver));
+ if (length != -1) {
+ aParams = InputStreamLengthWrapperParams(aParams, length, false);
+ }
+}
+
+already_AddRefed<nsIInputStream> InputStreamHelper::DeserializeInputStream(
+ const InputStreamParams& aParams) {
+ if (aParams.type() == InputStreamParams::TRemoteLazyInputStreamParams) {
+ const RemoteLazyInputStreamParams& params =
+ aParams.get_RemoteLazyInputStreamParams();
+
+ // If the RemoteLazyInputStream already has an internal stream, unwrap it.
+ // This is required as some code unfortunately depends on the precise
+ // topology of received streams, and cannot handle being passed a
+ // `RemoteLazyInputStream` in the parent process.
+ nsCOMPtr<nsIInputStream> innerStream;
+ if (XRE_IsParentProcess() &&
+ NS_SUCCEEDED(
+ params.stream()->TakeInternalStream(getter_AddRefs(innerStream)))) {
+ return innerStream.forget();
+ }
+ return do_AddRef(params.stream().get());
+ }
+
+ if (aParams.type() == InputStreamParams::TDataPipeReceiverStreamParams) {
+ const DataPipeReceiverStreamParams& pipeParams =
+ aParams.get_DataPipeReceiverStreamParams();
+ return do_AddRef(pipeParams.pipe().get());
+ }
+
+ nsCOMPtr<nsIIPCSerializableInputStream> serializable;
+
+ switch (aParams.type()) {
+ case InputStreamParams::TStringInputStreamParams: {
+ nsCOMPtr<nsIInputStream> stream;
+ NS_NewCStringInputStream(getter_AddRefs(stream), ""_ns);
+ serializable = do_QueryInterface(stream);
+ } break;
+
+ case InputStreamParams::TFileInputStreamParams: {
+ nsCOMPtr<nsIFileInputStream> stream;
+ nsFileInputStream::Create(NS_GET_IID(nsIFileInputStream),
+ getter_AddRefs(stream));
+ serializable = do_QueryInterface(stream);
+ } break;
+
+ case InputStreamParams::TBufferedInputStreamParams: {
+ nsCOMPtr<nsIBufferedInputStream> stream;
+ nsBufferedInputStream::Create(NS_GET_IID(nsIBufferedInputStream),
+ getter_AddRefs(stream));
+ serializable = do_QueryInterface(stream);
+ } break;
+
+ case InputStreamParams::TMIMEInputStreamParams: {
+ nsCOMPtr<nsIMIMEInputStream> stream;
+ nsMIMEInputStreamConstructor(NS_GET_IID(nsIMIMEInputStream),
+ getter_AddRefs(stream));
+ serializable = do_QueryInterface(stream);
+ } break;
+
+ case InputStreamParams::TMultiplexInputStreamParams: {
+ nsCOMPtr<nsIMultiplexInputStream> stream;
+ nsMultiplexInputStreamConstructor(NS_GET_IID(nsIMultiplexInputStream),
+ getter_AddRefs(stream));
+ serializable = do_QueryInterface(stream);
+ } break;
+
+ case InputStreamParams::TSlicedInputStreamParams:
+ serializable = new SlicedInputStream();
+ break;
+
+ case InputStreamParams::TInputStreamLengthWrapperParams:
+ serializable = new InputStreamLengthWrapper();
+ break;
+
+ case InputStreamParams::TEncryptedFileInputStreamParams:
+ serializable = new dom::quota::DecryptingInputStream<
+ dom::quota::IPCStreamCipherStrategy>();
+ break;
+
+ default:
+ MOZ_ASSERT(false, "Unknown params!");
+ return nullptr;
+ }
+
+ MOZ_ASSERT(serializable);
+
+ if (!serializable->Deserialize(aParams)) {
+ MOZ_ASSERT(false, "Deserialize failed!");
+ return nullptr;
+ }
+
+ nsCOMPtr<nsIInputStream> stream = do_QueryInterface(serializable);
+ MOZ_ASSERT(stream);
+
+ return stream.forget();
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/InputStreamUtils.h b/ipc/glue/InputStreamUtils.h
new file mode 100644
index 0000000000..27a65b02e2
--- /dev/null
+++ b/ipc/glue/InputStreamUtils.h
@@ -0,0 +1,50 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_InputStreamUtils_h
+#define mozilla_ipc_InputStreamUtils_h
+
+#include "mozilla/ipc/InputStreamParams.h"
+#include "nsCOMPtr.h"
+#include "nsIInputStream.h"
+#include "nsTArray.h"
+
+namespace mozilla {
+namespace ipc {
+
+class FileDescriptor;
+
+// If you want to serialize an inputStream, please use SerializeIPCStream or
+// nsIInputStream directly.
+class InputStreamHelper {
+ public:
+ static void SerializedComplexity(nsIInputStream* aInputStream,
+ uint32_t aMaxSize, uint32_t* aSizeUsed,
+ uint32_t* aPipes, uint32_t* aTransferables);
+
+ // These 2 methods allow to serialize an inputStream into InputStreamParams.
+ // The manager is needed in case a stream needs to serialize itself as
+ // IPCRemoteStream.
+ // The stream serializes itself fully only if the resulting IPC message will
+ // be smaller than |aMaxSize|. Otherwise, the stream serializes itself as a
+ // DataPipe, and, its content will be sent to the other side of the IPC pipe
+ // in chunks. The IPC message size is returned into |aSizeUsed|.
+ static void SerializeInputStream(nsIInputStream* aInputStream,
+ InputStreamParams& aParams,
+ uint32_t aMaxSize, uint32_t* aSizeUsed);
+
+ // When a stream wants to serialize itself as a DataPipe, it uses this method.
+ static void SerializeInputStreamAsPipe(nsIInputStream* aInputStream,
+ InputStreamParams& aParams);
+
+ static already_AddRefed<nsIInputStream> DeserializeInputStream(
+ const InputStreamParams& aParams);
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_InputStreamUtils_h
diff --git a/ipc/glue/LaunchError.cpp b/ipc/glue/LaunchError.cpp
new file mode 100644
index 0000000000..04ae34cfa6
--- /dev/null
+++ b/ipc/glue/LaunchError.cpp
@@ -0,0 +1,31 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "LaunchError.h"
+
+#if defined(XP_WIN)
+# include "mozilla/WinHeaderOnlyUtils.h"
+#endif
+
+namespace mozilla::ipc {
+
+LaunchError::LaunchError(const char* aFunction, OsError aError)
+ : mFunction(aFunction), mError(aError) {}
+
+#if defined(XP_WIN)
+LaunchError::LaunchError(const char* aFunction, PRErrorCode aError)
+ : mFunction(aFunction), mError((int)aError) {}
+
+LaunchError::LaunchError(const char* aFunction, DWORD aError)
+ : mFunction(aFunction),
+ mError(WindowsError::FromWin32Error(aError).AsHResult()) {}
+#endif // defined(XP_WIN)
+
+const char* LaunchError::FunctionName() const { return mFunction; }
+
+OsError LaunchError::ErrorCode() const { return mError; }
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/LaunchError.h b/ipc/glue/LaunchError.h
new file mode 100644
index 0000000000..efa8ba4de4
--- /dev/null
+++ b/ipc/glue/LaunchError.h
@@ -0,0 +1,40 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_LaunchError_h
+#define mozilla_ipc_LaunchError_h
+
+#include "prerror.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+# include <winerror.h>
+using OsError = HRESULT;
+#else
+using OsError = int;
+#endif
+
+namespace mozilla::ipc {
+
+class LaunchError {
+ public:
+ explicit LaunchError(const char* aFunction, OsError aError = 0);
+#if defined(XP_WIN)
+ explicit LaunchError(const char* aFunction, PRErrorCode aError);
+ explicit LaunchError(const char* aFunction, DWORD aError);
+#endif // defined(XP_WIN)
+
+ const char* FunctionName() const;
+ OsError ErrorCode() const;
+
+ private:
+ const char* mFunction;
+ OsError mError;
+};
+
+} // namespace mozilla::ipc
+
+#endif // ifndef mozilla_ipc_LaunchError_h
diff --git a/ipc/glue/MessageChannel.cpp b/ipc/glue/MessageChannel.cpp
new file mode 100644
index 0000000000..a7fc135748
--- /dev/null
+++ b/ipc/glue/MessageChannel.cpp
@@ -0,0 +1,2491 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/MessageChannel.h"
+
+#include <math.h>
+
+#include <utility>
+
+#include "CrashAnnotations.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/CycleCollectedJSContext.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/Fuzzing.h"
+#include "mozilla/IntentionalCrash.h"
+#include "mozilla/Logging.h"
+#include "mozilla/Monitor.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "mozilla/ScopeExit.h"
+#include "mozilla/Sprintf.h"
+#include "mozilla/StaticMutex.h"
+#include "mozilla/Telemetry.h"
+#include "mozilla/TimeStamp.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/dom/ScriptSettings.h"
+#include "mozilla/ipc/NodeController.h"
+#include "mozilla/ipc/ProcessChild.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "nsAppRunner.h"
+#include "nsContentUtils.h"
+#include "nsIDirectTaskDispatcher.h"
+#include "nsTHashMap.h"
+#include "nsDebug.h"
+#include "nsExceptionHandler.h"
+#include "nsIMemoryReporter.h"
+#include "nsISupportsImpl.h"
+#include "nsPrintfCString.h"
+#include "nsThreadUtils.h"
+
+#ifdef XP_WIN
+# include "mozilla/gfx/Logging.h"
+#endif
+
+#ifdef FUZZING_SNAPSHOT
+# include "mozilla/fuzzing/IPCFuzzController.h"
+#endif
+
+// Undo the damage done by mozzconf.h
+#undef compress
+
+static mozilla::LazyLogModule sLogModule("ipc");
+#define IPC_LOG(...) MOZ_LOG(sLogModule, LogLevel::Debug, (__VA_ARGS__))
+
+/*
+ * IPC design:
+ *
+ * There are two kinds of messages: async and sync. Sync messages are blocking.
+ *
+ * Terminology: To dispatch a message Foo is to run the RecvFoo code for
+ * it. This is also called "handling" the message.
+ *
+ * Sync and async messages can sometimes "nest" inside other sync messages
+ * (i.e., while waiting for the sync reply, we can dispatch the inner
+ * message). The three possible nesting levels are NOT_NESTED,
+ * NESTED_INSIDE_SYNC, and NESTED_INSIDE_CPOW. The intended uses are:
+ * NOT_NESTED - most messages.
+ * NESTED_INSIDE_SYNC - CPOW-related messages, which are always sync
+ * and can go in either direction.
+ * NESTED_INSIDE_CPOW - messages where we don't want to dispatch
+ * incoming CPOWs while waiting for the response.
+ * These nesting levels are ordered: NOT_NESTED, NESTED_INSIDE_SYNC,
+ * NESTED_INSIDE_CPOW. Async messages cannot be NESTED_INSIDE_SYNC but they can
+ * be NESTED_INSIDE_CPOW.
+ *
+ * To avoid jank, the parent process is not allowed to send NOT_NESTED sync
+ * messages. When a process is waiting for a response to a sync message M0, it
+ * will dispatch an incoming message M if:
+ * 1. M has a higher nesting level than M0, or
+ * 2. if M has the same nesting level as M0 and we're in the child, or
+ * 3. if M has the same nesting level as M0 and it was sent by the other side
+ * while dispatching M0.
+ * The idea is that messages with higher nesting should take precendence. The
+ * purpose of rule 2 is to handle a race where both processes send to each other
+ * simultaneously. In this case, we resolve the race in favor of the parent (so
+ * the child dispatches first).
+ *
+ * Messages satisfy the following properties:
+ * A. When waiting for a response to a sync message, we won't dispatch any
+ * messages of a lower nesting level.
+ * B. Messages of the same nesting level will be dispatched roughly in the
+ * order they were sent. The exception is when the parent and child send
+ * sync messages to each other simulataneously. In this case, the parent's
+ * message is dispatched first. While it is dispatched, the child may send
+ * further nested messages, and these messages may be dispatched before the
+ * child's original message. We can consider ordering to be preserved here
+ * because we pretend that the child's original message wasn't sent until
+ * after the parent's message is finished being dispatched.
+ *
+ * When waiting for a sync message reply, we dispatch an async message only if
+ * it is NESTED_INSIDE_CPOW. Normally NESTED_INSIDE_CPOW async
+ * messages are sent only from the child. However, the parent can send
+ * NESTED_INSIDE_CPOW async messages when it is creating a bridged protocol.
+ */
+
+using namespace mozilla;
+using namespace mozilla::ipc;
+
+using mozilla::MonitorAutoLock;
+using mozilla::MonitorAutoUnlock;
+using mozilla::dom::AutoNoJSAPI;
+
+#define IPC_ASSERT(_cond, ...) \
+ do { \
+ AssertWorkerThread(); \
+ mMonitor->AssertCurrentThreadOwns(); \
+ if (!(_cond)) DebugAbort(__FILE__, __LINE__, #_cond, ##__VA_ARGS__); \
+ } while (0)
+
+static MessageChannel* gParentProcessBlocker = nullptr;
+
+namespace mozilla {
+namespace ipc {
+
+static const uint32_t kMinTelemetryMessageSize = 4096;
+
+// Note: we round the time we spend waiting for a response to the nearest
+// millisecond. So a min value of 1 ms actually captures from 500us and above.
+// This is used for both the sending and receiving side telemetry for sync IPC,
+// (IPC_SYNC_MAIN_LATENCY_MS and IPC_SYNC_RECEIVE_MS).
+static const uint32_t kMinTelemetrySyncIPCLatencyMs = 1;
+
+// static
+bool MessageChannel::sIsPumpingMessages = false;
+
+class AutoEnterTransaction {
+ public:
+ explicit AutoEnterTransaction(MessageChannel* aChan, int32_t aMsgSeqno,
+ int32_t aTransactionID, int aNestedLevel)
+ MOZ_REQUIRES(*aChan->mMonitor)
+ : mChan(aChan),
+ mActive(true),
+ mOutgoing(true),
+ mNestedLevel(aNestedLevel),
+ mSeqno(aMsgSeqno),
+ mTransaction(aTransactionID),
+ mNext(mChan->mTransactionStack) {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+ mChan->mTransactionStack = this;
+ }
+
+ explicit AutoEnterTransaction(MessageChannel* aChan,
+ const IPC::Message& aMessage)
+ MOZ_REQUIRES(*aChan->mMonitor)
+ : mChan(aChan),
+ mActive(true),
+ mOutgoing(false),
+ mNestedLevel(aMessage.nested_level()),
+ mSeqno(aMessage.seqno()),
+ mTransaction(aMessage.transaction_id()),
+ mNext(mChan->mTransactionStack) {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ if (!aMessage.is_sync()) {
+ mActive = false;
+ return;
+ }
+
+ mChan->mTransactionStack = this;
+ }
+
+ ~AutoEnterTransaction() {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+ if (mActive) {
+ mChan->mTransactionStack = mNext;
+ }
+ }
+
+ void Cancel() {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+ AutoEnterTransaction* cur = mChan->mTransactionStack;
+ MOZ_RELEASE_ASSERT(cur == this);
+ while (cur && cur->mNestedLevel != IPC::Message::NOT_NESTED) {
+ // Note that, in the following situation, we will cancel multiple
+ // transactions:
+ // 1. Parent sends NESTED_INSIDE_SYNC message P1 to child.
+ // 2. Child sends NESTED_INSIDE_SYNC message C1 to child.
+ // 3. Child dispatches P1, parent blocks.
+ // 4. Child cancels.
+ // In this case, both P1 and C1 are cancelled. The parent will
+ // remove C1 from its queue when it gets the cancellation message.
+ MOZ_RELEASE_ASSERT(cur->mActive);
+ cur->mActive = false;
+ cur = cur->mNext;
+ }
+
+ mChan->mTransactionStack = cur;
+
+ MOZ_RELEASE_ASSERT(IsComplete());
+ }
+
+ bool AwaitingSyncReply() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ if (mOutgoing) {
+ return true;
+ }
+ return mNext ? mNext->AwaitingSyncReply() : false;
+ }
+
+ int AwaitingSyncReplyNestedLevel() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ if (mOutgoing) {
+ return mNestedLevel;
+ }
+ return mNext ? mNext->AwaitingSyncReplyNestedLevel() : 0;
+ }
+
+ bool DispatchingSyncMessage() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ if (!mOutgoing) {
+ return true;
+ }
+ return mNext ? mNext->DispatchingSyncMessage() : false;
+ }
+
+ int DispatchingSyncMessageNestedLevel() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ if (!mOutgoing) {
+ return mNestedLevel;
+ }
+ return mNext ? mNext->DispatchingSyncMessageNestedLevel() : 0;
+ }
+
+ int NestedLevel() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ return mNestedLevel;
+ }
+
+ int32_t SequenceNumber() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ return mSeqno;
+ }
+
+ int32_t TransactionID() const {
+ MOZ_RELEASE_ASSERT(mActive);
+ return mTransaction;
+ }
+
+ void ReceivedReply(UniquePtr<IPC::Message> aMessage) {
+ MOZ_RELEASE_ASSERT(aMessage->seqno() == mSeqno);
+ MOZ_RELEASE_ASSERT(aMessage->transaction_id() == mTransaction);
+ MOZ_RELEASE_ASSERT(!mReply);
+ IPC_LOG("Reply received on worker thread: seqno=%d", mSeqno);
+ mReply = std::move(aMessage);
+ MOZ_RELEASE_ASSERT(IsComplete());
+ }
+
+ void HandleReply(UniquePtr<IPC::Message> aMessage) {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+ AutoEnterTransaction* cur = mChan->mTransactionStack;
+ MOZ_RELEASE_ASSERT(cur == this);
+ while (cur) {
+ MOZ_RELEASE_ASSERT(cur->mActive);
+ if (aMessage->seqno() == cur->mSeqno) {
+ cur->ReceivedReply(std::move(aMessage));
+ break;
+ }
+ cur = cur->mNext;
+ MOZ_RELEASE_ASSERT(cur);
+ }
+ }
+
+ bool IsComplete() { return !mActive || mReply; }
+
+ bool IsOutgoing() { return mOutgoing; }
+
+ bool IsCanceled() { return !mActive; }
+
+ bool IsBottom() const { return !mNext; }
+
+ bool IsError() {
+ MOZ_RELEASE_ASSERT(mReply);
+ return mReply->is_reply_error();
+ }
+
+ UniquePtr<IPC::Message> GetReply() { return std::move(mReply); }
+
+ private:
+ MessageChannel* mChan;
+
+ // Active is true if this transaction is on the mChan->mTransactionStack
+ // stack. Generally we're not on the stack if the transaction was canceled
+ // or if it was for a message that doesn't require transactions (an async
+ // message).
+ bool mActive;
+
+ // Is this stack frame for an outgoing message?
+ bool mOutgoing;
+
+ // Properties of the message being sent/received.
+ int mNestedLevel;
+ int32_t mSeqno;
+ int32_t mTransaction;
+
+ // Next item in mChan->mTransactionStack.
+ AutoEnterTransaction* mNext;
+
+ // Pointer the a reply received for this message, if one was received.
+ UniquePtr<IPC::Message> mReply;
+};
+
+class PendingResponseReporter final : public nsIMemoryReporter {
+ ~PendingResponseReporter() = default;
+
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ NS_IMETHOD
+ CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData,
+ bool aAnonymize) override {
+ MOZ_COLLECT_REPORT(
+ "unresolved-ipc-responses", KIND_OTHER, UNITS_COUNT,
+ MessageChannel::gUnresolvedResponses,
+ "Outstanding IPC async message responses that are still not resolved.");
+ return NS_OK;
+ }
+};
+
+NS_IMPL_ISUPPORTS(PendingResponseReporter, nsIMemoryReporter)
+
+class ChannelCountReporter final : public nsIMemoryReporter {
+ ~ChannelCountReporter() = default;
+
+ struct ChannelCounts {
+ size_t mNow;
+ size_t mMax;
+
+ ChannelCounts() : mNow(0), mMax(0) {}
+
+ void Inc() {
+ ++mNow;
+ if (mMax < mNow) {
+ mMax = mNow;
+ }
+ }
+
+ void Dec() {
+ MOZ_ASSERT(mNow > 0);
+ --mNow;
+ }
+ };
+
+ using CountTable = nsTHashMap<nsDepCharHashKey, ChannelCounts>;
+
+ static StaticMutex sChannelCountMutex;
+ static CountTable* sChannelCounts MOZ_GUARDED_BY(sChannelCountMutex);
+
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ NS_IMETHOD
+ CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData,
+ bool aAnonymize) override {
+ AutoTArray<std::pair<const char*, ChannelCounts>, 16> counts;
+ {
+ StaticMutexAutoLock countLock(sChannelCountMutex);
+ if (!sChannelCounts) {
+ return NS_OK;
+ }
+ counts.SetCapacity(sChannelCounts->Count());
+ for (const auto& entry : *sChannelCounts) {
+ counts.AppendElement(std::pair{entry.GetKey(), entry.GetData()});
+ }
+ }
+
+ for (const auto& entry : counts) {
+ nsPrintfCString pathNow("ipc-channels/%s", entry.first);
+ nsPrintfCString pathMax("ipc-channels-peak/%s", entry.first);
+ nsPrintfCString descNow(
+ "Number of IPC channels for"
+ " top-level actor type %s",
+ entry.first);
+ nsPrintfCString descMax(
+ "Peak number of IPC channels for"
+ " top-level actor type %s",
+ entry.first);
+
+ aHandleReport->Callback(""_ns, pathNow, KIND_OTHER, UNITS_COUNT,
+ entry.second.mNow, descNow, aData);
+ aHandleReport->Callback(""_ns, pathMax, KIND_OTHER, UNITS_COUNT,
+ entry.second.mMax, descMax, aData);
+ }
+ return NS_OK;
+ }
+
+ static void Increment(const char* aName) {
+ StaticMutexAutoLock countLock(sChannelCountMutex);
+ if (!sChannelCounts) {
+ sChannelCounts = new CountTable;
+ }
+ sChannelCounts->LookupOrInsert(aName).Inc();
+ }
+
+ static void Decrement(const char* aName) {
+ StaticMutexAutoLock countLock(sChannelCountMutex);
+ MOZ_ASSERT(sChannelCounts);
+ sChannelCounts->LookupOrInsert(aName).Dec();
+ }
+};
+
+StaticMutex ChannelCountReporter::sChannelCountMutex;
+ChannelCountReporter::CountTable* ChannelCountReporter::sChannelCounts;
+
+NS_IMPL_ISUPPORTS(ChannelCountReporter, nsIMemoryReporter)
+
+// In child processes, the first MessageChannel is created before
+// XPCOM is initialized enough to construct the memory reporter
+// manager. This retries every time a MessageChannel is constructed,
+// which is good enough in practice.
+template <class Reporter>
+static void TryRegisterStrongMemoryReporter() {
+ static Atomic<bool> registered;
+ if (registered.compareExchange(false, true)) {
+ RefPtr<Reporter> reporter = new Reporter();
+ if (NS_FAILED(RegisterStrongMemoryReporter(reporter))) {
+ registered = false;
+ }
+ }
+}
+
+Atomic<size_t> MessageChannel::gUnresolvedResponses;
+
+MessageChannel::MessageChannel(const char* aName, IToplevelProtocol* aListener)
+ : mName(aName), mListener(aListener), mMonitor(new RefCountedMonitor()) {
+ MOZ_COUNT_CTOR(ipc::MessageChannel);
+
+#ifdef XP_WIN
+ mEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
+ MOZ_RELEASE_ASSERT(mEvent, "CreateEvent failed! Nothing is going to work!");
+#endif
+
+ TryRegisterStrongMemoryReporter<PendingResponseReporter>();
+ TryRegisterStrongMemoryReporter<ChannelCountReporter>();
+}
+
+MessageChannel::~MessageChannel() {
+ MOZ_COUNT_DTOR(ipc::MessageChannel);
+ MonitorAutoLock lock(*mMonitor);
+ MOZ_RELEASE_ASSERT(!mOnCxxStack,
+ "MessageChannel destroyed while code on CxxStack");
+#ifdef XP_WIN
+ if (mEvent) {
+ BOOL ok = CloseHandle(mEvent);
+ mEvent = nullptr;
+
+ if (!ok) {
+ gfxDevCrash(mozilla::gfx::LogReason::MessageChannelCloseFailure)
+ << "MessageChannel failed to close. GetLastError: " << GetLastError();
+ }
+ MOZ_RELEASE_ASSERT(ok);
+ } else {
+ gfxDevCrash(mozilla::gfx::LogReason::MessageChannelCloseFailure)
+ << "MessageChannel destructor ran without an mEvent Handle";
+ }
+#endif
+
+ // Make sure that the MessageChannel was closed (and therefore cleared) before
+ // it was destroyed. We can't properly close the channel at this point, as it
+ // would be unsafe to invoke our listener's callbacks, and we may be being
+ // destroyed on a thread other than `mWorkerThread`.
+ if (!IsClosedLocked()) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCFatalErrorProtocol,
+ nsDependentCString(mName));
+ switch (mChannelState) {
+ case ChannelConnected:
+ MOZ_CRASH(
+ "MessageChannel destroyed without being closed "
+ "(mChannelState == ChannelConnected).");
+ break;
+ case ChannelClosing:
+ MOZ_CRASH(
+ "MessageChannel destroyed without being closed "
+ "(mChannelState == ChannelClosing).");
+ break;
+ case ChannelError:
+ MOZ_CRASH(
+ "MessageChannel destroyed without being closed "
+ "(mChannelState == ChannelError).");
+ break;
+ default:
+ MOZ_CRASH("MessageChannel destroyed without being closed.");
+ }
+ }
+
+ // Double-check other properties for thoroughness.
+ MOZ_RELEASE_ASSERT(!mLink);
+ MOZ_RELEASE_ASSERT(mPendingResponses.empty());
+ MOZ_RELEASE_ASSERT(!mChannelErrorTask);
+ MOZ_RELEASE_ASSERT(mPending.isEmpty());
+ MOZ_RELEASE_ASSERT(!mShutdownTask);
+}
+
+#ifdef DEBUG
+void MessageChannel::AssertMaybeDeferredCountCorrect() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ size_t count = 0;
+ for (MessageTask* task : mPending) {
+ task->AssertMonitorHeld(*mMonitor);
+ if (!IsAlwaysDeferred(*task->Msg())) {
+ count++;
+ }
+ }
+
+ MOZ_ASSERT(count == mMaybeDeferredPendingCount);
+}
+#endif
+
+// This function returns the current transaction ID. Since the notion of a
+// "current transaction" can be hard to define when messages race with each
+// other and one gets canceled and the other doesn't, we require that this
+// function is only called when the current transaction is known to be for a
+// NESTED_INSIDE_SYNC message. In that case, we know for sure what the caller is
+// looking for.
+int32_t MessageChannel::CurrentNestedInsideSyncTransaction() const {
+ mMonitor->AssertCurrentThreadOwns();
+ if (!mTransactionStack) {
+ return 0;
+ }
+ MOZ_RELEASE_ASSERT(mTransactionStack->NestedLevel() ==
+ IPC::Message::NESTED_INSIDE_SYNC);
+ return mTransactionStack->TransactionID();
+}
+
+bool MessageChannel::AwaitingSyncReply() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return mTransactionStack ? mTransactionStack->AwaitingSyncReply() : false;
+}
+
+int MessageChannel::AwaitingSyncReplyNestedLevel() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return mTransactionStack ? mTransactionStack->AwaitingSyncReplyNestedLevel()
+ : 0;
+}
+
+bool MessageChannel::DispatchingSyncMessage() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return mTransactionStack ? mTransactionStack->DispatchingSyncMessage()
+ : false;
+}
+
+int MessageChannel::DispatchingSyncMessageNestedLevel() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return mTransactionStack
+ ? mTransactionStack->DispatchingSyncMessageNestedLevel()
+ : 0;
+}
+
+static void PrintErrorMessage(Side side, const char* channelName,
+ const char* msg) {
+ printf_stderr("\n###!!! [%s][%s] Error: %s\n\n", StringFromIPCSide(side),
+ channelName, msg);
+}
+
+bool MessageChannel::Connected() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return ChannelConnected == mChannelState;
+}
+
+bool MessageChannel::ConnectedOrClosing() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return ChannelConnected == mChannelState || ChannelClosing == mChannelState;
+}
+
+bool MessageChannel::CanSend() const {
+ if (!mMonitor) {
+ return false;
+ }
+ MonitorAutoLock lock(*mMonitor);
+ return Connected();
+}
+
+void MessageChannel::Clear() {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+ MOZ_DIAGNOSTIC_ASSERT(IsClosedLocked(), "MessageChannel cleared too early?");
+ MOZ_ASSERT(ChannelClosed == mChannelState || ChannelError == mChannelState);
+
+ // Don't clear mWorkerThread; we use it in AssertWorkerThread().
+ //
+ // Also don't clear mListener. If we clear it, then sending a message
+ // through this channel after it's Clear()'ed can cause this process to
+ // crash.
+
+ if (mShutdownTask) {
+ mShutdownTask->Clear();
+ mWorkerThread->UnregisterShutdownTask(mShutdownTask);
+ }
+ mShutdownTask = nullptr;
+
+ if (NS_IsMainThread() && gParentProcessBlocker == this) {
+ gParentProcessBlocker = nullptr;
+ }
+
+ gUnresolvedResponses -= mPendingResponses.size();
+ {
+ CallbackMap map = std::move(mPendingResponses);
+ MonitorAutoUnlock unlock(*mMonitor);
+ for (auto& pair : map) {
+ pair.second->Reject(ResponseRejectReason::ChannelClosed);
+ }
+ }
+ mPendingResponses.clear();
+
+ SetIsCrossProcess(false);
+
+ mLink = nullptr;
+
+ if (mChannelErrorTask) {
+ mChannelErrorTask->Cancel();
+ mChannelErrorTask = nullptr;
+ }
+
+ if (mFlushLazySendTask) {
+ mFlushLazySendTask->Cancel();
+ mFlushLazySendTask = nullptr;
+ }
+
+ // Free up any memory used by pending messages.
+ mPending.clear();
+
+ mMaybeDeferredPendingCount = 0;
+}
+
+bool MessageChannel::Open(ScopedPort aPort, Side aSide,
+ const nsID& aMessageChannelId,
+ nsISerialEventTarget* aEventTarget) {
+ nsCOMPtr<nsISerialEventTarget> eventTarget =
+ aEventTarget ? aEventTarget : GetCurrentSerialEventTarget();
+ MOZ_RELEASE_ASSERT(eventTarget,
+ "Must open MessageChannel on a nsISerialEventTarget");
+ MOZ_RELEASE_ASSERT(eventTarget->IsOnCurrentThread(),
+ "Must open MessageChannel from worker thread");
+
+ auto shutdownTask = MakeRefPtr<WorkerTargetShutdownTask>(eventTarget, this);
+ nsresult rv = eventTarget->RegisterShutdownTask(shutdownTask);
+ MOZ_ASSERT(rv != NS_ERROR_NOT_IMPLEMENTED,
+ "target for MessageChannel must support shutdown tasks");
+ if (rv == NS_ERROR_UNEXPECTED) {
+ // If shutdown tasks have already started running, dispatch our shutdown
+ // task manually.
+ NS_WARNING("Opening MessageChannel on EventTarget in shutdown");
+ rv = eventTarget->Dispatch(shutdownTask->AsRunnable());
+ }
+ MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv),
+ "error registering ShutdownTask for MessageChannel");
+
+ {
+ MonitorAutoLock lock(*mMonitor);
+ MOZ_RELEASE_ASSERT(!mLink, "Open() called > once");
+ MOZ_RELEASE_ASSERT(ChannelClosed == mChannelState, "Not currently closed");
+ MOZ_ASSERT(mSide == UnknownSide);
+
+ mMessageChannelId = aMessageChannelId;
+ mWorkerThread = eventTarget;
+ mShutdownTask = shutdownTask;
+ mLink = MakeUnique<PortLink>(this, std::move(aPort));
+ mChannelState = ChannelConnected;
+ mSide = aSide;
+ }
+
+ // Notify our listener that the underlying IPC channel has been established.
+ // IProtocol will use this callback to create the ActorLifecycleProxy, and
+ // perform an `AddRef` call to keep the actor alive until the channel is
+ // disconnected.
+ //
+ // We unlock our monitor before calling `OnIPCChannelOpened` to ensure that
+ // any calls back into `MessageChannel` do not deadlock. At this point, we may
+ // be receiving messages on the IO thread, however we cannot process them on
+ // the worker thread or have notified our listener until after this function
+ // returns.
+ mListener->OnIPCChannelOpened();
+ return true;
+}
+
+static Side GetOppSide(Side aSide) {
+ switch (aSide) {
+ case ChildSide:
+ return ParentSide;
+ case ParentSide:
+ return ChildSide;
+ default:
+ return UnknownSide;
+ }
+}
+
+bool MessageChannel::Open(MessageChannel* aTargetChan,
+ nsISerialEventTarget* aEventTarget, Side aSide) {
+ // Opens a connection to another thread in the same process.
+
+ MOZ_ASSERT(aTargetChan, "Need a target channel");
+
+ nsID channelId = nsID::GenerateUUID();
+
+ std::pair<ScopedPort, ScopedPort> ports =
+ NodeController::GetSingleton()->CreatePortPair();
+
+ // NOTE: This dispatch must be sync as it captures locals by non-owning
+ // reference, however we can't use `NS_DispatchAndSpinEventLoopUntilComplete`
+ // as that will spin a nested event loop, and doesn't work with certain types
+ // of calling event targets.
+ base::WaitableEvent event(/* manual_reset */ true,
+ /* initially_signaled */ false);
+ MOZ_ALWAYS_SUCCEEDS(aEventTarget->Dispatch(NS_NewCancelableRunnableFunction(
+ "ipc::MessageChannel::OpenAsOtherThread", [&]() {
+ aTargetChan->Open(std::move(ports.second), GetOppSide(aSide), channelId,
+ aEventTarget);
+ event.Signal();
+ })));
+ bool ok = event.Wait();
+ MOZ_RELEASE_ASSERT(ok);
+
+ // Now that the other side has connected, open the port on our side.
+ return Open(std::move(ports.first), aSide, channelId);
+}
+
+bool MessageChannel::OpenOnSameThread(MessageChannel* aTargetChan,
+ mozilla::ipc::Side aSide) {
+ auto [porta, portb] = NodeController::GetSingleton()->CreatePortPair();
+
+ nsID channelId = nsID::GenerateUUID();
+
+ aTargetChan->mIsSameThreadChannel = true;
+ mIsSameThreadChannel = true;
+
+ auto* currentThread = GetCurrentSerialEventTarget();
+ return aTargetChan->Open(std::move(portb), GetOppSide(aSide), channelId,
+ currentThread) &&
+ Open(std::move(porta), aSide, channelId, currentThread);
+}
+
+bool MessageChannel::Send(UniquePtr<Message> aMsg) {
+ if (aMsg->size() >= kMinTelemetryMessageSize) {
+ Telemetry::Accumulate(Telemetry::IPC_MESSAGE_SIZE2, aMsg->size());
+ }
+
+ MOZ_RELEASE_ASSERT(!aMsg->is_sync());
+ MOZ_RELEASE_ASSERT(aMsg->nested_level() != IPC::Message::NESTED_INSIDE_SYNC);
+
+ AutoSetValue<bool> setOnCxxStack(mOnCxxStack, true);
+
+ AssertWorkerThread();
+ mMonitor->AssertNotCurrentThreadOwns();
+ if (MSG_ROUTING_NONE == aMsg->routing_id()) {
+ ReportMessageRouteError("MessageChannel::Send");
+ return false;
+ }
+
+ if (aMsg->seqno() == 0) {
+ aMsg->set_seqno(NextSeqno());
+ }
+
+ MonitorAutoLock lock(*mMonitor);
+ if (!Connected()) {
+ ReportConnectionError("Send", aMsg->type());
+ return false;
+ }
+
+ AddProfilerMarker(*aMsg, MessageDirection::eSending);
+ SendMessageToLink(std::move(aMsg));
+ return true;
+}
+
+void MessageChannel::SendMessageToLink(UniquePtr<Message> aMsg) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ // If the channel is not cross-process, there's no reason to be lazy, so we
+ // ignore the flag in that case.
+ if (aMsg->is_lazy_send() && mIsCrossProcess) {
+ // If this is the first lazy message in the queue and our worker thread
+ // supports direct task dispatch, dispatch a task to flush messages,
+ // ensuring we don't leave them pending forever.
+ if (!mFlushLazySendTask) {
+ if (nsCOMPtr<nsIDirectTaskDispatcher> dispatcher =
+ do_QueryInterface(mWorkerThread)) {
+ mFlushLazySendTask = new FlushLazySendMessagesRunnable(this);
+ MOZ_ALWAYS_SUCCEEDS(
+ dispatcher->DispatchDirectTask(do_AddRef(mFlushLazySendTask)));
+ }
+ }
+ if (mFlushLazySendTask) {
+ mFlushLazySendTask->PushMessage(std::move(aMsg));
+ return;
+ }
+ }
+
+ if (mFlushLazySendTask) {
+ FlushLazySendMessages();
+ }
+ mLink->SendMessage(std::move(aMsg));
+}
+
+void MessageChannel::FlushLazySendMessages() {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ // Clean up any SendLazyTask which might be pending.
+ auto messages = mFlushLazySendTask->TakeMessages();
+ mFlushLazySendTask = nullptr;
+
+ // Send all lazy messages, then clear the queue.
+ for (auto& msg : messages) {
+ mLink->SendMessage(std::move(msg));
+ }
+}
+
+UniquePtr<MessageChannel::UntypedCallbackHolder> MessageChannel::PopCallback(
+ const Message& aMsg, int32_t aActorId) {
+ auto iter = mPendingResponses.find(aMsg.seqno());
+ if (iter != mPendingResponses.end() && iter->second->mActorId == aActorId &&
+ iter->second->mReplyMsgId == aMsg.type()) {
+ UniquePtr<MessageChannel::UntypedCallbackHolder> ret =
+ std::move(iter->second);
+ mPendingResponses.erase(iter);
+ gUnresolvedResponses--;
+ return ret;
+ }
+ return nullptr;
+}
+
+void MessageChannel::RejectPendingResponsesForActor(int32_t aActorId) {
+ auto itr = mPendingResponses.begin();
+ while (itr != mPendingResponses.end()) {
+ if (itr->second.get()->mActorId != aActorId) {
+ ++itr;
+ continue;
+ }
+ itr->second.get()->Reject(ResponseRejectReason::ActorDestroyed);
+ // Take special care of advancing the iterator since we are
+ // removing it while iterating.
+ itr = mPendingResponses.erase(itr);
+ gUnresolvedResponses--;
+ }
+}
+
+class BuildIDsMatchMessage : public IPC::Message {
+ public:
+ BuildIDsMatchMessage()
+ : IPC::Message(MSG_ROUTING_NONE, BUILD_IDS_MATCH_MESSAGE_TYPE) {}
+ void Log(const std::string& aPrefix, FILE* aOutf) const {
+ fputs("(special `Build IDs match' message)", aOutf);
+ }
+};
+
+// Send the parent a special async message to confirm when the parent and child
+// are of the same buildID. Skips sending the message and returns false if the
+// buildIDs don't match. This is a minor variation on
+// MessageChannel::Send(Message* aMsg).
+bool MessageChannel::SendBuildIDsMatchMessage(const char* aParentBuildID) {
+ MOZ_ASSERT(!XRE_IsParentProcess());
+
+ nsCString parentBuildID(aParentBuildID);
+ nsCString childBuildID(mozilla::PlatformBuildID());
+
+ if (parentBuildID != childBuildID) {
+ // The build IDs didn't match, usually because an update occurred in the
+ // background.
+ return false;
+ }
+
+ auto msg = MakeUnique<BuildIDsMatchMessage>();
+
+ MOZ_RELEASE_ASSERT(!msg->is_sync());
+ MOZ_RELEASE_ASSERT(msg->nested_level() != IPC::Message::NESTED_INSIDE_SYNC);
+
+ AssertWorkerThread();
+ mMonitor->AssertNotCurrentThreadOwns();
+ // Don't check for MSG_ROUTING_NONE.
+
+ MonitorAutoLock lock(*mMonitor);
+ if (!Connected()) {
+ ReportConnectionError("SendBuildIDsMatchMessage", msg->type());
+ return false;
+ }
+
+#if defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+ // Technically, the behavior is interesting for any kind of process
+ // but when exercising tests, we want to crash only a content process and
+ // avoid making noise with other kind of processes crashing
+ if (const char* dontSend = PR_GetEnv("MOZ_BUILDID_MATCH_DONTSEND")) {
+ if (dontSend[0] == '1') {
+ // Bug 1732999: We are going to crash, so we need to advise leak check
+ // tooling to avoid intermittent missing leakcheck
+ NoteIntentionalCrash(XRE_GetProcessTypeString());
+ if (XRE_IsContentProcess()) {
+ return false;
+ }
+ }
+ }
+#endif
+
+ SendMessageToLink(std::move(msg));
+ return true;
+}
+
+class CancelMessage : public IPC::Message {
+ public:
+ explicit CancelMessage(int transaction)
+ : IPC::Message(MSG_ROUTING_NONE, CANCEL_MESSAGE_TYPE) {
+ set_transaction_id(transaction);
+ }
+ static bool Read(const Message* msg) { return true; }
+ void Log(const std::string& aPrefix, FILE* aOutf) const {
+ fputs("(special `Cancel' message)", aOutf);
+ }
+};
+
+bool MessageChannel::MaybeInterceptSpecialIOMessage(const Message& aMsg) {
+ mMonitor->AssertCurrentThreadOwns();
+
+ if (MSG_ROUTING_NONE == aMsg.routing_id()) {
+ if (GOODBYE_MESSAGE_TYPE == aMsg.type()) {
+ // We've received a GOODBYE message, close the connection and mark
+ // ourselves as "Closing".
+ mLink->Close();
+ mChannelState = ChannelClosing;
+ if (LoggingEnabledFor(mListener->GetProtocolName(), mSide)) {
+ printf(
+ "[%s %u] NOTE: %s%s actor received `Goodbye' message. Closing "
+ "channel.\n",
+ XRE_GeckoProcessTypeToString(XRE_GetProcessType()),
+ static_cast<uint32_t>(base::GetCurrentProcId()),
+ mListener->GetProtocolName(), StringFromIPCSide(mSide));
+ }
+
+ // Notify the worker thread that the connection has been closed, as we
+ // will not receive an `OnChannelErrorFromLink` after calling
+ // `mLink->Close()`.
+ if (AwaitingSyncReply()) {
+ NotifyWorkerThread();
+ }
+ PostErrorNotifyTask();
+ return true;
+ } else if (CANCEL_MESSAGE_TYPE == aMsg.type()) {
+ IPC_LOG("Cancel from message");
+ CancelTransaction(aMsg.transaction_id());
+ NotifyWorkerThread();
+ return true;
+ } else if (BUILD_IDS_MATCH_MESSAGE_TYPE == aMsg.type()) {
+ IPC_LOG("Build IDs match message");
+ mBuildIDsConfirmedMatch = true;
+ return true;
+ } else if (IMPENDING_SHUTDOWN_MESSAGE_TYPE == aMsg.type()) {
+ IPC_LOG("Impending Shutdown received");
+ ProcessChild::NotifiedImpendingShutdown();
+ return true;
+ }
+ }
+ return false;
+}
+
+/* static */
+bool MessageChannel::IsAlwaysDeferred(const Message& aMsg) {
+ // If a message is not NESTED_INSIDE_CPOW and not sync, then we always defer
+ // it.
+ return aMsg.nested_level() != IPC::Message::NESTED_INSIDE_CPOW &&
+ !aMsg.is_sync();
+}
+
+bool MessageChannel::ShouldDeferMessage(const Message& aMsg) {
+ // Never defer messages that have the highest nested level, even async
+ // ones. This is safe because only the child can send these messages, so
+ // they can never nest.
+ if (aMsg.nested_level() == IPC::Message::NESTED_INSIDE_CPOW) {
+ MOZ_ASSERT(!IsAlwaysDeferred(aMsg));
+ return false;
+ }
+
+ // Unless they're NESTED_INSIDE_CPOW, we always defer async messages.
+ // Note that we never send an async NESTED_INSIDE_SYNC message.
+ if (!aMsg.is_sync()) {
+ MOZ_RELEASE_ASSERT(aMsg.nested_level() == IPC::Message::NOT_NESTED);
+ MOZ_ASSERT(IsAlwaysDeferred(aMsg));
+ return true;
+ }
+
+ MOZ_ASSERT(!IsAlwaysDeferred(aMsg));
+
+ int msgNestedLevel = aMsg.nested_level();
+ int waitingNestedLevel = AwaitingSyncReplyNestedLevel();
+
+ // Always defer if the nested level of the incoming message is less than the
+ // nested level of the message we're awaiting.
+ if (msgNestedLevel < waitingNestedLevel) return true;
+
+ // Never defer if the message has strictly greater nested level.
+ if (msgNestedLevel > waitingNestedLevel) return false;
+
+ // When both sides send sync messages of the same nested level, we resolve the
+ // race by dispatching in the child and deferring the incoming message in
+ // the parent. However, the parent still needs to dispatch nested sync
+ // messages.
+ //
+ // Deferring in the parent only sort of breaks message ordering. When the
+ // child's message comes in, we can pretend the child hasn't quite
+ // finished sending it yet. Since the message is sync, we know that the
+ // child hasn't moved on yet.
+ return mSide == ParentSide &&
+ aMsg.transaction_id() != CurrentNestedInsideSyncTransaction();
+}
+
+void MessageChannel::OnMessageReceivedFromLink(UniquePtr<Message> aMsg) {
+ mMonitor->AssertCurrentThreadOwns();
+ MOZ_ASSERT(mChannelState == ChannelConnected);
+
+ if (MaybeInterceptSpecialIOMessage(*aMsg)) {
+ return;
+ }
+
+ mListener->OnChannelReceivedMessage(*aMsg);
+
+ // If we're awaiting a sync reply, we know that it needs to be immediately
+ // handled to unblock us.
+ if (aMsg->is_sync() && aMsg->is_reply()) {
+ IPC_LOG("Received reply seqno=%d xid=%d", aMsg->seqno(),
+ aMsg->transaction_id());
+
+ if (aMsg->seqno() == mTimedOutMessageSeqno) {
+ // Drop the message, but allow future sync messages to be sent.
+ IPC_LOG("Received reply to timedout message; igoring; xid=%d",
+ mTimedOutMessageSeqno);
+ EndTimeout();
+ return;
+ }
+
+ MOZ_RELEASE_ASSERT(AwaitingSyncReply());
+ MOZ_RELEASE_ASSERT(!mTimedOutMessageSeqno);
+
+ mTransactionStack->HandleReply(std::move(aMsg));
+ NotifyWorkerThread();
+ return;
+ }
+
+ // Nested messages cannot be compressed.
+ MOZ_RELEASE_ASSERT(aMsg->compress_type() == IPC::Message::COMPRESSION_NONE ||
+ aMsg->nested_level() == IPC::Message::NOT_NESTED);
+
+ if (aMsg->compress_type() == IPC::Message::COMPRESSION_ENABLED &&
+ !mPending.isEmpty()) {
+ auto* last = mPending.getLast();
+ last->AssertMonitorHeld(*mMonitor);
+ bool compress = last->Msg()->type() == aMsg->type() &&
+ last->Msg()->routing_id() == aMsg->routing_id();
+ if (compress) {
+ // This message type has compression enabled, and the back of the
+ // queue was the same message type and routed to the same destination.
+ // Replace it with the newer message.
+ MOZ_RELEASE_ASSERT(last->Msg()->compress_type() ==
+ IPC::Message::COMPRESSION_ENABLED);
+ last->Msg() = std::move(aMsg);
+ return;
+ }
+ } else if (aMsg->compress_type() == IPC::Message::COMPRESSION_ALL &&
+ !mPending.isEmpty()) {
+ for (MessageTask* p = mPending.getLast(); p; p = p->getPrevious()) {
+ p->AssertMonitorHeld(*mMonitor);
+ if (p->Msg()->type() == aMsg->type() &&
+ p->Msg()->routing_id() == aMsg->routing_id()) {
+ // This message type has compression enabled, and the queue
+ // holds a message with the same message type and routed to the
+ // same destination. Erase it. Note that, since we always
+ // compress these redundancies, There Can Be Only One.
+ MOZ_RELEASE_ASSERT(p->Msg()->compress_type() ==
+ IPC::Message::COMPRESSION_ALL);
+ MOZ_RELEASE_ASSERT(IsAlwaysDeferred(*p->Msg()));
+ p->remove();
+ break;
+ }
+ }
+ }
+
+ bool alwaysDeferred = IsAlwaysDeferred(*aMsg);
+
+ bool shouldWakeUp = AwaitingSyncReply() && !ShouldDeferMessage(*aMsg);
+
+ IPC_LOG("Receive from link; seqno=%d, xid=%d, shouldWakeUp=%d", aMsg->seqno(),
+ aMsg->transaction_id(), shouldWakeUp);
+
+ // There are two cases we're concerned about, relating to the state of the
+ // worker thread:
+ //
+ // (1) We are waiting on a sync reply - worker thread is blocked on the
+ // IPC monitor.
+ // - If the message is NESTED_INSIDE_SYNC, we wake up the worker thread to
+ // deliver the message depending on ShouldDeferMessage. Otherwise, we
+ // leave it in the mPending queue, posting a task to the worker event
+ // loop, where it will be processed once the synchronous reply has been
+ // received.
+ //
+ // (2) We are not waiting on a reply.
+ // - We post a task to the worker event loop.
+ //
+ // Note that, we may notify the worker thread even though the monitor is not
+ // blocked. This is okay, since we always check for pending events before
+ // blocking again.
+
+ RefPtr<MessageTask> task = new MessageTask(this, std::move(aMsg));
+ mPending.insertBack(task);
+
+ if (!alwaysDeferred) {
+ mMaybeDeferredPendingCount++;
+ }
+
+ if (shouldWakeUp) {
+ NotifyWorkerThread();
+ }
+
+ // Although we usually don't need to post a message task if
+ // shouldWakeUp is true, it's easier to post anyway than to have to
+ // guarantee that every Send call processes everything it's supposed to
+ // before returning.
+ task->AssertMonitorHeld(*mMonitor);
+ task->Post();
+}
+
+void MessageChannel::PeekMessages(
+ const std::function<bool(const Message& aMsg)>& aInvoke) {
+ // FIXME: We shouldn't be holding the lock for aInvoke!
+ MonitorAutoLock lock(*mMonitor);
+
+ for (MessageTask* it : mPending) {
+ it->AssertMonitorHeld(*mMonitor);
+ const Message& msg = *it->Msg();
+ if (!aInvoke(msg)) {
+ break;
+ }
+ }
+}
+
+void MessageChannel::ProcessPendingRequests(
+ ActorLifecycleProxy* aProxy, AutoEnterTransaction& aTransaction) {
+ mMonitor->AssertCurrentThreadOwns();
+
+ AssertMaybeDeferredCountCorrect();
+ if (mMaybeDeferredPendingCount == 0) {
+ return;
+ }
+
+ IPC_LOG("ProcessPendingRequests for seqno=%d, xid=%d",
+ aTransaction.SequenceNumber(), aTransaction.TransactionID());
+
+ // Loop until there aren't any more nested messages to process.
+ for (;;) {
+ // If we canceled during ProcessPendingRequest, then we need to leave
+ // immediately because the results of ShouldDeferMessage will be
+ // operating with weird state (as if no Send is in progress). That could
+ // cause even NOT_NESTED sync messages to be processed (but not
+ // NOT_NESTED async messages), which would break message ordering.
+ if (aTransaction.IsCanceled()) {
+ return;
+ }
+
+ Vector<UniquePtr<Message>> toProcess;
+
+ for (MessageTask* p = mPending.getFirst(); p;) {
+ p->AssertMonitorHeld(*mMonitor);
+ UniquePtr<Message>& msg = p->Msg();
+
+ MOZ_RELEASE_ASSERT(!aTransaction.IsCanceled(),
+ "Calling ShouldDeferMessage when cancelled");
+ bool defer = ShouldDeferMessage(*msg);
+
+ // Only log the interesting messages.
+ if (msg->is_sync() ||
+ msg->nested_level() == IPC::Message::NESTED_INSIDE_CPOW) {
+ IPC_LOG("ShouldDeferMessage(seqno=%d) = %d", msg->seqno(), defer);
+ }
+
+ if (!defer) {
+ MOZ_ASSERT(!IsAlwaysDeferred(*msg));
+
+ if (!toProcess.append(std::move(msg))) MOZ_CRASH();
+
+ mMaybeDeferredPendingCount--;
+
+ p = p->removeAndGetNext();
+ continue;
+ }
+ p = p->getNext();
+ }
+
+ if (toProcess.empty()) {
+ break;
+ }
+
+ // Processing these messages could result in more messages, so we
+ // loop around to check for more afterwards.
+
+ for (auto& msg : toProcess) {
+ ProcessPendingRequest(aProxy, std::move(msg));
+ }
+ }
+
+ AssertMaybeDeferredCountCorrect();
+}
+
+bool MessageChannel::Send(UniquePtr<Message> aMsg, UniquePtr<Message>* aReply) {
+ mozilla::TimeStamp start = TimeStamp::Now();
+ if (aMsg->size() >= kMinTelemetryMessageSize) {
+ Telemetry::Accumulate(Telemetry::IPC_MESSAGE_SIZE2, aMsg->size());
+ }
+
+ // Sanity checks.
+ AssertWorkerThread();
+ mMonitor->AssertNotCurrentThreadOwns();
+ MOZ_RELEASE_ASSERT(!mIsSameThreadChannel,
+ "sync send over same-thread channel will deadlock!");
+
+ RefPtr<ActorLifecycleProxy> proxy = Listener()->GetLifecycleProxy();
+
+#ifdef XP_WIN
+ SyncStackFrame frame(this);
+ NeuteredWindowRegion neuteredRgn(mFlags &
+ REQUIRE_DEFERRED_MESSAGE_PROTECTION);
+#endif
+
+ AutoSetValue<bool> setOnCxxStack(mOnCxxStack, true);
+
+ MonitorAutoLock lock(*mMonitor);
+
+ if (mTimedOutMessageSeqno) {
+ // Don't bother sending another sync message if a previous one timed out
+ // and we haven't received a reply for it. Once the original timed-out
+ // message receives a reply, we'll be able to send more sync messages
+ // again.
+ IPC_LOG("Send() failed due to previous timeout");
+ mLastSendError = SyncSendError::PreviousTimeout;
+ return false;
+ }
+
+ if (DispatchingSyncMessageNestedLevel() == IPC::Message::NOT_NESTED &&
+ aMsg->nested_level() > IPC::Message::NOT_NESTED) {
+ // Don't allow sending CPOWs while we're dispatching a sync message.
+ IPC_LOG("Nested level forbids send");
+ mLastSendError = SyncSendError::SendingCPOWWhileDispatchingSync;
+ return false;
+ }
+
+ if (DispatchingSyncMessageNestedLevel() == IPC::Message::NESTED_INSIDE_CPOW ||
+ DispatchingAsyncMessageNestedLevel() ==
+ IPC::Message::NESTED_INSIDE_CPOW) {
+ // Generally only the parent dispatches urgent messages. And the only
+ // sync messages it can send are NESTED_INSIDE_SYNC. Mainly we want to
+ // ensure here that we don't return false for non-CPOW messages.
+ MOZ_RELEASE_ASSERT(aMsg->nested_level() ==
+ IPC::Message::NESTED_INSIDE_SYNC);
+ IPC_LOG("Sending while dispatching urgent message");
+ mLastSendError = SyncSendError::SendingCPOWWhileDispatchingUrgent;
+ return false;
+ }
+
+ if (aMsg->nested_level() < DispatchingSyncMessageNestedLevel() ||
+ aMsg->nested_level() < AwaitingSyncReplyNestedLevel()) {
+ MOZ_RELEASE_ASSERT(DispatchingSyncMessage() || DispatchingAsyncMessage());
+ IPC_LOG("Cancel from Send");
+ auto cancel =
+ MakeUnique<CancelMessage>(CurrentNestedInsideSyncTransaction());
+ CancelTransaction(CurrentNestedInsideSyncTransaction());
+ SendMessageToLink(std::move(cancel));
+ }
+
+ IPC_ASSERT(aMsg->is_sync(), "can only Send() sync messages here");
+
+ IPC_ASSERT(aMsg->nested_level() >= DispatchingSyncMessageNestedLevel(),
+ "can't send sync message of a lesser nested level than what's "
+ "being dispatched");
+ IPC_ASSERT(AwaitingSyncReplyNestedLevel() <= aMsg->nested_level(),
+ "nested sync message sends must be of increasing nested level");
+ IPC_ASSERT(
+ DispatchingSyncMessageNestedLevel() != IPC::Message::NESTED_INSIDE_CPOW,
+ "not allowed to send messages while dispatching urgent messages");
+
+ IPC_ASSERT(
+ DispatchingAsyncMessageNestedLevel() != IPC::Message::NESTED_INSIDE_CPOW,
+ "not allowed to send messages while dispatching urgent messages");
+
+ if (!Connected()) {
+ ReportConnectionError("SendAndWait", aMsg->type());
+ mLastSendError = SyncSendError::NotConnectedBeforeSend;
+ return false;
+ }
+
+ aMsg->set_seqno(NextSeqno());
+
+ int32_t seqno = aMsg->seqno();
+ int nestedLevel = aMsg->nested_level();
+ msgid_t replyType = aMsg->type() + 1;
+
+ AutoEnterTransaction* stackTop = mTransactionStack;
+
+ // If the most recent message on the stack is NESTED_INSIDE_SYNC, then our
+ // message should nest inside that and we use the same transaction
+ // ID. Otherwise we need a new transaction ID (so we use the seqno of the
+ // message we're sending).
+ bool nest =
+ stackTop && stackTop->NestedLevel() == IPC::Message::NESTED_INSIDE_SYNC;
+ int32_t transaction = nest ? stackTop->TransactionID() : seqno;
+ aMsg->set_transaction_id(transaction);
+
+ AutoEnterTransaction transact(this, seqno, transaction, nestedLevel);
+
+ IPC_LOG("Send seqno=%d, xid=%d", seqno, transaction);
+
+ // aMsg will be destroyed soon, let's keep its type.
+ const char* msgName = aMsg->name();
+ const msgid_t msgType = aMsg->type();
+
+ AddProfilerMarker(*aMsg, MessageDirection::eSending);
+ SendMessageToLink(std::move(aMsg));
+
+ while (true) {
+ MOZ_RELEASE_ASSERT(!transact.IsCanceled());
+ ProcessPendingRequests(proxy, transact);
+ if (transact.IsComplete()) {
+ break;
+ }
+ if (!Connected()) {
+ ReportConnectionError("Send", msgType);
+ mLastSendError = SyncSendError::DisconnectedDuringSend;
+ return false;
+ }
+
+ MOZ_RELEASE_ASSERT(!mTimedOutMessageSeqno);
+ MOZ_RELEASE_ASSERT(!transact.IsComplete());
+ MOZ_RELEASE_ASSERT(mTransactionStack == &transact);
+
+ bool maybeTimedOut = !WaitForSyncNotify();
+
+ if (mListener->NeedArtificialSleep()) {
+ MonitorAutoUnlock unlock(*mMonitor);
+ mListener->ArtificialSleep();
+ }
+
+ if (!Connected()) {
+ ReportConnectionError("SendAndWait", msgType);
+ mLastSendError = SyncSendError::DisconnectedDuringSend;
+ return false;
+ }
+
+ if (transact.IsCanceled()) {
+ break;
+ }
+
+ MOZ_RELEASE_ASSERT(mTransactionStack == &transact);
+
+ // We only time out a message if it initiated a new transaction (i.e.,
+ // if neither side has any other message Sends on the stack).
+ bool canTimeOut = transact.IsBottom();
+ if (maybeTimedOut && canTimeOut && !ShouldContinueFromTimeout()) {
+ // Since ShouldContinueFromTimeout drops the lock, we need to
+ // re-check all our conditions here. We shouldn't time out if any of
+ // these things happen because there won't be a reply to the timed
+ // out message in these cases.
+ if (transact.IsComplete()) {
+ break;
+ }
+
+ IPC_LOG("Timing out Send: xid=%d", transaction);
+
+ mTimedOutMessageSeqno = seqno;
+ mTimedOutMessageNestedLevel = nestedLevel;
+ mLastSendError = SyncSendError::TimedOut;
+ return false;
+ }
+
+ if (transact.IsCanceled()) {
+ break;
+ }
+ }
+
+ if (transact.IsCanceled()) {
+ IPC_LOG("Other side canceled seqno=%d, xid=%d", seqno, transaction);
+ mLastSendError = SyncSendError::CancelledAfterSend;
+ return false;
+ }
+
+ if (transact.IsError()) {
+ IPC_LOG("Error: seqno=%d, xid=%d", seqno, transaction);
+ mLastSendError = SyncSendError::ReplyError;
+ return false;
+ }
+
+ uint32_t latencyMs = round((TimeStamp::Now() - start).ToMilliseconds());
+ IPC_LOG("Got reply: seqno=%d, xid=%d, msgName=%s, latency=%ums", seqno,
+ transaction, msgName, latencyMs);
+
+ UniquePtr<Message> reply = transact.GetReply();
+
+ MOZ_RELEASE_ASSERT(reply);
+ MOZ_RELEASE_ASSERT(reply->is_reply(), "expected reply");
+ MOZ_RELEASE_ASSERT(!reply->is_reply_error());
+ MOZ_RELEASE_ASSERT(reply->seqno() == seqno);
+ MOZ_RELEASE_ASSERT(reply->type() == replyType, "wrong reply type");
+ MOZ_RELEASE_ASSERT(reply->is_sync());
+
+ AddProfilerMarker(*reply, MessageDirection::eReceiving);
+
+ if (reply->size() >= kMinTelemetryMessageSize) {
+ Telemetry::Accumulate(Telemetry::IPC_REPLY_SIZE,
+ nsDependentCString(msgName), reply->size());
+ }
+
+ *aReply = std::move(reply);
+
+ // NOTE: Only collect IPC_SYNC_MAIN_LATENCY_MS on the main thread (bug
+ // 1343729)
+ if (NS_IsMainThread() && latencyMs >= kMinTelemetrySyncIPCLatencyMs) {
+ Telemetry::Accumulate(Telemetry::IPC_SYNC_MAIN_LATENCY_MS,
+ nsDependentCString(msgName), latencyMs);
+ }
+ return true;
+}
+
+bool MessageChannel::HasPendingEvents() {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+ return ConnectedOrClosing() && !mPending.isEmpty();
+}
+
+bool MessageChannel::ProcessPendingRequest(ActorLifecycleProxy* aProxy,
+ UniquePtr<Message> aUrgent) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ IPC_LOG("Process pending: seqno=%d, xid=%d", aUrgent->seqno(),
+ aUrgent->transaction_id());
+
+ // keep the error relevant information
+ msgid_t msgType = aUrgent->type();
+
+ DispatchMessage(aProxy, std::move(aUrgent));
+ if (!ConnectedOrClosing()) {
+ ReportConnectionError("ProcessPendingRequest", msgType);
+ return false;
+ }
+
+ return true;
+}
+
+bool MessageChannel::ShouldRunMessage(const Message& aMsg) {
+ if (!mTimedOutMessageSeqno) {
+ return true;
+ }
+
+ // If we've timed out a message and we're awaiting the reply to the timed
+ // out message, we have to be careful what messages we process. Here's what
+ // can go wrong:
+ // 1. child sends a NOT_NESTED sync message S
+ // 2. parent sends a NESTED_INSIDE_SYNC sync message H at the same time
+ // 3. parent times out H
+ // 4. child starts processing H and sends a NESTED_INSIDE_SYNC message H'
+ // nested within the same transaction
+ // 5. parent dispatches S and sends reply
+ // 6. child asserts because it instead expected a reply to H'.
+ //
+ // To solve this, we refuse to process S in the parent until we get a reply
+ // to H. More generally, let the timed out message be M. We don't process a
+ // message unless the child would need the response to that message in order
+ // to process M. Those messages are the ones that have a higher nested level
+ // than M or that are part of the same transaction as M.
+ if (aMsg.nested_level() < mTimedOutMessageNestedLevel ||
+ (aMsg.nested_level() == mTimedOutMessageNestedLevel &&
+ aMsg.transaction_id() != mTimedOutMessageSeqno)) {
+ return false;
+ }
+
+ return true;
+}
+
+void MessageChannel::RunMessage(ActorLifecycleProxy* aProxy,
+ MessageTask& aTask) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+ aTask.AssertMonitorHeld(*mMonitor);
+
+ UniquePtr<Message>& msg = aTask.Msg();
+
+ if (!ConnectedOrClosing()) {
+ ReportConnectionError("RunMessage", msg->type());
+ return;
+ }
+
+ // Check that we're going to run the first message that's valid to run.
+#if 0
+# ifdef DEBUG
+ for (MessageTask* task : mPending) {
+ if (task == &aTask) {
+ break;
+ }
+
+ MOZ_ASSERT(!ShouldRunMessage(*task->Msg()) ||
+ aTask.Msg()->priority() != task->Msg()->priority());
+
+ }
+# endif
+#endif
+
+ if (!ShouldRunMessage(*msg)) {
+ return;
+ }
+
+ MOZ_RELEASE_ASSERT(aTask.isInList());
+ aTask.remove();
+
+ if (!IsAlwaysDeferred(*msg)) {
+ mMaybeDeferredPendingCount--;
+ }
+
+ DispatchMessage(aProxy, std::move(msg));
+}
+
+NS_IMPL_ISUPPORTS_INHERITED(MessageChannel::MessageTask, CancelableRunnable,
+ nsIRunnablePriority, nsIRunnableIPCMessageType)
+
+static uint32_t ToRunnablePriority(IPC::Message::PriorityValue aPriority) {
+ switch (aPriority) {
+ case IPC::Message::NORMAL_PRIORITY:
+ return nsIRunnablePriority::PRIORITY_NORMAL;
+ case IPC::Message::INPUT_PRIORITY:
+ return nsIRunnablePriority::PRIORITY_INPUT_HIGH;
+ case IPC::Message::VSYNC_PRIORITY:
+ return nsIRunnablePriority::PRIORITY_VSYNC;
+ case IPC::Message::MEDIUMHIGH_PRIORITY:
+ return nsIRunnablePriority::PRIORITY_MEDIUMHIGH;
+ case IPC::Message::CONTROL_PRIORITY:
+ return nsIRunnablePriority::PRIORITY_CONTROL;
+ default:
+ MOZ_ASSERT_UNREACHABLE();
+ return nsIRunnablePriority::PRIORITY_NORMAL;
+ }
+}
+
+MessageChannel::MessageTask::MessageTask(MessageChannel* aChannel,
+ UniquePtr<Message> aMessage)
+ : CancelableRunnable(aMessage->name()),
+ mMonitor(aChannel->mMonitor),
+ mChannel(aChannel),
+ mMessage(std::move(aMessage)),
+ mPriority(ToRunnablePriority(mMessage->priority())),
+ mScheduled(false)
+#ifdef FUZZING_SNAPSHOT
+ ,
+ mIsFuzzMsg(mMessage->IsFuzzMsg()),
+ mFuzzStopped(false)
+#endif
+{
+ MOZ_DIAGNOSTIC_ASSERT(mMessage, "message may not be null");
+#ifdef FUZZING_SNAPSHOT
+ if (mIsFuzzMsg) {
+ MOZ_FUZZING_IPC_MT_CTOR();
+ }
+#endif
+}
+
+MessageChannel::MessageTask::~MessageTask() {
+#ifdef FUZZING_SNAPSHOT
+ // We track fuzzing messages until their run is complete. To make sure
+ // that we don't miss messages that are for some reason destroyed without
+ // being run (e.g. canceled), we catch this condition in the destructor.
+ if (mIsFuzzMsg && !mFuzzStopped) {
+ MOZ_FUZZING_IPC_MT_STOP();
+ } else if (!mIsFuzzMsg && !fuzzing::Nyx::instance().started()) {
+ MOZ_FUZZING_IPC_PRE_FUZZ_MT_STOP();
+ }
+#endif
+}
+
+nsresult MessageChannel::MessageTask::Run() {
+ mMonitor->AssertNotCurrentThreadOwns();
+
+ // Drop the toplevel actor's lifecycle proxy outside of our monitor if we take
+ // it, as destroying our ActorLifecycleProxy reference can acquire the
+ // monitor.
+ RefPtr<ActorLifecycleProxy> proxy;
+
+ MonitorAutoLock lock(*mMonitor);
+
+ // In case we choose not to run this message, we may need to be able to Post
+ // it again.
+ mScheduled = false;
+
+ if (!isInList()) {
+ return NS_OK;
+ }
+
+#ifdef FUZZING_SNAPSHOT
+ if (!mIsFuzzMsg) {
+ if (fuzzing::Nyx::instance().started()) {
+ // Once we started fuzzing, prevent non-fuzzing tasks from being
+ // run and potentially blocking worker threads.
+ //
+ // TODO: This currently blocks all MessageTasks from running, not
+ // just those belonging to the target process pair. We currently
+ // do this for performance reasons, but it should be re-evaluated
+ // at a later stage when we found a better snapshot point.
+ return NS_OK;
+ }
+ // Record all running tasks prior to fuzzing, so we can wait for
+ // them to settle before snapshotting.
+ MOZ_FUZZING_IPC_PRE_FUZZ_MT_RUN();
+ }
+#endif
+
+ Channel()->AssertWorkerThread();
+ mMonitor->AssertSameMonitor(*Channel()->mMonitor);
+ proxy = Channel()->Listener()->GetLifecycleProxy();
+ Channel()->RunMessage(proxy, *this);
+
+#ifdef FUZZING_SNAPSHOT
+ if (mIsFuzzMsg && !mFuzzStopped) {
+ MOZ_FUZZING_IPC_MT_STOP();
+ mFuzzStopped = true;
+ }
+#endif
+ return NS_OK;
+}
+
+// Warning: This method removes the receiver from whatever list it might be in.
+nsresult MessageChannel::MessageTask::Cancel() {
+ mMonitor->AssertNotCurrentThreadOwns();
+
+ MonitorAutoLock lock(*mMonitor);
+
+ if (!isInList()) {
+ return NS_OK;
+ }
+
+ Channel()->AssertWorkerThread();
+ mMonitor->AssertSameMonitor(*Channel()->mMonitor);
+ if (!IsAlwaysDeferred(*Msg())) {
+ Channel()->mMaybeDeferredPendingCount--;
+ }
+
+ remove();
+
+#ifdef FUZZING_SNAPSHOT
+ if (mIsFuzzMsg && !mFuzzStopped) {
+ MOZ_FUZZING_IPC_MT_STOP();
+ mFuzzStopped = true;
+ }
+#endif
+
+ return NS_OK;
+}
+
+void MessageChannel::MessageTask::Post() {
+ mMonitor->AssertCurrentThreadOwns();
+ mMonitor->AssertSameMonitor(*Channel()->mMonitor);
+ MOZ_RELEASE_ASSERT(!mScheduled);
+ MOZ_RELEASE_ASSERT(isInList());
+
+ mScheduled = true;
+
+ Channel()->mWorkerThread->Dispatch(do_AddRef(this));
+}
+
+NS_IMETHODIMP
+MessageChannel::MessageTask::GetPriority(uint32_t* aPriority) {
+ *aPriority = mPriority;
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessageChannel::MessageTask::GetType(uint32_t* aType) {
+ mMonitor->AssertNotCurrentThreadOwns();
+
+ MonitorAutoLock lock(*mMonitor);
+ if (!mMessage) {
+ // If mMessage has been moved already elsewhere, we can't know what the type
+ // has been.
+ return NS_ERROR_FAILURE;
+ }
+
+ *aType = mMessage->type();
+ return NS_OK;
+}
+
+void MessageChannel::DispatchMessage(ActorLifecycleProxy* aProxy,
+ UniquePtr<Message> aMsg) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ Maybe<AutoNoJSAPI> nojsapi;
+ if (NS_IsMainThread() && CycleCollectedJSContext::Get()) {
+ nojsapi.emplace();
+ }
+
+ UniquePtr<Message> reply;
+
+#ifdef FUZZING_SNAPSHOT
+ if (IsCrossProcess()) {
+ aMsg = mozilla::fuzzing::IPCFuzzController::instance().replaceIPCMessage(
+ std::move(aMsg));
+ }
+#endif
+
+ IPC_LOG("DispatchMessage: seqno=%d, xid=%d", aMsg->seqno(),
+ aMsg->transaction_id());
+ AddProfilerMarker(*aMsg, MessageDirection::eReceiving);
+
+ {
+ AutoEnterTransaction transaction(this, *aMsg);
+
+ int id = aMsg->transaction_id();
+ MOZ_RELEASE_ASSERT(!aMsg->is_sync() || id == transaction.TransactionID());
+
+ {
+ MonitorAutoUnlock unlock(*mMonitor);
+ AutoSetValue<bool> setOnCxxStack(mOnCxxStack, true);
+
+ mListener->ArtificialSleep();
+
+ if (aMsg->is_sync()) {
+ DispatchSyncMessage(aProxy, *aMsg, reply);
+ } else {
+ DispatchAsyncMessage(aProxy, *aMsg);
+ }
+
+ mListener->ArtificialSleep();
+ }
+
+ if (reply && transaction.IsCanceled()) {
+ // The transaction has been canceled. Don't send a reply.
+ IPC_LOG("Nulling out reply due to cancellation, seqno=%d, xid=%d",
+ aMsg->seqno(), id);
+ reply = nullptr;
+ }
+ }
+
+#ifdef FUZZING_SNAPSHOT
+ if (aMsg->IsFuzzMsg()) {
+ mozilla::fuzzing::IPCFuzzController::instance().syncAfterReplace();
+ }
+#endif
+
+ if (reply && ChannelConnected == mChannelState) {
+ IPC_LOG("Sending reply seqno=%d, xid=%d", aMsg->seqno(),
+ aMsg->transaction_id());
+ AddProfilerMarker(*reply, MessageDirection::eSending);
+
+ SendMessageToLink(std::move(reply));
+ }
+}
+
+void MessageChannel::DispatchSyncMessage(ActorLifecycleProxy* aProxy,
+ const Message& aMsg,
+ UniquePtr<Message>& aReply) {
+ AssertWorkerThread();
+
+ mozilla::TimeStamp start = TimeStamp::Now();
+
+ int nestedLevel = aMsg.nested_level();
+
+ MOZ_RELEASE_ASSERT(nestedLevel == IPC::Message::NOT_NESTED ||
+ NS_IsMainThread());
+
+ MessageChannel* dummy;
+ MessageChannel*& blockingVar =
+ mSide == ChildSide && NS_IsMainThread() ? gParentProcessBlocker : dummy;
+
+ Result rv;
+ {
+ AutoSetValue<MessageChannel*> blocked(blockingVar, this);
+ rv = aProxy->Get()->OnMessageReceived(aMsg, aReply);
+ }
+
+ uint32_t latencyMs = round((TimeStamp::Now() - start).ToMilliseconds());
+ if (latencyMs >= kMinTelemetrySyncIPCLatencyMs) {
+ Telemetry::Accumulate(Telemetry::IPC_SYNC_RECEIVE_MS,
+ nsDependentCString(aMsg.name()), latencyMs);
+ }
+
+ if (!MaybeHandleError(rv, aMsg, "DispatchSyncMessage")) {
+ aReply = Message::ForSyncDispatchError(aMsg.nested_level());
+ }
+ aReply->set_seqno(aMsg.seqno());
+ aReply->set_transaction_id(aMsg.transaction_id());
+}
+
+void MessageChannel::DispatchAsyncMessage(ActorLifecycleProxy* aProxy,
+ const Message& aMsg) {
+ AssertWorkerThread();
+ MOZ_RELEASE_ASSERT(!aMsg.is_sync());
+
+ if (aMsg.routing_id() == MSG_ROUTING_NONE) {
+ NS_WARNING("unhandled special message!");
+ MaybeHandleError(MsgNotKnown, aMsg, "DispatchAsyncMessage");
+ return;
+ }
+
+ Result rv;
+ {
+ int nestedLevel = aMsg.nested_level();
+ AutoSetValue<bool> async(mDispatchingAsyncMessage, true);
+ AutoSetValue<int> nestedLevelSet(mDispatchingAsyncMessageNestedLevel,
+ nestedLevel);
+ rv = aProxy->Get()->OnMessageReceived(aMsg);
+ }
+ MaybeHandleError(rv, aMsg, "DispatchAsyncMessage");
+}
+
+void MessageChannel::EnqueuePendingMessages() {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ // XXX performance tuning knob: could process all or k pending
+ // messages here, rather than enqueuing for later processing
+
+ RepostAllMessages();
+}
+
+bool MessageChannel::WaitResponse(bool aWaitTimedOut) {
+ AssertWorkerThread();
+ if (aWaitTimedOut) {
+ if (mInTimeoutSecondHalf) {
+ // We've really timed out this time.
+ return false;
+ }
+ // Try a second time.
+ mInTimeoutSecondHalf = true;
+ } else {
+ mInTimeoutSecondHalf = false;
+ }
+ return true;
+}
+
+#ifndef XP_WIN
+bool MessageChannel::WaitForSyncNotify() {
+ AssertWorkerThread();
+# ifdef DEBUG
+ // WARNING: We don't release the lock here. We can't because the link
+ // could signal at this time and we would miss it. Instead we require
+ // ArtificialTimeout() to be extremely simple.
+ if (mListener->ArtificialTimeout()) {
+ return false;
+ }
+# endif
+
+ MOZ_RELEASE_ASSERT(!mIsSameThreadChannel,
+ "Wait on same-thread channel will deadlock!");
+
+ TimeDuration timeout = (kNoTimeout == mTimeoutMs)
+ ? TimeDuration::Forever()
+ : TimeDuration::FromMilliseconds(mTimeoutMs);
+ CVStatus status = mMonitor->Wait(timeout);
+
+ // If the timeout didn't expire, we know we received an event. The
+ // converse is not true.
+ return WaitResponse(status == CVStatus::Timeout);
+}
+
+void MessageChannel::NotifyWorkerThread() { mMonitor->Notify(); }
+#endif
+
+bool MessageChannel::ShouldContinueFromTimeout() {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ bool cont;
+ {
+ MonitorAutoUnlock unlock(*mMonitor);
+ cont = mListener->ShouldContinueFromReplyTimeout();
+ mListener->ArtificialSleep();
+ }
+
+ static enum {
+ UNKNOWN,
+ NOT_DEBUGGING,
+ DEBUGGING
+ } sDebuggingChildren = UNKNOWN;
+
+ if (sDebuggingChildren == UNKNOWN) {
+ sDebuggingChildren =
+ getenv("MOZ_DEBUG_CHILD_PROCESS") || getenv("MOZ_DEBUG_CHILD_PAUSE")
+ ? DEBUGGING
+ : NOT_DEBUGGING;
+ }
+ if (sDebuggingChildren == DEBUGGING) {
+ return true;
+ }
+
+ return cont;
+}
+
+void MessageChannel::SetReplyTimeoutMs(int32_t aTimeoutMs) {
+ // Set channel timeout value. Since this is broken up into
+ // two period, the minimum timeout value is 2ms.
+ AssertWorkerThread();
+ mTimeoutMs =
+ (aTimeoutMs <= 0) ? kNoTimeout : (int32_t)ceil((double)aTimeoutMs / 2.0);
+}
+
+void MessageChannel::ReportConnectionError(const char* aFunctionName,
+ const uint32_t aMsgType) const {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ const char* errorMsg = nullptr;
+ switch (mChannelState) {
+ case ChannelClosed:
+ errorMsg = "Closed channel: cannot send/recv";
+ break;
+ case ChannelClosing:
+ errorMsg = "Channel closing: too late to send, messages will be lost";
+ break;
+ case ChannelError:
+ errorMsg = "Channel error: cannot send/recv";
+ break;
+
+ default:
+ MOZ_CRASH("unreached");
+ }
+
+ // IPC connection errors are fairly common, especially "Channel closing: too
+ // late to send/recv, messages will be lost", so shouldn't be being reported
+ // on release builds, as that's misleading as to their severity.
+ NS_WARNING(nsPrintfCString("IPC Connection Error: [%s][%s] %s(msgname=%s) %s",
+ StringFromIPCSide(mSide), mName, aFunctionName,
+ IPC::StringFromIPCMessageType(aMsgType), errorMsg)
+ .get());
+
+ MonitorAutoUnlock unlock(*mMonitor);
+ mListener->ProcessingError(MsgDropped, errorMsg);
+}
+
+void MessageChannel::ReportMessageRouteError(const char* channelName) const {
+ PrintErrorMessage(mSide, channelName, "Need a route");
+ mListener->ProcessingError(MsgRouteError, "MsgRouteError");
+}
+
+bool MessageChannel::MaybeHandleError(Result code, const Message& aMsg,
+ const char* channelName) {
+ if (MsgProcessed == code) return true;
+
+#ifdef FUZZING_SNAPSHOT
+ mozilla::fuzzing::IPCFuzzController::instance().OnMessageError(code, aMsg);
+#endif
+
+ const char* errorMsg = nullptr;
+ switch (code) {
+ case MsgNotKnown:
+ errorMsg = "Unknown message: not processed";
+ break;
+ case MsgNotAllowed:
+ errorMsg = "Message not allowed: cannot be sent/recvd in this state";
+ break;
+ case MsgPayloadError:
+ errorMsg = "Payload error: message could not be deserialized";
+ break;
+ case MsgProcessingError:
+ errorMsg =
+ "Processing error: message was deserialized, but the handler "
+ "returned false (indicating failure)";
+ break;
+ case MsgRouteError:
+ errorMsg = "Route error: message sent to unknown actor ID";
+ break;
+ case MsgValueError:
+ errorMsg =
+ "Value error: message was deserialized, but contained an illegal "
+ "value";
+ break;
+
+ default:
+ MOZ_CRASH("unknown Result code");
+ return false;
+ }
+
+ char reason[512];
+ const char* msgname = aMsg.name();
+ if (msgname[0] == '?') {
+ SprintfLiteral(reason, "(msgtype=0x%X) %s", aMsg.type(), errorMsg);
+ } else {
+ SprintfLiteral(reason, "%s %s", msgname, errorMsg);
+ }
+
+ PrintErrorMessage(mSide, channelName, reason);
+
+ // Error handled in mozilla::ipc::IPCResult.
+ if (code == MsgProcessingError) {
+ return false;
+ }
+
+ mListener->ProcessingError(code, reason);
+
+ return false;
+}
+
+void MessageChannel::OnChannelErrorFromLink() {
+ mMonitor->AssertCurrentThreadOwns();
+ MOZ_ASSERT(mChannelState == ChannelConnected);
+
+ IPC_LOG("OnChannelErrorFromLink");
+
+ if (AwaitingSyncReply()) {
+ NotifyWorkerThread();
+ }
+
+ if (mAbortOnError) {
+ // mAbortOnError is set by main actors (e.g., ContentChild) to ensure
+ // that the process terminates even if normal shutdown is prevented.
+ // A MOZ_CRASH() here is not helpful because crash reporting relies
+ // on the parent process which we know is dead or otherwise unusable.
+ //
+ // Additionally, the parent process can (and often is) killed on Android
+ // when apps are backgrounded. We don't need to report a crash for
+ // normal behavior in that case.
+ printf_stderr("Exiting due to channel error.\n");
+ ProcessChild::QuickExit();
+ }
+ mChannelState = ChannelError;
+ mMonitor->Notify();
+
+ PostErrorNotifyTask();
+}
+
+void MessageChannel::NotifyMaybeChannelError(ReleasableMonitorAutoLock& aLock) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+ aLock.AssertCurrentThreadOwns();
+ MOZ_ASSERT(mChannelState != ChannelConnected);
+
+ if (ChannelClosing == mChannelState || ChannelClosed == mChannelState) {
+ // the channel closed, but we received a "Goodbye" message warning us
+ // about it. no worries
+ mChannelState = ChannelClosed;
+ NotifyChannelClosed(aLock);
+ return;
+ }
+
+ MOZ_ASSERT(ChannelError == mChannelState);
+
+ Clear();
+
+ // IPDL assumes these notifications do not fire twice, so we do not let
+ // that happen.
+ if (mNotifiedChannelDone) {
+ return;
+ }
+ mNotifiedChannelDone = true;
+
+ // Let our listener know that the channel errored. This may cause the
+ // channel to be deleted. Release our caller's `MonitorAutoLock` before
+ // invoking the listener, as this may call back into MessageChannel, and/or
+ // cause the channel to be destroyed.
+ aLock.Unlock();
+ mListener->OnChannelError();
+}
+
+void MessageChannel::OnNotifyMaybeChannelError() {
+ AssertWorkerThread();
+ mMonitor->AssertNotCurrentThreadOwns();
+
+ // This lock guard may be reset by `NotifyMaybeChannelError` before invoking
+ // listener callbacks which may destroy this `MessageChannel`.
+ //
+ // Acquiring the lock here also allows us to ensure that
+ // `OnChannelErrorFromLink` has finished running before this task is allowed
+ // to continue.
+ ReleasableMonitorAutoLock lock(*mMonitor);
+
+ mChannelErrorTask = nullptr;
+
+ if (IsOnCxxStack()) {
+ // This used to post a 10ms delayed task; however not all
+ // nsISerialEventTarget implementations support delayed dispatch.
+ // The delay being completely arbitrary, we may not as well have any.
+ PostErrorNotifyTask();
+ return;
+ }
+
+ // This call may destroy `this`.
+ NotifyMaybeChannelError(lock);
+}
+
+void MessageChannel::PostErrorNotifyTask() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ if (mChannelErrorTask) {
+ return;
+ }
+
+ // This must be the last code that runs on this thread!
+ mChannelErrorTask = NewNonOwningCancelableRunnableMethod(
+ "ipc::MessageChannel::OnNotifyMaybeChannelError", this,
+ &MessageChannel::OnNotifyMaybeChannelError);
+ mWorkerThread->Dispatch(do_AddRef(mChannelErrorTask));
+}
+
+// Special async message.
+class GoodbyeMessage : public IPC::Message {
+ public:
+ GoodbyeMessage() : IPC::Message(MSG_ROUTING_NONE, GOODBYE_MESSAGE_TYPE) {}
+ static bool Read(const Message* msg) { return true; }
+ void Log(const std::string& aPrefix, FILE* aOutf) const {
+ fputs("(special `Goodbye' message)", aOutf);
+ }
+};
+
+void MessageChannel::InduceConnectionError() {
+ MonitorAutoLock lock(*mMonitor);
+
+ // Either connected or closing, immediately convert to an error and notify.
+ switch (mChannelState) {
+ case ChannelConnected:
+ // The channel is still actively connected. Immediately shut down the
+ // connection with our peer and simulate it invoking
+ // OnChannelErrorFromLink on us.
+ //
+ // This will update the state to ChannelError, preventing new messages
+ // from being processed, leading to an error being reported asynchronously
+ // to our listener.
+ mLink->Close();
+ OnChannelErrorFromLink();
+ return;
+
+ case ChannelClosing:
+ // An notify task has already been posted. Update mChannelState to stop
+ // processing new messages and treat the notification as an error.
+ mChannelState = ChannelError;
+ return;
+
+ default:
+ // Either already closed or errored. Nothing to do.
+ MOZ_ASSERT(mChannelState == ChannelClosed ||
+ mChannelState == ChannelError);
+ return;
+ }
+}
+
+void MessageChannel::NotifyImpendingShutdown() {
+ UniquePtr<Message> msg =
+ MakeUnique<Message>(MSG_ROUTING_NONE, IMPENDING_SHUTDOWN_MESSAGE_TYPE);
+ MonitorAutoLock lock(*mMonitor);
+ if (Connected()) {
+ SendMessageToLink(std::move(msg));
+ }
+}
+
+void MessageChannel::Close() {
+ AssertWorkerThread();
+ mMonitor->AssertNotCurrentThreadOwns();
+
+ // This lock guard may be reset by `Notify{ChannelClosed,MaybeChannelError}`
+ // before invoking listener callbacks which may destroy this `MessageChannel`.
+ ReleasableMonitorAutoLock lock(*mMonitor);
+
+ switch (mChannelState) {
+ case ChannelError:
+ // See bug 538586: if the listener gets deleted while the
+ // IO thread's NotifyChannelError event is still enqueued
+ // and subsequently deletes us, then the error event will
+ // also be deleted and the listener will never be notified
+ // of the channel error.
+ NotifyMaybeChannelError(lock);
+ return;
+ case ChannelClosed:
+ // Slightly unexpected but harmless; ignore. See bug 1554244.
+ return;
+
+ default:
+ // Notify the other side that we're about to close our socket. If we've
+ // already received a Goodbye from the other side (and our state is
+ // ChannelClosing), there's no reason to send one.
+ if (ChannelConnected == mChannelState) {
+ SendMessageToLink(MakeUnique<GoodbyeMessage>());
+ }
+ mLink->Close();
+ mChannelState = ChannelClosed;
+ NotifyChannelClosed(lock);
+ return;
+ }
+}
+
+void MessageChannel::NotifyChannelClosed(ReleasableMonitorAutoLock& aLock) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+ aLock.AssertCurrentThreadOwns();
+
+ if (ChannelClosed != mChannelState) {
+ MOZ_CRASH("channel should have been closed!");
+ }
+
+ Clear();
+
+ // IPDL assumes these notifications do not fire twice, so we do not let
+ // that happen.
+ if (mNotifiedChannelDone) {
+ return;
+ }
+ mNotifiedChannelDone = true;
+
+ // Let our listener know that the channel was closed. This may cause the
+ // channel to be deleted. Release our caller's `MonitorAutoLock` before
+ // invoking the listener, as this may call back into MessageChannel, and/or
+ // cause the channel to be destroyed.
+ aLock.Unlock();
+ mListener->OnChannelClose();
+}
+
+void MessageChannel::DebugAbort(const char* file, int line, const char* cond,
+ const char* why, bool reply) {
+ AssertWorkerThread();
+ mMonitor->AssertCurrentThreadOwns();
+
+ printf_stderr(
+ "###!!! [MessageChannel][%s][%s:%d] "
+ "Assertion (%s) failed. %s %s\n",
+ StringFromIPCSide(mSide), file, line, cond, why, reply ? "(reply)" : "");
+
+ MessageQueue pending = std::move(mPending);
+ while (!pending.isEmpty()) {
+ pending.getFirst()->AssertMonitorHeld(*mMonitor);
+ printf_stderr(" [ %s%s ]\n",
+ pending.getFirst()->Msg()->is_sync() ? "sync" : "async",
+ pending.getFirst()->Msg()->is_reply() ? "reply" : "");
+ pending.popFirst();
+ }
+
+ MOZ_CRASH_UNSAFE(why);
+}
+
+void MessageChannel::AddProfilerMarker(const IPC::Message& aMessage,
+ MessageDirection aDirection) {
+ mMonitor->AssertCurrentThreadOwns();
+
+ if (profiler_feature_active(ProfilerFeature::IPCMessages)) {
+ base::ProcessId pid = mListener->OtherPidMaybeInvalid();
+ // Only record markers for IPCs with a valid pid.
+ // And if one of the profiler mutexes is locked on this thread, don't record
+ // markers, because we don't want to expose profiler IPCs due to the
+ // profiler itself, and also to avoid possible re-entrancy issues.
+ if (pid != base::kInvalidProcessId &&
+ !profiler_is_locked_on_current_thread()) {
+ // The current timestamp must be given to the `IPCMarker` payload.
+ [[maybe_unused]] const TimeStamp now = TimeStamp::Now();
+ bool isThreadBeingProfiled =
+ profiler_thread_is_being_profiled_for_markers();
+ PROFILER_MARKER(
+ "IPC", IPC,
+ mozilla::MarkerOptions(
+ mozilla::MarkerTiming::InstantAt(now),
+ // If the thread is being profiled, add the marker to
+ // the current thread. If the thread is not being
+ // profiled, add the marker to the main thread. It
+ // will appear in the main thread's IPC track. Profiler analysis
+ // UI correlates all the IPC markers from different threads and
+ // generates processed markers.
+ isThreadBeingProfiled ? mozilla::MarkerThreadId::CurrentThread()
+ : mozilla::MarkerThreadId::MainThread()),
+ IPCMarker, now, now, pid, aMessage.seqno(), aMessage.type(), mSide,
+ aDirection, MessagePhase::Endpoint, aMessage.is_sync(),
+ // aOriginThreadId: If the thread is being profiled, do not include a
+ // thread ID, as it's the same as the markers. Only include this field
+ // when the marker is being sent from another thread.
+ isThreadBeingProfiled ? mozilla::MarkerThreadId{}
+ : mozilla::MarkerThreadId::CurrentThread());
+ }
+ }
+}
+
+void MessageChannel::EndTimeout() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ IPC_LOG("Ending timeout of seqno=%d", mTimedOutMessageSeqno);
+ mTimedOutMessageSeqno = 0;
+ mTimedOutMessageNestedLevel = 0;
+
+ RepostAllMessages();
+}
+
+void MessageChannel::RepostAllMessages() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ bool needRepost = false;
+ for (MessageTask* task : mPending) {
+ task->AssertMonitorHeld(*mMonitor);
+ if (!task->IsScheduled()) {
+ needRepost = true;
+ break;
+ }
+ }
+ if (!needRepost) {
+ // If everything is already scheduled to run, do nothing.
+ return;
+ }
+
+ // In some cases we may have deferred dispatch of some messages in the
+ // queue. Now we want to run them again. However, we can't just re-post
+ // those messages since the messages after them in mPending would then be
+ // before them in the event queue. So instead we cancel everything and
+ // re-post all messages in the correct order.
+ MessageQueue queue = std::move(mPending);
+ while (RefPtr<MessageTask> task = queue.popFirst()) {
+ task->AssertMonitorHeld(*mMonitor);
+ RefPtr<MessageTask> newTask = new MessageTask(this, std::move(task->Msg()));
+ newTask->AssertMonitorHeld(*mMonitor);
+ mPending.insertBack(newTask);
+ newTask->Post();
+ }
+
+ AssertMaybeDeferredCountCorrect();
+}
+
+void MessageChannel::CancelTransaction(int transaction) {
+ mMonitor->AssertCurrentThreadOwns();
+
+ // When we cancel a transaction, we need to behave as if there's no longer
+ // any IPC on the stack. Anything we were dispatching or sending will get
+ // canceled. Consequently, we have to update the state variables below.
+ //
+ // We also need to ensure that when any IPC functions on the stack return,
+ // they don't reset these values using an RAII class like AutoSetValue. To
+ // avoid that, these RAII classes check if the variable they set has been
+ // tampered with (by us). If so, they don't reset the variable to the old
+ // value.
+
+ IPC_LOG("CancelTransaction: xid=%d", transaction);
+
+ // An unusual case: We timed out a transaction which the other side then
+ // cancelled. In this case we just leave the timedout state and try to
+ // forget this ever happened.
+ if (transaction == mTimedOutMessageSeqno) {
+ IPC_LOG("Cancelled timed out message %d", mTimedOutMessageSeqno);
+ EndTimeout();
+
+ // Normally mCurrentTransaction == 0 here. But it can be non-zero if:
+ // 1. Parent sends NESTED_INSIDE_SYNC message H.
+ // 2. Parent times out H.
+ // 3. Child dispatches H and sends nested message H' (same transaction).
+ // 4. Parent dispatches H' and cancels.
+ MOZ_RELEASE_ASSERT(!mTransactionStack ||
+ mTransactionStack->TransactionID() == transaction);
+ if (mTransactionStack) {
+ mTransactionStack->Cancel();
+ }
+ } else {
+ MOZ_RELEASE_ASSERT(mTransactionStack->TransactionID() == transaction);
+ mTransactionStack->Cancel();
+ }
+
+ bool foundSync = false;
+ for (MessageTask* p = mPending.getFirst(); p;) {
+ p->AssertMonitorHeld(*mMonitor);
+ UniquePtr<Message>& msg = p->Msg();
+
+ // If there was a race between the parent and the child, then we may
+ // have a queued sync message. We want to drop this message from the
+ // queue since if will get cancelled along with the transaction being
+ // cancelled. This happens if the message in the queue is
+ // NESTED_INSIDE_SYNC.
+ if (msg->is_sync() && msg->nested_level() != IPC::Message::NOT_NESTED) {
+ MOZ_RELEASE_ASSERT(!foundSync);
+ MOZ_RELEASE_ASSERT(msg->transaction_id() != transaction);
+ IPC_LOG("Removing msg from queue seqno=%d xid=%d", msg->seqno(),
+ msg->transaction_id());
+ foundSync = true;
+ if (!IsAlwaysDeferred(*msg)) {
+ mMaybeDeferredPendingCount--;
+ }
+ p = p->removeAndGetNext();
+ continue;
+ }
+
+ p = p->getNext();
+ }
+
+ AssertMaybeDeferredCountCorrect();
+}
+
+void MessageChannel::CancelCurrentTransaction() {
+ MonitorAutoLock lock(*mMonitor);
+ if (DispatchingSyncMessageNestedLevel() >= IPC::Message::NESTED_INSIDE_SYNC) {
+ if (DispatchingSyncMessageNestedLevel() ==
+ IPC::Message::NESTED_INSIDE_CPOW ||
+ DispatchingAsyncMessageNestedLevel() ==
+ IPC::Message::NESTED_INSIDE_CPOW) {
+ mListener->IntentionalCrash();
+ }
+
+ IPC_LOG("Cancel requested: current xid=%d",
+ CurrentNestedInsideSyncTransaction());
+ MOZ_RELEASE_ASSERT(DispatchingSyncMessage());
+ auto cancel =
+ MakeUnique<CancelMessage>(CurrentNestedInsideSyncTransaction());
+ CancelTransaction(CurrentNestedInsideSyncTransaction());
+ SendMessageToLink(std::move(cancel));
+ }
+}
+
+void CancelCPOWs() {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ if (gParentProcessBlocker) {
+ mozilla::Telemetry::Accumulate(mozilla::Telemetry::IPC_TRANSACTION_CANCEL,
+ true);
+ gParentProcessBlocker->CancelCurrentTransaction();
+ }
+}
+
+bool MessageChannel::IsCrossProcess() const {
+ mMonitor->AssertCurrentThreadOwns();
+ return mIsCrossProcess;
+}
+
+void MessageChannel::SetIsCrossProcess(bool aIsCrossProcess) {
+ mMonitor->AssertCurrentThreadOwns();
+ if (aIsCrossProcess == mIsCrossProcess) {
+ return;
+ }
+ mIsCrossProcess = aIsCrossProcess;
+ if (mIsCrossProcess) {
+ ChannelCountReporter::Increment(mName);
+ } else {
+ ChannelCountReporter::Decrement(mName);
+ }
+}
+
+NS_IMPL_ISUPPORTS(MessageChannel::WorkerTargetShutdownTask,
+ nsITargetShutdownTask)
+
+MessageChannel::WorkerTargetShutdownTask::WorkerTargetShutdownTask(
+ nsISerialEventTarget* aTarget, MessageChannel* aChannel)
+ : mTarget(aTarget), mChannel(aChannel) {}
+
+void MessageChannel::WorkerTargetShutdownTask::TargetShutdown() {
+ MOZ_RELEASE_ASSERT(mTarget->IsOnCurrentThread());
+ IPC_LOG("Closing channel due to event target shutdown");
+ if (MessageChannel* channel = std::exchange(mChannel, nullptr)) {
+ channel->Close();
+ }
+}
+
+void MessageChannel::WorkerTargetShutdownTask::Clear() {
+ MOZ_RELEASE_ASSERT(mTarget->IsOnCurrentThread());
+ mChannel = nullptr;
+}
+
+NS_IMPL_ISUPPORTS_INHERITED0(MessageChannel::FlushLazySendMessagesRunnable,
+ CancelableRunnable)
+
+MessageChannel::FlushLazySendMessagesRunnable::FlushLazySendMessagesRunnable(
+ MessageChannel* aChannel)
+ : CancelableRunnable("MessageChannel::FlushLazyMessagesRunnable"),
+ mChannel(aChannel) {}
+
+NS_IMETHODIMP MessageChannel::FlushLazySendMessagesRunnable::Run() {
+ if (mChannel) {
+ MonitorAutoLock lock(*mChannel->mMonitor);
+ MOZ_ASSERT(mChannel->mFlushLazySendTask == this);
+ mChannel->FlushLazySendMessages();
+ }
+ return NS_OK;
+}
+
+nsresult MessageChannel::FlushLazySendMessagesRunnable::Cancel() {
+ mQueue.Clear();
+ mChannel = nullptr;
+ return NS_OK;
+}
+
+void MessageChannel::FlushLazySendMessagesRunnable::PushMessage(
+ UniquePtr<Message> aMsg) {
+ MOZ_ASSERT(mChannel);
+ mQueue.AppendElement(std::move(aMsg));
+}
+
+nsTArray<UniquePtr<IPC::Message>>
+MessageChannel::FlushLazySendMessagesRunnable::TakeMessages() {
+ mChannel = nullptr;
+ return std::move(mQueue);
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/MessageChannel.h b/ipc/glue/MessageChannel.h
new file mode 100644
index 0000000000..67540b4ac8
--- /dev/null
+++ b/ipc/glue/MessageChannel.h
@@ -0,0 +1,888 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef ipc_glue_MessageChannel_h
+#define ipc_glue_MessageChannel_h
+
+#include "ipc/EnumSerializer.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/BaseProfilerMarkers.h"
+#include "mozilla/LinkedList.h"
+#include "mozilla/Monitor.h"
+#include "mozilla/Vector.h"
+#if defined(XP_WIN)
+# include "mozilla/ipc/Neutering.h"
+#endif // defined(XP_WIN)
+
+#include <functional>
+#include <map>
+#include <stack>
+#include <vector>
+
+#include "MessageLink.h" // for HasResultCodes
+#include "mozilla/ipc/ScopedPort.h"
+#include "nsITargetShutdownTask.h"
+
+#ifdef FUZZING_SNAPSHOT
+# include "mozilla/fuzzing/IPCFuzzController.h"
+#endif
+
+class MessageLoop;
+
+namespace IPC {
+template <typename T>
+struct ParamTraits;
+}
+
+namespace mozilla {
+namespace ipc {
+
+class IToplevelProtocol;
+class ActorLifecycleProxy;
+
+class RefCountedMonitor : public Monitor {
+ public:
+ RefCountedMonitor() : Monitor("mozilla.ipc.MessageChannel.mMonitor") {}
+
+ void AssertSameMonitor(const RefCountedMonitor& aOther) const
+ MOZ_REQUIRES(*this) MOZ_ASSERT_CAPABILITY(aOther) {
+ MOZ_ASSERT(this == &aOther);
+ }
+
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(RefCountedMonitor)
+
+ private:
+ ~RefCountedMonitor() = default;
+};
+
+enum class MessageDirection {
+ eSending,
+ eReceiving,
+};
+
+enum class MessagePhase {
+ Endpoint,
+ TransferStart,
+ TransferEnd,
+};
+
+enum class SyncSendError {
+ SendSuccess,
+ PreviousTimeout,
+ SendingCPOWWhileDispatchingSync,
+ SendingCPOWWhileDispatchingUrgent,
+ NotConnectedBeforeSend,
+ DisconnectedDuringSend,
+ CancelledBeforeSend,
+ CancelledAfterSend,
+ TimedOut,
+ ReplyError,
+};
+
+enum class ResponseRejectReason {
+ SendError,
+ ChannelClosed,
+ HandlerRejected,
+ ActorDestroyed,
+ ResolverDestroyed,
+ EndGuard_,
+};
+
+template <typename T>
+using ResolveCallback = std::function<void(T&&)>;
+
+using RejectCallback = std::function<void(ResponseRejectReason)>;
+
+enum ChannelState {
+ ChannelClosed,
+ ChannelConnected,
+ ChannelClosing,
+ ChannelError
+};
+
+class AutoEnterTransaction;
+
+class MessageChannel : HasResultCodes {
+ friend class PortLink;
+
+ typedef mozilla::Monitor Monitor;
+
+ public:
+ using Message = IPC::Message;
+
+ struct UntypedCallbackHolder {
+ UntypedCallbackHolder(int32_t aActorId, Message::msgid_t aReplyMsgId,
+ RejectCallback&& aReject)
+ : mActorId(aActorId),
+ mReplyMsgId(aReplyMsgId),
+ mReject(std::move(aReject)) {}
+
+ virtual ~UntypedCallbackHolder() = default;
+
+ void Reject(ResponseRejectReason&& aReason) { mReject(std::move(aReason)); }
+
+ int32_t mActorId;
+ Message::msgid_t mReplyMsgId;
+ RejectCallback mReject;
+ };
+
+ template <typename Value>
+ struct CallbackHolder : public UntypedCallbackHolder {
+ CallbackHolder(int32_t aActorId, Message::msgid_t aReplyMsgId,
+ ResolveCallback<Value>&& aResolve, RejectCallback&& aReject)
+ : UntypedCallbackHolder(aActorId, aReplyMsgId, std::move(aReject)),
+ mResolve(std::move(aResolve)) {}
+
+ void Resolve(Value&& aReason) { mResolve(std::move(aReason)); }
+
+ ResolveCallback<Value> mResolve;
+ };
+
+ private:
+ static Atomic<size_t> gUnresolvedResponses;
+ friend class PendingResponseReporter;
+
+ public:
+ static constexpr int32_t kNoTimeout = INT32_MIN;
+
+ using ScopedPort = mozilla::ipc::ScopedPort;
+
+ explicit MessageChannel(const char* aName, IToplevelProtocol* aListener);
+ ~MessageChannel();
+
+ IToplevelProtocol* Listener() const { return mListener; }
+
+ // Returns the event target which the worker lives on and must be used for
+ // operations on the current thread. Only safe to access after the
+ // MessageChannel has been opened.
+ nsISerialEventTarget* GetWorkerEventTarget() const { return mWorkerThread; }
+
+ // "Open" a connection using an existing ScopedPort. The ScopedPort must be
+ // valid and connected to a remote.
+ //
+ // The `aEventTarget` parameter must be on the current thread.
+ bool Open(ScopedPort aPort, Side aSide, const nsID& aMessageChannelId,
+ nsISerialEventTarget* aEventTarget = nullptr);
+
+ // "Open" a connection to another thread in the same process.
+ //
+ // Returns true if the transport layer was successfully connected,
+ // i.e., mChannelState == ChannelConnected.
+ //
+ // For more details on the process of opening a channel between
+ // threads, see the extended comment on this function
+ // in MessageChannel.cpp.
+ bool Open(MessageChannel* aTargetChan, nsISerialEventTarget* aEventTarget,
+ Side aSide);
+
+ // "Open" a connection to an actor on the current thread.
+ //
+ // Returns true if the transport layer was successfully connected,
+ // i.e., mChannelState == ChannelConnected.
+ //
+ // Same-thread channels may not perform synchronous or blocking message
+ // sends, to avoid deadlocks.
+ bool OpenOnSameThread(MessageChannel* aTargetChan, Side aSide);
+
+ /**
+ * This sends a special message that is processed on the IO thread, so that
+ * other actors can know that the process will soon shutdown.
+ */
+ void NotifyImpendingShutdown() MOZ_EXCLUDES(*mMonitor);
+
+ // Close the underlying transport channel.
+ void Close() MOZ_EXCLUDES(*mMonitor);
+
+ // Induce an error in this MessageChannel's connection.
+ //
+ // After this method is called, no more message notifications will be
+ // delivered to the listener, and the channel will be unable to send or
+ // receive future messages, as if the peer dropped the connection
+ // unexpectedly.
+ //
+ // The OnChannelError notification will be delivered either asynchronously or
+ // during an explicit call to Close(), whichever happens first.
+ //
+ // NOTE: If SetAbortOnError(true) has been called on this MessageChannel,
+ // calling this function will immediately exit the current process.
+ void InduceConnectionError() MOZ_EXCLUDES(*mMonitor);
+
+ void SetAbortOnError(bool abort) MOZ_EXCLUDES(*mMonitor) {
+ MonitorAutoLock lock(*mMonitor);
+ mAbortOnError = abort;
+ }
+
+ // Call aInvoke for each pending message until it returns false.
+ // XXX: You must get permission from an IPC peer to use this function
+ // since it requires custom deserialization and re-orders events.
+ void PeekMessages(const std::function<bool(const Message& aMsg)>& aInvoke)
+ MOZ_EXCLUDES(*mMonitor);
+
+ // Misc. behavioral traits consumers can request for this channel
+ enum ChannelFlags {
+ REQUIRE_DEFAULT = 0,
+ // Windows: if this channel operates on the UI thread, indicates
+ // WindowsMessageLoop code should enable deferred native message
+ // handling to prevent deadlocks. Should only be used for protocols
+ // that manage child processes which might create native UI, like
+ // plugins.
+ REQUIRE_DEFERRED_MESSAGE_PROTECTION = 1 << 0,
+ };
+ void SetChannelFlags(ChannelFlags aFlags) { mFlags = aFlags; }
+ ChannelFlags GetChannelFlags() { return mFlags; }
+
+ // Asynchronously send a message to the other side of the channel
+ bool Send(UniquePtr<Message> aMsg) MOZ_EXCLUDES(*mMonitor);
+
+ // Asynchronously send a message to the other side of the channel
+ // and wait for asynchronous reply.
+ template <typename Value>
+ void Send(UniquePtr<Message> aMsg, int32_t aActorId,
+ Message::msgid_t aReplyMsgId, ResolveCallback<Value>&& aResolve,
+ RejectCallback&& aReject) MOZ_EXCLUDES(*mMonitor) {
+ int32_t seqno = NextSeqno();
+ aMsg->set_seqno(seqno);
+ if (!Send(std::move(aMsg))) {
+ aReject(ResponseRejectReason::SendError);
+ return;
+ }
+
+ UniquePtr<UntypedCallbackHolder> callback =
+ MakeUnique<CallbackHolder<Value>>(
+ aActorId, aReplyMsgId, std::move(aResolve), std::move(aReject));
+ mPendingResponses.insert(std::make_pair(seqno, std::move(callback)));
+ gUnresolvedResponses++;
+ }
+
+ bool SendBuildIDsMatchMessage(const char* aParentBuildID)
+ MOZ_EXCLUDES(*mMonitor);
+ bool DoBuildIDsMatch() MOZ_EXCLUDES(*mMonitor) {
+ MonitorAutoLock lock(*mMonitor);
+ return mBuildIDsConfirmedMatch;
+ }
+
+ // Synchronously send |aMsg| (i.e., wait for |aReply|)
+ bool Send(UniquePtr<Message> aMsg, UniquePtr<Message>* aReply)
+ MOZ_EXCLUDES(*mMonitor);
+
+ bool CanSend() const MOZ_EXCLUDES(*mMonitor);
+
+ // Remove and return a callback that needs reply
+ UniquePtr<UntypedCallbackHolder> PopCallback(const Message& aMsg,
+ int32_t aActorId);
+
+ // Used to reject and remove pending responses owned by the given
+ // actor when it's about to be destroyed.
+ void RejectPendingResponsesForActor(int32_t aActorId);
+
+ // If sending a sync message returns an error, this function gives a more
+ // descriptive error message.
+ SyncSendError LastSendError() const {
+ AssertWorkerThread();
+ return mLastSendError;
+ }
+
+ void SetReplyTimeoutMs(int32_t aTimeoutMs);
+
+ bool IsOnCxxStack() const { return mOnCxxStack; }
+
+ void CancelCurrentTransaction() MOZ_EXCLUDES(*mMonitor);
+
+ // IsClosed and NumQueuedMessages are safe to call from any thread, but
+ // may provide an out-of-date value.
+ bool IsClosed() MOZ_EXCLUDES(*mMonitor) {
+ MonitorAutoLock lock(*mMonitor);
+ return IsClosedLocked();
+ }
+ bool IsClosedLocked() const MOZ_REQUIRES(*mMonitor) {
+ mMonitor->AssertCurrentThreadOwns();
+ return mLink ? mLink->IsClosed() : true;
+ }
+
+ static bool IsPumpingMessages() { return sIsPumpingMessages; }
+ static void SetIsPumpingMessages(bool aIsPumping) {
+ sIsPumpingMessages = aIsPumping;
+ }
+
+ /**
+ * Does this MessageChannel currently cross process boundaries?
+ */
+ bool IsCrossProcess() const MOZ_REQUIRES(*mMonitor);
+ void SetIsCrossProcess(bool aIsCrossProcess) MOZ_REQUIRES(*mMonitor);
+
+ nsID GetMessageChannelId() const {
+ MonitorAutoLock lock(*mMonitor);
+ return mMessageChannelId;
+ }
+
+#ifdef FUZZING_SNAPSHOT
+ Maybe<mojo::core::ports::PortName> GetPortName() {
+ MonitorAutoLock lock(*mMonitor);
+ return mLink ? mLink->GetPortName() : Nothing();
+ }
+#endif
+
+#ifdef XP_WIN
+ struct MOZ_STACK_CLASS SyncStackFrame {
+ explicit SyncStackFrame(MessageChannel* channel);
+ ~SyncStackFrame();
+
+ bool mSpinNestedEvents;
+ bool mListenerNotified;
+ MessageChannel* mChannel;
+
+ // The previous stack frame for this channel.
+ SyncStackFrame* mPrev;
+
+ // The previous stack frame on any channel.
+ SyncStackFrame* mStaticPrev;
+ };
+ friend struct MessageChannel::SyncStackFrame;
+
+ static bool IsSpinLoopActive() {
+ for (SyncStackFrame* frame = sStaticTopFrame; frame; frame = frame->mPrev) {
+ if (frame->mSpinNestedEvents) return true;
+ }
+ return false;
+ }
+
+ protected:
+ // The deepest sync stack frame for this channel.
+ SyncStackFrame* mTopFrame = nullptr;
+
+ bool mIsSyncWaitingOnNonMainThread = false;
+
+ // The deepest sync stack frame on any channel.
+ static SyncStackFrame* sStaticTopFrame;
+
+ public:
+ void ProcessNativeEventsInInterruptCall();
+ static void NotifyGeckoEventDispatch();
+
+ private:
+ void SpinInternalEventLoop();
+#endif // defined(XP_WIN)
+
+ private:
+ void PostErrorNotifyTask() MOZ_REQUIRES(*mMonitor);
+ void OnNotifyMaybeChannelError() MOZ_EXCLUDES(*mMonitor);
+ void ReportConnectionError(const char* aFunctionName,
+ const uint32_t aMsgTyp) const
+ MOZ_REQUIRES(*mMonitor);
+ void ReportMessageRouteError(const char* channelName) const
+ MOZ_EXCLUDES(*mMonitor);
+ bool MaybeHandleError(Result code, const Message& aMsg,
+ const char* channelName) MOZ_EXCLUDES(*mMonitor);
+
+ void Clear() MOZ_REQUIRES(*mMonitor);
+
+ bool HasPendingEvents() MOZ_REQUIRES(*mMonitor);
+
+ void ProcessPendingRequests(ActorLifecycleProxy* aProxy,
+ AutoEnterTransaction& aTransaction)
+ MOZ_REQUIRES(*mMonitor);
+ bool ProcessPendingRequest(ActorLifecycleProxy* aProxy,
+ UniquePtr<Message> aUrgent)
+ MOZ_REQUIRES(*mMonitor);
+
+ void EnqueuePendingMessages() MOZ_REQUIRES(*mMonitor);
+
+ // Dispatches an incoming message to its appropriate handler.
+ void DispatchMessage(ActorLifecycleProxy* aProxy, UniquePtr<Message> aMsg)
+ MOZ_REQUIRES(*mMonitor);
+
+ // DispatchMessage will route to one of these functions depending on the
+ // protocol type of the message.
+ void DispatchSyncMessage(ActorLifecycleProxy* aProxy, const Message& aMsg,
+ UniquePtr<Message>& aReply) MOZ_EXCLUDES(*mMonitor);
+ void DispatchAsyncMessage(ActorLifecycleProxy* aProxy, const Message& aMsg)
+ MOZ_EXCLUDES(*mMonitor);
+
+ // Return true if the wait ended because a notification was received.
+ //
+ // Return false if the time elapsed from when we started the process of
+ // waiting until afterwards exceeded the currently allotted timeout.
+ // That *DOES NOT* mean false => "no event" (== timeout); there are many
+ // circumstances that could cause the measured elapsed time to exceed the
+ // timeout EVEN WHEN we were notified.
+ //
+ // So in sum: true is a meaningful return value; false isn't,
+ // necessarily.
+ bool WaitForSyncNotify() MOZ_REQUIRES(*mMonitor);
+
+ bool WaitResponse(bool aWaitTimedOut);
+
+ bool ShouldContinueFromTimeout() MOZ_REQUIRES(*mMonitor);
+
+ void EndTimeout() MOZ_REQUIRES(*mMonitor);
+ void CancelTransaction(int transaction) MOZ_REQUIRES(*mMonitor);
+
+ void RepostAllMessages() MOZ_REQUIRES(*mMonitor);
+
+ int32_t NextSeqno() {
+ AssertWorkerThread();
+ return (mSide == ChildSide) ? --mNextSeqno : ++mNextSeqno;
+ }
+
+ void DebugAbort(const char* file, int line, const char* cond, const char* why,
+ bool reply = false) MOZ_REQUIRES(*mMonitor);
+
+ void AddProfilerMarker(const IPC::Message& aMessage,
+ MessageDirection aDirection) MOZ_REQUIRES(*mMonitor);
+
+ private:
+ // Returns true if we're dispatching an async message's callback.
+ bool DispatchingAsyncMessage() const {
+ AssertWorkerThread();
+ return mDispatchingAsyncMessage;
+ }
+
+ int DispatchingAsyncMessageNestedLevel() const {
+ AssertWorkerThread();
+ return mDispatchingAsyncMessageNestedLevel;
+ }
+
+ // Check if there is still a live connection to our peer. This may change to
+ // `false` at any time due to the connection to our peer being closed or
+ // dropped (e.g. due to a crash).
+ bool Connected() const MOZ_REQUIRES(*mMonitor);
+
+ // Check if there is either still a live connection to our peer, or we have
+ // received a `Goodbye` from our peer, and are actively shutting down our
+ // connection with our peer.
+ bool ConnectedOrClosing() const MOZ_REQUIRES(*mMonitor);
+
+ private:
+ // Executed on the IO thread.
+ void NotifyWorkerThread() MOZ_REQUIRES(*mMonitor);
+
+ // Return true if |aMsg| is a special message targeted at the IO
+ // thread, in which case it shouldn't be delivered to the worker.
+ bool MaybeInterceptSpecialIOMessage(const Message& aMsg)
+ MOZ_REQUIRES(*mMonitor);
+
+ // Returns true if ShouldDeferMessage(aMsg) is guaranteed to return true.
+ // Otherwise, the result of ShouldDeferMessage(aMsg) may be true or false,
+ // depending on context.
+ static bool IsAlwaysDeferred(const Message& aMsg);
+
+ // Helper for sending a message via the link. If the message is [LazySend], it
+ // will be queued, and if the message is not-[LazySend], it will flush any
+ // pending [LazySend] messages.
+ void SendMessageToLink(UniquePtr<Message> aMsg) MOZ_REQUIRES(*mMonitor);
+
+ // Called to flush [LazySend] messages to the link.
+ void FlushLazySendMessages() MOZ_REQUIRES(*mMonitor);
+
+ bool WasTransactionCanceled(int transaction);
+ bool ShouldDeferMessage(const Message& aMsg) MOZ_REQUIRES(*mMonitor);
+ void OnMessageReceivedFromLink(UniquePtr<Message> aMsg)
+ MOZ_REQUIRES(*mMonitor);
+ void OnChannelErrorFromLink() MOZ_REQUIRES(*mMonitor);
+
+ private:
+ // Clear this channel, and notify the listener that the channel has either
+ // closed or errored.
+ //
+ // These methods must be called on the worker thread, passing in a
+ // `ReleasableMonitorAutoLock`. This lock guard will be reset before the
+ // listener is called, allowing for the monitor to be unlocked before the
+ // MessageChannel is potentially destroyed.
+ void NotifyChannelClosed(ReleasableMonitorAutoLock& aLock)
+ MOZ_REQUIRES(*mMonitor);
+ void NotifyMaybeChannelError(ReleasableMonitorAutoLock& aLock)
+ MOZ_REQUIRES(*mMonitor);
+
+ private:
+ void AssertWorkerThread() const {
+ MOZ_ASSERT(mWorkerThread, "Channel hasn't been opened yet");
+ MOZ_RELEASE_ASSERT(mWorkerThread && mWorkerThread->IsOnCurrentThread(),
+ "not on worker thread!");
+ }
+
+ private:
+ class MessageTask : public CancelableRunnable,
+ public LinkedListElement<RefPtr<MessageTask>>,
+ public nsIRunnablePriority,
+ public nsIRunnableIPCMessageType {
+ public:
+ explicit MessageTask(MessageChannel* aChannel, UniquePtr<Message> aMessage);
+ MessageTask() = delete;
+ MessageTask(const MessageTask&) = delete;
+
+ NS_DECL_ISUPPORTS_INHERITED
+
+ NS_IMETHOD Run() override;
+ nsresult Cancel() override;
+ NS_IMETHOD GetPriority(uint32_t* aPriority) override;
+ NS_DECL_NSIRUNNABLEIPCMESSAGETYPE
+ void Post() MOZ_REQUIRES(*mMonitor);
+
+ bool IsScheduled() const MOZ_REQUIRES(*mMonitor) {
+ mMonitor->AssertCurrentThreadOwns();
+ return mScheduled;
+ }
+
+ UniquePtr<Message>& Msg() MOZ_REQUIRES(*mMonitor) {
+ MOZ_DIAGNOSTIC_ASSERT(mMessage, "message was moved");
+ return mMessage;
+ }
+ const UniquePtr<Message>& Msg() const MOZ_REQUIRES(*mMonitor) {
+ MOZ_DIAGNOSTIC_ASSERT(mMessage, "message was moved");
+ return mMessage;
+ }
+
+ void AssertMonitorHeld(const RefCountedMonitor& aMonitor)
+ MOZ_REQUIRES(aMonitor) MOZ_ASSERT_CAPABILITY(*mMonitor) {
+ aMonitor.AssertSameMonitor(*mMonitor);
+ }
+
+ private:
+ ~MessageTask();
+
+ MessageChannel* Channel() MOZ_REQUIRES(*mMonitor) {
+ mMonitor->AssertCurrentThreadOwns();
+ MOZ_RELEASE_ASSERT(isInList());
+ return mChannel;
+ }
+
+ // The connected MessageChannel's monitor. Guards `mChannel` and
+ // `mScheduled`.
+ RefPtr<RefCountedMonitor> const mMonitor;
+ // The channel which this MessageTask is associated with. Only valid while
+ // `mMonitor` is held, and this MessageTask `isInList()`.
+ MessageChannel* const mChannel;
+ UniquePtr<Message> mMessage MOZ_GUARDED_BY(*mMonitor);
+ uint32_t const mPriority;
+ bool mScheduled : 1 MOZ_GUARDED_BY(*mMonitor);
+#ifdef FUZZING_SNAPSHOT
+ const bool mIsFuzzMsg;
+ bool mFuzzStopped MOZ_GUARDED_BY(*mMonitor);
+#endif
+ };
+
+ bool ShouldRunMessage(const Message& aMsg) MOZ_REQUIRES(*mMonitor);
+ void RunMessage(ActorLifecycleProxy* aProxy, MessageTask& aTask)
+ MOZ_REQUIRES(*mMonitor);
+
+ class WorkerTargetShutdownTask final : public nsITargetShutdownTask {
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ WorkerTargetShutdownTask(nsISerialEventTarget* aTarget,
+ MessageChannel* aChannel);
+
+ void TargetShutdown() override;
+ void Clear();
+
+ private:
+ ~WorkerTargetShutdownTask() = default;
+
+ const nsCOMPtr<nsISerialEventTarget> mTarget;
+ // Cleared by MessageChannel before it is destroyed.
+ MessageChannel* MOZ_NON_OWNING_REF mChannel;
+ };
+
+ class FlushLazySendMessagesRunnable final : public CancelableRunnable {
+ public:
+ explicit FlushLazySendMessagesRunnable(MessageChannel* aChannel);
+
+ NS_DECL_ISUPPORTS_INHERITED
+
+ NS_IMETHOD Run() override;
+ nsresult Cancel() override;
+
+ void PushMessage(UniquePtr<Message> aMsg);
+ nsTArray<UniquePtr<Message>> TakeMessages();
+
+ private:
+ ~FlushLazySendMessagesRunnable() = default;
+
+ // Cleared by MessageChannel before it is destroyed.
+ MessageChannel* MOZ_NON_OWNING_REF mChannel;
+
+ // LazySend messages which haven't been sent yet, but will be sent as soon
+ // as a non-LazySend message is sent, or this runnable is executed.
+ nsTArray<UniquePtr<Message>> mQueue;
+ };
+
+ typedef LinkedList<RefPtr<MessageTask>> MessageQueue;
+ typedef std::map<size_t, UniquePtr<UntypedCallbackHolder>> CallbackMap;
+ typedef IPC::Message::msgid_t msgid_t;
+
+ private:
+ // This will be a string literal, so lifetime is not an issue.
+ const char* const mName;
+
+ // ID for each MessageChannel. Set when it is opened, and never cleared
+ // afterwards.
+ //
+ // This ID is only intended for diagnostics, debugging, and reporting
+ // purposes, and shouldn't be used for message routing or permissions checks.
+ nsID mMessageChannelId MOZ_GUARDED_BY(*mMonitor) = {};
+
+ // Based on presumption the listener owns and overlives the channel,
+ // this is never nullified.
+ IToplevelProtocol* const mListener;
+
+ // This monitor guards all state in this MessageChannel, except where
+ // otherwise noted. It is refcounted so a reference to it can be shared with
+ // IPC listener objects which need to access weak references to this
+ // `MessageChannel`.
+ RefPtr<RefCountedMonitor> const mMonitor;
+
+ ChannelState mChannelState MOZ_GUARDED_BY(*mMonitor) = ChannelClosed;
+ Side mSide = UnknownSide;
+ bool mIsCrossProcess MOZ_GUARDED_BY(*mMonitor) = false;
+ UniquePtr<MessageLink> mLink MOZ_GUARDED_BY(*mMonitor);
+
+ // NotifyMaybeChannelError runnable
+ RefPtr<CancelableRunnable> mChannelErrorTask MOZ_GUARDED_BY(*mMonitor);
+
+ // Thread we are allowed to send and receive on. Set in Open(); never
+ // changed, and we can only call Open() once. We shouldn't be accessing
+ // from multiple threads before Open().
+ nsCOMPtr<nsISerialEventTarget> mWorkerThread;
+
+ // Shutdown task to close the channel before mWorkerThread goes away.
+ RefPtr<WorkerTargetShutdownTask> mShutdownTask MOZ_GUARDED_BY(*mMonitor);
+
+ // Task to force sending lazy messages when mQueuedLazyMessages is non-empty.
+ RefPtr<FlushLazySendMessagesRunnable> mFlushLazySendTask
+ MOZ_GUARDED_BY(*mMonitor);
+
+ // Timeout periods are broken up in two to prevent system suspension from
+ // triggering an abort. This method (called by WaitForEvent with a 'did
+ // timeout' flag) decides if we should wait again for half of mTimeoutMs
+ // or give up.
+ // only accessed on WorkerThread
+ int32_t mTimeoutMs = kNoTimeout;
+ bool mInTimeoutSecondHalf = false;
+
+ // Worker-thread only; sequence numbers for messages that require
+ // replies.
+ int32_t mNextSeqno = 0;
+
+ static bool sIsPumpingMessages;
+
+ // If ::Send returns false, this gives a more descriptive error.
+ SyncSendError mLastSendError = SyncSendError::SendSuccess;
+
+ template <class T>
+ class AutoSetValue {
+ public:
+ explicit AutoSetValue(T& var, const T& newValue)
+ : mVar(var), mPrev(var), mNew(newValue) {
+ mVar = newValue;
+ }
+ ~AutoSetValue() {
+ // The value may have been zeroed if the transaction was
+ // canceled. In that case we shouldn't return it to its previous
+ // value.
+ if (mVar == mNew) {
+ mVar = mPrev;
+ }
+ }
+
+ private:
+ T& mVar;
+ T mPrev;
+ T mNew;
+ };
+
+ bool mDispatchingAsyncMessage = false;
+ int mDispatchingAsyncMessageNestedLevel = 0;
+
+ // When we send an urgent request from the parent process, we could race
+ // with an RPC message that was issued by the child beforehand. In this
+ // case, if the parent were to wake up while waiting for the urgent reply,
+ // and process the RPC, it could send an additional urgent message. The
+ // child would wake up to process the urgent message (as it always will),
+ // then send a reply, which could be received by the parent out-of-order
+ // with respect to the first urgent reply.
+ //
+ // To address this problem, urgent or RPC requests are associated with a
+ // "transaction". Whenever one side of the channel wishes to start a
+ // chain of RPC/urgent messages, it allocates a new transaction ID. Any
+ // messages the parent receives, not apart of this transaction, are
+ // deferred. When issuing RPC/urgent requests on top of a started
+ // transaction, the initiating transaction ID is used.
+ //
+ // To ensure IDs are unique, we use sequence numbers for transaction IDs,
+ // which grow in opposite directions from child to parent.
+
+ friend class AutoEnterTransaction;
+ AutoEnterTransaction* mTransactionStack MOZ_GUARDED_BY(*mMonitor) = nullptr;
+
+ int32_t CurrentNestedInsideSyncTransaction() const MOZ_REQUIRES(*mMonitor);
+
+ bool AwaitingSyncReply() const MOZ_REQUIRES(*mMonitor);
+ int AwaitingSyncReplyNestedLevel() const MOZ_REQUIRES(*mMonitor);
+
+ bool DispatchingSyncMessage() const MOZ_REQUIRES(*mMonitor);
+ int DispatchingSyncMessageNestedLevel() const MOZ_REQUIRES(*mMonitor);
+
+#ifdef DEBUG
+ void AssertMaybeDeferredCountCorrect() MOZ_REQUIRES(*mMonitor);
+#else
+ void AssertMaybeDeferredCountCorrect() MOZ_REQUIRES(*mMonitor) {}
+#endif
+
+ // If a sync message times out, we store its sequence number here. Any
+ // future sync messages will fail immediately. Once the reply for original
+ // sync message is received, we allow sync messages again.
+ //
+ // When a message times out, nothing is done to inform the other side. The
+ // other side will eventually dispatch the message and send a reply. Our
+ // side is responsible for replying to all sync messages sent by the other
+ // side when it dispatches the timed out message. The response is always an
+ // error.
+ //
+ // A message is only timed out if it initiated a transaction. This avoids
+ // hitting a lot of corner cases with message nesting that we don't really
+ // care about.
+ int32_t mTimedOutMessageSeqno MOZ_GUARDED_BY(*mMonitor) = 0;
+ int mTimedOutMessageNestedLevel MOZ_GUARDED_BY(*mMonitor) = 0;
+
+ // Queue of all incoming messages.
+ //
+ // If both this side and the other side are functioning correctly, the other
+ // side can send as many async messages as it wants before sending us a
+ // blocking message. After sending a blocking message, the other side must be
+ // blocked, and thus can't send us any more messages until we process the sync
+ // in-msg.
+ //
+ MessageQueue mPending MOZ_GUARDED_BY(*mMonitor);
+
+ // The number of messages in mPending for which IsAlwaysDeferred is false
+ // (i.e., the number of messages that might not be deferred, depending on
+ // context).
+ size_t mMaybeDeferredPendingCount MOZ_GUARDED_BY(*mMonitor) = 0;
+
+ // Is there currently MessageChannel logic for this channel on the C++ stack?
+ // This member is only accessed on the worker thread, and so is not protected
+ // by mMonitor.
+ bool mOnCxxStack = false;
+
+ // Map of async Callbacks that are still waiting replies.
+ CallbackMap mPendingResponses;
+
+#ifdef XP_WIN
+ HANDLE mEvent;
+#endif
+
+ // Should the channel abort the process from the I/O thread when
+ // a channel error occurs?
+ bool mAbortOnError MOZ_GUARDED_BY(*mMonitor) = false;
+
+ // True if the listener has already been notified of a channel close or
+ // error.
+ bool mNotifiedChannelDone MOZ_GUARDED_BY(*mMonitor) = false;
+
+ // See SetChannelFlags
+ ChannelFlags mFlags = REQUIRE_DEFAULT;
+
+ bool mBuildIDsConfirmedMatch MOZ_GUARDED_BY(*mMonitor) = false;
+
+ // If this is true, both ends of this message channel have event targets
+ // on the same thread.
+ bool mIsSameThreadChannel = false;
+};
+
+void CancelCPOWs();
+
+} // namespace ipc
+} // namespace mozilla
+
+namespace IPC {
+template <>
+struct ParamTraits<mozilla::ipc::ResponseRejectReason>
+ : public ContiguousEnumSerializer<
+ mozilla::ipc::ResponseRejectReason,
+ mozilla::ipc::ResponseRejectReason::SendError,
+ mozilla::ipc::ResponseRejectReason::EndGuard_> {};
+} // namespace IPC
+
+namespace geckoprofiler::markers {
+
+struct IPCMarker {
+ static constexpr mozilla::Span<const char> MarkerTypeName() {
+ return mozilla::MakeStringSpan("IPC");
+ }
+ static void StreamJSONMarkerData(
+ mozilla::baseprofiler::SpliceableJSONWriter& aWriter,
+ mozilla::TimeStamp aStart, mozilla::TimeStamp aEnd, int32_t aOtherPid,
+ int32_t aMessageSeqno, IPC::Message::msgid_t aMessageType,
+ mozilla::ipc::Side aSide, mozilla::ipc::MessageDirection aDirection,
+ mozilla::ipc::MessagePhase aPhase, bool aSync,
+ mozilla::MarkerThreadId aOriginThreadId) {
+ using namespace mozilla::ipc;
+ // This payload still streams a startTime and endTime property because it
+ // made the migration to MarkerTiming on the front-end easier.
+ aWriter.TimeProperty("startTime", aStart);
+ aWriter.TimeProperty("endTime", aEnd);
+
+ aWriter.IntProperty("otherPid", aOtherPid);
+ aWriter.IntProperty("messageSeqno", aMessageSeqno);
+ aWriter.StringProperty(
+ "messageType",
+ mozilla::MakeStringSpan(IPC::StringFromIPCMessageType(aMessageType)));
+ aWriter.StringProperty("side", IPCSideToString(aSide));
+ aWriter.StringProperty("direction",
+ aDirection == MessageDirection::eSending
+ ? mozilla::MakeStringSpan("sending")
+ : mozilla::MakeStringSpan("receiving"));
+ aWriter.StringProperty("phase", IPCPhaseToString(aPhase));
+ aWriter.BoolProperty("sync", aSync);
+ if (!aOriginThreadId.IsUnspecified()) {
+ // Tech note: If `ToNumber()` returns a uint64_t, the conversion to
+ // int64_t is "implementation-defined" before C++20. This is acceptable
+ // here, because this is a one-way conversion to a unique identifier
+ // that's used to visually separate data by thread on the front-end.
+ aWriter.IntProperty(
+ "threadId",
+ static_cast<int64_t>(aOriginThreadId.ThreadId().ToNumber()));
+ }
+ }
+ static mozilla::MarkerSchema MarkerTypeDisplay() {
+ return mozilla::MarkerSchema::SpecialFrontendLocation{};
+ }
+
+ private:
+ static mozilla::Span<const char> IPCSideToString(mozilla::ipc::Side aSide) {
+ switch (aSide) {
+ case mozilla::ipc::ParentSide:
+ return mozilla::MakeStringSpan("parent");
+ case mozilla::ipc::ChildSide:
+ return mozilla::MakeStringSpan("child");
+ case mozilla::ipc::UnknownSide:
+ return mozilla::MakeStringSpan("unknown");
+ default:
+ MOZ_ASSERT_UNREACHABLE("Invalid IPC side");
+ return mozilla::MakeStringSpan("<invalid IPC side>");
+ }
+ }
+
+ static mozilla::Span<const char> IPCPhaseToString(
+ mozilla::ipc::MessagePhase aPhase) {
+ switch (aPhase) {
+ case mozilla::ipc::MessagePhase::Endpoint:
+ return mozilla::MakeStringSpan("endpoint");
+ case mozilla::ipc::MessagePhase::TransferStart:
+ return mozilla::MakeStringSpan("transferStart");
+ case mozilla::ipc::MessagePhase::TransferEnd:
+ return mozilla::MakeStringSpan("transferEnd");
+ default:
+ MOZ_ASSERT_UNREACHABLE("Invalid IPC phase");
+ return mozilla::MakeStringSpan("<invalid IPC phase>");
+ }
+ }
+};
+
+} // namespace geckoprofiler::markers
+
+#endif // ifndef ipc_glue_MessageChannel_h
diff --git a/ipc/glue/MessageLink.cpp b/ipc/glue/MessageLink.cpp
new file mode 100644
index 0000000000..5505322a2f
--- /dev/null
+++ b/ipc/glue/MessageLink.cpp
@@ -0,0 +1,206 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/MessageLink.h"
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/node.h"
+#include "mozilla/ipc/MessageChannel.h"
+#include "mozilla/ipc/BrowserProcessSubThread.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/ipc/NodeController.h"
+#include "chrome/common/ipc_channel.h"
+#include "base/task.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/DebugOnly.h"
+#include "nsDebug.h"
+#include "nsExceptionHandler.h"
+#include "nsISupportsImpl.h"
+#include "nsPrintfCString.h"
+#include "nsXULAppAPI.h"
+
+using namespace mozilla;
+
+namespace mozilla {
+namespace ipc {
+
+const char* StringFromIPCSide(Side side) {
+ switch (side) {
+ case ChildSide:
+ return "Child";
+ case ParentSide:
+ return "Parent";
+ default:
+ return "Unknown";
+ }
+}
+
+MessageLink::MessageLink(MessageChannel* aChan) : mChan(aChan) {}
+
+MessageLink::~MessageLink() {
+#ifdef DEBUG
+ mChan = nullptr;
+#endif
+}
+
+class PortLink::PortObserverThunk : public NodeController::PortObserver {
+ public:
+ PortObserverThunk(RefCountedMonitor* aMonitor, PortLink* aLink)
+ : mMonitor(aMonitor), mLink(aLink) {}
+
+ void OnPortStatusChanged() override {
+ MonitorAutoLock lock(*mMonitor);
+ if (mLink) {
+ mLink->OnPortStatusChanged();
+ }
+ }
+
+ private:
+ friend class PortLink;
+
+ // The monitor from our PortLink's MessageChannel. Guards access to `mLink`.
+ RefPtr<RefCountedMonitor> mMonitor;
+
+ // Cleared by `PortLink` in `PortLink::Clear()`.
+ PortLink* MOZ_NON_OWNING_REF mLink;
+};
+
+PortLink::PortLink(MessageChannel* aChan, ScopedPort aPort)
+ : MessageLink(aChan), mNode(aPort.Controller()), mPort(aPort.Release()) {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ mObserver = new PortObserverThunk(mChan->mMonitor, this);
+ mNode->SetPortObserver(mPort, mObserver);
+
+ // Dispatch an event to the IO loop to trigger an initial
+ // `OnPortStatusChanged` to deliver any pending messages. This needs to be run
+ // asynchronously from a different thread (or in the case of a same-thread
+ // channel, from the current thread), for now due to assertions in
+ // `MessageChannel`.
+ nsCOMPtr<nsIRunnable> openRunnable = NewRunnableMethod(
+ "PortLink::Open", mObserver, &PortObserverThunk::OnPortStatusChanged);
+ if (aChan->mIsSameThreadChannel) {
+ aChan->mWorkerThread->Dispatch(openRunnable.forget());
+ } else {
+ XRE_GetIOMessageLoop()->PostTask(openRunnable.forget());
+ }
+}
+
+PortLink::~PortLink() {
+ MOZ_RELEASE_ASSERT(!mObserver, "PortLink destroyed without being closed!");
+}
+
+void PortLink::SendMessage(UniquePtr<Message> aMessage) {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ if (aMessage->size() > IPC::Channel::kMaximumMessageSize) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCMessageName,
+ nsDependentCString(aMessage->name()));
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCMessageSize,
+ static_cast<unsigned int>(aMessage->size()));
+ MOZ_CRASH("IPC message size is too large");
+ }
+ aMessage->AssertAsLargeAsHeader();
+
+ RefPtr<PortObserverThunk> observer = mObserver;
+ if (!observer) {
+ NS_WARNING("Ignoring message to closed PortLink");
+ return;
+ }
+
+ // Make local copies of relevant member variables, so we can unlock the
+ // monitor for the rest of this function. This protects us in case `this` is
+ // deleted during the call (although that shouldn't happen in practice).
+ //
+ // We don't want the monitor to be held when calling into ports, as we may be
+ // re-entrantly called by our `PortObserverThunk` which will attempt to
+ // acquire the monitor.
+ RefPtr<RefCountedMonitor> monitor = mChan->mMonitor;
+ RefPtr<NodeController> node = mNode;
+ PortRef port = mPort;
+
+ bool ok = false;
+ monitor->AssertCurrentThreadOwns();
+ {
+ MonitorAutoUnlock guard(*monitor);
+ ok = node->SendUserMessage(port, std::move(aMessage));
+ }
+ if (!ok) {
+ // The send failed, but double-check that we weren't closed racily while
+ // sending, which could lead to an invalid state error.
+ if (observer->mLink) {
+ MOZ_CRASH("Invalid argument to SendUserMessage");
+ }
+ NS_WARNING("Message dropped as PortLink was closed");
+ }
+}
+
+void PortLink::Close() {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ if (!mObserver) {
+ // We're already being closed.
+ return;
+ }
+
+ Clear();
+}
+
+void PortLink::Clear() {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ // NOTE: We're calling into `ports` with our monitor held! Usually, this could
+ // lead to deadlocks due to the PortObserverThunk acquiring the lock
+ // re-entrantly, but is OK here as we're immediately clearing the port's
+ // observer. We shouldn't have issues with any re-entrant calls on this thread
+ // acquiring this MessageChannel's monitor.
+ //
+ // We also clear out the reference in `mObserver` back to this type so that
+ // notifications from other threads won't try to call us again once we release
+ // the monitor.
+ mNode->SetPortObserver(mPort, nullptr);
+ mObserver->mLink = nullptr;
+ mObserver = nullptr;
+ mNode->ClosePort(mPort);
+}
+
+void PortLink::OnPortStatusChanged() {
+ mChan->mMonitor->AssertCurrentThreadOwns();
+
+ // Check if the port's remoteness status has updated, and tell our channel if
+ // it has.
+ if (Maybe<PortStatus> status = mNode->GetStatus(mPort);
+ status && status->peer_remote != mChan->IsCrossProcess()) {
+ mChan->SetIsCrossProcess(status->peer_remote);
+ }
+
+ while (mObserver) {
+ UniquePtr<IPC::Message> message;
+ if (!mNode->GetMessage(mPort, &message)) {
+ Clear();
+ mChan->OnChannelErrorFromLink();
+ return;
+ }
+ if (!message) {
+ return;
+ }
+
+ mChan->OnMessageReceivedFromLink(std::move(message));
+ }
+}
+
+bool PortLink::IsClosed() const {
+ if (Maybe<PortStatus> status = mNode->GetStatus(mPort)) {
+ return !(status->has_messages || status->receiving_messages);
+ }
+ return true;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/MessageLink.h b/ipc/glue/MessageLink.h
new file mode 100644
index 0000000000..1ad33030b7
--- /dev/null
+++ b/ipc/glue/MessageLink.h
@@ -0,0 +1,114 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef ipc_glue_MessageLink_h
+#define ipc_glue_MessageLink_h
+
+#include <cstdint>
+#include "base/message_loop.h"
+#include "mojo/core/ports/node.h"
+#include "mojo/core/ports/port_ref.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/ScopedPort.h"
+
+namespace IPC {
+class Message;
+class MessageReader;
+class MessageWriter;
+} // namespace IPC
+
+namespace mozilla {
+namespace ipc {
+
+class MessageChannel;
+class NodeController;
+
+struct HasResultCodes {
+ enum Result {
+ MsgProcessed,
+ MsgDropped,
+ MsgNotKnown,
+ MsgNotAllowed,
+ MsgPayloadError,
+ MsgProcessingError,
+ MsgRouteError,
+ MsgValueError
+ };
+};
+
+enum Side : uint8_t { ParentSide, ChildSide, UnknownSide };
+
+const char* StringFromIPCSide(Side side);
+
+class MessageLink {
+ public:
+ typedef IPC::Message Message;
+
+ explicit MessageLink(MessageChannel* aChan);
+ virtual ~MessageLink();
+
+ // n.b.: These methods all require that the channel monitor is
+ // held when they are invoked.
+ virtual void SendMessage(mozilla::UniquePtr<Message> msg) = 0;
+
+ // Synchronously close the connection, such that no further notifications will
+ // be delivered to the MessageChannel instance. Must be called with the
+ // channel monitor held.
+ virtual void Close() = 0;
+
+ virtual bool IsClosed() const = 0;
+
+#ifdef FUZZING_SNAPSHOT
+ virtual Maybe<mojo::core::ports::PortName> GetPortName() { return Nothing(); }
+#endif
+
+ protected:
+ MessageChannel* mChan;
+};
+
+class PortLink final : public MessageLink {
+ using PortRef = mojo::core::ports::PortRef;
+ using PortStatus = mojo::core::ports::PortStatus;
+ using UserMessage = mojo::core::ports::UserMessage;
+ using UserMessageEvent = mojo::core::ports::UserMessageEvent;
+
+ public:
+ PortLink(MessageChannel* aChan, ScopedPort aPort);
+ virtual ~PortLink();
+
+ void SendMessage(UniquePtr<Message> aMessage) override;
+ void Close() override;
+
+ bool IsClosed() const override;
+
+#ifdef FUZZING_SNAPSHOT
+ Maybe<mojo::core::ports::PortName> GetPortName() override {
+ return Some(mPort.name());
+ }
+#endif
+
+ private:
+ class PortObserverThunk;
+ friend class PortObserverThunk;
+
+ void OnPortStatusChanged();
+
+ // Called either when an error is detected on the port from the port observer,
+ // or when `SendClose()` is called.
+ void Clear();
+
+ const RefPtr<NodeController> mNode;
+ const PortRef mPort;
+
+ RefPtr<PortObserverThunk> mObserver;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef ipc_glue_MessageLink_h
diff --git a/ipc/glue/MessagePump.cpp b/ipc/glue/MessagePump.cpp
new file mode 100644
index 0000000000..50c916608c
--- /dev/null
+++ b/ipc/glue/MessagePump.cpp
@@ -0,0 +1,336 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "MessagePump.h"
+
+#include "nsIThread.h"
+#include "nsITimer.h"
+#include "nsICancelableRunnable.h"
+
+#include "base/basictypes.h"
+#include "base/logging.h"
+#include "base/scoped_nsautorelease_pool.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/DebugOnly.h"
+#include "nsComponentManagerUtils.h"
+#include "nsDebug.h"
+#include "nsServiceManagerUtils.h"
+#include "nsString.h"
+#include "nsThreadUtils.h"
+#include "nsTimerImpl.h"
+#include "nsXULAppAPI.h"
+#include "prthread.h"
+
+using base::TimeTicks;
+using namespace mozilla::ipc;
+
+#ifdef DEBUG
+static MessagePump::Delegate* gFirstDelegate;
+#endif
+
+namespace mozilla {
+namespace ipc {
+
+class DoWorkRunnable final : public CancelableRunnable,
+ public nsITimerCallback {
+ public:
+ explicit DoWorkRunnable(MessagePump* aPump)
+ : CancelableRunnable("ipc::DoWorkRunnable"), mPump(aPump) {
+ MOZ_ASSERT(aPump);
+ }
+
+ NS_DECL_ISUPPORTS_INHERITED
+ NS_DECL_NSIRUNNABLE
+ NS_DECL_NSITIMERCALLBACK
+ nsresult Cancel() override;
+
+ private:
+ ~DoWorkRunnable() = default;
+
+ MessagePump* mPump;
+ // DoWorkRunnable is designed as a stateless singleton. Do not add stateful
+ // members here!
+};
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+MessagePump::MessagePump(nsISerialEventTarget* aEventTarget)
+ : mEventTarget(aEventTarget) {
+ mDoWorkEvent = new DoWorkRunnable(this);
+}
+
+MessagePump::~MessagePump() = default;
+
+void MessagePump::Run(MessagePump::Delegate* aDelegate) {
+ MOZ_ASSERT(keep_running_);
+ MOZ_RELEASE_ASSERT(NS_IsMainThread(),
+ "Use mozilla::ipc::MessagePumpForNonMainThreads instead!");
+ MOZ_RELEASE_ASSERT(!mEventTarget);
+
+ nsIThread* thisThread = NS_GetCurrentThread();
+ MOZ_ASSERT(thisThread);
+
+ mDelayedWorkTimer = NS_NewTimer();
+ MOZ_ASSERT(mDelayedWorkTimer);
+
+ base::ScopedNSAutoreleasePool autoReleasePool;
+
+ for (;;) {
+ autoReleasePool.Recycle();
+
+ bool did_work = NS_ProcessNextEvent(thisThread, false) ? true : false;
+ if (!keep_running_) break;
+
+ // NB: it is crucial *not* to directly call |aDelegate->DoWork()|
+ // here. To ensure that MessageLoop tasks and XPCOM events have
+ // equal priority, we sensitively rely on processing exactly one
+ // Task per DoWorkRunnable XPCOM event.
+
+ did_work |= aDelegate->DoDelayedWork(&delayed_work_time_);
+
+ if (did_work && delayed_work_time_.is_null()) mDelayedWorkTimer->Cancel();
+
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ did_work = aDelegate->DoIdleWork();
+ if (!keep_running_) break;
+
+ if (did_work) continue;
+
+ // This will either sleep or process an event.
+ NS_ProcessNextEvent(thisThread, true);
+ }
+
+ mDelayedWorkTimer->Cancel();
+
+ keep_running_ = true;
+}
+
+void MessagePump::ScheduleWork() {
+ // Make sure the event loop wakes up.
+ if (mEventTarget) {
+ mEventTarget->Dispatch(mDoWorkEvent, NS_DISPATCH_NORMAL);
+ } else {
+ // Some things (like xpcshell) don't use the app shell and so Run hasn't
+ // been called. We still need to wake up the main thread.
+ NS_DispatchToMainThread(mDoWorkEvent);
+ }
+ event_.Signal();
+}
+
+void MessagePump::ScheduleWorkForNestedLoop() {
+ // This method is called when our MessageLoop has just allowed
+ // nested tasks. In our setup, whenever that happens we know that
+ // DoWork() will be called "soon", so there's no need to pay the
+ // cost of what will be a no-op nsThread::Dispatch(mDoWorkEvent).
+}
+
+void MessagePump::ScheduleDelayedWork(const base::TimeTicks& aDelayedTime) {
+ // To avoid racing on mDelayedWorkTimer, we need to be on the same thread as
+ // ::Run().
+ MOZ_RELEASE_ASSERT((!mEventTarget && NS_IsMainThread()) ||
+ mEventTarget->IsOnCurrentThread());
+
+ if (!mDelayedWorkTimer) {
+ mDelayedWorkTimer = NS_NewTimer();
+ if (!mDelayedWorkTimer) {
+ // Called before XPCOM has started up? We can't do this correctly.
+ NS_WARNING("Delayed task might not run!");
+ delayed_work_time_ = aDelayedTime;
+ return;
+ }
+ }
+
+ if (!delayed_work_time_.is_null()) {
+ mDelayedWorkTimer->Cancel();
+ }
+
+ delayed_work_time_ = aDelayedTime;
+
+ // TimeDelta's constructor initializes to 0
+ base::TimeDelta delay;
+ if (aDelayedTime > base::TimeTicks::Now())
+ delay = aDelayedTime - base::TimeTicks::Now();
+
+ uint32_t delayMS = uint32_t(delay.InMilliseconds());
+ mDelayedWorkTimer->InitWithCallback(mDoWorkEvent, delayMS,
+ nsITimer::TYPE_ONE_SHOT);
+}
+
+nsISerialEventTarget* MessagePump::GetXPCOMThread() {
+ if (mEventTarget) {
+ return mEventTarget;
+ }
+
+ // Main thread
+ return GetMainThreadSerialEventTarget();
+}
+
+void MessagePump::DoDelayedWork(base::MessagePump::Delegate* aDelegate) {
+ aDelegate->DoDelayedWork(&delayed_work_time_);
+ if (!delayed_work_time_.is_null()) {
+ ScheduleDelayedWork(delayed_work_time_);
+ }
+}
+
+NS_IMPL_ISUPPORTS_INHERITED(DoWorkRunnable, CancelableRunnable,
+ nsITimerCallback)
+
+NS_IMETHODIMP
+DoWorkRunnable::Run() {
+ MessageLoop* loop = MessageLoop::current();
+ MOZ_ASSERT(loop);
+
+ bool nestableTasksAllowed = loop->NestableTasksAllowed();
+
+ // MessageLoop::RunTask() disallows nesting, but our Frankenventloop will
+ // always dispatch DoWork() below from what looks to MessageLoop like a nested
+ // context. So we unconditionally allow nesting here.
+ loop->SetNestableTasksAllowed(true);
+ loop->DoWork();
+ loop->SetNestableTasksAllowed(nestableTasksAllowed);
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+DoWorkRunnable::Notify(nsITimer* aTimer) {
+ MessageLoop* loop = MessageLoop::current();
+ MOZ_ASSERT(loop);
+
+ bool nestableTasksAllowed = loop->NestableTasksAllowed();
+ loop->SetNestableTasksAllowed(true);
+ mPump->DoDelayedWork(loop);
+ loop->SetNestableTasksAllowed(nestableTasksAllowed);
+
+ return NS_OK;
+}
+
+nsresult DoWorkRunnable::Cancel() {
+ // Workers require cancelable runnables, but we can't really cancel cleanly
+ // here. If we don't process this runnable then we will leave something
+ // unprocessed in the message_loop. Therefore, eagerly complete our work
+ // instead by immediately calling Run(). Run() should be called separately
+ // after this. Unfortunately we cannot use flags to verify this because
+ // DoWorkRunnable is a stateless singleton that can be in the event queue
+ // multiple times simultaneously.
+ MOZ_ALWAYS_SUCCEEDS(Run());
+ return NS_OK;
+}
+
+void MessagePumpForChildProcess::Run(base::MessagePump::Delegate* aDelegate) {
+ if (mFirstRun) {
+ MOZ_ASSERT(aDelegate && !gFirstDelegate);
+#ifdef DEBUG
+ gFirstDelegate = aDelegate;
+#endif
+
+ mFirstRun = false;
+ if (NS_FAILED(XRE_RunAppShell())) {
+ NS_WARNING("Failed to run app shell?!");
+ }
+
+ MOZ_ASSERT(aDelegate && aDelegate == gFirstDelegate);
+#ifdef DEBUG
+ gFirstDelegate = nullptr;
+#endif
+
+ return;
+ }
+
+ MOZ_ASSERT(aDelegate && aDelegate == gFirstDelegate);
+
+ // We can get to this point in startup with Tasks in our loop's
+ // incoming_queue_ or pending_queue_, but without a matching
+ // DoWorkRunnable(). In MessagePump::Run() above, we sensitively
+ // depend on *not* directly calling delegate->DoWork(), because that
+ // prioritizes Tasks above XPCOM events. However, from this point
+ // forward, any Task posted to our loop is guaranteed to have a
+ // DoWorkRunnable enqueued for it.
+ //
+ // So we just flush the pending work here and move on.
+ MessageLoop* loop = MessageLoop::current();
+ bool nestableTasksAllowed = loop->NestableTasksAllowed();
+ loop->SetNestableTasksAllowed(true);
+
+ while (aDelegate->DoWork())
+ ;
+
+ loop->SetNestableTasksAllowed(nestableTasksAllowed);
+
+ // Really run.
+ mozilla::ipc::MessagePump::Run(aDelegate);
+}
+
+void MessagePumpForNonMainThreads::Run(base::MessagePump::Delegate* aDelegate) {
+ MOZ_ASSERT(keep_running_);
+ MOZ_RELEASE_ASSERT(!NS_IsMainThread(),
+ "Use mozilla::ipc::MessagePump instead!");
+
+ nsIThread* thread = NS_GetCurrentThread();
+ MOZ_RELEASE_ASSERT(mEventTarget->IsOnCurrentThread());
+
+ mDelayedWorkTimer = NS_NewTimer(mEventTarget);
+ MOZ_ASSERT(mDelayedWorkTimer);
+
+ // Chromium event notifications to be processed will be received by this
+ // event loop as a DoWorkRunnables via ScheduleWork. Chromium events that
+ // were received before our thread is valid, however, will not generate
+ // runnable wrappers. We must process any of these before we enter this
+ // loop, or we will forever have unprocessed chromium messages in our queue.
+ //
+ // Note we would like to request a flush of the chromium event queue
+ // using a runnable on the xpcom side, but some thread implementations
+ // (dom workers) get cranky if we call ScheduleWork here (ScheduleWork
+ // calls dispatch on mEventTarget) before the thread processes an event. As
+ // such, clear the queue manually.
+ while (aDelegate->DoWork()) {
+ }
+
+ base::ScopedNSAutoreleasePool autoReleasePool;
+ for (;;) {
+ autoReleasePool.Recycle();
+
+ bool didWork = NS_ProcessNextEvent(thread, false) ? true : false;
+ if (!keep_running_) {
+ break;
+ }
+
+ didWork |= aDelegate->DoDelayedWork(&delayed_work_time_);
+
+ if (didWork && delayed_work_time_.is_null()) {
+ mDelayedWorkTimer->Cancel();
+ }
+
+ if (!keep_running_) {
+ break;
+ }
+
+ if (didWork) {
+ continue;
+ }
+
+ DebugOnly<bool> didIdleWork = aDelegate->DoIdleWork();
+ MOZ_ASSERT(!didIdleWork);
+ if (!keep_running_) {
+ break;
+ }
+
+ if (didWork) {
+ continue;
+ }
+
+ // This will either sleep or process an event.
+ NS_ProcessNextEvent(thread, true);
+ }
+
+ mDelayedWorkTimer->Cancel();
+
+ keep_running_ = true;
+}
diff --git a/ipc/glue/MessagePump.h b/ipc/glue/MessagePump.h
new file mode 100644
index 0000000000..50b97efd79
--- /dev/null
+++ b/ipc/glue/MessagePump.h
@@ -0,0 +1,203 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_MESSAGEPUMP_H__
+#define __IPC_GLUE_MESSAGEPUMP_H__
+
+#include "base/message_pump_default.h"
+#if defined(XP_WIN)
+# include "base/message_pump_win.h"
+#elif defined(XP_DARWIN)
+# include "base/message_pump_mac.h"
+#endif
+
+#include "base/time.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Mutex.h"
+#include "nsCOMPtr.h"
+#include "nsIThreadInternal.h"
+
+class nsIEventTarget;
+class nsITimer;
+
+namespace mozilla {
+namespace ipc {
+
+class DoWorkRunnable;
+
+class MessagePump : public base::MessagePumpDefault {
+ friend class DoWorkRunnable;
+
+ public:
+ explicit MessagePump(nsISerialEventTarget* aEventTarget);
+
+ // From base::MessagePump.
+ virtual void Run(base::MessagePump::Delegate* aDelegate) override;
+
+ // From base::MessagePump.
+ virtual void ScheduleWork() override;
+
+ // From base::MessagePump.
+ virtual void ScheduleWorkForNestedLoop() override;
+
+ // From base::MessagePump.
+ virtual void ScheduleDelayedWork(
+ const base::TimeTicks& aDelayedWorkTime) override;
+
+ virtual nsISerialEventTarget* GetXPCOMThread() override;
+
+ protected:
+ virtual ~MessagePump();
+
+ private:
+ // Only called by DoWorkRunnable.
+ void DoDelayedWork(base::MessagePump::Delegate* aDelegate);
+
+ protected:
+ nsISerialEventTarget* mEventTarget;
+
+ // mDelayedWorkTimer and mEventTarget are set in Run() by this class or its
+ // subclasses.
+ nsCOMPtr<nsITimer> mDelayedWorkTimer;
+
+ private:
+ // Only accessed by this class.
+ RefPtr<DoWorkRunnable> mDoWorkEvent;
+};
+
+class MessagePumpForChildProcess final : public MessagePump {
+ public:
+ MessagePumpForChildProcess() : MessagePump(nullptr), mFirstRun(true) {}
+
+ virtual void Run(base::MessagePump::Delegate* aDelegate) override;
+
+ private:
+ ~MessagePumpForChildProcess() = default;
+
+ bool mFirstRun;
+};
+
+class MessagePumpForNonMainThreads final : public MessagePump {
+ public:
+ explicit MessagePumpForNonMainThreads(nsISerialEventTarget* aEventTarget)
+ : MessagePump(aEventTarget) {}
+
+ virtual void Run(base::MessagePump::Delegate* aDelegate) override;
+
+ private:
+ ~MessagePumpForNonMainThreads() = default;
+};
+
+#if defined(XP_WIN)
+// Extends the TYPE_UI message pump to process xpcom events.
+class MessagePumpForNonMainUIThreads final : public base::MessagePumpForUI,
+ public nsIThreadObserver {
+ public:
+ NS_DECL_ISUPPORTS_INHERITED
+ NS_DECL_NSITHREADOBSERVER
+
+ public:
+ explicit MessagePumpForNonMainUIThreads(nsISerialEventTarget* aEventTarget)
+ : mInWait(false), mWaitLock("mInWait") {}
+
+ // The main run loop for this thread.
+ virtual void DoRunLoop() override;
+
+ virtual nsISerialEventTarget* GetXPCOMThread() override {
+ return nullptr; // not sure what to do with this one
+ }
+
+ protected:
+ void SetInWait() {
+ MutexAutoLock lock(mWaitLock);
+ mInWait = true;
+ }
+
+ void ClearInWait() {
+ MutexAutoLock lock(mWaitLock);
+ mInWait = false;
+ }
+
+ bool GetInWait() {
+ MutexAutoLock lock(mWaitLock);
+ return mInWait;
+ }
+
+ private:
+ ~MessagePumpForNonMainUIThreads() {}
+
+ bool mInWait MOZ_GUARDED_BY(mWaitLock);
+ mozilla::Mutex mWaitLock;
+};
+#elif defined(XP_DARWIN)
+// Extends the CFRunLoopBase message pump to process xpcom events. Based on
+// MessagePumpNSRunLoop.
+class MessagePumpForNonMainUIThreads final
+ : public base::MessagePumpCFRunLoopBase,
+ public nsIThreadObserver {
+ public:
+ NS_DECL_ISUPPORTS_INHERITED
+ NS_DECL_NSITHREADOBSERVER
+
+ public:
+ explicit MessagePumpForNonMainUIThreads(nsISerialEventTarget* aEventTarget);
+
+ void DoRun(base::MessagePump::Delegate* aDelegate) override;
+ void Quit() override;
+
+ nsISerialEventTarget* GetXPCOMThread() override { return mEventTarget; }
+
+ private:
+ ~MessagePumpForNonMainUIThreads();
+
+ nsISerialEventTarget* mEventTarget;
+
+ // A source that doesn't do anything but provide something signalable
+ // attached to the run loop. This source will be signalled when Quit
+ // is called, to cause the loop to wake up so that it can stop.
+ CFRunLoopSourceRef quit_source_;
+
+ // False after Quit is called.
+ bool keep_running_;
+
+ DISALLOW_COPY_AND_ASSIGN(MessagePumpForNonMainUIThreads);
+};
+#endif // defined(XP_DARWIN)
+
+#if defined(MOZ_WIDGET_ANDROID)
+/*`
+ * The MessagePumpForAndroidUI exists to enable IPDL in the Android UI thread.
+ * The Android UI thread event loop is controlled by Android. This prevents
+ * running an existing MessagePump implementation in the Android UI thread. In
+ * order to enable IPDL on the Android UI thread it is necessary to have a
+ * non-looping MessagePump. This class enables forwarding of nsIRunnables from
+ * MessageLoop::PostTask_Helper to the registered nsIEventTarget with out the
+ * need to control the event loop. The only member function that should be
+ * invoked is GetXPCOMThread. All other member functions will invoke MOZ_CRASH
+ */
+class MessagePumpForAndroidUI : public base::MessagePump {
+ public:
+ explicit MessagePumpForAndroidUI(nsISerialEventTarget* aEventTarget)
+ : mEventTarget(aEventTarget) {}
+
+ virtual void Run(Delegate* delegate);
+ virtual void Quit();
+ virtual void ScheduleWork();
+ virtual void ScheduleDelayedWork(const base::TimeTicks& delayed_work_time);
+ virtual nsISerialEventTarget* GetXPCOMThread() { return mEventTarget; }
+
+ private:
+ ~MessagePumpForAndroidUI() {}
+ MessagePumpForAndroidUI() {}
+
+ nsISerialEventTarget* mEventTarget;
+};
+#endif // defined(MOZ_WIDGET_ANDROID)
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* __IPC_GLUE_MESSAGEPUMP_H__ */
diff --git a/ipc/glue/MessagePump_android.cpp b/ipc/glue/MessagePump_android.cpp
new file mode 100644
index 0000000000..f237d4d7ed
--- /dev/null
+++ b/ipc/glue/MessagePump_android.cpp
@@ -0,0 +1,26 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "MessagePump.h"
+
+namespace mozilla::ipc {
+void MessagePumpForAndroidUI::Run(Delegate* delegate) {
+ MOZ_CRASH("MessagePumpForAndroidUI should never be Run.");
+}
+
+void MessagePumpForAndroidUI::Quit() {
+ MOZ_CRASH("MessagePumpForAndroidUI should never be Quit.");
+}
+
+void MessagePumpForAndroidUI::ScheduleWork() {
+ MOZ_CRASH("MessagePumpForAndroidUI should never ScheduleWork");
+}
+
+void MessagePumpForAndroidUI::ScheduleDelayedWork(
+ const base::TimeTicks& delayed_work_time) {
+ MOZ_CRASH("MessagePumpForAndroidUI should never ScheduleDelayedWork");
+}
+} // namespace mozilla::ipc
diff --git a/ipc/glue/MessagePump_mac.mm b/ipc/glue/MessagePump_mac.mm
new file mode 100644
index 0000000000..69b8f1f87e
--- /dev/null
+++ b/ipc/glue/MessagePump_mac.mm
@@ -0,0 +1,100 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "MessagePump.h"
+
+#include <Foundation/Foundation.h>
+
+#include "base/scoped_nsautorelease_pool.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "nsISupportsImpl.h"
+
+using namespace mozilla::ipc;
+
+static void NoOp(void* info) {}
+
+NS_IMPL_ADDREF_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
+NS_IMPL_RELEASE_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
+NS_IMPL_QUERY_INTERFACE(MessagePumpForNonMainUIThreads, nsIThreadObserver)
+
+MessagePumpForNonMainUIThreads::MessagePumpForNonMainUIThreads(
+ nsISerialEventTarget* aEventTarget)
+ : mEventTarget(aEventTarget), keep_running_(true) {
+ MOZ_ASSERT(mEventTarget);
+ CFRunLoopSourceContext source_context = CFRunLoopSourceContext();
+ source_context.perform = NoOp;
+ quit_source_ = CFRunLoopSourceCreate(nullptr, // allocator
+ 0, // priority
+ &source_context);
+ CFRunLoopAddSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
+}
+
+MessagePumpForNonMainUIThreads::~MessagePumpForNonMainUIThreads() {
+ CFRunLoopRemoveSource(run_loop(), quit_source_, kCFRunLoopCommonModes);
+ CFRelease(quit_source_);
+}
+
+void MessagePumpForNonMainUIThreads::DoRun(
+ base::MessagePump::Delegate* aDelegate) {
+ // If this is a chromium thread and no nsThread is associated with it, this
+ // call will create a new nsThread.
+ nsIThread* thread = NS_GetCurrentThread();
+ MOZ_ASSERT(thread);
+
+ // Set the main thread observer so we can wake up when xpcom events need to
+ // get processed.
+ nsCOMPtr<nsIThreadInternal> ti(do_QueryInterface(thread));
+ MOZ_ASSERT(ti);
+ ti->SetObserver(this);
+
+ base::ScopedNSAutoreleasePool autoReleasePool;
+
+ while (keep_running_) {
+ // Drain the xpcom event loop first.
+ if (NS_ProcessNextEvent(nullptr, false)) {
+ continue;
+ }
+
+ autoReleasePool.Recycle();
+
+ if (!keep_running_) {
+ break;
+ }
+
+ // Now process the CFRunLoop. It exits after running once.
+ // NSRunLoop manages autorelease pools itself.
+ [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
+ beforeDate:[NSDate distantFuture]];
+ }
+
+ ti->SetObserver(nullptr);
+ keep_running_ = true;
+}
+
+void MessagePumpForNonMainUIThreads::Quit() {
+ keep_running_ = false;
+ CFRunLoopSourceSignal(quit_source_);
+ CFRunLoopWakeUp(run_loop());
+}
+
+NS_IMETHODIMP MessagePumpForNonMainUIThreads::OnDispatchedEvent() {
+ // ScheduleWork will signal an input source to the run loop, making it exit so
+ // it can process the xpcom event.
+ ScheduleWork();
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal* thread,
+ bool mayWait) {
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessagePumpForNonMainUIThreads::AfterProcessNextEvent(nsIThreadInternal* thread,
+ bool eventWasProcessed) {
+ return NS_OK;
+}
diff --git a/ipc/glue/MessagePump_windows.cpp b/ipc/glue/MessagePump_windows.cpp
new file mode 100644
index 0000000000..c0109f3f43
--- /dev/null
+++ b/ipc/glue/MessagePump_windows.cpp
@@ -0,0 +1,96 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "MessagePump.h"
+
+using namespace mozilla::ipc;
+
+NS_IMPL_ADDREF_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
+NS_IMPL_RELEASE_INHERITED(MessagePumpForNonMainUIThreads, MessagePump)
+NS_IMPL_QUERY_INTERFACE(MessagePumpForNonMainUIThreads, nsIThreadObserver)
+
+#define CHECK_QUIT_STATE \
+ { \
+ if (state_->should_quit) { \
+ break; \
+ } \
+ }
+
+void MessagePumpForNonMainUIThreads::DoRunLoop() {
+ MOZ_RELEASE_ASSERT(!NS_IsMainThread(),
+ "Use mozilla::ipc::MessagePump instead!");
+
+ // If this is a chromium thread and no nsThread is associated
+ // with it, this call will create a new nsThread.
+ nsIThread* thread = NS_GetCurrentThread();
+ MOZ_ASSERT(thread);
+
+ // Set the main thread observer so we can wake up when
+ // xpcom events need to get processed.
+ nsCOMPtr<nsIThreadInternal> ti(do_QueryInterface(thread));
+ MOZ_ASSERT(ti);
+ ti->SetObserver(this);
+
+ for (;;) {
+ bool didWork = NS_ProcessNextEvent(thread, false);
+
+ didWork |= ProcessNextWindowsMessage();
+ CHECK_QUIT_STATE
+
+ didWork |= state_->delegate->DoWork();
+ CHECK_QUIT_STATE
+
+ didWork |= state_->delegate->DoDelayedWork(&delayed_work_time_);
+ if (didWork && delayed_work_time_.is_null()) {
+ KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
+ }
+ CHECK_QUIT_STATE
+
+ if (didWork) {
+ continue;
+ }
+
+ DebugOnly<bool> didIdleWork = state_->delegate->DoIdleWork();
+ MOZ_ASSERT(!didIdleWork);
+ CHECK_QUIT_STATE
+
+ SetInWait();
+ bool hasWork = NS_HasPendingEvents(thread);
+ if (didWork || hasWork) {
+ ClearInWait();
+ continue;
+ }
+ WaitForWork(); // Calls MsgWaitForMultipleObjectsEx(QS_ALLINPUT)
+ ClearInWait();
+ }
+
+ ClearInWait();
+
+ ti->SetObserver(nullptr);
+}
+
+NS_IMETHODIMP
+MessagePumpForNonMainUIThreads::OnDispatchedEvent() {
+ // If our thread is sleeping in DoRunLoop's call to WaitForWork() and an
+ // event posts to the nsIThread event queue - break our thread out of
+ // chromium's WaitForWork.
+ if (GetInWait()) {
+ ScheduleWork();
+ }
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessagePumpForNonMainUIThreads::OnProcessNextEvent(nsIThreadInternal* thread,
+ bool mayWait) {
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+MessagePumpForNonMainUIThreads::AfterProcessNextEvent(nsIThreadInternal* thread,
+ bool eventWasProcessed) {
+ return NS_OK;
+}
diff --git a/ipc/glue/MiniTransceiver.cpp b/ipc/glue/MiniTransceiver.cpp
new file mode 100644
index 0000000000..efb12d2fe2
--- /dev/null
+++ b/ipc/glue/MiniTransceiver.cpp
@@ -0,0 +1,255 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set ts=8 sts=4 et sw=4 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "mozilla/ipc/MiniTransceiver.h"
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "base/eintr_wrapper.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/Sprintf.h"
+#include "mozilla/ScopeExit.h"
+#include "nsDebug.h"
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <string.h>
+#include <errno.h>
+
+namespace mozilla::ipc {
+
+static const size_t kMaxIOVecSize = 64;
+static const size_t kMaxDataSize = 8 * 1024;
+static const size_t kMaxNumFds = 16;
+
+MiniTransceiver::MiniTransceiver(int aFd, DataBufferClear aDataBufClear)
+ : mFd(aFd),
+#ifdef DEBUG
+ mState(STATE_NONE),
+#endif
+ mDataBufClear(aDataBufClear) {
+}
+
+namespace {
+
+/**
+ * Initialize the IO vector for sending data and the control buffer for sending
+ * FDs.
+ */
+static void InitMsgHdr(msghdr* aHdr, int aIOVSize, size_t aMaxNumFds) {
+ aHdr->msg_name = nullptr;
+ aHdr->msg_namelen = 0;
+ aHdr->msg_flags = 0;
+
+ // Prepare the IO vector to receive the content of message.
+ auto* iov = new iovec[aIOVSize];
+ aHdr->msg_iov = iov;
+ aHdr->msg_iovlen = aIOVSize;
+
+ // Prepare the control buffer to receive file descriptors.
+ const size_t cbufSize = CMSG_SPACE(sizeof(int) * aMaxNumFds);
+ auto* cbuf = new char[cbufSize];
+ // Avoid valgrind complaints about uninitialized padding (but also,
+ // fill with a value that isn't a valid fd, just in case).
+ memset(cbuf, 255, cbufSize);
+ aHdr->msg_control = cbuf;
+ aHdr->msg_controllen = cbufSize;
+}
+
+/**
+ * Delete resources allocated by InitMsgHdr().
+ */
+static void DeinitMsgHdr(msghdr* aHdr) {
+ delete aHdr->msg_iov;
+ delete static_cast<char*>(aHdr->msg_control);
+}
+
+} // namespace
+
+void MiniTransceiver::PrepareFDs(msghdr* aHdr, IPC::Message& aMsg) {
+ // Set control buffer to send file descriptors of the Message.
+ size_t num_fds = aMsg.attached_handles_.Length();
+
+ cmsghdr* cmsg = CMSG_FIRSTHDR(aHdr);
+ cmsg->cmsg_level = SOL_SOCKET;
+ cmsg->cmsg_type = SCM_RIGHTS;
+ cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
+ for (size_t i = 0; i < num_fds; ++i) {
+ reinterpret_cast<int*>(CMSG_DATA(cmsg))[i] =
+ aMsg.attached_handles_[i].get();
+ }
+
+ // This number will be sent in the header of the message. So, we
+ // can check it at the other side.
+ aMsg.header()->num_handles = num_fds;
+}
+
+size_t MiniTransceiver::PrepareBuffers(msghdr* aHdr, IPC::Message& aMsg) {
+ // Set iovec to send for all buffers of the Message.
+ iovec* iov = aHdr->msg_iov;
+ size_t iovlen = 0;
+ size_t bytes_to_send = 0;
+ for (Pickle::BufferList::IterImpl iter(aMsg.Buffers()); !iter.Done();
+ iter.Advance(aMsg.Buffers(), iter.RemainingInSegment())) {
+ char* data = iter.Data();
+ size_t size = iter.RemainingInSegment();
+ iov[iovlen].iov_base = data;
+ iov[iovlen].iov_len = size;
+ iovlen++;
+ MOZ_ASSERT(iovlen <= kMaxIOVecSize);
+ bytes_to_send += size;
+ }
+ MOZ_ASSERT(bytes_to_send <= kMaxDataSize);
+ aHdr->msg_iovlen = iovlen;
+
+ return bytes_to_send;
+}
+
+bool MiniTransceiver::Send(IPC::Message& aMsg) {
+#ifdef DEBUG
+ if (mState == STATE_SENDING) {
+ MOZ_CRASH(
+ "STATE_SENDING: It violates of request-response and no concurrent "
+ "rules");
+ }
+ mState = STATE_SENDING;
+#endif
+
+ auto clean_fdset = MakeScopeExit([&] { aMsg.attached_handles_.Clear(); });
+
+ size_t num_fds = aMsg.attached_handles_.Length();
+ msghdr hdr{};
+ InitMsgHdr(&hdr, kMaxIOVecSize, num_fds);
+
+ UniquePtr<msghdr, decltype(&DeinitMsgHdr)> uniq(&hdr, &DeinitMsgHdr);
+
+ PrepareFDs(&hdr, aMsg);
+ DebugOnly<size_t> bytes_to_send = PrepareBuffers(&hdr, aMsg);
+
+ ssize_t bytes_written = HANDLE_EINTR(sendmsg(mFd, &hdr, 0));
+
+ if (bytes_written < 0) {
+ char error[128];
+ SprintfLiteral(error, "sendmsg: %s", strerror(errno));
+ NS_WARNING(error);
+ return false;
+ }
+ MOZ_ASSERT(bytes_written == (ssize_t)bytes_to_send,
+ "The message is too big?!");
+
+ return true;
+}
+
+unsigned MiniTransceiver::RecvFDs(msghdr* aHdr, int* aAllFds,
+ unsigned aMaxFds) {
+ if (aHdr->msg_controllen == 0) {
+ return 0;
+ }
+
+ unsigned num_all_fds = 0;
+ for (cmsghdr* cmsg = CMSG_FIRSTHDR(aHdr); cmsg;
+ cmsg = CMSG_NXTHDR(aHdr, cmsg)) {
+ MOZ_ASSERT(cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS,
+ "Accept only SCM_RIGHTS to receive file descriptors");
+
+ unsigned payload_sz = cmsg->cmsg_len - CMSG_LEN(0);
+ MOZ_ASSERT(payload_sz % sizeof(int) == 0);
+
+ // Add fds to |aAllFds|
+ unsigned num_part_fds = payload_sz / sizeof(int);
+ int* part_fds = reinterpret_cast<int*>(CMSG_DATA(cmsg));
+ MOZ_ASSERT(num_all_fds + num_part_fds <= aMaxFds);
+
+ memcpy(aAllFds + num_all_fds, part_fds, num_part_fds * sizeof(int));
+ num_all_fds += num_part_fds;
+ }
+ return num_all_fds;
+}
+
+bool MiniTransceiver::RecvData(char* aDataBuf, size_t aBufSize,
+ uint32_t* aMsgSize, int* aFdsBuf,
+ unsigned aMaxFds, unsigned* aNumFds) {
+ msghdr hdr;
+ InitMsgHdr(&hdr, 1, aMaxFds);
+
+ UniquePtr<msghdr, decltype(&DeinitMsgHdr)> uniq(&hdr, &DeinitMsgHdr);
+
+ // The buffer to collect all fds received from the socket.
+ int* all_fds = aFdsBuf;
+ unsigned num_all_fds = 0;
+
+ size_t total_readed = 0;
+ uint32_t msgsz = 0;
+ while (msgsz == 0 || total_readed < msgsz) {
+ // Set IO vector with the begin of the unused buffer.
+ hdr.msg_iov->iov_base = aDataBuf + total_readed;
+ hdr.msg_iov->iov_len = (msgsz == 0 ? aBufSize : msgsz) - total_readed;
+
+ // Read the socket
+ ssize_t bytes_readed = HANDLE_EINTR(recvmsg(mFd, &hdr, 0));
+ if (bytes_readed <= 0) {
+ // Closed or error!
+ return false;
+ }
+ total_readed += bytes_readed;
+ MOZ_ASSERT(total_readed <= aBufSize);
+
+ if (msgsz == 0) {
+ // Parse the size of the message.
+ // Get 0 if data in the buffer is no enough to get message size.
+ msgsz = IPC::Message::MessageSize(aDataBuf, aDataBuf + total_readed);
+ }
+
+ num_all_fds += RecvFDs(&hdr, all_fds + num_all_fds, aMaxFds - num_all_fds);
+ }
+
+ *aMsgSize = msgsz;
+ *aNumFds = num_all_fds;
+ return true;
+}
+
+bool MiniTransceiver::Recv(UniquePtr<IPC::Message>& aMsg) {
+#ifdef DEBUG
+ if (mState == STATE_RECEIVING) {
+ MOZ_CRASH(
+ "STATE_RECEIVING: It violates of request-response and no concurrent "
+ "rules");
+ }
+ mState = STATE_RECEIVING;
+#endif
+
+ UniquePtr<char[]> databuf = MakeUnique<char[]>(kMaxDataSize);
+ uint32_t msgsz = 0;
+ int all_fds[kMaxNumFds];
+ unsigned num_all_fds = 0;
+
+ if (!RecvData(databuf.get(), kMaxDataSize, &msgsz, all_fds, kMaxDataSize,
+ &num_all_fds)) {
+ return false;
+ }
+
+ // Create Message from databuf & all_fds.
+ UniquePtr<IPC::Message> msg = MakeUnique<IPC::Message>(databuf.get(), msgsz);
+ nsTArray<UniqueFileHandle> handles(num_all_fds);
+ for (unsigned i = 0; i < num_all_fds; ++i) {
+ handles.AppendElement(UniqueFileHandle(all_fds[i]));
+ }
+ msg->SetAttachedFileHandles(std::move(handles));
+
+ if (mDataBufClear == DataBufferClear::AfterReceiving) {
+ // Avoid content processes from reading the content of
+ // messages.
+ memset(databuf.get(), 0, msgsz);
+ }
+
+ MOZ_ASSERT(msg->header()->num_handles == msg->attached_handles_.Length(),
+ "The number of file descriptors in the header is different from"
+ " the number actually received");
+
+ aMsg = std::move(msg);
+ return true;
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/MiniTransceiver.h b/ipc/glue/MiniTransceiver.h
new file mode 100644
index 0000000000..9568dc2685
--- /dev/null
+++ b/ipc/glue/MiniTransceiver.h
@@ -0,0 +1,118 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* vim: set ts=8 sts=4 et sw=4 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef __MINITRANSCEIVER_H_
+#define __MINITRANSCEIVER_H_
+
+#include "chrome/common/ipc_message.h"
+#include "mozilla/Assertions.h"
+
+struct msghdr;
+
+namespace mozilla {
+namespace ipc {
+
+enum class DataBufferClear { None, AfterReceiving };
+
+/**
+ * This simple implementation handles the transmissions of IPC
+ * messages.
+ *
+ * It works according to a strict request-response paradigm, no
+ * concurrent messaging is allowed. Sending a message from A to B must
+ * be followed by another one from B to A. Because of this we don't
+ * need to handle data crossing the boundaries of a
+ * message. Transmission is done via blocking I/O to avoid the
+ * complexity of asynchronous I/O.
+ */
+class MiniTransceiver {
+ public:
+ /**
+ * \param aFd should be a blocking, no O_NONBLOCK, fd.
+ * \param aClearDataBuf is true to clear data buffers after
+ * receiving a message.
+ */
+ explicit MiniTransceiver(
+ int aFd, DataBufferClear aDataBufClear = DataBufferClear::None);
+
+ bool Send(IPC::Message& aMsg);
+ inline bool SendInfallible(IPC::Message& aMsg, const char* aCrashMessage) {
+ bool Ok = Send(aMsg);
+ if (!Ok) {
+ MOZ_CRASH_UNSAFE(aCrashMessage);
+ }
+ return Ok;
+ }
+
+ /**
+ * \param aMsg will hold the content of the received message.
+ * \return false if the fd is closed or with an error.
+ */
+ bool Recv(UniquePtr<IPC::Message>& aMsg);
+ inline bool RecvInfallible(UniquePtr<IPC::Message>& aMsg,
+ const char* aCrashMessage) {
+ bool Ok = Recv(aMsg);
+ if (!Ok) {
+ MOZ_CRASH_UNSAFE(aCrashMessage);
+ }
+ return Ok;
+ }
+
+ int GetFD() { return mFd; }
+
+ private:
+ /**
+ * Set control buffer to make file descriptors ready to be sent
+ * through a socket.
+ */
+ void PrepareFDs(msghdr* aHdr, IPC::Message& aMsg);
+ /**
+ * Collect buffers of the message and make them ready to be sent.
+ *
+ * \param aHdr is the structure going to be passed to sendmsg().
+ * \param aMsg is the Message to send.
+ */
+ size_t PrepareBuffers(msghdr* aHdr, IPC::Message& aMsg);
+ /**
+ * Collect file descriptors received.
+ *
+ * \param aAllFds is where to store file descriptors.
+ * \param aMaxFds is how many file descriptors can be stored in aAllFds.
+ * \return the number of received file descriptors.
+ */
+ unsigned RecvFDs(msghdr* aHdr, int* aAllFds, unsigned aMaxFds);
+ /**
+ * Received data from the socket.
+ *
+ * \param aDataBuf is where to store the data from the socket.
+ * \param aBufSize is the size of the buffer.
+ * \param aMsgSize returns how many bytes were readed from the socket.
+ * \param aFdsBuf is the buffer to return file desriptors received.
+ * \param aMaxFds is the number of file descriptors that can be held.
+ * \param aNumFds returns the number of file descriptors received.
+ * \return true if sucess, or false for error.
+ */
+ bool RecvData(char* aDataBuf, size_t aBufSize, uint32_t* aMsgSize,
+ int* aFdsBuf, unsigned aMaxFds, unsigned* aNumFds);
+
+ int mFd; // The file descriptor of the socket for IPC.
+
+#ifdef DEBUG
+ enum State {
+ STATE_NONE,
+ STATE_SENDING,
+ STATE_RECEIVING,
+ };
+ State mState;
+#endif
+
+ // Clear all received data in temp buffers to avoid data leaking.
+ DataBufferClear mDataBufClear;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // __MINITRANSCEIVER_H_
diff --git a/ipc/glue/Neutering.h b/ipc/glue/Neutering.h
new file mode 100644
index 0000000000..44cbe042ae
--- /dev/null
+++ b/ipc/glue/Neutering.h
@@ -0,0 +1,70 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_Neutering_h
+#define mozilla_ipc_Neutering_h
+
+/**
+ * This header declares RAII wrappers for Window neutering. See
+ * WindowsMessageLoop.cpp for more details.
+ */
+
+namespace mozilla {
+namespace ipc {
+
+/**
+ * This class is a RAII wrapper around Window neutering. As long as a
+ * NeuteredWindowRegion object is instantiated, Win32 windows belonging to the
+ * current thread will be neutered. It is safe to nest multiple instances of
+ * this class.
+ */
+class MOZ_RAII NeuteredWindowRegion {
+ public:
+ explicit NeuteredWindowRegion(bool aDoNeuter);
+ ~NeuteredWindowRegion();
+
+ /**
+ * This function clears any backlog of nonqueued messages that are pending for
+ * the current thread.
+ */
+ void PumpOnce();
+
+ private:
+ bool mNeuteredByThis;
+};
+
+/**
+ * This class is analagous to MutexAutoUnlock for Mutex; it is an RAII class
+ * that is to be instantiated within a NeuteredWindowRegion, thus temporarily
+ * disabling neutering for the remainder of its enclosing block.
+ * @see NeuteredWindowRegion
+ */
+class MOZ_RAII DeneuteredWindowRegion {
+ public:
+ explicit DeneuteredWindowRegion();
+ ~DeneuteredWindowRegion();
+
+ private:
+ bool mReneuter;
+};
+
+class MOZ_RAII SuppressedNeuteringRegion {
+ public:
+ explicit SuppressedNeuteringRegion();
+ ~SuppressedNeuteringRegion();
+
+ static inline bool IsNeuteringSuppressed() { return sSuppressNeutering; }
+
+ private:
+ bool mReenable;
+
+ static bool sSuppressNeutering;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_Neutering_h
diff --git a/ipc/glue/NodeChannel.cpp b/ipc/glue/NodeChannel.cpp
new file mode 100644
index 0000000000..70e67bc473
--- /dev/null
+++ b/ipc/glue/NodeChannel.cpp
@@ -0,0 +1,305 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/NodeChannel.h"
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mojo/core/ports/name.h"
+#include "mozilla/ipc/BrowserProcessSubThread.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "nsThreadUtils.h"
+#include "nsXULAppAPI.h"
+
+#ifdef FUZZING_SNAPSHOT
+# include "mozilla/fuzzing/IPCFuzzController.h"
+#endif
+
+template <>
+struct IPC::ParamTraits<mozilla::ipc::NodeChannel::Introduction> {
+ using paramType = mozilla::ipc::NodeChannel::Introduction;
+ static void Write(MessageWriter* aWriter, paramType&& aParam) {
+ WriteParam(aWriter, aParam.mName);
+ WriteParam(aWriter, std::move(aParam.mHandle));
+ WriteParam(aWriter, aParam.mMode);
+ WriteParam(aWriter, aParam.mMyPid);
+ WriteParam(aWriter, aParam.mOtherPid);
+ }
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadParam(aReader, &aResult->mName) &&
+ ReadParam(aReader, &aResult->mHandle) &&
+ ReadParam(aReader, &aResult->mMode) &&
+ ReadParam(aReader, &aResult->mMyPid) &&
+ ReadParam(aReader, &aResult->mOtherPid);
+ }
+};
+
+namespace mozilla::ipc {
+
+NodeChannel::NodeChannel(const NodeName& aName,
+ UniquePtr<IPC::Channel> aChannel, Listener* aListener,
+ base::ProcessId aPid,
+ GeckoChildProcessHost* aChildProcessHost)
+ : mListener(aListener),
+ mName(aName),
+ mOtherPid(aPid),
+ mChannel(std::move(aChannel)),
+ mChildProcessHost(aChildProcessHost) {}
+
+NodeChannel::~NodeChannel() { Close(); }
+
+// Called when the NodeChannel's refcount drops to `0`.
+void NodeChannel::Destroy() {
+ // Dispatch the `delete` operation to the IO thread. We need to do this even
+ // if we're already on the IO thread, as we could be in an `IPC::Channel`
+ // callback which unfortunately will not hold a strong reference to keep
+ // `this` alive.
+ MessageLoop* ioThread = XRE_GetIOMessageLoop();
+ if (ioThread->IsAcceptingTasks()) {
+ ioThread->PostTask(NewNonOwningRunnableMethod("NodeChannel::Destroy", this,
+ &NodeChannel::FinalDestroy));
+ return;
+ }
+
+ // If the IOThread has already been destroyed, we must be shutting it down and
+ // need to synchronously invoke `FinalDestroy` to ensure we're cleaned up
+ // before the thread dies. This is safe as we can't be in a non-owning
+ // IPC::Channel callback at this point.
+ if (MessageLoop::current() == ioThread) {
+ FinalDestroy();
+ return;
+ }
+
+ MOZ_ASSERT_UNREACHABLE("Leaking NodeChannel after IOThread destroyed!");
+}
+
+void NodeChannel::FinalDestroy() {
+ AssertIOThread();
+ delete this;
+}
+
+void NodeChannel::Start() {
+ AssertIOThread();
+
+ if (!mChannel->Connect(this)) {
+ OnChannelError();
+ }
+}
+
+void NodeChannel::Close() {
+ AssertIOThread();
+
+ if (mState.exchange(State::Closed) != State::Closed) {
+ mChannel->Close();
+ }
+}
+
+void NodeChannel::SetOtherPid(base::ProcessId aNewPid) {
+ AssertIOThread();
+ MOZ_ASSERT(aNewPid != base::kInvalidProcessId);
+
+ base::ProcessId previousPid = base::kInvalidProcessId;
+ if (!mOtherPid.compare_exchange_strong(previousPid, aNewPid)) {
+ // The PID was already set before this call, double-check that it's correct.
+ MOZ_RELEASE_ASSERT(previousPid == aNewPid,
+ "Different sources disagree on the correct pid?");
+ }
+
+ mChannel->SetOtherPid(aNewPid);
+}
+
+#ifdef XP_MACOSX
+void NodeChannel::SetMachTaskPort(task_t aTask) {
+ AssertIOThread();
+
+ if (mState != State::Closed) {
+ mChannel->SetOtherMachTask(aTask);
+ }
+}
+#endif
+
+void NodeChannel::SendEventMessage(UniquePtr<IPC::Message> aMessage) {
+ // Make sure we're not sending a message with one of our special internal
+ // types ,as those should only be sent using the corresponding methods on
+ // NodeChannel.
+ MOZ_DIAGNOSTIC_ASSERT(aMessage->type() != BROADCAST_MESSAGE_TYPE &&
+ aMessage->type() != INTRODUCE_MESSAGE_TYPE &&
+ aMessage->type() != REQUEST_INTRODUCTION_MESSAGE_TYPE &&
+ aMessage->type() != ACCEPT_INVITE_MESSAGE_TYPE);
+ SendMessage(std::move(aMessage));
+}
+
+void NodeChannel::RequestIntroduction(const NodeName& aPeerName) {
+ MOZ_ASSERT(aPeerName != mojo::core::ports::kInvalidNodeName);
+ auto message = MakeUnique<IPC::Message>(MSG_ROUTING_CONTROL,
+ REQUEST_INTRODUCTION_MESSAGE_TYPE);
+ IPC::MessageWriter writer(*message);
+ WriteParam(&writer, aPeerName);
+ SendMessage(std::move(message));
+}
+
+void NodeChannel::Introduce(Introduction aIntroduction) {
+ auto message =
+ MakeUnique<IPC::Message>(MSG_ROUTING_CONTROL, INTRODUCE_MESSAGE_TYPE);
+ IPC::MessageWriter writer(*message);
+ WriteParam(&writer, std::move(aIntroduction));
+ SendMessage(std::move(message));
+}
+
+void NodeChannel::Broadcast(UniquePtr<IPC::Message> aMessage) {
+ MOZ_DIAGNOSTIC_ASSERT(aMessage->type() == BROADCAST_MESSAGE_TYPE,
+ "Can only broadcast messages with the correct type");
+ SendMessage(std::move(aMessage));
+}
+
+void NodeChannel::AcceptInvite(const NodeName& aRealName,
+ const PortName& aInitialPort) {
+ MOZ_ASSERT(aRealName != mojo::core::ports::kInvalidNodeName);
+ MOZ_ASSERT(aInitialPort != mojo::core::ports::kInvalidPortName);
+ auto message =
+ MakeUnique<IPC::Message>(MSG_ROUTING_CONTROL, ACCEPT_INVITE_MESSAGE_TYPE);
+ IPC::MessageWriter writer(*message);
+ WriteParam(&writer, aRealName);
+ WriteParam(&writer, aInitialPort);
+ SendMessage(std::move(message));
+}
+
+void NodeChannel::SendMessage(UniquePtr<IPC::Message> aMessage) {
+ if (aMessage->size() > IPC::Channel::kMaximumMessageSize) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCMessageName,
+ nsDependentCString(aMessage->name()));
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCMessageSize,
+ static_cast<unsigned int>(aMessage->size()));
+ MOZ_CRASH("IPC message size is too large");
+ }
+ aMessage->AssertAsLargeAsHeader();
+
+#ifdef FUZZING_SNAPSHOT
+ if (mBlockSendRecv) {
+ return;
+ }
+#endif
+
+ if (mState != State::Active) {
+ NS_WARNING("Dropping message as channel has been closed");
+ return;
+ }
+
+ // NOTE: As this is not guaranteed to be running on the I/O thread, the
+ // channel may have become closed since we checked above. IPC::Channel will
+ // handle that and return `false` here, so we can re-check `mState`.
+ if (!mChannel->Send(std::move(aMessage))) {
+ NS_WARNING("Call to Send() failed");
+
+ // If we're still active, update `mState` to `State::Closing`, and dispatch
+ // a runnable to actually close our channel.
+ State expected = State::Active;
+ if (mState.compare_exchange_strong(expected, State::Closing)) {
+ XRE_GetIOMessageLoop()->PostTask(
+ NewRunnableMethod("NodeChannel::CloseForSendError", this,
+ &NodeChannel::OnChannelError));
+ }
+ }
+}
+
+void NodeChannel::OnMessageReceived(UniquePtr<IPC::Message> aMessage) {
+ AssertIOThread();
+
+#ifdef FUZZING_SNAPSHOT
+ if (mBlockSendRecv && !aMessage->IsFuzzMsg()) {
+ return;
+ }
+#endif
+
+ IPC::MessageReader reader(*aMessage);
+ switch (aMessage->type()) {
+ case REQUEST_INTRODUCTION_MESSAGE_TYPE: {
+ NodeName name;
+ if (IPC::ReadParam(&reader, &name)) {
+ mListener->OnRequestIntroduction(mName, name);
+ return;
+ }
+ break;
+ }
+ case INTRODUCE_MESSAGE_TYPE: {
+ Introduction introduction;
+ if (IPC::ReadParam(&reader, &introduction)) {
+ mListener->OnIntroduce(mName, std::move(introduction));
+ return;
+ }
+ break;
+ }
+ case BROADCAST_MESSAGE_TYPE: {
+ mListener->OnBroadcast(mName, std::move(aMessage));
+ return;
+ }
+ case ACCEPT_INVITE_MESSAGE_TYPE: {
+ NodeName realName;
+ PortName initialPort;
+ if (IPC::ReadParam(&reader, &realName) &&
+ IPC::ReadParam(&reader, &initialPort)) {
+ mListener->OnAcceptInvite(mName, realName, initialPort);
+ return;
+ }
+ break;
+ }
+ // Assume all unrecognized types are intended as user event messages, and
+ // deliver them to our listener as such. This allows us to use the same type
+ // field for both internal messages and protocol messages.
+ //
+ // FIXME: Consider doing something cleaner in the future?
+ case EVENT_MESSAGE_TYPE:
+ default: {
+#ifdef FUZZING_SNAPSHOT
+ if (!fuzzing::IPCFuzzController::instance().ObserveIPCMessage(
+ this, *aMessage)) {
+ return;
+ }
+#endif
+
+ mListener->OnEventMessage(mName, std::move(aMessage));
+ return;
+ }
+ }
+
+ // If we got to this point without early returning the message was malformed
+ // in some way. Report an error.
+
+ NS_WARNING("NodeChannel received a malformed message");
+ OnChannelError();
+}
+
+void NodeChannel::OnChannelConnected(base::ProcessId aPeerPid) {
+ AssertIOThread();
+
+ SetOtherPid(aPeerPid);
+
+ // We may need to tell the GeckoChildProcessHost which we were created by that
+ // the channel has been connected to unblock completing the process launch.
+ if (mChildProcessHost) {
+ mChildProcessHost->OnChannelConnected(aPeerPid);
+ }
+}
+
+void NodeChannel::OnChannelError() {
+ AssertIOThread();
+
+ State prev = mState.exchange(State::Closed);
+ if (prev == State::Closed) {
+ return;
+ }
+
+ // Clean up the channel.
+ mChannel->Close();
+
+ // Tell our listener about the error.
+ mListener->OnChannelError(mName);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/NodeChannel.h b/ipc/glue/NodeChannel.h
new file mode 100644
index 0000000000..fb3d297348
--- /dev/null
+++ b/ipc/glue/NodeChannel.h
@@ -0,0 +1,178 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_NodeChannel_h
+#define mozilla_ipc_NodeChannel_h
+
+#include "mojo/core/ports/node.h"
+#include "mojo/core/ports/node_delegate.h"
+#include "base/process.h"
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_channel.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "nsISupports.h"
+#include "nsTHashMap.h"
+#include "mozilla/Queue.h"
+#include "mozilla/DataMutex.h"
+#include "mozilla/UniquePtr.h"
+
+#ifdef FUZZING_SNAPSHOT
+# include "mozilla/fuzzing/IPCFuzzController.h"
+#endif
+
+namespace mozilla::ipc {
+
+class GeckoChildProcessHost;
+class NodeController;
+
+// Represents a live connection between our Node and a remote process. This
+// object acts as an IPC::Channel listener and performs basic processing on
+// messages as they're passed between processes.
+
+class NodeChannel final : public IPC::Channel::Listener {
+ using NodeName = mojo::core::ports::NodeName;
+ using PortName = mojo::core::ports::PortName;
+
+#ifdef FUZZING_SNAPSHOT
+ // Required because IPCFuzzController calls OnMessageReceived.
+ friend class mozilla::fuzzing::IPCFuzzController;
+#endif
+
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(NodeChannel, Destroy())
+
+ struct Introduction {
+ NodeName mName;
+ IPC::Channel::ChannelHandle mHandle;
+ IPC::Channel::Mode mMode;
+ base::ProcessId mMyPid = base::kInvalidProcessId;
+ base::ProcessId mOtherPid = base::kInvalidProcessId;
+ };
+
+ class Listener {
+ public:
+ virtual ~Listener() = default;
+
+ NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
+
+ virtual void OnEventMessage(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) = 0;
+ virtual void OnBroadcast(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) = 0;
+ virtual void OnIntroduce(const NodeName& aFromNode,
+ Introduction aIntroduction) = 0;
+ virtual void OnRequestIntroduction(const NodeName& aFromNode,
+ const NodeName& aName) = 0;
+ virtual void OnAcceptInvite(const NodeName& aFromNode,
+ const NodeName& aRealName,
+ const PortName& aInitialPort) = 0;
+ virtual void OnChannelError(const NodeName& aFromNode) = 0;
+ };
+
+ NodeChannel(const NodeName& aName, UniquePtr<IPC::Channel> aChannel,
+ Listener* aListener,
+ base::ProcessId aPid = base::kInvalidProcessId,
+ GeckoChildProcessHost* aChildProcessHost = nullptr);
+
+ // Send the given message over this peer channel link. May be called from any
+ // thread.
+ void SendEventMessage(UniquePtr<IPC::Message> aMessage);
+
+ // Ask the broker process to broadcast this message to every node. May be
+ // called from any thread.
+ void Broadcast(UniquePtr<IPC::Message> aMessage);
+
+ // Ask the broker process to introduce this node to another node with the
+ // given name. May be called from any thread.
+ void RequestIntroduction(const NodeName& aPeerName);
+
+ // Send an introduction to the target node. May be called from any thread.
+ void Introduce(Introduction aIntroduction);
+
+ void AcceptInvite(const NodeName& aRealName, const PortName& aInitialPort);
+
+ // The PID of the remote process, once known. May be called from any thread.
+ base::ProcessId OtherPid() const { return mOtherPid; }
+
+ // Start communicating with the remote process using this NodeChannel. MUST BE
+ // CALLED FROM THE IO THREAD.
+ void Start();
+
+ // Stop communicating with the remote process using this NodeChannel, MUST BE
+ // CALLED FROM THE IO THREAD.
+ void Close();
+
+ // Only ever called by NodeController to update the name after an invite has
+ // completed. MUST BE CALLED FROM THE IO THREAD.
+ void SetName(const NodeName& aNewName) { mName = aNewName; }
+
+#ifdef FUZZING_SNAPSHOT
+ // MUST BE CALLED FROM THE IO THREAD.
+ const NodeName& GetName() { return mName; }
+#endif
+
+ // Update the known PID for the remote process. MUST BE CALLED FROM THE IO
+ // THREAD.
+ void SetOtherPid(base::ProcessId aNewPid);
+
+#ifdef XP_MACOSX
+ // Called by the GeckoChildProcessHost to provide the task_t for the peer
+ // process. MUST BE CALLED FROM THE IO THREAD.
+ void SetMachTaskPort(task_t aTask);
+#endif
+
+ private:
+ ~NodeChannel();
+
+ void Destroy();
+ void FinalDestroy();
+
+ void SendMessage(UniquePtr<IPC::Message> aMessage);
+
+ // IPC::Channel::Listener implementation
+ void OnMessageReceived(UniquePtr<IPC::Message> aMessage) override;
+ void OnChannelConnected(base::ProcessId aPeerPid) override;
+ void OnChannelError() override;
+
+ // NOTE: This strong reference will create a reference cycle between the
+ // listener and the NodeChannel while it is in use. The Listener must clear
+ // its reference to the NodeChannel to avoid leaks before shutdown.
+ const RefPtr<Listener> mListener;
+
+ // The apparent name of this Node. This may change during the invite process
+ // while waiting for the remote node name to be communicated to us.
+
+ // WARNING: This must only be accessed on the IO thread.
+ NodeName mName;
+
+ // NOTE: This won't change once the connection has been established, but may
+ // be `-1` until then. This will only be written to on the IO thread, but may
+ // be read from other threads.
+ std::atomic<base::ProcessId> mOtherPid;
+
+ // WARNING: Most methods on the IPC::Channel are only safe to call on the IO
+ // thread, however it is safe to call `Send()` and `IsClosed()` from other
+ // threads. See IPC::Channel's documentation for details.
+ const mozilla::UniquePtr<IPC::Channel> mChannel;
+
+ // The state will start out as `State::Active`, and will only transition to
+ // `State::Closed` on the IO thread. If a Send fails, the state will
+ // transition to `State::Closing`, and a runnable will be dispatched to the
+ // I/O thread to notify callbacks.
+ enum class State { Active, Closing, Closed };
+ std::atomic<State> mState = State::Active;
+
+#ifdef FUZZING_SNAPSHOT
+ std::atomic<bool> mBlockSendRecv = false;
+#endif
+
+ // WARNING: Must only be accessed on the IO thread.
+ WeakPtr<mozilla::ipc::GeckoChildProcessHost> mChildProcessHost;
+};
+
+} // namespace mozilla::ipc
+
+#endif
diff --git a/ipc/glue/NodeController.cpp b/ipc/glue/NodeController.cpp
new file mode 100644
index 0000000000..532e4fa509
--- /dev/null
+++ b/ipc/glue/NodeController.cpp
@@ -0,0 +1,869 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/NodeController.h"
+#include "MainThreadUtils.h"
+#include "base/process_util.h"
+#include "chrome/common/ipc_message.h"
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/node.h"
+#include "mojo/core/ports/port_locker.h"
+#include "mozilla/AlreadyAddRefed.h"
+#include "mozilla/RandomNum.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/ToString.h"
+#include "mozilla/ipc/BrowserProcessSubThread.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/mozalloc.h"
+#include "nsISerialEventTarget.h"
+#include "nsTArray.h"
+#include "nsXULAppAPI.h"
+#include "nsPrintfCString.h"
+
+#define PORTS_ALWAYS_OK(expr) MOZ_ALWAYS_TRUE(mojo::core::ports::OK == (expr))
+
+namespace mozilla::ipc {
+
+static StaticRefPtr<NodeController> gNodeController;
+
+static LazyLogModule gNodeControllerLog{"NodeController"};
+
+// Helper logger macro which includes the name of the `this` NodeController in
+// the logged messages.
+#define NODECONTROLLER_LOG(level_, fmt_, ...) \
+ MOZ_LOG(gNodeControllerLog, level_, \
+ ("[%s]: " fmt_, ToString(mName).c_str(), ##__VA_ARGS__))
+
+// Helper warning macro which both does logger logging and emits NS_WARNING logs
+// under debug mode.
+#ifdef DEBUG
+# define NODECONTROLLER_WARNING(fmt_, ...) \
+ do { \
+ nsPrintfCString warning("[%s]: " fmt_, ToString(mName).c_str(), \
+ ##__VA_ARGS__); \
+ NS_WARNING(warning.get()); \
+ MOZ_LOG(gNodeControllerLog, LogLevel::Debug, ("%s", warning.get())); \
+ } while (0)
+#else
+# define NODECONTROLLER_WARNING(fmt_, ...) \
+ NODECONTROLLER_LOG(LogLevel::Warning, fmt_, ##__VA_ARGS__)
+#endif
+
+NodeController::NodeController(const NodeName& aName)
+ : mName(aName), mNode(MakeUnique<Node>(aName, this)) {}
+
+NodeController::~NodeController() {
+ auto state = mState.Lock();
+ MOZ_RELEASE_ASSERT(state->mPeers.IsEmpty(),
+ "Destroying NodeController before closing all peers");
+ MOZ_RELEASE_ASSERT(state->mInvites.IsEmpty(),
+ "Destroying NodeController before closing all invites");
+};
+
+// FIXME: Actually provide some way to create the thing.
+/* static */ NodeController* NodeController::GetSingleton() {
+ MOZ_ASSERT(gNodeController);
+ return gNodeController;
+}
+
+std::pair<ScopedPort, ScopedPort> NodeController::CreatePortPair() {
+ PortRef port0, port1;
+ PORTS_ALWAYS_OK(mNode->CreatePortPair(&port0, &port1));
+ return {ScopedPort{std::move(port0), this},
+ ScopedPort{std::move(port1), this}};
+}
+
+auto NodeController::GetPort(const PortName& aName) -> PortRef {
+ PortRef port;
+ int rv = mNode->GetPort(aName, &port);
+ if (NS_WARN_IF(rv != mojo::core::ports::OK)) {
+ NODECONTROLLER_WARNING("Call to GetPort(%s) Failed",
+ ToString(aName).c_str());
+ return {};
+ }
+ return port;
+}
+
+void NodeController::SetPortObserver(const PortRef& aPort,
+ PortObserver* aObserver) {
+ PORTS_ALWAYS_OK(mNode->SetUserData(aPort, aObserver));
+}
+
+auto NodeController::GetStatus(const PortRef& aPort) -> Maybe<PortStatus> {
+ PortStatus status{};
+ int rv = mNode->GetStatus(aPort, &status);
+ if (rv != mojo::core::ports::OK) {
+ return Nothing();
+ }
+ return Some(status);
+}
+
+void NodeController::ClosePort(const PortRef& aPort) {
+ PORTS_ALWAYS_OK(mNode->ClosePort(aPort));
+}
+
+bool NodeController::GetMessage(const PortRef& aPort,
+ UniquePtr<IPC::Message>* aMessage) {
+ UniquePtr<UserMessageEvent> messageEvent;
+ int rv = mNode->GetMessage(aPort, &messageEvent, nullptr);
+ if (rv != mojo::core::ports::OK) {
+ if (rv == mojo::core::ports::ERROR_PORT_PEER_CLOSED) {
+ return false;
+ }
+ MOZ_CRASH("GetMessage on port in invalid state");
+ }
+
+ if (messageEvent) {
+ UniquePtr<IPC::Message> message = messageEvent->TakeMessage<IPC::Message>();
+
+ // If our UserMessageEvent has any ports directly attached to it, fetch them
+ // from our node and attach them to the IPC::Message we extracted.
+ //
+ // It's important to only do this if we have nonempty set of ports on the
+ // event, as we may have never serialized our IPC::Message's ports onto the
+ // event if it was routed in-process.
+ if (messageEvent->num_ports() > 0) {
+ nsTArray<ScopedPort> attachedPorts(messageEvent->num_ports());
+ for (size_t i = 0; i < messageEvent->num_ports(); ++i) {
+ attachedPorts.AppendElement(
+ ScopedPort{GetPort(messageEvent->ports()[i]), this});
+ }
+ message->SetAttachedPorts(std::move(attachedPorts));
+ }
+
+ *aMessage = std::move(message);
+ } else {
+ *aMessage = nullptr;
+ }
+ return true;
+}
+
+bool NodeController::SendUserMessage(const PortRef& aPort,
+ UniquePtr<IPC::Message> aMessage) {
+ auto messageEvent = MakeUnique<UserMessageEvent>(0);
+ messageEvent->AttachMessage(std::move(aMessage));
+
+ int rv = mNode->SendUserMessage(aPort, std::move(messageEvent));
+ if (rv == mojo::core::ports::OK) {
+ return true;
+ }
+ if (rv == mojo::core::ports::ERROR_PORT_PEER_CLOSED) {
+ NODECONTROLLER_LOG(LogLevel::Debug,
+ "Ignoring message to port %s as peer was closed",
+ ToString(aPort.name()).c_str());
+ return true;
+ }
+ NODECONTROLLER_WARNING("Failed to send message to port %s",
+ ToString(aPort.name()).c_str());
+ return false;
+}
+
+auto NodeController::SerializeEventMessage(UniquePtr<Event> aEvent,
+ const NodeName* aRelayTarget,
+ uint32_t aType)
+ -> UniquePtr<IPC::Message> {
+ UniquePtr<IPC::Message> message;
+ if (aEvent->type() == Event::kUserMessage) {
+ MOZ_DIAGNOSTIC_ASSERT(
+ aType == EVENT_MESSAGE_TYPE,
+ "Can only send a UserMessage in an EVENT_MESSAGE_TYPE");
+ message = static_cast<UserMessageEvent*>(aEvent.get())
+ ->TakeMessage<IPC::Message>();
+ } else {
+ message = MakeUnique<IPC::Message>(MSG_ROUTING_CONTROL, aType);
+ }
+
+ message->set_relay(aRelayTarget != nullptr);
+
+ size_t length = aEvent->GetSerializedSize();
+ if (aRelayTarget) {
+ length += sizeof(NodeName);
+ }
+
+ // Use an intermediate buffer to serialize to avoid potential issues with the
+ // segmented `IPC::Message` bufferlist. This should be fairly cheap, as the
+ // majority of events are fairly small.
+ Vector<char, 256, InfallibleAllocPolicy> buffer;
+ (void)buffer.initLengthUninitialized(length);
+ if (aRelayTarget) {
+ memcpy(buffer.begin(), aRelayTarget, sizeof(NodeName));
+ aEvent->Serialize(buffer.begin() + sizeof(NodeName));
+ } else {
+ aEvent->Serialize(buffer.begin());
+ }
+
+ message->WriteFooter(buffer.begin(), buffer.length());
+ message->set_event_footer_size(buffer.length());
+
+#ifdef DEBUG
+ // Debug-assert that we can read the same data back out of the buffer.
+ MOZ_ASSERT(message->event_footer_size() == length);
+ Vector<char, 256, InfallibleAllocPolicy> buffer2;
+ (void)buffer2.initLengthUninitialized(message->event_footer_size());
+ MOZ_ASSERT(message->ReadFooter(buffer2.begin(), buffer2.length(),
+ /* truncate */ false));
+ MOZ_ASSERT(!memcmp(buffer2.begin(), buffer.begin(), buffer.length()));
+#endif
+
+ return message;
+}
+
+auto NodeController::DeserializeEventMessage(UniquePtr<IPC::Message> aMessage,
+ NodeName* aRelayTarget)
+ -> UniquePtr<Event> {
+ if (aMessage->is_relay() && !aRelayTarget) {
+ NODECONTROLLER_WARNING("Unexpected relay message '%s'", aMessage->name());
+ return nullptr;
+ }
+
+ Vector<char, 256, InfallibleAllocPolicy> buffer;
+ (void)buffer.initLengthUninitialized(aMessage->event_footer_size());
+ // Truncate the message when reading the footer, so that the extra footer data
+ // is no longer present in the message. This allows future code to eventually
+ // send the same `IPC::Message` to another process.
+ if (!aMessage->ReadFooter(buffer.begin(), buffer.length(),
+ /* truncate */ true)) {
+ NODECONTROLLER_WARNING("Call to ReadFooter for message '%s' Failed",
+ aMessage->name());
+ return nullptr;
+ }
+ aMessage->set_event_footer_size(0);
+
+ UniquePtr<Event> event;
+ if (aRelayTarget) {
+ MOZ_ASSERT(aMessage->is_relay());
+ if (buffer.length() < sizeof(NodeName)) {
+ NODECONTROLLER_WARNING(
+ "Insufficient space in message footer for message '%s'",
+ aMessage->name());
+ return nullptr;
+ }
+ memcpy(aRelayTarget, buffer.begin(), sizeof(NodeName));
+ event = Event::Deserialize(buffer.begin() + sizeof(NodeName),
+ buffer.length() - sizeof(NodeName));
+ } else {
+ event = Event::Deserialize(buffer.begin(), buffer.length());
+ }
+
+ if (!event) {
+ NODECONTROLLER_WARNING("Call to Event::Deserialize for message '%s' Failed",
+ aMessage->name());
+ return nullptr;
+ }
+
+ if (event->type() == Event::kUserMessage) {
+ static_cast<UserMessageEvent*>(event.get())
+ ->AttachMessage(std::move(aMessage));
+ }
+ return event;
+}
+
+already_AddRefed<NodeChannel> NodeController::GetNodeChannel(
+ const NodeName& aName) {
+ auto state = mState.Lock();
+ return do_AddRef(state->mPeers.Get(aName));
+}
+
+void NodeController::DropPeer(NodeName aNodeName) {
+ AssertIOThread();
+
+#ifdef FUZZING_SNAPSHOT
+ MOZ_FUZZING_IPC_DROP_PEER("NodeController::DropPeer");
+#endif
+
+ Invite invite;
+ RefPtr<NodeChannel> channel;
+ nsTArray<PortRef> pendingMerges;
+ {
+ auto state = mState.Lock();
+ state->mPeers.Remove(aNodeName, &channel);
+ state->mPendingMessages.Remove(aNodeName);
+ state->mInvites.Remove(aNodeName, &invite);
+ state->mPendingMerges.Remove(aNodeName, &pendingMerges);
+ }
+
+ NODECONTROLLER_LOG(LogLevel::Info, "Dropping Peer %s (pid: %" PRIPID ")",
+ ToString(aNodeName).c_str(),
+ channel ? channel->OtherPid() : base::kInvalidProcessId);
+
+ if (channel) {
+ channel->Close();
+ }
+ if (invite.mChannel) {
+ invite.mChannel->Close();
+ }
+ if (invite.mToMerge.is_valid()) {
+ // Ignore any possible errors here.
+ (void)mNode->ClosePort(invite.mToMerge);
+ }
+ for (auto& port : pendingMerges) {
+ // Ignore any possible errors here.
+ (void)mNode->ClosePort(port);
+ }
+ mNode->LostConnectionToNode(aNodeName);
+}
+
+void NodeController::ForwardEvent(const NodeName& aNode,
+ UniquePtr<Event> aEvent) {
+ if (aNode == mName) {
+ (void)mNode->AcceptEvent(mName, std::move(aEvent));
+ } else {
+ // On Windows and macOS, messages holding HANDLEs or mach ports must be
+ // relayed via the broker process so it can transfer ownership.
+ bool needsRelay = false;
+#if defined(XP_WIN) || defined(XP_MACOSX)
+ if (!IsBroker() && aNode != kBrokerNodeName &&
+ aEvent->type() == Event::kUserMessage) {
+ auto* userEvent = static_cast<UserMessageEvent*>(aEvent.get());
+ needsRelay =
+ userEvent->HasMessage() &&
+ userEvent->GetMessage<IPC::Message>()->num_relayed_attachments() > 0;
+ }
+#endif
+
+ UniquePtr<IPC::Message> message =
+ SerializeEventMessage(std::move(aEvent), needsRelay ? &aNode : nullptr);
+ MOZ_ASSERT(message->is_relay() == needsRelay,
+ "Message relay status set incorrectly");
+
+ RefPtr<NodeChannel> peer;
+ RefPtr<NodeChannel> broker;
+ bool needsIntroduction = false;
+ {
+ auto state = mState.Lock();
+
+ // Check if we know this peer. If we don't, we'll need to request an
+ // introduction.
+ peer = state->mPeers.Get(aNode);
+ if (!peer || needsRelay) {
+ if (IsBroker()) {
+ NODECONTROLLER_WARNING("Ignoring message '%s' to unknown peer %s",
+ message->name(), ToString(aNode).c_str());
+ return;
+ }
+
+ broker = state->mPeers.Get(kBrokerNodeName);
+ if (!broker) {
+ NODECONTROLLER_WARNING(
+ "Ignoring message '%s' to peer %s due to a missing broker",
+ message->name(), ToString(aNode).c_str());
+ return;
+ }
+
+ if (!needsRelay) {
+ auto& queue =
+ state->mPendingMessages.LookupOrInsertWith(aNode, [&]() {
+ needsIntroduction = true;
+ return Queue<UniquePtr<IPC::Message>, 64>{};
+ });
+ queue.Push(std::move(message));
+ }
+ }
+ }
+
+ MOZ_ASSERT(!needsIntroduction || !needsRelay,
+ "Only one of the two should ever be set");
+
+ if (needsRelay) {
+ NODECONTROLLER_LOG(LogLevel::Info,
+ "Relaying message '%s' for peer %s due to %" PRIu32
+ " attachments",
+ message->name(), ToString(aNode).c_str(),
+ message->num_relayed_attachments());
+ MOZ_ASSERT(message->num_relayed_attachments() > 0 && broker);
+ broker->SendEventMessage(std::move(message));
+ } else if (needsIntroduction) {
+ MOZ_ASSERT(broker);
+ broker->RequestIntroduction(aNode);
+ } else if (peer) {
+ peer->SendEventMessage(std::move(message));
+ }
+ }
+}
+
+void NodeController::BroadcastEvent(UniquePtr<Event> aEvent) {
+ UniquePtr<IPC::Message> message =
+ SerializeEventMessage(std::move(aEvent), nullptr, BROADCAST_MESSAGE_TYPE);
+
+ if (IsBroker()) {
+ OnBroadcast(mName, std::move(message));
+ } else if (RefPtr<NodeChannel> broker = GetNodeChannel(kBrokerNodeName)) {
+ broker->Broadcast(std::move(message));
+ } else {
+ NODECONTROLLER_WARNING(
+ "Trying to broadcast event, but no connection to broker");
+ }
+}
+
+void NodeController::PortStatusChanged(const PortRef& aPortRef) {
+ RefPtr<UserData> userData;
+ int rv = mNode->GetUserData(aPortRef, &userData);
+ if (rv != mojo::core::ports::OK) {
+ NODECONTROLLER_WARNING("GetUserData call for port '%s' failed",
+ ToString(aPortRef.name()).c_str());
+ return;
+ }
+ if (userData) {
+ // All instances of `UserData` attached to ports in this node must be of
+ // type `PortObserver`, so we can call `OnPortStatusChanged` directly on
+ // them.
+ static_cast<PortObserver*>(userData.get())->OnPortStatusChanged();
+ }
+}
+
+void NodeController::OnEventMessage(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) {
+ AssertIOThread();
+
+ bool isRelay = aMessage->is_relay();
+ if (isRelay && aMessage->num_relayed_attachments() == 0) {
+ NODECONTROLLER_WARNING(
+ "Invalid relay message without relayed attachments from peer %s!",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+
+ NodeName relayTarget;
+ UniquePtr<Event> event = DeserializeEventMessage(
+ std::move(aMessage), isRelay ? &relayTarget : nullptr);
+ if (!event) {
+ NODECONTROLLER_WARNING("Invalid EventMessage from peer %s!",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+
+ NodeName fromNode = aFromNode;
+#if defined(XP_WIN) || defined(XP_MACOSX)
+ if (isRelay) {
+ if (event->type() != Event::kUserMessage) {
+ NODECONTROLLER_WARNING(
+ "Unexpected relay of non-UserMessage event from peer %s!",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+
+ // If we're the broker, then we'll need to forward this message on to the
+ // true recipient. To do this, we re-serialize the message, passing along
+ // the original source node, and send it to the final node.
+ if (IsBroker()) {
+ UniquePtr<IPC::Message> message =
+ SerializeEventMessage(std::move(event), &aFromNode);
+ if (!message) {
+ NODECONTROLLER_WARNING(
+ "Relaying EventMessage from peer %s failed to re-serialize!",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+ MOZ_ASSERT(message->is_relay(), "Message stopped being a relay message?");
+ MOZ_ASSERT(message->num_relayed_attachments() > 0,
+ "Message doesn't have relayed attachments?");
+
+ NODECONTROLLER_LOG(
+ LogLevel::Info,
+ "Relaying message '%s' from peer %s to peer %s (%" PRIu32
+ " attachments)",
+ message->name(), ToString(aFromNode).c_str(),
+ ToString(relayTarget).c_str(), message->num_relayed_attachments());
+
+ RefPtr<NodeChannel> peer;
+ {
+ auto state = mState.Lock();
+ peer = state->mPeers.Get(relayTarget);
+ }
+ if (!peer) {
+ NODECONTROLLER_WARNING(
+ "Dropping relayed message from %s to unknown peer %s",
+ ToString(aFromNode).c_str(), ToString(relayTarget).c_str());
+ return;
+ }
+
+ peer->SendEventMessage(std::move(message));
+ return;
+ }
+
+ // Otherwise, we're the final recipient, so we can continue & process the
+ // message as usual.
+ if (aFromNode != kBrokerNodeName) {
+ NODECONTROLLER_WARNING(
+ "Unexpected relayed EventMessage from non-broker peer %s!",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+ fromNode = relayTarget;
+
+ NODECONTROLLER_LOG(LogLevel::Info, "Got relayed message from peer %s",
+ ToString(fromNode).c_str());
+ }
+#endif
+
+ // If we're getting a requested port merge from another process, check to make
+ // sure that we're expecting the request, and record that the merge has
+ // arrived so we don't try to close the port on error.
+ if (event->type() == Event::kMergePort) {
+ // Check that the target port for the merge actually exists.
+ auto targetPort = GetPort(event->port_name());
+ if (!targetPort.is_valid()) {
+ NODECONTROLLER_WARNING(
+ "Unexpected MergePortEvent from peer %s for unknown port %s",
+ ToString(fromNode).c_str(), ToString(event->port_name()).c_str());
+ DropPeer(fromNode);
+ return;
+ }
+
+ // Check if `targetPort` is in our pending merges entry for the given source
+ // node. If this makes the `mPendingMerges` entry empty, remove it.
+ bool expectingMerge = [&] {
+ auto state = mState.Lock();
+ auto pendingMerges = state->mPendingMerges.Lookup(aFromNode);
+ if (!pendingMerges) {
+ return false;
+ }
+ size_t removed = pendingMerges->RemoveElementsBy(
+ [&](auto& port) { return port.name() == targetPort.name(); });
+ if (removed != 0 && pendingMerges->IsEmpty()) {
+ pendingMerges.Remove();
+ }
+ return removed != 0;
+ }();
+
+ if (!expectingMerge) {
+ NODECONTROLLER_WARNING(
+ "Unexpected MergePortEvent from peer %s for port %s",
+ ToString(fromNode).c_str(), ToString(event->port_name()).c_str());
+ DropPeer(fromNode);
+ return;
+ }
+ }
+
+ (void)mNode->AcceptEvent(fromNode, std::move(event));
+}
+
+void NodeController::OnBroadcast(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) {
+ MOZ_DIAGNOSTIC_ASSERT(aMessage->type() == BROADCAST_MESSAGE_TYPE);
+
+ // NOTE: This method may be called off of the IO thread by the
+ // `BroadcastEvent` node callback.
+ if (!IsBroker()) {
+ NODECONTROLLER_WARNING("Broadcast request received by non-broker node");
+ return;
+ }
+
+ UniquePtr<Event> event = DeserializeEventMessage(std::move(aMessage));
+ if (!event) {
+ NODECONTROLLER_WARNING("Invalid broadcast message from peer");
+ return;
+ }
+
+ nsTArray<RefPtr<NodeChannel>> peers;
+ {
+ auto state = mState.Lock();
+ peers.SetCapacity(state->mPeers.Count());
+ for (const auto& peer : state->mPeers.Values()) {
+ peers.AppendElement(peer);
+ }
+ }
+ for (const auto& peer : peers) {
+ // NOTE: This `clone` operation is only supported for a limited number of
+ // message types by the ports API, which provides some extra security by
+ // only allowing those specific types of messages to be broadcasted.
+ // Messages which don't support `CloneForBroadcast` cannot be broadcast, and
+ // the ports library will not attempt to broadcast them.
+ auto clone = event->CloneForBroadcast();
+ if (!clone) {
+ NODECONTROLLER_WARNING("Attempt to broadcast unsupported message");
+ break;
+ }
+
+ peer->SendEventMessage(SerializeEventMessage(std::move(clone)));
+ }
+}
+
+void NodeController::OnIntroduce(const NodeName& aFromNode,
+ NodeChannel::Introduction aIntroduction) {
+ AssertIOThread();
+
+ if (aFromNode != kBrokerNodeName) {
+ NODECONTROLLER_WARNING("Introduction received from non-broker node");
+ DropPeer(aFromNode);
+ return;
+ }
+
+ MOZ_ASSERT(aIntroduction.mMyPid == base::GetCurrentProcId(),
+ "We're the wrong process to receive this?");
+
+ if (!aIntroduction.mHandle) {
+ NODECONTROLLER_WARNING("Could not be introduced to peer %s",
+ ToString(aIntroduction.mName).c_str());
+ mNode->LostConnectionToNode(aIntroduction.mName);
+
+ auto state = mState.Lock();
+ state->mPendingMessages.Remove(aIntroduction.mName);
+ return;
+ }
+
+ auto channel =
+ MakeUnique<IPC::Channel>(std::move(aIntroduction.mHandle),
+ aIntroduction.mMode, aIntroduction.mOtherPid);
+ auto nodeChannel = MakeRefPtr<NodeChannel>(
+ aIntroduction.mName, std::move(channel), this, aIntroduction.mOtherPid);
+
+ {
+ auto state = mState.Lock();
+ bool isNew = false;
+ state->mPeers.LookupOrInsertWith(aIntroduction.mName, [&]() {
+ isNew = true;
+ return nodeChannel;
+ });
+ if (!isNew) {
+ // We got a duplicate introduction. This can happen during normal
+ // execution if both sides request an introduction at the same time. We
+ // can just ignore the second one, as they'll arrive in the same order in
+ // both processes.
+ nodeChannel->Close();
+ return;
+ }
+
+ // Deliver any pending messages, then remove the entry from our table. We do
+ // this while `mState` is still held to ensure that these messages are
+ // all sent before another thread can observe the newly created channel.
+ // As the channel hasn't been `Connect()`-ed yet, this will only queue the
+ // messages up to be sent, so is OK to do with the mutex held. These
+ // messages will be processed to be sent during `Start()` below, which is
+ // performed outside of the lock.
+ if (auto pending = state->mPendingMessages.Lookup(aIntroduction.mName)) {
+ while (!pending->IsEmpty()) {
+ nodeChannel->SendEventMessage(pending->Pop());
+ }
+ pending.Remove();
+ }
+ }
+
+ // NodeChannel::Start must be called with the lock not held, as it may lead to
+ // callbacks being made into `OnChannelError` or `OnMessageReceived`, which
+ // will attempt to re-acquire our lock.
+ nodeChannel->Start();
+}
+
+void NodeController::OnRequestIntroduction(const NodeName& aFromNode,
+ const NodeName& aName) {
+ AssertIOThread();
+ if (NS_WARN_IF(!IsBroker())) {
+ return;
+ }
+
+ RefPtr<NodeChannel> peerA = GetNodeChannel(aFromNode);
+ if (!peerA || aName == mojo::core::ports::kInvalidNodeName) {
+ NODECONTROLLER_WARNING("Invalid OnRequestIntroduction message from node %s",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+
+ RefPtr<NodeChannel> peerB = GetNodeChannel(aName);
+ IPC::Channel::ChannelHandle handleA, handleB;
+ if (!peerB || !IPC::Channel::CreateRawPipe(&handleA, &handleB)) {
+ NODECONTROLLER_WARNING(
+ "Rejecting introduction request from '%s' for unknown peer '%s'",
+ ToString(aFromNode).c_str(), ToString(aName).c_str());
+
+ // We don't know this peer, or ran into issues creating the descriptor! Send
+ // an invalid introduction to content to clean up any pending outbound
+ // messages.
+ NodeChannel::Introduction intro{aName, nullptr, IPC::Channel::MODE_SERVER,
+ peerA->OtherPid(), base::kInvalidProcessId};
+ peerA->Introduce(std::move(intro));
+ return;
+ }
+
+ NodeChannel::Introduction introA{aName, std::move(handleA),
+ IPC::Channel::MODE_SERVER, peerA->OtherPid(),
+ peerB->OtherPid()};
+ NodeChannel::Introduction introB{aFromNode, std::move(handleB),
+ IPC::Channel::MODE_CLIENT, peerB->OtherPid(),
+ peerA->OtherPid()};
+ peerA->Introduce(std::move(introA));
+ peerB->Introduce(std::move(introB));
+}
+
+void NodeController::OnAcceptInvite(const NodeName& aFromNode,
+ const NodeName& aRealName,
+ const PortName& aInitialPort) {
+ AssertIOThread();
+ if (!IsBroker()) {
+ NODECONTROLLER_WARNING("Ignoring AcceptInvite message as non-broker");
+ return;
+ }
+
+ if (aRealName == mojo::core::ports::kInvalidNodeName ||
+ aInitialPort == mojo::core::ports::kInvalidPortName) {
+ NODECONTROLLER_WARNING("Invalid name in AcceptInvite message");
+ DropPeer(aFromNode);
+ return;
+ }
+
+ bool inserted = false;
+ Invite invite;
+ {
+ auto state = mState.Lock();
+ MOZ_ASSERT(state->mPendingMessages.IsEmpty(),
+ "Shouldn't have pending messages in broker");
+
+ // Try to remove the source node from our invites list and insert it into
+ // our peers map under the new name.
+ if (state->mInvites.Remove(aFromNode, &invite)) {
+ MOZ_ASSERT(invite.mChannel && invite.mToMerge.is_valid());
+ state->mPeers.LookupOrInsertWith(aRealName, [&]() {
+ inserted = true;
+ return invite.mChannel;
+ });
+ }
+ }
+ if (!inserted) {
+ NODECONTROLLER_WARNING("Invalid AcceptInvite message from node %s",
+ ToString(aFromNode).c_str());
+ DropPeer(aFromNode);
+ return;
+ }
+
+ // Update the name of the node. This field is only accessed from the IO
+ // thread, so it's safe to update it without a lock held.
+ invite.mChannel->SetName(aRealName);
+
+ // Start the port merge to allow our existing initial port to begin
+ // communicating with the remote port.
+ PORTS_ALWAYS_OK(mNode->MergePorts(invite.mToMerge, aRealName, aInitialPort));
+}
+
+void NodeController::OnChannelError(const NodeName& aFromNode) {
+ AssertIOThread();
+ DropPeer(aFromNode);
+}
+
+static mojo::core::ports::NodeName RandomNodeName() {
+ return {RandomUint64OrDie(), RandomUint64OrDie()};
+}
+
+std::tuple<ScopedPort, RefPtr<NodeChannel>> NodeController::InviteChildProcess(
+ UniquePtr<IPC::Channel> aChannel,
+ GeckoChildProcessHost* aChildProcessHost) {
+ MOZ_ASSERT(IsBroker());
+ AssertIOThread();
+
+ // Create the peer with a randomly generated name, and store it in `mInvites`.
+ // This channel and name will be used for communication with the node until it
+ // sends us its' real name in an `AcceptInvite` message.
+ auto ports = CreatePortPair();
+ auto inviteName = RandomNodeName();
+ auto nodeChannel =
+ MakeRefPtr<NodeChannel>(inviteName, std::move(aChannel), this,
+ base::kInvalidProcessId, aChildProcessHost);
+ {
+ auto state = mState.Lock();
+ MOZ_DIAGNOSTIC_ASSERT(!state->mPeers.Contains(inviteName),
+ "UUID conflict?");
+ MOZ_DIAGNOSTIC_ASSERT(!state->mInvites.Contains(inviteName),
+ "UUID conflict?");
+ state->mInvites.InsertOrUpdate(inviteName,
+ Invite{nodeChannel, ports.second.Release()});
+ }
+
+ nodeChannel->Start();
+ return std::tuple{std::move(ports.first), std::move(nodeChannel)};
+}
+
+void NodeController::InitBrokerProcess() {
+ AssertIOThread();
+ MOZ_ASSERT(!gNodeController);
+ gNodeController = new NodeController(kBrokerNodeName);
+}
+
+ScopedPort NodeController::InitChildProcess(UniquePtr<IPC::Channel> aChannel,
+ base::ProcessId aParentPid) {
+ AssertIOThread();
+ MOZ_ASSERT(!gNodeController);
+
+ auto nodeName = RandomNodeName();
+ gNodeController = new NodeController(nodeName);
+
+ auto ports = gNodeController->CreatePortPair();
+ PortRef toMerge = ports.second.Release();
+
+ // Mark the port as expecting a pending merge. This is a duplicate of the
+ // information tracked by `mPendingMerges`, and was added by upstream
+ // chromium.
+ // See https://chromium-review.googlesource.com/c/chromium/src/+/3289065
+ {
+ mojo::core::ports::SinglePortLocker locker(&toMerge);
+ locker.port()->pending_merge_peer = true;
+ }
+
+ auto nodeChannel = MakeRefPtr<NodeChannel>(
+ kBrokerNodeName, std::move(aChannel), gNodeController, aParentPid);
+ {
+ auto state = gNodeController->mState.Lock();
+ MOZ_DIAGNOSTIC_ASSERT(!state->mPeers.Contains(kBrokerNodeName));
+ state->mPeers.InsertOrUpdate(kBrokerNodeName, nodeChannel);
+ MOZ_DIAGNOSTIC_ASSERT(!state->mPendingMerges.Contains(kBrokerNodeName));
+ state->mPendingMerges.LookupOrInsert(kBrokerNodeName)
+ .AppendElement(toMerge);
+ }
+
+ nodeChannel->Start();
+ nodeChannel->AcceptInvite(nodeName, toMerge.name());
+ return std::move(ports.first);
+}
+
+void NodeController::CleanUp() {
+ AssertIOThread();
+ MOZ_ASSERT(gNodeController);
+
+ RefPtr<NodeController> nodeController = gNodeController;
+ gNodeController = nullptr;
+
+ // Collect all objects from our state which need to be cleaned up.
+ nsTArray<NodeName> lostConnections;
+ nsTArray<RefPtr<NodeChannel>> channelsToClose;
+ nsTArray<PortRef> portsToClose;
+ {
+ auto state = nodeController->mState.Lock();
+ for (const auto& chan : state->mPeers) {
+ lostConnections.AppendElement(chan.GetKey());
+ channelsToClose.AppendElement(chan.GetData());
+ }
+ for (const auto& invite : state->mInvites.Values()) {
+ channelsToClose.AppendElement(invite.mChannel);
+ portsToClose.AppendElement(invite.mToMerge);
+ }
+ for (const auto& pendingPorts : state->mPendingMerges.Values()) {
+ portsToClose.AppendElements(pendingPorts);
+ }
+ state->mPeers.Clear();
+ state->mPendingMessages.Clear();
+ state->mInvites.Clear();
+ state->mPendingMerges.Clear();
+ }
+ for (auto& nodeChannel : channelsToClose) {
+ nodeChannel->Close();
+ }
+ for (auto& port : portsToClose) {
+ nodeController->mNode->ClosePort(port);
+ }
+ for (auto& name : lostConnections) {
+ nodeController->mNode->LostConnectionToNode(name);
+ }
+}
+
+#undef NODECONTROLLER_LOG
+#undef NODECONTROLLER_WARNING
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/NodeController.h b/ipc/glue/NodeController.h
new file mode 100644
index 0000000000..5356b85084
--- /dev/null
+++ b/ipc/glue/NodeController.h
@@ -0,0 +1,176 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_NodeController_h
+#define mozilla_ipc_NodeController_h
+
+#include "mojo/core/ports/event.h"
+#include "mojo/core/ports/name.h"
+#include "mojo/core/ports/node.h"
+#include "mojo/core/ports/node_delegate.h"
+#include "chrome/common/ipc_message.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "nsTHashMap.h"
+#include "mozilla/Queue.h"
+#include "mozilla/DataMutex.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/NodeChannel.h"
+
+namespace mozilla::ipc {
+
+class GeckoChildProcessHost;
+
+class NodeController final : public mojo::core::ports::NodeDelegate,
+ public NodeChannel::Listener {
+ using NodeName = mojo::core::ports::NodeName;
+ using PortName = mojo::core::ports::PortName;
+ using PortRef = mojo::core::ports::PortRef;
+ using Event = mojo::core::ports::Event;
+ using Node = mojo::core::ports::Node;
+ using UserData = mojo::core::ports::UserData;
+ using PortStatus = mojo::core::ports::PortStatus;
+ using UserMessageEvent = mojo::core::ports::UserMessageEvent;
+ using UserMessage = mojo::core::ports::UserMessage;
+
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(NodeController, override)
+
+ // Return the global singleton instance. The returned value is only valid
+ // while the IO thread is alive.
+ static NodeController* GetSingleton();
+
+ class PortObserver : public UserData {
+ public:
+ virtual void OnPortStatusChanged() = 0;
+
+ protected:
+ ~PortObserver() override = default;
+ };
+
+ // NOTE: For now there will always be a single broker process, and all
+ // processes in the graph need to be able to talk to it (the parent process).
+ // Give it a fixed node name for now to simplify things.
+ //
+ // If we ever decide to have multiple node networks intercommunicating (e.g.
+ // multiple instances or background services), we may need to change this.
+ static constexpr NodeName kBrokerNodeName{0x1, 0x1};
+
+ bool IsBroker() const { return mName == kBrokerNodeName; }
+
+ // Mint a new connected pair of ports within the current process.
+ std::pair<ScopedPort, ScopedPort> CreatePortPair();
+
+ // Get a reference to the port with the given name. Returns an invalid
+ // `PortRef` if the name wasn't found.
+ PortRef GetPort(const PortName& aName);
+
+ // Set the observer for the given port. This observer will be notified when
+ // the status of the port changes.
+ void SetPortObserver(const PortRef& aPort, PortObserver* aObserver);
+
+ // See `mojo::core::ports::Node::GetStatus`
+ Maybe<PortStatus> GetStatus(const PortRef& aPort);
+
+ // See `mojo::core::ports::Node::ClosePort`
+ void ClosePort(const PortRef& aPort);
+
+ // Send a message to the the port's connected peer.
+ bool SendUserMessage(const PortRef& aPort, UniquePtr<IPC::Message> aMessage);
+
+ // Get the next message from the port's message queue.
+ // Will set `*aMessage` to the found message, or `nullptr`.
+ // Returns `false` and sets `*aMessage` to `nullptr` if no further messages
+ // will be delivered to this port as its peer has been closed.
+ bool GetMessage(const PortRef& aPort, UniquePtr<IPC::Message>* aMessage);
+
+ // Called in the broker process from GeckoChildProcessHost to introduce a new
+ // child process into the network. Returns a `PortRef` which can be used to
+ // communicate with the `PortRef` returned from `InitChildProcess`, and a
+ // reference to the `NodeChannel` created for the new process. The port can
+ // immediately have messages sent to it.
+ std::tuple<ScopedPort, RefPtr<NodeChannel>> InviteChildProcess(
+ UniquePtr<IPC::Channel> aChannel,
+ GeckoChildProcessHost* aChildProcessHost);
+
+ // Called as the IO thread is started in the parent process.
+ static void InitBrokerProcess();
+
+ // Called as the IO thread is started in a child process.
+ static ScopedPort InitChildProcess(UniquePtr<IPC::Channel> aChannel,
+ base::ProcessId aParentPid);
+
+ // Called when the IO thread is torn down.
+ static void CleanUp();
+
+ private:
+ explicit NodeController(const NodeName& aName);
+ ~NodeController();
+
+ UniquePtr<IPC::Message> SerializeEventMessage(
+ UniquePtr<Event> aEvent, const NodeName* aRelayTarget = nullptr,
+ uint32_t aType = EVENT_MESSAGE_TYPE);
+ UniquePtr<Event> DeserializeEventMessage(UniquePtr<IPC::Message> aMessage,
+ NodeName* aRelayTarget = nullptr);
+
+ // Get the `NodeChannel` for the named node.
+ already_AddRefed<NodeChannel> GetNodeChannel(const NodeName& aName);
+
+ // Stop communicating with this peer. Must be called on the IO thread.
+ void DropPeer(NodeName aNodeName);
+
+ // Message Handlers
+ void OnEventMessage(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) override;
+ void OnBroadcast(const NodeName& aFromNode,
+ UniquePtr<IPC::Message> aMessage) override;
+ void OnIntroduce(const NodeName& aFromNode,
+ NodeChannel::Introduction aIntroduction) override;
+ void OnRequestIntroduction(const NodeName& aFromNode,
+ const NodeName& aName) override;
+ void OnAcceptInvite(const NodeName& aFromNode, const NodeName& aRealName,
+ const PortName& aInitialPort) override;
+ void OnChannelError(const NodeName& aFromNode) override;
+
+ // NodeDelegate Implementation
+ void ForwardEvent(const NodeName& aNode, UniquePtr<Event> aEvent) override;
+ void BroadcastEvent(UniquePtr<Event> aEvent) override;
+ void PortStatusChanged(const PortRef& aPortRef) override;
+
+ const NodeName mName;
+ const UniquePtr<Node> mNode;
+
+ template <class T>
+ using NodeMap = nsTHashMap<NodeNameHashKey, T>;
+
+ struct Invite {
+ // The channel which is being invited. This will have a temporary name until
+ // the invite is completed.
+ RefPtr<NodeChannel> mChannel;
+ // The port which will be merged with the port information from the new
+ // child process when recieved.
+ PortRef mToMerge;
+ };
+
+ struct State {
+ // Channels for connecting to all known peers.
+ NodeMap<RefPtr<NodeChannel>> mPeers;
+
+ // Messages which are queued for peers which we been introduced to yet.
+ NodeMap<Queue<UniquePtr<IPC::Message>, 64>> mPendingMessages;
+
+ // Connections for peers being invited to the network.
+ NodeMap<Invite> mInvites;
+
+ // Ports which are waiting to be merged by a particular peer node.
+ NodeMap<nsTArray<PortRef>> mPendingMerges;
+ };
+
+ DataMutex<State> mState{"NodeController::mState"};
+};
+
+} // namespace mozilla::ipc
+
+#endif
diff --git a/ipc/glue/PBackground.ipdl b/ipc/glue/PBackground.ipdl
new file mode 100644
index 0000000000..94b0079ff7
--- /dev/null
+++ b/ipc/glue/PBackground.ipdl
@@ -0,0 +1,296 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PBackgroundDataBridge;
+include protocol PBackgroundIDBFactory;
+include protocol PBackgroundIndexedDBUtils;
+include protocol PBackgroundSDBConnection;
+include protocol PBackgroundLSDatabase;
+include protocol PBackgroundLSObserver;
+include protocol PBackgroundLSRequest;
+include protocol PBackgroundLSSimpleRequest;
+include protocol PBackgroundLocalStorageCache;
+include protocol PBackgroundSessionStorageManager;
+include protocol PBackgroundSessionStorageService;
+include protocol PBackgroundStorage;
+include protocol PBackgroundTest;
+include protocol PBroadcastChannel;
+include protocol PCache;
+include protocol PCacheStorage;
+include protocol PCacheStreamControl;
+include protocol PClientManager;
+include protocol PEndpointForReport;
+include protocol PFileSystemManager;
+include protocol PFileSystemRequest;
+include protocol PGamepadEventChannel;
+include protocol PGamepadTestChannel;
+include protocol PHttpBackgroundChannel;
+include protocol PIdleScheduler;
+include protocol PRemoteWorker;
+include protocol PRemoteWorkerController;
+include protocol PRemoteWorkerService;
+include protocol PSharedWorker;
+include protocol PTemporaryIPCBlob;
+include protocol PFileCreator;
+include protocol PMessagePort;
+include protocol PCameras;
+include protocol PLockManager;
+include protocol PMIDIManager;
+include protocol PMIDIPort;
+include protocol PQuota;
+include protocol PServiceWorker;
+include protocol PServiceWorkerContainer;
+include protocol PServiceWorkerManager;
+include protocol PServiceWorkerRegistration;
+include protocol PWebAuthnTransaction;
+include protocol PUDPSocket;
+include protocol PVsync;
+include protocol PRemoteDecoderManager;
+include protocol PWebTransport;
+include protocol PFetch;
+
+include ClientIPCTypes;
+include DOMTypes;
+include IPCBlob;
+include IPCServiceWorkerDescriptor;
+include IPCServiceWorkerRegistrationDescriptor;
+include PBackgroundLSSharedTypes;
+include PBackgroundSharedTypes;
+include PBackgroundIDBSharedTypes;
+include PFileSystemParams;
+include ProtocolTypes;
+include RemoteWorkerTypes;
+include MIDITypes;
+
+include "mozilla/dom/cache/IPCUtils.h";
+include "mozilla/dom/quota/SerializationHelpers.h";
+include "mozilla/dom/PermissionMessageUtils.h";
+include "mozilla/layers/LayersMessageUtils.h";
+
+using mozilla::dom::cache::Namespace
+ from "mozilla/dom/cache/Types.h";
+
+using class mozilla::dom::SSCacheCopy from "mozilla/dom/PBackgroundSessionStorageCache.h";
+
+using mozilla::RemoteDecodeIn from "mozilla/RemoteDecoderManagerChild.h";
+
+using mozilla::camera::CamerasAccessStatus from "mozilla/media/CamerasTypes.h";
+
+namespace mozilla {
+namespace ipc {
+
+[NeedsOtherPid, ChildImpl=virtual, ParentImpl=virtual, ChildProc=anydom]
+sync protocol PBackground
+{
+ manages PBackgroundIDBFactory;
+ manages PBackgroundIndexedDBUtils;
+ manages PBackgroundSDBConnection;
+ manages PBackgroundLSDatabase;
+ manages PBackgroundLSObserver;
+ manages PBackgroundLSRequest;
+ manages PBackgroundLSSimpleRequest;
+ manages PBackgroundLocalStorageCache;
+ manages PBackgroundSessionStorageManager;
+ manages PBackgroundSessionStorageService;
+ manages PBackgroundStorage;
+ manages PBackgroundTest;
+ manages PBroadcastChannel;
+ manages PCache;
+ manages PCacheStorage;
+ manages PCacheStreamControl;
+ manages PClientManager;
+ manages PEndpointForReport;
+ manages PFileSystemRequest;
+ manages PGamepadEventChannel;
+ manages PGamepadTestChannel;
+ manages PHttpBackgroundChannel;
+ manages PIdleScheduler;
+ manages PLockManager;
+ manages PRemoteWorker;
+ manages PRemoteWorkerController;
+ manages PRemoteWorkerService;
+ manages PSharedWorker;
+ manages PTemporaryIPCBlob;
+ manages PFileCreator;
+ manages PMessagePort;
+ manages PCameras;
+ manages PQuota;
+ manages PServiceWorker;
+ manages PServiceWorkerContainer;
+ manages PServiceWorkerManager;
+ manages PServiceWorkerRegistration;
+ manages PWebAuthnTransaction;
+ manages PUDPSocket;
+ manages PVsync;
+ manages PFetch;
+
+parent:
+ // Only called at startup during mochitests to check the basic infrastructure.
+ async PBackgroundTest(nsCString testArg);
+
+ async PBackgroundIDBFactory(LoggingInfo loggingInfo);
+
+ async PBackgroundIndexedDBUtils();
+
+ // Use only for testing!
+ async FlushPendingFileDeletions();
+
+ async PBackgroundSDBConnection(PersistenceType persistenceType,
+ PrincipalInfo principalInfo);
+
+ async PBackgroundLSDatabase(PrincipalInfo principalInfo,
+ uint32_t privateBrowsingId,
+ uint64_t datastoreId);
+
+ async PBackgroundLSObserver(uint64_t observerId);
+
+ /**
+ * Issue an asynchronous request that will be used in a synchronous fashion
+ * through complex machinations described in `PBackgroundLSRequest.ipdl` and
+ * `LSObject.h`.
+ */
+ async PBackgroundLSRequest(LSRequestParams params);
+
+ /**
+ * Issues a simple, non-cancelable asynchronous request that's used in an
+ * asynchronous fashion by callers. (LSRequest is not simple because it used
+ * in a synchronous fashion which leads to complexities regarding cancelation,
+ * see `PBackgroundLSRequest.ipdl` for details.)
+ */
+ async PBackgroundLSSimpleRequest(LSSimpleRequestParams params);
+
+ async PBackgroundLocalStorageCache(PrincipalInfo principalInfo,
+ nsCString originKey,
+ uint32_t privateBrowsingId);
+
+ async PBackgroundSessionStorageManager(uint64_t aTopContextId);
+
+ async PBackgroundSessionStorageService();
+
+ async PBackgroundStorage(nsString profilePath, uint32_t privateBrowsingId);
+
+ /**
+ * Finish the setup of a new PFileSystemManager top level protocol.
+ */
+ async CreateFileSystemManagerParent(
+ PrincipalInfo principalInfo,
+ Endpoint<PFileSystemManagerParent> aParentEndpoint)
+ returns(nsresult rv);
+
+ /**
+ * Finish the setup of a new PWebTransport top level protocol.
+ */
+ async CreateWebTransportParent(
+ nsString aURL,
+ nullable nsIPrincipal aPrincipal,
+ IPCClientInfo? aClientInfo,
+ bool aDedicated,
+ bool aRequireUnreliable,
+ uint32_t aCongestionControl,
+ WebTransportHash[] aServerCertHashes,
+ Endpoint<PWebTransportParent> aParentEndpoint)
+ returns(nsresult rv, uint8_t aReliability); // Actually WebTransportReliabityMode enum
+
+ async PVsync();
+
+ async PCameras();
+
+ async PUDPSocket(PrincipalInfo? pInfo, nsCString filter);
+ async PBroadcastChannel(PrincipalInfo pInfo, nsCString origin, nsString channel);
+
+ async PServiceWorkerManager();
+
+ async ShutdownServiceWorkerRegistrar();
+
+ async PCacheStorage(Namespace aNamespace, PrincipalInfo aPrincipalInfo);
+
+ async PMessagePort(nsID uuid, nsID destinationUuid, uint32_t sequenceId);
+
+ async MessagePortForceClose(nsID uuid, nsID destinationUuid, uint32_t sequenceId);
+
+ async PQuota();
+
+ async ShutdownQuotaManager();
+
+ async ShutdownBackgroundSessionStorageManagers();
+
+ async PropagateBackgroundSessionStorageManager(uint64_t currentTopContextId, uint64_t targetTopContextId);
+
+ async RemoveBackgroundSessionStorageManager(uint64_t topContextId);
+
+ async GetSessionStorageManagerData(
+ uint64_t aTopContextId, uint32_t aSizeLimit, bool aCancelSessionStoreTimer)
+ returns(SSCacheCopy[] aCacheCopy);
+
+ async LoadSessionStorageManagerData(uint64_t aTopContextId, SSCacheCopy[] aOriginCacheCopy);
+
+ async PFileSystemRequest(FileSystemParams params);
+
+ async PGamepadEventChannel();
+
+ async PGamepadTestChannel();
+
+ async PHttpBackgroundChannel(uint64_t channelId);
+
+ async PWebAuthnTransaction();
+
+ async PSharedWorker(RemoteWorkerData data,
+ uint64_t windowID,
+ MessagePortIdentifier portIdentifier);
+
+ async PTemporaryIPCBlob();
+
+ async PFileCreator(nsString aFullPath, nsString aType, nsString aName,
+ int64_t? lastModified, bool aExistenceCheck,
+ bool aIsFromNsIFile);
+
+ async PClientManager();
+
+ async CreateMIDIManager(Endpoint<PMIDIManagerParent> aEndpoint);
+ async CreateMIDIPort(Endpoint<PMIDIPortParent> aEndpoint,
+ MIDIPortInfo portInfo, bool sysexEnabled);
+ async HasMIDIDevice() returns (bool hasDevice);
+
+ // This method is used to propagate storage activities from the child actor
+ // to the parent actor. See StorageActivityService.
+ async StorageActivity(PrincipalInfo principalInfo);
+
+ async PServiceWorker(IPCServiceWorkerDescriptor aDescriptor);
+
+ async PRemoteWorkerController(RemoteWorkerData aData);
+
+ async PRemoteWorkerService();
+
+ async PServiceWorkerContainer();
+
+ async PServiceWorkerRegistration(IPCServiceWorkerRegistrationDescriptor aDescriptor);
+
+ async PEndpointForReport(nsString aGroupName, PrincipalInfo aPrincipalInfo);
+
+ async RemoveEndpoint(nsString aGroupName, nsCString aEndpointURL,
+ PrincipalInfo aPrincipalInfo);
+
+ async PIdleScheduler();
+
+ async EnsureRDDProcessAndCreateBridge()
+ returns (nsresult rv, Endpoint<PRemoteDecoderManagerChild> aEndpoint);
+
+ async EnsureUtilityProcessAndCreateBridge(RemoteDecodeIn aLocation)
+ returns (nsresult rv, Endpoint<PRemoteDecoderManagerChild> aEndpoint);
+
+ async PLockManager(nsIPrincipal aPrincipalInfo, nsID aClientId);
+
+ async PFetch();
+
+ async RequestCameraAccess(bool aAllowPermissionRequest) returns (CamerasAccessStatus rv);
+
+child:
+ async PCache();
+ async PCacheStreamControl();
+
+ async PRemoteWorker(RemoteWorkerData data);
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/PBackgroundSharedTypes.ipdlh b/ipc/glue/PBackgroundSharedTypes.ipdlh
new file mode 100644
index 0000000000..92175b782d
--- /dev/null
+++ b/ipc/glue/PBackgroundSharedTypes.ipdlh
@@ -0,0 +1,78 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+using mozilla::OriginAttributes from "mozilla/ipc/BackgroundUtils.h";
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+
+namespace mozilla {
+namespace ipc {
+
+[Comparable] struct ContentSecurityPolicy
+{
+ nsString policy;
+ bool reportOnlyFlag;
+ bool deliveredViaMetaTagFlag;
+};
+
+[Comparable] struct ContentPrincipalInfo
+{
+ OriginAttributes attrs;
+
+ // Origin is not simply a part of the spec. Based on the scheme of the URI
+ // spec, we generate different kind of origins: for instance any file: URL
+ // shares the same origin, about: URLs have the full spec as origin and so
+ // on.
+ // Another important reason why we have this attribute is that
+ // ContentPrincipalInfo is used out of the main-thread. Having this value
+ // here allows us to retrive the origin without creating a full nsIPrincipal.
+ nsCString originNoSuffix;
+
+ nsCString spec;
+
+ nsCString? domain;
+
+ // Like originNoSuffix, baseDomain is used out of the main-thread.
+ nsCString baseDomain;
+};
+
+[Comparable] struct SystemPrincipalInfo
+{ };
+
+[Comparable] struct NullPrincipalInfo
+{
+ OriginAttributes attrs;
+ nsCString spec;
+};
+
+[Comparable] struct ExpandedPrincipalInfo
+{
+ OriginAttributes attrs;
+ PrincipalInfo[] allowlist;
+};
+
+[Comparable] union PrincipalInfo
+{
+ ContentPrincipalInfo;
+ SystemPrincipalInfo;
+ NullPrincipalInfo;
+ ExpandedPrincipalInfo;
+};
+
+[Comparable] struct CSPInfo
+{
+ ContentSecurityPolicy[] policyInfos;
+ PrincipalInfo requestPrincipalInfo;
+ nsCString selfURISpec;
+ nsString referrer;
+ uint64_t innerWindowID;
+ bool skipAllowInlineStyleCheck;
+};
+
+[Comparable] struct WebTransportHash {
+ nsCString algorithm;
+ uint8_t[] value;
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/PBackgroundStarter.ipdl b/ipc/glue/PBackgroundStarter.ipdl
new file mode 100644
index 0000000000..60fd6a3423
--- /dev/null
+++ b/ipc/glue/PBackgroundStarter.ipdl
@@ -0,0 +1,18 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PBackground;
+
+namespace mozilla {
+namespace ipc {
+
+[NeedsOtherPid, ChildProc=anydom]
+async protocol PBackgroundStarter
+{
+parent:
+ async InitBackground(Endpoint<PBackgroundParent> aEndpoint);
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/PBackgroundTest.ipdl b/ipc/glue/PBackgroundTest.ipdl
new file mode 100644
index 0000000000..5027010994
--- /dev/null
+++ b/ipc/glue/PBackgroundTest.ipdl
@@ -0,0 +1,21 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PBackground;
+
+namespace mozilla {
+namespace ipc {
+
+// This is a very simple testing protocol that is only used during mochitests.
+[ManualDealloc, ChildImpl=virtual, ParentImpl=virtual]
+protocol PBackgroundTest
+{
+ manager PBackground;
+
+child:
+ async __delete__(nsCString testArg);
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/PIdleScheduler.ipdl b/ipc/glue/PIdleScheduler.ipdl
new file mode 100644
index 0000000000..1857c12eaf
--- /dev/null
+++ b/ipc/glue/PIdleScheduler.ipdl
@@ -0,0 +1,70 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PBackground;
+using mozilla::TimeDuration from "mozilla/TimeStamp.h";
+[MoveOnly] using base::SharedMemoryHandle from "base/shared_memory.h";
+namespace mozilla {
+namespace ipc {
+
+/**
+ * PIdleScheduler is the protocol for cross-process idle scheduling.
+ * Only child processes participate in the scheduling and parent process
+ * can run its idle tasks whenever it needs to.
+ *
+ * The scheduler keeps track of the following things.
+ * - Activity of the main thread of each child process. A process is active
+ * when it is running tasks. Because of performance cross-process
+ * counters in shared memory are used for the activity tracking. There is
+ * one counter counting the activity state of all the processes and one
+ * counter for each process. This way if a child process crashes, the global
+ * counter can be updated by decrementing the per process counter from it.
+ * - Child processes running prioritized operation. Top level page loads is an
+ * example of a prioritized operation. When such is ongoing, idle tasks are
+ * less likely to run.
+ * - Idle requests. When a child process locally has idle tasks to run, it
+ * requests idle time from the scheduler. Initially requests go to a wait list
+ * and the scheduler runs and if there are free logical cores for the child
+ * processes, idle time is given to the child process, and the process goes to
+ * the idle list. Once idle time has been consumed or there are no tasks to
+ * process, child process informs the scheduler and the process is moved back
+ * to the default queue.
+ */
+async protocol PIdleScheduler
+{
+ manager PBackground;
+
+child:
+ async IdleTime(uint64_t id, TimeDuration budget);
+
+parent:
+ async InitForIdleUse() returns (SharedMemoryHandle? state, uint32_t childId);
+ async RequestIdleTime(uint64_t id, TimeDuration budget);
+ async IdleTimeUsed(uint64_t id);
+
+ // Child can send explicit Schedule message to parent if it thinks parent process
+ // might be able to let some other process to use idle time.
+ async Schedule();
+
+ // Note, these two messages can be sent even before InitForIdleUse.
+ async RunningPrioritizedOperation();
+ async PrioritizedOperationDone();
+
+ // Ask if now would be a good time to GC
+ async RequestGC() returns (bool may_gc);
+
+ // Let the parent know when we start a GC without asking first.
+ async StartedGC();
+
+ // Called for ending any kind of GC.
+ async DoneGC();
+
+ // This message is never sent. Each PIdleScheduler actor will stay alive as long as
+ // its PBackground manager.
+ async __delete__();
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/PUtilityAudioDecoder.ipdl b/ipc/glue/PUtilityAudioDecoder.ipdl
new file mode 100644
index 0000000000..74dbbd2c54
--- /dev/null
+++ b/ipc/glue/PUtilityAudioDecoder.ipdl
@@ -0,0 +1,57 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include GraphicsMessages;
+include protocol PRemoteDecoderManager;
+include protocol PVideoBridge;
+
+using mozilla::dom::ContentParentId from "mozilla/dom/ipc/IdType.h";
+using mozilla::media::MediaCodecsSupported from "MediaCodecsSupport.h";
+using mozilla::RemoteDecodeIn from "mozilla/RemoteDecoderManagerChild.h";
+
+#ifdef MOZ_WMF_CDM
+using mozilla::MFCDMCapabilitiesIPDL from "mozilla/PMFCDM.h";
+#endif
+
+namespace mozilla {
+
+namespace ipc {
+
+// This protocol allows to run media audio decoding infrastructure on top
+// of the Utility process
+[ParentProc=Utility, ChildProc=Parent]
+protocol PUtilityAudioDecoder
+{
+parent:
+ async NewContentRemoteDecoderManager(
+ Endpoint<PRemoteDecoderManagerParent> endpoint, ContentParentId parentId);
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ async InitVideoBridge(Endpoint<PVideoBridgeChild> endpoint,
+ GfxVarUpdate[] updates,
+ ContentDeviceData contentDeviceData);
+
+ async UpdateVar(GfxVarUpdate var);
+#endif
+
+#ifdef MOZ_WMF_CDM
+ async GetKeySystemCapabilities() returns (MFCDMCapabilitiesIPDL[] result);
+
+ async UpdateWidevineL1Path(nsString path);
+#endif
+
+child:
+ async UpdateMediaCodecsSupported(RemoteDecodeIn aLocation,
+ MediaCodecsSupported aSupported);
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ async CompleteCreatedVideoBridge();
+#endif
+
+};
+
+} // namespace ipc
+
+} // namespace mozilla
diff --git a/ipc/glue/PUtilityProcess.ipdl b/ipc/glue/PUtilityProcess.ipdl
new file mode 100644
index 0000000000..585590799f
--- /dev/null
+++ b/ipc/glue/PUtilityProcess.ipdl
@@ -0,0 +1,126 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include MemoryReportTypes;
+include PrefsTypes;
+
+include protocol PProfiler;
+include protocol PUtilityAudioDecoder;
+include protocol PJSOracle;
+
+#if defined(XP_WIN)
+include protocol PWindowsUtils;
+include protocol PWinFileDialog;
+#endif
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+include protocol PSandboxTesting;
+#endif
+
+include "mozilla/ipc/ByteBufUtils.h";
+
+using mozilla::dom::NativeThreadId from "mozilla/dom/NativeThreadId.h";
+
+// Telemetry
+using mozilla::Telemetry::HistogramAccumulation from "mozilla/TelemetryComms.h";
+using mozilla::Telemetry::KeyedHistogramAccumulation from "mozilla/TelemetryComms.h";
+using mozilla::Telemetry::ScalarAction from "mozilla/TelemetryComms.h";
+using mozilla::Telemetry::KeyedScalarAction from "mozilla/TelemetryComms.h";
+using mozilla::Telemetry::ChildEventData from "mozilla/TelemetryComms.h";
+using mozilla::Telemetry::DiscardedData from "mozilla/TelemetryComms.h";
+
+#if defined(XP_WIN)
+[MoveOnly] using mozilla::UntrustedModulesData from "mozilla/UntrustedModulesData.h";
+[MoveOnly] using mozilla::ModulePaths from "mozilla/UntrustedModulesData.h";
+[MoveOnly] using mozilla::ModulesMapResult from "mozilla/UntrustedModulesData.h";
+#endif // defined(XP_WIN)
+
+namespace mozilla {
+
+namespace ipc {
+
+// This protocol allows the UI process to talk to the Utility process. There is
+// one instance of this protocol, with the UtilityProcessParent living on the main thread
+// of the main process and the UtilityProcessChild living on the main thread of the Utility
+// process.
+[NeedsOtherPid, ChildProc=Utility]
+protocol PUtilityProcess
+{
+parent:
+ async InitCrashReporter(NativeThreadId threadId);
+
+ async AddMemoryReport(MemoryReport aReport);
+
+ // Sent from time-to-time to limit the amount of telemetry vulnerable to loss
+ // Buffer contains bincoded Rust structs.
+ // https://firefox-source-docs.mozilla.org/toolkit/components/glean/dev/ipc.html
+ async FOGData(ByteBuf buf);
+
+#if defined(XP_WIN)
+ async GetModulesTrust(ModulePaths aModPaths, bool aRunAtNormalPriority)
+ returns (ModulesMapResult? modMapResult);
+#endif // defined(XP_WIN)
+
+ // Messages for sending telemetry to parent process.
+ async AccumulateChildHistograms(HistogramAccumulation[] accumulations);
+ async AccumulateChildKeyedHistograms(KeyedHistogramAccumulation[] accumulations);
+ async UpdateChildScalars(ScalarAction[] actions);
+ async UpdateChildKeyedScalars(KeyedScalarAction[] actions);
+ async RecordChildEvents(ChildEventData[] events);
+ async RecordDiscardedData(DiscardedData data);
+
+ async InitCompleted();
+
+child:
+ async Init(FileDescriptor? sandboxBroker, bool canRecordReleaseTelemetry, bool aIsReadyForBackgroundProcessing);
+
+ async InitProfiler(Endpoint<PProfilerChild> endpoint);
+
+ async RequestMemoryReport(uint32_t generation,
+ bool anonymize,
+ bool minimizeMemoryUsage,
+ FileDescriptor? DMDFile)
+ returns (uint32_t aGeneration);
+
+ async PreferenceUpdate(Pref pref);
+
+ // Tells the Utility process to flush any pending telemetry.
+ // Used in tests and ping assembly. Buffer contains bincoded Rust structs.
+ // https://firefox-source-docs.mozilla.org/toolkit/components/glean/dev/ipc.html
+ async FlushFOGData() returns (ByteBuf buf);
+
+ // Test-only method.
+ // Asks the Utility process to trigger test-only instrumentation.
+ // The unused returned value is to have a promise we can await.
+ async TestTriggerMetrics() returns (bool unused);
+
+ async TestTelemetryProbes();
+
+ async StartUtilityAudioDecoderService(Endpoint<PUtilityAudioDecoderParent> aEndpoint);
+
+ async StartJSOracleService(Endpoint<PJSOracleChild> aEndpoint);
+
+#if defined(XP_WIN)
+ async StartWindowsUtilsService(Endpoint<PWindowsUtilsChild> aEndpoint);
+ async StartWinFileDialogService(Endpoint<PWinFileDialogChild> aEndpoint);
+
+ async GetUntrustedModulesData() returns (UntrustedModulesData? data);
+
+ /**
+ * This method is used to notify a child process to start
+ * processing module loading events in UntrustedModulesProcessor.
+ * This should be called when the parent process has gone idle.
+ */
+ async UnblockUntrustedModulesThread();
+#endif // defined(XP_WIN)
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+ async InitSandboxTesting(Endpoint<PSandboxTestingChild> aEndpoint);
+#endif
+};
+
+} // namespace ipc
+
+} // namespace mozilla
diff --git a/ipc/glue/ProcessChild.cpp b/ipc/glue/ProcessChild.cpp
new file mode 100644
index 0000000000..724d2b09bf
--- /dev/null
+++ b/ipc/glue/ProcessChild.cpp
@@ -0,0 +1,137 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/ProcessChild.h"
+
+#include "Endpoint.h"
+#include "nsDebug.h"
+
+#ifdef XP_WIN
+# include <stdlib.h> // for _exit()
+# include <synchapi.h>
+#else
+# include <unistd.h> // for _exit()
+# include <time.h>
+# include "base/eintr_wrapper.h"
+# include "prenv.h"
+#endif
+
+#include "nsAppRunner.h"
+#include "mozilla/AppShutdown.h"
+#include "mozilla/ipc/CrashReporterClient.h"
+#include "mozilla/ipc/IOThreadChild.h"
+#include "mozilla/GeckoArgs.h"
+
+namespace mozilla {
+namespace ipc {
+
+ProcessChild* ProcessChild::gProcessChild;
+
+static Atomic<bool> sExpectingShutdown(false);
+
+ProcessChild::ProcessChild(ProcessId aParentPid, const nsID& aMessageChannelId)
+ : ChildProcess(new IOThreadChild(aParentPid)),
+ mUILoop(MessageLoop::current()),
+ mParentPid(aParentPid),
+ mMessageChannelId(aMessageChannelId) {
+ MOZ_ASSERT(mUILoop, "UILoop should be created by now");
+ MOZ_ASSERT(!gProcessChild, "should only be one ProcessChild");
+ gProcessChild = this;
+}
+
+/* static */
+void ProcessChild::AddPlatformBuildID(std::vector<std::string>& aExtraArgs) {
+ nsCString parentBuildID(mozilla::PlatformBuildID());
+ geckoargs::sParentBuildID.Put(parentBuildID.get(), aExtraArgs);
+}
+
+/* static */
+bool ProcessChild::InitPrefs(int aArgc, char* aArgv[]) {
+ Maybe<uint64_t> prefsHandle = Some(0);
+ Maybe<uint64_t> prefMapHandle = Some(0);
+ Maybe<uint64_t> prefsLen = geckoargs::sPrefsLen.Get(aArgc, aArgv);
+ Maybe<uint64_t> prefMapSize = geckoargs::sPrefMapSize.Get(aArgc, aArgv);
+
+ if (prefsLen.isNothing() || prefMapSize.isNothing()) {
+ return false;
+ }
+
+#ifdef XP_WIN
+ prefsHandle = geckoargs::sPrefsHandle.Get(aArgc, aArgv);
+ prefMapHandle = geckoargs::sPrefMapHandle.Get(aArgc, aArgv);
+
+ if (prefsHandle.isNothing() || prefMapHandle.isNothing()) {
+ return false;
+ }
+#endif
+
+ SharedPreferenceDeserializer deserializer;
+ return deserializer.DeserializeFromSharedMemory(*prefsHandle, *prefMapHandle,
+ *prefsLen, *prefMapSize);
+}
+
+#ifdef ENABLE_TESTS
+// Allow tests to cause a synthetic delay/"hang" during child process
+// shutdown by setting environment variables.
+# ifdef XP_UNIX
+static void ReallySleep(int aSeconds) {
+ struct ::timespec snooze = {aSeconds, 0};
+ HANDLE_EINTR(nanosleep(&snooze, &snooze));
+}
+# else
+static void ReallySleep(int aSeconds) { ::Sleep(aSeconds * 1000); }
+# endif // Unix/Win
+static void SleepIfEnv(const char* aName) {
+ if (auto* value = PR_GetEnv(aName)) {
+ ReallySleep(atoi(value));
+ }
+}
+#else // not tests
+static void SleepIfEnv(const char* aName) {}
+#endif
+
+ProcessChild::~ProcessChild() {
+#ifdef NS_FREE_PERMANENT_DATA
+ // In this case, we won't early-exit and we'll wait indefinitely for
+ // child processes to terminate. This sleep is late enough that, in
+ // content processes, it won't block parent process shutdown, so
+ // we'll get into late IPC shutdown with processes still running.
+ SleepIfEnv("MOZ_TEST_CHILD_EXIT_HANG");
+#endif
+ gProcessChild = nullptr;
+}
+
+/* static */
+void ProcessChild::NotifiedImpendingShutdown() {
+ sExpectingShutdown = true;
+ CrashReporter::AppendToCrashReportAnnotation(
+ CrashReporter::Annotation::IPCShutdownState,
+ "NotifiedImpendingShutdown"_ns);
+}
+
+/* static */
+bool ProcessChild::ExpectingShutdown() { return sExpectingShutdown; }
+
+/* static */
+void ProcessChild::QuickExit() {
+#ifndef NS_FREE_PERMANENT_DATA
+ // In this case, we're going to terminate the child process before
+ // we get to ~ProcessChild above (and terminate the parent process
+ // before the shutdown hook in ProcessWatcher). Instead, blocking
+ // earlier will let us exercise ProcessWatcher's kill timer.
+ SleepIfEnv("MOZ_TEST_CHILD_EXIT_HANG");
+#endif
+ AppShutdown::DoImmediateExit();
+}
+
+UntypedEndpoint ProcessChild::TakeInitialEndpoint() {
+ return UntypedEndpoint{PrivateIPDLInterface{},
+ child_thread()->TakeInitialPort(), mMessageChannelId,
+ base::GetCurrentProcId(), mParentPid};
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProcessChild.h b/ipc/glue/ProcessChild.h
new file mode 100644
index 0000000000..29948a9127
--- /dev/null
+++ b/ipc/glue/ProcessChild.h
@@ -0,0 +1,75 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_ProcessChild_h
+#define mozilla_ipc_ProcessChild_h
+
+#include "Endpoint.h"
+#include "base/message_loop.h"
+#include "base/process.h"
+
+#include "chrome/common/child_process.h"
+
+#include "mozilla/ipc/ProcessUtils.h"
+
+// ProcessChild is the base class for all subprocesses of the main
+// browser process. Its code runs on the thread that started in
+// main().
+
+namespace mozilla {
+namespace ipc {
+
+class ProcessChild : public ChildProcess {
+ protected:
+ typedef base::ProcessId ProcessId;
+
+ public:
+ explicit ProcessChild(ProcessId aParentPid, const nsID& aMessageChannelId);
+
+ ProcessChild(const ProcessChild&) = delete;
+ ProcessChild& operator=(const ProcessChild&) = delete;
+
+ virtual ~ProcessChild();
+
+ virtual bool Init(int aArgc, char* aArgv[]) = 0;
+
+ static void AddPlatformBuildID(std::vector<std::string>& aExtraArgs);
+
+ static bool InitPrefs(int aArgc, char* aArgv[]);
+
+ virtual void CleanUp() {}
+
+ static MessageLoop* message_loop() { return gProcessChild->mUILoop; }
+
+ static void NotifiedImpendingShutdown();
+
+ static bool ExpectingShutdown();
+
+ /**
+ * Exit *now*. Do not shut down XPCOM, do not pass Go, do not run
+ * static destructors, do not collect $200.
+ */
+ static void QuickExit();
+
+ protected:
+ static ProcessChild* current() { return gProcessChild; }
+
+ ProcessId ParentPid() { return mParentPid; }
+
+ UntypedEndpoint TakeInitialEndpoint();
+
+ private:
+ static ProcessChild* gProcessChild;
+
+ MessageLoop* mUILoop;
+ ProcessId mParentPid;
+ nsID mMessageChannelId;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_ProcessChild_h
diff --git a/ipc/glue/ProcessUtils.h b/ipc/glue/ProcessUtils.h
new file mode 100644
index 0000000000..b0f146ef6d
--- /dev/null
+++ b/ipc/glue/ProcessUtils.h
@@ -0,0 +1,93 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_ProcessUtils_h
+#define mozilla_ipc_ProcessUtils_h
+
+#include <functional>
+#include <vector>
+
+#include "mozilla/ipc/FileDescriptor.h"
+#include "base/shared_memory.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Preferences.h"
+#include "nsXULAppAPI.h"
+
+namespace mozilla {
+namespace ipc {
+
+class GeckoChildProcessHost;
+
+// You probably should call ContentChild::SetProcessName instead of calling
+// this directly.
+void SetThisProcessName(const char* aName);
+
+class SharedPreferenceSerializer final {
+ public:
+ explicit SharedPreferenceSerializer();
+ SharedPreferenceSerializer(SharedPreferenceSerializer&& aOther);
+ ~SharedPreferenceSerializer();
+
+ bool SerializeToSharedMemory(const GeckoProcessType aDestinationProcessType,
+ const nsACString& aDestinationRemoteType);
+
+ size_t GetPrefMapSize() const { return mPrefMapSize; }
+ size_t GetPrefsLength() const { return mPrefsLength; }
+
+ const UniqueFileHandle& GetPrefsHandle() const { return mPrefsHandle; }
+
+ const UniqueFileHandle& GetPrefMapHandle() const { return mPrefMapHandle; }
+
+ void AddSharedPrefCmdLineArgs(GeckoChildProcessHost& procHost,
+ std::vector<std::string>& aExtraOpts) const;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SharedPreferenceSerializer);
+ size_t mPrefMapSize;
+ size_t mPrefsLength;
+ UniqueFileHandle mPrefMapHandle;
+ UniqueFileHandle mPrefsHandle;
+};
+
+class SharedPreferenceDeserializer final {
+ public:
+ SharedPreferenceDeserializer();
+ ~SharedPreferenceDeserializer();
+
+ bool DeserializeFromSharedMemory(uint64_t aPrefsHandle,
+ uint64_t aPrefMapHandle, uint64_t aPrefsLen,
+ uint64_t aPrefMapSize);
+
+ const FileDescriptor& GetPrefMapHandle() const;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SharedPreferenceDeserializer);
+ Maybe<FileDescriptor> mPrefMapHandle;
+ Maybe<size_t> mPrefsLen;
+ Maybe<size_t> mPrefMapSize;
+ base::SharedMemory mShmem;
+};
+
+#ifdef ANDROID
+// Android doesn't use -prefsHandle or -prefMapHandle. It gets those FDs
+// another way.
+void SetPrefsFd(int aFd);
+void SetPrefMapFd(int aFd);
+#endif
+
+// Generate command line argument to spawn a child process. If the shared memory
+// is not properly initialized, this would be a no-op.
+void ExportSharedJSInit(GeckoChildProcessHost& procHost,
+ std::vector<std::string>& aExtraOpts);
+
+// Initialize the content used by the JS engine during the initialization of a
+// JS::Runtime.
+bool ImportSharedJSInit(uint64_t aJsInitHandle, uint64_t aJsInitLen);
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_ProcessUtils_h
diff --git a/ipc/glue/ProcessUtils_bsd.cpp b/ipc/glue/ProcessUtils_bsd.cpp
new file mode 100644
index 0000000000..12dfa15c6f
--- /dev/null
+++ b/ipc/glue/ProcessUtils_bsd.cpp
@@ -0,0 +1,27 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProcessUtils.h"
+
+#include <pthread.h>
+
+#if !defined(XP_NETBSD)
+# include <pthread_np.h>
+#endif
+
+namespace mozilla {
+namespace ipc {
+
+void SetThisProcessName(const char* aName) {
+#if defined(XP_NETBSD)
+ pthread_setname_np(pthread_self(), "%s", (void*)aName);
+#else
+ pthread_set_name_np(pthread_self(), aName);
+#endif
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProcessUtils_common.cpp b/ipc/glue/ProcessUtils_common.cpp
new file mode 100644
index 0000000000..69eb4bdf28
--- /dev/null
+++ b/ipc/glue/ProcessUtils_common.cpp
@@ -0,0 +1,275 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProcessUtils.h"
+
+#include "mozilla/Preferences.h"
+#include "mozilla/GeckoArgs.h"
+#include "mozilla/dom/RemoteType.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+#include "mozilla/UniquePtrExtensions.h"
+#include "nsPrintfCString.h"
+
+#include "XPCSelfHostedShmem.h"
+
+namespace mozilla {
+namespace ipc {
+
+SharedPreferenceSerializer::SharedPreferenceSerializer()
+ : mPrefMapSize(0), mPrefsLength(0) {
+ MOZ_COUNT_CTOR(SharedPreferenceSerializer);
+}
+
+SharedPreferenceSerializer::~SharedPreferenceSerializer() {
+ MOZ_COUNT_DTOR(SharedPreferenceSerializer);
+}
+
+SharedPreferenceSerializer::SharedPreferenceSerializer(
+ SharedPreferenceSerializer&& aOther)
+ : mPrefMapSize(aOther.mPrefMapSize),
+ mPrefsLength(aOther.mPrefsLength),
+ mPrefMapHandle(std::move(aOther.mPrefMapHandle)),
+ mPrefsHandle(std::move(aOther.mPrefsHandle)) {
+ MOZ_COUNT_CTOR(SharedPreferenceSerializer);
+}
+
+bool SharedPreferenceSerializer::SerializeToSharedMemory(
+ const GeckoProcessType aDestinationProcessType,
+ const nsACString& aDestinationRemoteType) {
+ mPrefMapHandle =
+ Preferences::EnsureSnapshot(&mPrefMapSize).TakePlatformHandle();
+
+ bool destIsWebContent =
+ aDestinationProcessType == GeckoProcessType_Content &&
+ (StringBeginsWith(aDestinationRemoteType, WEB_REMOTE_TYPE) ||
+ StringBeginsWith(aDestinationRemoteType, PREALLOC_REMOTE_TYPE));
+
+ // Serialize the early prefs.
+ nsAutoCStringN<1024> prefs;
+ Preferences::SerializePreferences(prefs, destIsWebContent);
+ mPrefsLength = prefs.Length();
+
+ base::SharedMemory shm;
+ // Set up the shared memory.
+ if (!shm.Create(prefs.Length())) {
+ NS_ERROR("failed to create shared memory in the parent");
+ return false;
+ }
+ if (!shm.Map(prefs.Length())) {
+ NS_ERROR("failed to map shared memory in the parent");
+ return false;
+ }
+
+ // Copy the serialized prefs into the shared memory.
+ memcpy(static_cast<char*>(shm.memory()), prefs.get(), mPrefsLength);
+
+ mPrefsHandle = shm.TakeHandle();
+ return true;
+}
+
+void SharedPreferenceSerializer::AddSharedPrefCmdLineArgs(
+ mozilla::ipc::GeckoChildProcessHost& procHost,
+ std::vector<std::string>& aExtraOpts) const {
+#if defined(XP_WIN)
+ // Record the handle as to-be-shared, and pass it via a command flag. This
+ // works because Windows handles are system-wide.
+ procHost.AddHandleToShare(GetPrefsHandle().get());
+ procHost.AddHandleToShare(GetPrefMapHandle().get());
+ geckoargs::sPrefsHandle.Put((uintptr_t)(GetPrefsHandle().get()), aExtraOpts);
+ geckoargs::sPrefMapHandle.Put((uintptr_t)(GetPrefMapHandle().get()),
+ aExtraOpts);
+#else
+ // In contrast, Unix fds are per-process. So remap the fd to a fixed one that
+ // will be used in the child.
+ // XXX: bug 1440207 is about improving how fixed fds are used.
+ //
+ // Note: on Android, AddFdToRemap() sets up the fd to be passed via a Parcel,
+ // and the fixed fd isn't used. However, we still need to mark it for
+ // remapping so it doesn't get closed in the child.
+ procHost.AddFdToRemap(GetPrefsHandle().get(), kPrefsFileDescriptor);
+ procHost.AddFdToRemap(GetPrefMapHandle().get(), kPrefMapFileDescriptor);
+#endif
+
+ // Pass the lengths via command line flags.
+ geckoargs::sPrefsLen.Put((uintptr_t)(GetPrefsLength()), aExtraOpts);
+ geckoargs::sPrefMapSize.Put((uintptr_t)(GetPrefMapSize()), aExtraOpts);
+}
+
+#ifdef ANDROID
+static int gPrefsFd = -1;
+static int gPrefMapFd = -1;
+
+void SetPrefsFd(int aFd) { gPrefsFd = aFd; }
+
+void SetPrefMapFd(int aFd) { gPrefMapFd = aFd; }
+#endif
+
+SharedPreferenceDeserializer::SharedPreferenceDeserializer() {
+ MOZ_COUNT_CTOR(SharedPreferenceDeserializer);
+}
+
+SharedPreferenceDeserializer::~SharedPreferenceDeserializer() {
+ MOZ_COUNT_DTOR(SharedPreferenceDeserializer);
+}
+
+bool SharedPreferenceDeserializer::DeserializeFromSharedMemory(
+ uint64_t aPrefsHandle, uint64_t aPrefMapHandle, uint64_t aPrefsLen,
+ uint64_t aPrefMapSize) {
+ Maybe<base::SharedMemoryHandle> prefsHandle;
+
+#ifdef XP_WIN
+ prefsHandle = Some(UniqueFileHandle(HANDLE((uintptr_t)(aPrefsHandle))));
+ if (!aPrefsHandle) {
+ return false;
+ }
+
+ FileDescriptor::UniquePlatformHandle handle(
+ HANDLE((uintptr_t)(aPrefMapHandle)));
+ if (!aPrefMapHandle) {
+ return false;
+ }
+
+ mPrefMapHandle.emplace(std::move(handle));
+#endif
+
+ mPrefsLen = Some((uintptr_t)(aPrefsLen));
+ if (!aPrefsLen) {
+ return false;
+ }
+
+ mPrefMapSize = Some((uintptr_t)(aPrefMapSize));
+ if (!aPrefMapSize) {
+ return false;
+ }
+
+#ifdef ANDROID
+ // Android is different; get the FD via gPrefsFd instead of a fixed fd.
+ MOZ_RELEASE_ASSERT(gPrefsFd != -1);
+ prefsHandle = Some(UniqueFileHandle(gPrefsFd));
+
+ mPrefMapHandle.emplace(UniqueFileHandle(gPrefMapFd));
+#elif XP_UNIX
+ prefsHandle = Some(UniqueFileHandle(kPrefsFileDescriptor));
+
+ mPrefMapHandle.emplace(UniqueFileHandle(kPrefMapFileDescriptor));
+#endif
+
+ if (prefsHandle.isNothing() || mPrefsLen.isNothing() ||
+ mPrefMapHandle.isNothing() || mPrefMapSize.isNothing()) {
+ return false;
+ }
+
+ // Init the shared-memory base preference mapping first, so that only changed
+ // preferences wind up in heap memory.
+ Preferences::InitSnapshot(mPrefMapHandle.ref(), *mPrefMapSize);
+
+ // Set up early prefs from the shared memory.
+ if (!mShmem.SetHandle(std::move(*prefsHandle), /* read_only */ true)) {
+ NS_ERROR("failed to open shared memory in the child");
+ return false;
+ }
+ if (!mShmem.Map(*mPrefsLen)) {
+ NS_ERROR("failed to map shared memory in the child");
+ return false;
+ }
+ Preferences::DeserializePreferences(static_cast<char*>(mShmem.memory()),
+ *mPrefsLen);
+
+ return true;
+}
+
+const FileDescriptor& SharedPreferenceDeserializer::GetPrefMapHandle() const {
+ MOZ_ASSERT(mPrefMapHandle.isSome());
+
+ return mPrefMapHandle.ref();
+}
+
+#ifdef XP_UNIX
+// On Unix, file descriptors are per-process. This value is used when mapping
+// a parent process handle to a content process handle.
+static const int kJSInitFileDescriptor = 11;
+#endif
+
+void ExportSharedJSInit(mozilla::ipc::GeckoChildProcessHost& procHost,
+ std::vector<std::string>& aExtraOpts) {
+#ifdef ANDROID
+ // The code to support Android is added in a follow-up patch.
+ return;
+#else
+ auto& shmem = xpc::SelfHostedShmem::GetSingleton();
+ const mozilla::UniqueFileHandle& uniqHandle = shmem.Handle();
+ size_t len = shmem.Content().Length();
+
+ // If the file is not found or the content is empty, then we would start the
+ // content process without this optimization.
+ if (!uniqHandle || !len) {
+ return;
+ }
+
+ mozilla::detail::FileHandleType handle = uniqHandle.get();
+ // command line: [-jsInitHandle handle] -jsInitLen length
+# if defined(XP_WIN)
+ // Record the handle as to-be-shared, and pass it via a command flag.
+ procHost.AddHandleToShare(HANDLE(handle));
+ geckoargs::sJsInitHandle.Put((uintptr_t)(HANDLE(handle)), aExtraOpts);
+# else
+ // In contrast, Unix fds are per-process. So remap the fd to a fixed one that
+ // will be used in the child.
+ // XXX: bug 1440207 is about improving how fixed fds are used.
+ //
+ // Note: on Android, AddFdToRemap() sets up the fd to be passed via a Parcel,
+ // and the fixed fd isn't used. However, we still need to mark it for
+ // remapping so it doesn't get closed in the child.
+ procHost.AddFdToRemap(handle, kJSInitFileDescriptor);
+# endif
+
+ // Pass the lengths via command line flags.
+ geckoargs::sJsInitLen.Put((uintptr_t)(len), aExtraOpts);
+#endif
+}
+
+bool ImportSharedJSInit(uint64_t aJsInitHandle, uint64_t aJsInitLen) {
+ // This is an optimization, and as such we can safely recover if the command
+ // line argument are not provided.
+ if (!aJsInitLen) {
+ return true;
+ }
+
+#ifdef XP_WIN
+ if (!aJsInitHandle) {
+ return true;
+ }
+#endif
+
+#ifdef XP_WIN
+ base::SharedMemoryHandle handle(HANDLE((uintptr_t)(aJsInitHandle)));
+ if (!aJsInitHandle) {
+ return false;
+ }
+#endif
+
+ size_t len = (uintptr_t)(aJsInitLen);
+ if (!aJsInitLen) {
+ return false;
+ }
+
+#ifdef XP_UNIX
+ auto handle = UniqueFileHandle(kJSInitFileDescriptor);
+#endif
+
+ // Initialize the shared memory with the file handle and size of the content
+ // of the self-hosted Xdr.
+ auto& shmem = xpc::SelfHostedShmem::GetSingleton();
+ if (!shmem.InitFromChild(std::move(handle), len)) {
+ NS_ERROR("failed to open shared memory in the child");
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProcessUtils_linux.cpp b/ipc/glue/ProcessUtils_linux.cpp
new file mode 100644
index 0000000000..da15745753
--- /dev/null
+++ b/ipc/glue/ProcessUtils_linux.cpp
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProcessUtils.h"
+
+#include "nsString.h"
+
+#include <sys/prctl.h>
+
+namespace mozilla {
+
+namespace ipc {
+
+void SetThisProcessName(const char* aName) {
+ prctl(PR_SET_NAME, (unsigned long)aName, 0uL, 0uL, 0uL);
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProcessUtils_mac.mm b/ipc/glue/ProcessUtils_mac.mm
new file mode 100644
index 0000000000..e850c486aa
--- /dev/null
+++ b/ipc/glue/ProcessUtils_mac.mm
@@ -0,0 +1,116 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProcessUtils.h"
+
+#include "nsObjCExceptions.h"
+#include "nsCocoaUtils.h"
+#include "nsString.h"
+#include "mozilla/Sprintf.h"
+
+#define UNDOCUMENTED_SESSION_CONSTANT ((int)-2)
+
+namespace mozilla {
+namespace ipc {
+
+static void* sApplicationASN = NULL;
+static void* sApplicationInfoItem = NULL;
+
+void SetThisProcessName(const char* aProcessName) {
+ NS_OBJC_BEGIN_TRY_ABORT_BLOCK;
+ nsAutoreleasePool localPool;
+
+ if (!aProcessName || strcmp(aProcessName, "") == 0) {
+ return;
+ }
+
+ NSString* currentName = [[[NSBundle mainBundle] localizedInfoDictionary]
+ objectForKey:(NSString*)kCFBundleNameKey];
+
+ char formattedName[1024];
+ SprintfLiteral(formattedName, "%s %s", [currentName UTF8String],
+ aProcessName);
+
+ aProcessName = formattedName;
+
+ // This function is based on Chrome/Webkit's and relies on potentially
+ // dangerous SPI.
+ typedef CFTypeRef (*LSGetASNType)();
+ typedef OSStatus (*LSSetInformationItemType)(int, CFTypeRef, CFStringRef,
+ CFStringRef, CFDictionaryRef*);
+
+ CFBundleRef launchServices =
+ ::CFBundleGetBundleWithIdentifier(CFSTR("com.apple.LaunchServices"));
+ if (!launchServices) {
+ NS_WARNING(
+ "Failed to set process name: Could not open LaunchServices bundle");
+ return;
+ }
+
+ if (!sApplicationASN) {
+ sApplicationASN = ::CFBundleGetFunctionPointerForName(
+ launchServices, CFSTR("_LSGetCurrentApplicationASN"));
+ if (!sApplicationASN) {
+ NS_WARNING("Failed to set process name: Could not get function pointer "
+ "for LaunchServices");
+ return;
+ }
+ }
+
+ LSGetASNType getASNFunc = reinterpret_cast<LSGetASNType>(sApplicationASN);
+
+ if (!sApplicationInfoItem) {
+ sApplicationInfoItem = ::CFBundleGetFunctionPointerForName(
+ launchServices, CFSTR("_LSSetApplicationInformationItem"));
+ }
+
+ LSSetInformationItemType setInformationItemFunc =
+ reinterpret_cast<LSSetInformationItemType>(sApplicationInfoItem);
+
+ void* displayNameKeyAddr = ::CFBundleGetDataPointerForName(
+ launchServices, CFSTR("_kLSDisplayNameKey"));
+
+ CFStringRef displayNameKey = nil;
+ if (displayNameKeyAddr) {
+ displayNameKey =
+ reinterpret_cast<CFStringRef>(*(CFStringRef*)displayNameKeyAddr);
+ }
+
+ // We need this to ensure we have a connection to the Process Manager, not
+ // doing so will silently fail and process name wont be updated.
+ ProcessSerialNumber psn;
+ if (::GetCurrentProcess(&psn) != noErr) {
+ return;
+ }
+
+ CFTypeRef currentAsn = getASNFunc ? getASNFunc() : nullptr;
+
+ if (!getASNFunc || !setInformationItemFunc || !displayNameKey ||
+ !currentAsn) {
+ NS_WARNING("Failed to set process name: Accessing launchServices failed");
+ return;
+ }
+
+ CFStringRef processName =
+ ::CFStringCreateWithCString(nil, aProcessName, kCFStringEncodingASCII);
+ if (!processName) {
+ NS_WARNING("Failed to set process name: Could not create CFStringRef");
+ return;
+ }
+
+ OSErr err = setInformationItemFunc(UNDOCUMENTED_SESSION_CONSTANT, currentAsn,
+ displayNameKey, processName,
+ nil); // Optional out param
+ ::CFRelease(processName);
+ if (err != noErr) {
+ NS_WARNING("Failed to set process name: LSSetInformationItemType err");
+ return;
+ }
+
+ return;
+ NS_OBJC_END_TRY_ABORT_BLOCK;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProcessUtils_none.cpp b/ipc/glue/ProcessUtils_none.cpp
new file mode 100644
index 0000000000..49566a0720
--- /dev/null
+++ b/ipc/glue/ProcessUtils_none.cpp
@@ -0,0 +1,15 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProcessUtils.h"
+
+namespace mozilla {
+namespace ipc {
+
+void SetThisProcessName(const char* aString) { (void)aString; }
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProtocolMessageUtils.h b/ipc/glue/ProtocolMessageUtils.h
new file mode 100644
index 0000000000..48485596ea
--- /dev/null
+++ b/ipc/glue/ProtocolMessageUtils.h
@@ -0,0 +1,121 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef IPC_GLUE_PROTOCOLMESSAGEUTILS_H
+#define IPC_GLUE_PROTOCOLMESSAGEUTILS_H
+
+#include <stdint.h>
+#include <string>
+#include "base/string_util.h"
+#include "chrome/common/ipc_channel.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "ipc/EnumSerializer.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+class PickleIterator;
+
+namespace mozilla::ipc {
+class FileDescriptor;
+template <class PFooSide>
+class Endpoint;
+template <class PFooSide>
+class ManagedEndpoint;
+template <typename P>
+struct IPDLParamTraits;
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+class Message;
+class MessageReader;
+class MessageWriter;
+
+template <>
+struct ParamTraits<Channel::Mode>
+ : ContiguousEnumSerializerInclusive<Channel::Mode, Channel::MODE_SERVER,
+ Channel::MODE_CLIENT> {};
+
+template <>
+struct ParamTraits<IPCMessageStart>
+ : ContiguousEnumSerializer<IPCMessageStart, IPCMessageStart(0),
+ LastMsgIndex> {};
+
+template <>
+struct ParamTraits<mozilla::ipc::ActorHandle> {
+ typedef mozilla::ipc::ActorHandle paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ IPC::WriteParam(aWriter, aParam.mId);
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ int id;
+ if (IPC::ReadParam(aReader, &id)) {
+ aResult->mId = id;
+ return true;
+ }
+ return false;
+ }
+};
+
+template <>
+struct ParamTraits<mozilla::ipc::UntypedEndpoint> {
+ using paramType = mozilla::ipc::UntypedEndpoint;
+
+ static void Write(MessageWriter* aWriter, paramType&& aParam);
+
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+template <class PFooSide>
+struct ParamTraits<mozilla::ipc::Endpoint<PFooSide>>
+ : ParamTraits<mozilla::ipc::UntypedEndpoint> {};
+
+} // namespace IPC
+
+namespace mozilla::ipc {
+
+template <>
+struct IPDLParamTraits<UntypedManagedEndpoint> {
+ using paramType = UntypedManagedEndpoint;
+
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ paramType&& aParam);
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ paramType* aResult);
+};
+
+template <class PFooSide>
+struct IPDLParamTraits<ManagedEndpoint<PFooSide>> {
+ using paramType = ManagedEndpoint<PFooSide>;
+
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ paramType&& aParam) {
+ IPDLParamTraits<UntypedManagedEndpoint>::Write(aWriter, aActor,
+ std::move(aParam));
+ }
+
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ paramType* aResult) {
+ return IPDLParamTraits<UntypedManagedEndpoint>::Read(aReader, aActor,
+ aResult);
+ }
+};
+
+template <>
+struct IPDLParamTraits<FileDescriptor> {
+ typedef FileDescriptor paramType;
+
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ const paramType& aParam);
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ paramType* aResult);
+};
+} // namespace mozilla::ipc
+
+#endif // IPC_GLUE_PROTOCOLMESSAGEUTILS_H
diff --git a/ipc/glue/ProtocolTypes.ipdlh b/ipc/glue/ProtocolTypes.ipdlh
new file mode 100644
index 0000000000..b1d5316731
--- /dev/null
+++ b/ipc/glue/ProtocolTypes.ipdlh
@@ -0,0 +1,21 @@
+/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* vim: set sw=4 ts=8 et tw=80 ft=cpp : */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+using struct nsID
+ from "nsID.h";
+
+namespace mozilla {
+namespace ipc {
+
+struct ProtocolFdMapping
+{
+ uint32_t protocolId;
+ FileDescriptor fd;
+};
+
+}
+}
+
diff --git a/ipc/glue/ProtocolUtils.cpp b/ipc/glue/ProtocolUtils.cpp
new file mode 100644
index 0000000000..bd78dce607
--- /dev/null
+++ b/ipc/glue/ProtocolUtils.cpp
@@ -0,0 +1,849 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "base/process_util.h"
+#include "base/task.h"
+
+#ifdef XP_UNIX
+# include <errno.h>
+#endif
+#include <type_traits>
+
+#include "mozilla/IntegerPrintfMacros.h"
+
+#include "mozilla/ipc/ProtocolMessageUtils.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+#include "mozilla/ipc/MessageChannel.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "mozilla/StaticMutex.h"
+#if defined(DEBUG) || defined(FUZZING)
+# include "mozilla/Tokenizer.h"
+#endif
+#include "mozilla/Unused.h"
+#include "nsPrintfCString.h"
+#include "nsReadableUtils.h"
+
+#if defined(MOZ_SANDBOX) && defined(XP_WIN)
+# include "mozilla/sandboxTarget.h"
+#endif
+
+#if defined(XP_WIN)
+# include "aclapi.h"
+# include "sddl.h"
+#endif
+
+#ifdef FUZZING_SNAPSHOT
+# include "mozilla/fuzzing/IPCFuzzController.h"
+#endif
+
+using namespace IPC;
+
+using base::GetCurrentProcId;
+using base::ProcessHandle;
+using base::ProcessId;
+
+namespace mozilla {
+namespace ipc {
+
+/* static */
+IPCResult IPCResult::FailImpl(NotNull<IProtocol*> actor, const char* where,
+ const char* why) {
+ // Calls top-level protocol to handle the error.
+ nsPrintfCString errorMsg("%s %s\n", where, why);
+ actor->GetIPCChannel()->Listener()->ProcessingError(
+ HasResultCodes::MsgProcessingError, errorMsg.get());
+
+#if defined(DEBUG) && !defined(FUZZING)
+ // We do not expect IPC_FAIL to ever happen in normal operations. If this
+ // happens in DEBUG, we most likely see some behavior during a test we should
+ // really investigate.
+ nsPrintfCString crashMsg(
+ "Use IPC_FAIL only in an "
+ "unrecoverable, unexpected state: %s",
+ errorMsg.get());
+ // We already leak the same information potentially on child process failures
+ // even in release, and here we are only in DEBUG.
+ MOZ_CRASH_UNSAFE(crashMsg.get());
+#else
+ return IPCResult(false);
+#endif
+}
+
+void AnnotateSystemError() {
+ int64_t error = 0;
+#if defined(XP_WIN)
+ error = ::GetLastError();
+#else
+ error = errno;
+#endif
+ if (error) {
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCSystemError,
+ nsPrintfCString("%" PRId64, error));
+ }
+}
+
+#if defined(XP_MACOSX)
+void AnnotateCrashReportWithErrno(CrashReporter::Annotation tag, int error) {
+ CrashReporter::AnnotateCrashReport(tag, error);
+}
+#endif // defined(XP_MACOSX)
+
+#if defined(DEBUG) || defined(FUZZING)
+// If aTopLevelProtocol matches any token in aFilter, return true.
+//
+// aTopLevelProtocol is a protocol name, without the "Parent" / "Child" suffix.
+// aSide indicates whether we're logging parent-side or child-side activity.
+//
+// aFilter is a list of protocol names separated by commas and/or
+// spaces. These may include the "Child" / "Parent" suffix, or omit
+// the suffix to log activity on both sides.
+//
+// This overload is for testability; application code should use the single-
+// argument version (defined in the ProtocolUtils.h) which takes the filter from
+// the environment.
+bool LoggingEnabledFor(const char* aTopLevelProtocol, Side aSide,
+ const char* aFilter) {
+ if (!aFilter) {
+ return false;
+ }
+ if (strcmp(aFilter, "1") == 0) {
+ return true;
+ }
+
+ const char kDelimiters[] = ", ";
+ Tokenizer tokens(aFilter, kDelimiters);
+ Tokenizer::Token t;
+ while (tokens.Next(t)) {
+ if (t.Type() == Tokenizer::TOKEN_WORD) {
+ auto filter = t.AsString();
+
+ // Since aTopLevelProtocol never includes the "Parent" / "Child" suffix,
+ // this will only occur when filter doesn't include it either, meaning
+ // that we should log activity on both sides.
+ if (filter == aTopLevelProtocol) {
+ return true;
+ }
+
+ if (aSide == ParentSide &&
+ StringEndsWith(filter, nsDependentCString("Parent")) &&
+ Substring(filter, 0, filter.Length() - 6) == aTopLevelProtocol) {
+ return true;
+ }
+
+ if (aSide == ChildSide &&
+ StringEndsWith(filter, nsDependentCString("Child")) &&
+ Substring(filter, 0, filter.Length() - 5) == aTopLevelProtocol) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+#endif // defined(DEBUG) || defined(FUZZING)
+
+void LogMessageForProtocol(const char* aTopLevelProtocol,
+ base::ProcessId aOtherPid,
+ const char* aContextDescription, uint32_t aMessageId,
+ MessageDirection aDirection) {
+ nsPrintfCString logMessage(
+ "[time: %" PRId64 "][%" PRIPID "%s%" PRIPID "] [%s] %s %s\n", PR_Now(),
+ base::GetCurrentProcId(),
+ aDirection == MessageDirection::eReceiving ? "<-" : "->", aOtherPid,
+ aTopLevelProtocol, aContextDescription,
+ StringFromIPCMessageType(aMessageId));
+#ifdef ANDROID
+ __android_log_write(ANDROID_LOG_INFO, "GeckoIPC", logMessage.get());
+#endif
+ fputs(logMessage.get(), stderr);
+}
+
+void ProtocolErrorBreakpoint(const char* aMsg) {
+ // Bugs that generate these error messages can be tough to
+ // reproduce. Log always in the hope that someone finds the error
+ // message.
+ printf_stderr("IPDL protocol error: %s\n", aMsg);
+}
+
+void PickleFatalError(const char* aMsg, IProtocol* aActor) {
+ if (aActor) {
+ aActor->FatalError(aMsg);
+ } else {
+ FatalError(aMsg, false);
+ }
+}
+
+void FatalError(const char* aMsg, bool aIsParent) {
+#ifndef FUZZING
+ ProtocolErrorBreakpoint(aMsg);
+#endif
+
+ nsAutoCString formattedMessage("IPDL error: \"");
+ formattedMessage.AppendASCII(aMsg);
+ if (aIsParent) {
+ // We're going to crash the parent process because at this time
+ // there's no other really nice way of getting a minidump out of
+ // this process if we're off the main thread.
+ formattedMessage.AppendLiteral("\". Intentionally crashing.");
+ NS_ERROR(formattedMessage.get());
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::IPCFatalErrorMsg, nsDependentCString(aMsg));
+ AnnotateSystemError();
+#ifndef FUZZING
+ MOZ_CRASH("IPC FatalError in the parent process!");
+#endif
+ } else {
+ formattedMessage.AppendLiteral("\". abort()ing as a result.");
+#ifndef FUZZING
+ MOZ_CRASH_UNSAFE(formattedMessage.get());
+#endif
+ }
+}
+
+void LogicError(const char* aMsg) { MOZ_CRASH_UNSAFE(aMsg); }
+
+void ActorIdReadError(const char* aActorDescription) {
+#ifndef FUZZING
+ MOZ_CRASH_UNSAFE_PRINTF("Error deserializing id for %s", aActorDescription);
+#endif
+}
+
+void BadActorIdError(const char* aActorDescription) {
+ nsPrintfCString message("bad id for %s", aActorDescription);
+ ProtocolErrorBreakpoint(message.get());
+}
+
+void ActorLookupError(const char* aActorDescription) {
+ nsPrintfCString message("could not lookup id for %s", aActorDescription);
+ ProtocolErrorBreakpoint(message.get());
+}
+
+void MismatchedActorTypeError(const char* aActorDescription) {
+ nsPrintfCString message("actor that should be of type %s has different type",
+ aActorDescription);
+ ProtocolErrorBreakpoint(message.get());
+}
+
+void UnionTypeReadError(const char* aUnionName) {
+ MOZ_CRASH_UNSAFE_PRINTF("error deserializing type of union %s", aUnionName);
+}
+
+void ArrayLengthReadError(const char* aElementName) {
+ MOZ_CRASH_UNSAFE_PRINTF("error deserializing length of %s[]", aElementName);
+}
+
+void SentinelReadError(const char* aClassName) {
+ MOZ_CRASH_UNSAFE_PRINTF("incorrect sentinel when reading %s", aClassName);
+}
+
+ActorLifecycleProxy::ActorLifecycleProxy(IProtocol* aActor) : mActor(aActor) {
+ MOZ_ASSERT(mActor);
+ MOZ_ASSERT(mActor->CanSend(),
+ "Cannot create LifecycleProxy for non-connected actor!");
+
+ // Take a reference to our manager's lifecycle proxy to try to hold it &
+ // ensure it doesn't die before us.
+ if (mActor->mManager) {
+ mManager = mActor->mManager->mLifecycleProxy;
+ }
+
+ // Record that we've taken our first reference to our actor.
+ mActor->ActorAlloc();
+}
+
+WeakActorLifecycleProxy* ActorLifecycleProxy::GetWeakProxy() {
+ if (!mWeakProxy) {
+ mWeakProxy = new WeakActorLifecycleProxy(this);
+ }
+ return mWeakProxy;
+}
+
+ActorLifecycleProxy::~ActorLifecycleProxy() {
+ if (mWeakProxy) {
+ mWeakProxy->mProxy = nullptr;
+ mWeakProxy = nullptr;
+ }
+
+ // When the LifecycleProxy's lifetime has come to an end, it means that the
+ // actor should have its `Dealloc` method called on it. In a well-behaved
+ // actor, this will release the IPC-held reference to the actor.
+ //
+ // If the actor has already died before the `LifecycleProxy`, the `IProtocol`
+ // destructor below will clear our reference to it, preventing us from
+ // performing a use-after-free here.
+ if (!mActor) {
+ return;
+ }
+
+ // Clear our actor's state back to inactive, and then invoke ActorDealloc.
+ MOZ_ASSERT(mActor->mLinkStatus == LinkStatus::Destroyed,
+ "Deallocating non-destroyed actor!");
+ mActor->mLifecycleProxy = nullptr;
+ mActor->mLinkStatus = LinkStatus::Inactive;
+ mActor->ActorDealloc();
+ mActor = nullptr;
+}
+
+WeakActorLifecycleProxy::WeakActorLifecycleProxy(ActorLifecycleProxy* aProxy)
+ : mProxy(aProxy), mActorEventTarget(GetCurrentSerialEventTarget()) {}
+
+WeakActorLifecycleProxy::~WeakActorLifecycleProxy() {
+ MOZ_DIAGNOSTIC_ASSERT(!mProxy, "Destroyed before mProxy was cleared?");
+}
+
+IProtocol* WeakActorLifecycleProxy::Get() const {
+ MOZ_DIAGNOSTIC_ASSERT(mActorEventTarget->IsOnCurrentThread());
+ return mProxy ? mProxy->Get() : nullptr;
+}
+
+WeakActorLifecycleProxy* IProtocol::GetWeakLifecycleProxy() {
+ return mLifecycleProxy ? mLifecycleProxy->GetWeakProxy() : nullptr;
+}
+
+IProtocol::~IProtocol() {
+ // If the actor still has a lifecycle proxy when it is being torn down, it
+ // means that IPC was not given control over the lifecycle of the actor
+ // correctly. Usually this means that the actor was destroyed while IPC is
+ // calling a message handler for it, and the actor incorrectly frees itself
+ // during that operation.
+ //
+ // As this happens unfortunately frequently, due to many odd protocols in
+ // Gecko, simply emit a warning and clear the weak backreference from our
+ // LifecycleProxy back to us.
+ if (mLifecycleProxy) {
+ NS_WARNING(
+ nsPrintfCString("Actor destructor for '%s%s' called before IPC "
+ "lifecycle complete!\n"
+ "References to this actor may unexpectedly dangle!",
+ GetProtocolName(), StringFromIPCSide(GetSide()))
+ .get());
+
+ mLifecycleProxy->mActor = nullptr;
+
+ // If we are somehow being destroyed while active, make sure that the
+ // existing IPC reference has been freed. If the status of the actor is
+ // `Destroyed`, the reference has already been freed, and we shouldn't free
+ // it a second time.
+ MOZ_ASSERT(mLinkStatus != LinkStatus::Inactive);
+ if (mLinkStatus != LinkStatus::Destroyed) {
+ NS_IF_RELEASE(mLifecycleProxy);
+ }
+ mLifecycleProxy = nullptr;
+ }
+}
+
+// The following methods either directly forward to the toplevel protocol, or
+// almost directly do.
+int32_t IProtocol::Register(IProtocol* aRouted) {
+ return mToplevel->Register(aRouted);
+}
+int32_t IProtocol::RegisterID(IProtocol* aRouted, int32_t aId) {
+ return mToplevel->RegisterID(aRouted, aId);
+}
+IProtocol* IProtocol::Lookup(int32_t aId) { return mToplevel->Lookup(aId); }
+void IProtocol::Unregister(int32_t aId) {
+ if (aId == mId) {
+ mId = kFreedActorId;
+ }
+ return mToplevel->Unregister(aId);
+}
+
+Shmem::SharedMemory* IProtocol::CreateSharedMemory(size_t aSize, bool aUnsafe,
+ int32_t* aId) {
+ return mToplevel->CreateSharedMemory(aSize, aUnsafe, aId);
+}
+Shmem::SharedMemory* IProtocol::LookupSharedMemory(int32_t aId) {
+ return mToplevel->LookupSharedMemory(aId);
+}
+bool IProtocol::IsTrackingSharedMemory(Shmem::SharedMemory* aSegment) {
+ return mToplevel->IsTrackingSharedMemory(aSegment);
+}
+bool IProtocol::DestroySharedMemory(Shmem& aShmem) {
+ return mToplevel->DestroySharedMemory(aShmem);
+}
+
+MessageChannel* IProtocol::GetIPCChannel() {
+ return mToplevel->GetIPCChannel();
+}
+const MessageChannel* IProtocol::GetIPCChannel() const {
+ return mToplevel->GetIPCChannel();
+}
+
+nsISerialEventTarget* IProtocol::GetActorEventTarget() {
+ return GetIPCChannel()->GetWorkerEventTarget();
+}
+
+void IProtocol::SetId(int32_t aId) {
+ MOZ_ASSERT(mId == aId || mLinkStatus == LinkStatus::Inactive);
+ mId = aId;
+}
+
+Maybe<IProtocol*> IProtocol::ReadActor(IPC::MessageReader* aReader,
+ bool aNullable,
+ const char* aActorDescription,
+ int32_t aProtocolTypeId) {
+ int32_t id;
+ if (!IPC::ReadParam(aReader, &id)) {
+ ActorIdReadError(aActorDescription);
+ return Nothing();
+ }
+
+ if (id == 1 || (id == 0 && !aNullable)) {
+ BadActorIdError(aActorDescription);
+ return Nothing();
+ }
+
+ if (id == 0) {
+ return Some(static_cast<IProtocol*>(nullptr));
+ }
+
+ IProtocol* listener = this->Lookup(id);
+ if (!listener) {
+ ActorLookupError(aActorDescription);
+ return Nothing();
+ }
+
+ if (listener->GetProtocolId() != aProtocolTypeId) {
+ MismatchedActorTypeError(aActorDescription);
+ return Nothing();
+ }
+
+ return Some(listener);
+}
+
+void IProtocol::FatalError(const char* const aErrorMsg) {
+ HandleFatalError(aErrorMsg);
+}
+
+void IProtocol::HandleFatalError(const char* aErrorMsg) {
+ if (IProtocol* manager = Manager()) {
+ manager->HandleFatalError(aErrorMsg);
+ return;
+ }
+
+ mozilla::ipc::FatalError(aErrorMsg, mSide == ParentSide);
+ if (CanSend()) {
+ GetIPCChannel()->InduceConnectionError();
+ }
+}
+
+bool IProtocol::AllocShmem(size_t aSize, Shmem* aOutMem) {
+ if (!CanSend()) {
+ NS_WARNING(
+ "Shmem not allocated. Cannot communicate with the other actor.");
+ return false;
+ }
+
+ Shmem::id_t id;
+ Shmem::SharedMemory* rawmem(CreateSharedMemory(aSize, false, &id));
+ if (!rawmem) {
+ return false;
+ }
+
+ *aOutMem = Shmem(rawmem, id, aSize, false);
+ return true;
+}
+
+bool IProtocol::AllocUnsafeShmem(size_t aSize, Shmem* aOutMem) {
+ if (!CanSend()) {
+ NS_WARNING(
+ "Shmem not allocated. Cannot communicate with the other actor.");
+ return false;
+ }
+
+ Shmem::id_t id;
+ Shmem::SharedMemory* rawmem(CreateSharedMemory(aSize, true, &id));
+ if (!rawmem) {
+ return false;
+ }
+
+ *aOutMem = Shmem(rawmem, id, aSize, true);
+ return true;
+}
+
+bool IProtocol::DeallocShmem(Shmem& aMem) {
+ bool ok = DestroySharedMemory(aMem);
+#ifdef DEBUG
+ if (!ok) {
+ if (mSide == ChildSide) {
+ FatalError("bad Shmem");
+ } else {
+ NS_WARNING("bad Shmem");
+ }
+ return false;
+ }
+#endif // DEBUG
+ aMem.forget();
+ return ok;
+}
+
+void IProtocol::SetManager(IProtocol* aManager) {
+ MOZ_RELEASE_ASSERT(!mManager || mManager == aManager);
+ mManager = aManager;
+ mToplevel = aManager->mToplevel;
+}
+
+void IProtocol::SetManagerAndRegister(IProtocol* aManager) {
+ // Set the manager prior to registering so registering properly inherits
+ // the manager's event target.
+ SetManager(aManager);
+
+ aManager->Register(this);
+}
+
+void IProtocol::SetManagerAndRegister(IProtocol* aManager, int32_t aId) {
+ // Set the manager prior to registering so registering properly inherits
+ // the manager's event target.
+ SetManager(aManager);
+
+ aManager->RegisterID(this, aId);
+}
+
+bool IProtocol::ChannelSend(UniquePtr<IPC::Message> aMsg) {
+ if (CanSend()) {
+ // NOTE: This send call failing can only occur during toplevel channel
+ // teardown. As this is an async call, this isn't reasonable to predict or
+ // respond to, so just drop the message on the floor silently.
+ GetIPCChannel()->Send(std::move(aMsg));
+ return true;
+ }
+
+ WarnMessageDiscarded(aMsg.get());
+ return false;
+}
+
+bool IProtocol::ChannelSend(UniquePtr<IPC::Message> aMsg,
+ UniquePtr<IPC::Message>* aReply) {
+ if (CanSend()) {
+ return GetIPCChannel()->Send(std::move(aMsg), aReply);
+ }
+
+ WarnMessageDiscarded(aMsg.get());
+ return false;
+}
+
+#ifdef DEBUG
+void IProtocol::WarnMessageDiscarded(IPC::Message* aMsg) {
+ NS_WARNING(nsPrintfCString("IPC message '%s' discarded: actor cannot send",
+ aMsg->name())
+ .get());
+}
+#endif
+
+void IProtocol::ActorConnected() {
+ if (mLinkStatus != LinkStatus::Inactive) {
+ return;
+ }
+
+#ifdef FUZZING_SNAPSHOT
+ fuzzing::IPCFuzzController::instance().OnActorConnected(this);
+#endif
+
+ mLinkStatus = LinkStatus::Connected;
+
+ MOZ_ASSERT(!mLifecycleProxy, "double-connecting live actor");
+ mLifecycleProxy = new ActorLifecycleProxy(this);
+ NS_ADDREF(mLifecycleProxy); // Reference freed in DestroySubtree();
+}
+
+void IProtocol::DoomSubtree() {
+ MOZ_ASSERT(CanSend(), "dooming non-connected actor");
+ MOZ_ASSERT(mLifecycleProxy, "dooming zombie actor");
+
+ nsTArray<RefPtr<ActorLifecycleProxy>> managed;
+ AllManagedActors(managed);
+ for (ActorLifecycleProxy* proxy : managed) {
+ // Guard against actor being disconnected or destroyed during previous Doom
+ IProtocol* actor = proxy->Get();
+ if (actor && actor->CanSend()) {
+ actor->DoomSubtree();
+ }
+ }
+
+ // ActorDoom is called immediately before changing state, this allows messages
+ // to be sent during ActorDoom immediately before the channel is closed and
+ // sending messages is disabled.
+ ActorDoom();
+ mLinkStatus = LinkStatus::Doomed;
+}
+
+void IProtocol::DestroySubtree(ActorDestroyReason aWhy) {
+ MOZ_ASSERT(CanRecv(), "destroying non-connected actor");
+ MOZ_ASSERT(mLifecycleProxy, "destroying zombie actor");
+
+#ifdef FUZZING_SNAPSHOT
+ fuzzing::IPCFuzzController::instance().OnActorDestroyed(this);
+#endif
+
+ int32_t id = Id();
+
+ // If we're a managed actor, unregister from our manager
+ if (Manager()) {
+ Unregister(id);
+ }
+
+ // Destroy subtree
+ ActorDestroyReason subtreeWhy = aWhy;
+ if (aWhy == Deletion || aWhy == FailedConstructor) {
+ subtreeWhy = AncestorDeletion;
+ }
+
+ nsTArray<RefPtr<ActorLifecycleProxy>> managed;
+ AllManagedActors(managed);
+ for (ActorLifecycleProxy* proxy : managed) {
+ // Guard against actor being disconnected or destroyed during previous
+ // Destroy
+ IProtocol* actor = proxy->Get();
+ if (actor && actor->CanRecv()) {
+ actor->DestroySubtree(subtreeWhy);
+ }
+ }
+
+ // Ensure that we don't send any messages while we're calling `ActorDestroy`
+ // by setting our state to `Doomed`.
+ mLinkStatus = LinkStatus::Doomed;
+
+ // The actor is being destroyed, reject any pending responses, invoke
+ // `ActorDestroy` to destroy it, and then clear our status to
+ // `LinkStatus::Destroyed`.
+ GetIPCChannel()->RejectPendingResponsesForActor(id);
+ ActorDestroy(aWhy);
+ mLinkStatus = LinkStatus::Destroyed;
+}
+
+IToplevelProtocol::IToplevelProtocol(const char* aName, ProtocolId aProtoId,
+ Side aSide)
+ : IRefCountedProtocol(aProtoId, aSide),
+ mOtherPid(base::kInvalidProcessId),
+ mLastLocalId(0),
+ mChannel(aName, this) {
+ mToplevel = this;
+}
+
+void IToplevelProtocol::SetOtherProcessId(base::ProcessId aOtherPid) {
+ mOtherPid = aOtherPid;
+}
+
+bool IToplevelProtocol::Open(ScopedPort aPort, const nsID& aMessageChannelId,
+ base::ProcessId aOtherPid,
+ nsISerialEventTarget* aEventTarget) {
+ SetOtherProcessId(aOtherPid);
+ return GetIPCChannel()->Open(std::move(aPort), mSide, aMessageChannelId,
+ aEventTarget);
+}
+
+bool IToplevelProtocol::Open(IToplevelProtocol* aTarget,
+ nsISerialEventTarget* aEventTarget,
+ mozilla::ipc::Side aSide) {
+ SetOtherProcessId(base::GetCurrentProcId());
+ aTarget->SetOtherProcessId(base::GetCurrentProcId());
+ return GetIPCChannel()->Open(aTarget->GetIPCChannel(), aEventTarget, aSide);
+}
+
+bool IToplevelProtocol::OpenOnSameThread(IToplevelProtocol* aTarget,
+ Side aSide) {
+ SetOtherProcessId(base::GetCurrentProcId());
+ aTarget->SetOtherProcessId(base::GetCurrentProcId());
+ return GetIPCChannel()->OpenOnSameThread(aTarget->GetIPCChannel(), aSide);
+}
+
+void IToplevelProtocol::NotifyImpendingShutdown() {
+ if (CanRecv()) {
+ GetIPCChannel()->NotifyImpendingShutdown();
+ }
+}
+
+void IToplevelProtocol::Close() { GetIPCChannel()->Close(); }
+
+void IToplevelProtocol::SetReplyTimeoutMs(int32_t aTimeoutMs) {
+ GetIPCChannel()->SetReplyTimeoutMs(aTimeoutMs);
+}
+
+bool IToplevelProtocol::IsOnCxxStack() const {
+ return GetIPCChannel()->IsOnCxxStack();
+}
+
+int32_t IToplevelProtocol::NextId() {
+ // Generate the next ID to use for a shared memory or protocol. Parent and
+ // Child sides of the protocol use different pools.
+ int32_t tag = 0;
+ if (GetSide() == ParentSide) {
+ tag |= 1 << 1;
+ }
+
+ // Check any overflow
+ MOZ_RELEASE_ASSERT(mLastLocalId < (1 << 29));
+
+ // Compute the ID to use with the low two bits as our tag, and the remaining
+ // bits as a monotonic.
+ return (++mLastLocalId << 2) | tag;
+}
+
+int32_t IToplevelProtocol::Register(IProtocol* aRouted) {
+ if (aRouted->Id() != kNullActorId && aRouted->Id() != kFreedActorId) {
+ // If there's already an ID, just return that.
+ return aRouted->Id();
+ }
+ return RegisterID(aRouted, NextId());
+}
+
+int32_t IToplevelProtocol::RegisterID(IProtocol* aRouted, int32_t aId) {
+ aRouted->SetId(aId);
+ aRouted->ActorConnected();
+ MOZ_ASSERT(!mActorMap.Contains(aId), "Don't insert with an existing ID");
+ mActorMap.InsertOrUpdate(aId, aRouted);
+ return aId;
+}
+
+IProtocol* IToplevelProtocol::Lookup(int32_t aId) { return mActorMap.Get(aId); }
+
+void IToplevelProtocol::Unregister(int32_t aId) {
+ MOZ_ASSERT(mActorMap.Contains(aId),
+ "Attempting to remove an ID not in the actor map");
+ mActorMap.Remove(aId);
+}
+
+Shmem::SharedMemory* IToplevelProtocol::CreateSharedMemory(size_t aSize,
+ bool aUnsafe,
+ Shmem::id_t* aId) {
+ RefPtr<Shmem::SharedMemory> segment(Shmem::Alloc(aSize));
+ if (!segment) {
+ return nullptr;
+ }
+ int32_t id = NextId();
+ Shmem shmem(segment.get(), id, aSize, aUnsafe);
+
+ UniquePtr<Message> descriptor = shmem.MkCreatedMessage(MSG_ROUTING_CONTROL);
+ if (!descriptor) {
+ return nullptr;
+ }
+ Unused << GetIPCChannel()->Send(std::move(descriptor));
+
+ *aId = shmem.Id();
+ Shmem::SharedMemory* rawSegment = segment.get();
+ MOZ_ASSERT(!mShmemMap.Contains(*aId), "Don't insert with an existing ID");
+ mShmemMap.InsertOrUpdate(*aId, std::move(segment));
+ return rawSegment;
+}
+
+Shmem::SharedMemory* IToplevelProtocol::LookupSharedMemory(Shmem::id_t aId) {
+ auto entry = mShmemMap.Lookup(aId);
+ return entry ? entry.Data().get() : nullptr;
+}
+
+bool IToplevelProtocol::IsTrackingSharedMemory(Shmem::SharedMemory* segment) {
+ for (const auto& shmem : mShmemMap.Values()) {
+ if (segment == shmem) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool IToplevelProtocol::DestroySharedMemory(Shmem& shmem) {
+ Shmem::id_t aId = shmem.Id();
+ Shmem::SharedMemory* segment = LookupSharedMemory(aId);
+ if (!segment) {
+ return false;
+ }
+
+ UniquePtr<Message> descriptor = shmem.MkDestroyedMessage(MSG_ROUTING_CONTROL);
+
+ MOZ_ASSERT(mShmemMap.Contains(aId),
+ "Attempting to remove an ID not in the shmem map");
+ mShmemMap.Remove(aId);
+
+ MessageChannel* channel = GetIPCChannel();
+ if (!channel->CanSend()) {
+ return true;
+ }
+
+ return descriptor && channel->Send(std::move(descriptor));
+}
+
+void IToplevelProtocol::DeallocShmems() { mShmemMap.Clear(); }
+
+bool IToplevelProtocol::ShmemCreated(const Message& aMsg) {
+ Shmem::id_t id;
+ RefPtr<Shmem::SharedMemory> rawmem(Shmem::OpenExisting(aMsg, &id, true));
+ if (!rawmem) {
+ return false;
+ }
+ MOZ_ASSERT(!mShmemMap.Contains(id), "Don't insert with an existing ID");
+ mShmemMap.InsertOrUpdate(id, std::move(rawmem));
+ return true;
+}
+
+bool IToplevelProtocol::ShmemDestroyed(const Message& aMsg) {
+ Shmem::id_t id;
+ MessageReader reader(aMsg);
+ if (!IPC::ReadParam(&reader, &id)) {
+ return false;
+ }
+ reader.EndRead();
+
+ mShmemMap.Remove(id);
+ return true;
+}
+
+IPDLResolverInner::IPDLResolverInner(UniquePtr<IPC::Message> aReply,
+ IProtocol* aActor)
+ : mReply(std::move(aReply)),
+ mWeakProxy(aActor->GetLifecycleProxy()->GetWeakProxy()) {}
+
+void IPDLResolverInner::ResolveOrReject(
+ bool aResolve, FunctionRef<void(IPC::Message*, IProtocol*)> aWrite) {
+ MOZ_ASSERT(mWeakProxy);
+ MOZ_ASSERT(mWeakProxy->ActorEventTarget()->IsOnCurrentThread());
+ MOZ_ASSERT(mReply);
+
+ UniquePtr<IPC::Message> reply = std::move(mReply);
+
+ IProtocol* actor = mWeakProxy->Get();
+ if (!actor) {
+ NS_WARNING(nsPrintfCString("Not resolving response '%s': actor is dead",
+ reply->name())
+ .get());
+ return;
+ }
+
+ IPC::MessageWriter writer(*reply, actor);
+ WriteIPDLParam(&writer, actor, aResolve);
+ aWrite(reply.get(), actor);
+
+ actor->ChannelSend(std::move(reply));
+}
+
+void IPDLResolverInner::Destroy() {
+ if (mReply) {
+ NS_PROXY_DELETE_TO_EVENT_TARGET(IPDLResolverInner,
+ mWeakProxy->ActorEventTarget());
+ } else {
+ // If we've already been consumed, just delete without proxying. This avoids
+ // leaking the resolver if the actor's thread is already dead.
+ delete this;
+ }
+}
+
+IPDLResolverInner::~IPDLResolverInner() {
+ if (mReply) {
+ NS_WARNING(
+ nsPrintfCString(
+ "Rejecting reply '%s': resolver dropped without being called",
+ mReply->name())
+ .get());
+ ResolveOrReject(false, [](IPC::Message* aMessage, IProtocol* aActor) {
+ IPC::MessageWriter writer(*aMessage, aActor);
+ ResponseRejectReason reason = ResponseRejectReason::ResolverDestroyed;
+ WriteIPDLParam(&writer, aActor, reason);
+ });
+ }
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/ProtocolUtils.h b/ipc/glue/ProtocolUtils.h
new file mode 100644
index 0000000000..2a0c64de20
--- /dev/null
+++ b/ipc/glue/ProtocolUtils.h
@@ -0,0 +1,781 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_ProtocolUtils_h
+#define mozilla_ipc_ProtocolUtils_h
+
+#include <cstddef>
+#include <cstdint>
+#include <utility>
+#include "IPCMessageStart.h"
+#include "base/basictypes.h"
+#include "base/process.h"
+#include "chrome/common/ipc_message.h"
+#include "mojo/core/ports/port_ref.h"
+#include "mozilla/AlreadyAddRefed.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/FunctionRef.h"
+#include "mozilla/Maybe.h"
+#include "mozilla/Mutex.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/MessageChannel.h"
+#include "mozilla/ipc/MessageLink.h"
+#include "mozilla/ipc/SharedMemory.h"
+#include "mozilla/ipc/Shmem.h"
+#include "nsPrintfCString.h"
+#include "nsTHashMap.h"
+#include "nsDebug.h"
+#include "nsISupports.h"
+#include "nsTArrayForwardDeclare.h"
+#include "nsTHashSet.h"
+
+// XXX Things that could be moved to ProtocolUtils.cpp
+#include "base/process_util.h" // for CloseProcessHandle
+#include "prenv.h" // for PR_GetEnv
+
+#if defined(ANDROID) && defined(DEBUG)
+# include <android/log.h>
+#endif
+
+template <typename T>
+class nsPtrHashKey;
+
+// WARNING: this takes into account the private, special-message-type
+// enum in ipc_channel.h. They need to be kept in sync.
+namespace {
+// XXX the max message ID is actually kuint32max now ... when this
+// changed, the assumptions of the special message IDs changed in that
+// they're not carving out messages from likely-unallocated space, but
+// rather carving out messages from the end of space allocated to
+// protocol 0. Oops! We can get away with this until protocol 0
+// starts approaching its 65,536th message.
+enum {
+ // Message types used by DataPipe
+ DATA_PIPE_CLOSED_MESSAGE_TYPE = kuint16max - 18,
+ DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE = kuint16max - 17,
+
+ // Message types used by NodeChannel
+ ACCEPT_INVITE_MESSAGE_TYPE = kuint16max - 16,
+ REQUEST_INTRODUCTION_MESSAGE_TYPE = kuint16max - 15,
+ INTRODUCE_MESSAGE_TYPE = kuint16max - 14,
+ BROADCAST_MESSAGE_TYPE = kuint16max - 13,
+ EVENT_MESSAGE_TYPE = kuint16max - 12,
+
+ // Message types used by MessageChannel
+ MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE = kuint16max - 11,
+ MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE = kuint16max - 10,
+ IMPENDING_SHUTDOWN_MESSAGE_TYPE = kuint16max - 9,
+ BUILD_IDS_MATCH_MESSAGE_TYPE = kuint16max - 8,
+ BUILD_ID_MESSAGE_TYPE = kuint16max - 7, // unused
+ CHANNEL_OPENED_MESSAGE_TYPE = kuint16max - 6,
+ SHMEM_DESTROYED_MESSAGE_TYPE = kuint16max - 5,
+ SHMEM_CREATED_MESSAGE_TYPE = kuint16max - 4,
+ GOODBYE_MESSAGE_TYPE = kuint16max - 3,
+ CANCEL_MESSAGE_TYPE = kuint16max - 2,
+
+ // kuint16max - 1 is used by ipc_channel.h.
+};
+
+} // namespace
+
+class MessageLoop;
+class PickleIterator;
+class nsISerialEventTarget;
+
+namespace mozilla {
+class SchedulerGroup;
+
+namespace dom {
+class ContentParent;
+} // namespace dom
+
+namespace net {
+class NeckoParent;
+} // namespace net
+
+namespace ipc {
+
+class ProtocolFdMapping;
+class ProtocolCloneContext;
+
+// Used to pass references to protocol actors across the wire.
+// Actors created on the parent-side have a positive ID, and actors
+// allocated on the child side have a negative ID.
+struct ActorHandle {
+ int mId;
+};
+
+// What happens if Interrupt calls race?
+enum RacyInterruptPolicy { RIPError, RIPChildWins, RIPParentWins };
+
+enum class LinkStatus : uint8_t {
+ // The actor has not established a link yet, or the actor is no longer in use
+ // by IPC, and its 'Dealloc' method has been called or is being called.
+ //
+ // NOTE: This state is used instead of an explicit `Freed` state when IPC no
+ // longer holds references to the current actor as we currently re-open
+ // existing actors. Once we fix these poorly behaved actors, this loopback
+ // state can be split to have the final state not be the same as the initial
+ // state.
+ Inactive,
+
+ // A live link is connected to the other side of this actor.
+ Connected,
+
+ // The link has begun being destroyed. Messages may still be received, but
+ // cannot be sent. (exception: sync/intr replies may be sent while Doomed).
+ Doomed,
+
+ // The link has been destroyed, and messages will no longer be sent or
+ // received.
+ Destroyed,
+};
+
+typedef IPCMessageStart ProtocolId;
+
+// Generated by IPDL compiler
+const char* ProtocolIdToName(IPCMessageStart aId);
+
+class IRefCountedProtocol;
+class IToplevelProtocol;
+class ActorLifecycleProxy;
+class WeakActorLifecycleProxy;
+class IPDLResolverInner;
+class UntypedManagedEndpoint;
+
+class IProtocol : public HasResultCodes {
+ public:
+ enum ActorDestroyReason {
+ FailedConstructor,
+ Deletion,
+ AncestorDeletion,
+ NormalShutdown,
+ AbnormalShutdown,
+ ManagedEndpointDropped
+ };
+
+ typedef base::ProcessId ProcessId;
+ typedef IPC::Message Message;
+
+ IProtocol(ProtocolId aProtoId, Side aSide)
+ : mId(0),
+ mProtocolId(aProtoId),
+ mSide(aSide),
+ mLinkStatus(LinkStatus::Inactive),
+ mLifecycleProxy(nullptr),
+ mManager(nullptr),
+ mToplevel(nullptr) {}
+
+ IToplevelProtocol* ToplevelProtocol() { return mToplevel; }
+ const IToplevelProtocol* ToplevelProtocol() const { return mToplevel; }
+
+ // The following methods either directly forward to the toplevel protocol, or
+ // almost directly do.
+ int32_t Register(IProtocol* aRouted);
+ int32_t RegisterID(IProtocol* aRouted, int32_t aId);
+ IProtocol* Lookup(int32_t aId);
+ void Unregister(int32_t aId);
+
+ Shmem::SharedMemory* CreateSharedMemory(size_t aSize, bool aUnsafe,
+ int32_t* aId);
+ Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
+ bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
+ bool DestroySharedMemory(Shmem& aShmem);
+
+ MessageChannel* GetIPCChannel();
+ const MessageChannel* GetIPCChannel() const;
+
+ // Get the nsISerialEventTarget which all messages sent to this actor will be
+ // processed on. Unless stated otherwise, all operations on IProtocol which
+ // don't occur on this `nsISerialEventTarget` are unsafe.
+ nsISerialEventTarget* GetActorEventTarget();
+
+ // Actor lifecycle and other properties.
+ ProtocolId GetProtocolId() const { return mProtocolId; }
+ const char* GetProtocolName() const { return ProtocolIdToName(mProtocolId); }
+
+ int32_t Id() const { return mId; }
+ IProtocol* Manager() const { return mManager; }
+
+ ActorLifecycleProxy* GetLifecycleProxy() { return mLifecycleProxy; }
+ WeakActorLifecycleProxy* GetWeakLifecycleProxy();
+
+ Side GetSide() const { return mSide; }
+ bool CanSend() const { return mLinkStatus == LinkStatus::Connected; }
+ bool CanRecv() const {
+ return mLinkStatus == LinkStatus::Connected ||
+ mLinkStatus == LinkStatus::Doomed;
+ }
+
+ // Remove or deallocate a managee given its type.
+ virtual void RemoveManagee(int32_t, IProtocol*) = 0;
+ virtual void DeallocManagee(int32_t, IProtocol*) = 0;
+
+ Maybe<IProtocol*> ReadActor(IPC::MessageReader* aReader, bool aNullable,
+ const char* aActorDescription,
+ int32_t aProtocolTypeId);
+
+ virtual Result OnMessageReceived(const Message& aMessage) = 0;
+ virtual Result OnMessageReceived(const Message& aMessage,
+ UniquePtr<Message>& aReply) = 0;
+ virtual Result OnCallReceived(const Message& aMessage,
+ UniquePtr<Message>& aReply) = 0;
+ bool AllocShmem(size_t aSize, Shmem* aOutMem);
+ bool AllocUnsafeShmem(size_t aSize, Shmem* aOutMem);
+ bool DeallocShmem(Shmem& aMem);
+
+ void FatalError(const char* const aErrorMsg);
+ virtual void HandleFatalError(const char* aErrorMsg);
+
+ protected:
+ virtual ~IProtocol();
+
+ friend class IToplevelProtocol;
+ friend class ActorLifecycleProxy;
+ friend class IPDLResolverInner;
+ friend class UntypedManagedEndpoint;
+
+ void SetId(int32_t aId);
+
+ // We have separate functions because the accessibility code manually
+ // calls SetManager.
+ void SetManager(IProtocol* aManager);
+
+ // Sets the manager for the protocol and registers the protocol with
+ // its manager, setting up channels for the protocol as well. Not
+ // for use outside of IPDL.
+ void SetManagerAndRegister(IProtocol* aManager);
+ void SetManagerAndRegister(IProtocol* aManager, int32_t aId);
+
+ // Helpers for calling `Send` on our underlying IPC channel.
+ bool ChannelSend(UniquePtr<IPC::Message> aMsg);
+ bool ChannelSend(UniquePtr<IPC::Message> aMsg,
+ UniquePtr<IPC::Message>* aReply);
+ template <typename Value>
+ void ChannelSend(UniquePtr<IPC::Message> aMsg,
+ IPC::Message::msgid_t aReplyMsgId,
+ ResolveCallback<Value>&& aResolve,
+ RejectCallback&& aReject) {
+ if (CanSend()) {
+ GetIPCChannel()->Send(std::move(aMsg), Id(), aReplyMsgId,
+ std::move(aResolve), std::move(aReject));
+ } else {
+ WarnMessageDiscarded(aMsg.get());
+ aReject(ResponseRejectReason::SendError);
+ }
+ }
+
+ // Collect all actors managed by this object in an array. To make this safer
+ // to iterate, `ActorLifecycleProxy` references are returned rather than raw
+ // actor pointers.
+ virtual void AllManagedActors(
+ nsTArray<RefPtr<ActorLifecycleProxy>>& aActors) const = 0;
+
+ virtual uint32_t AllManagedActorsCount() const = 0;
+
+ // Internal method called when the actor becomes connected.
+ void ActorConnected();
+
+ // Called immediately before setting the actor state to doomed, and triggering
+ // async actor destruction. Messages may be sent from this callback, but no
+ // later.
+ // FIXME(nika): This is currently unused!
+ virtual void ActorDoom() {}
+ void DoomSubtree();
+
+ // Called when the actor has been destroyed due to an error, a __delete__
+ // message, or a __doom__ reply.
+ virtual void ActorDestroy(ActorDestroyReason aWhy) {}
+ void DestroySubtree(ActorDestroyReason aWhy);
+
+ // Called when IPC has acquired its first reference to the actor. This method
+ // may take references which will later be freed by `ActorDealloc`.
+ virtual void ActorAlloc() = 0;
+
+ // Called when IPC has released its final reference to the actor. It will call
+ // the dealloc method, causing the actor to be actually freed.
+ //
+ // The actor has been freed after this method returns.
+ virtual void ActorDealloc() = 0;
+
+ static const int32_t kNullActorId = 0;
+ static const int32_t kFreedActorId = 1;
+
+ private:
+#ifdef DEBUG
+ void WarnMessageDiscarded(IPC::Message* aMsg);
+#else
+ void WarnMessageDiscarded(IPC::Message*) {}
+#endif
+
+ int32_t mId;
+ ProtocolId mProtocolId;
+ Side mSide;
+ LinkStatus mLinkStatus;
+ ActorLifecycleProxy* mLifecycleProxy;
+ IProtocol* mManager;
+ IToplevelProtocol* mToplevel;
+};
+
+#define IPC_OK() mozilla::ipc::IPCResult::Ok()
+#define IPC_FAIL(actor, why) \
+ mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__, (why))
+#define IPC_FAIL_NO_REASON(actor) \
+ mozilla::ipc::IPCResult::Fail(WrapNotNull(actor), __func__)
+
+/*
+ * IPC_FAIL_UNSAFE_PRINTF(actor, format, ...)
+ *
+ * Create a failure IPCResult with a dynamic reason-string.
+ *
+ * @note This macro causes data collection because IPC failure reasons may be
+ * sent to crash-stats, where they are publicly visible. Firefox data stewards
+ * must do data review on usages of this macro.
+ */
+#define IPC_FAIL_UNSAFE_PRINTF(actor, format, ...) \
+ mozilla::ipc::IPCResult::FailUnsafePrintfImpl( \
+ WrapNotNull(actor), __func__, nsPrintfCString(format, ##__VA_ARGS__))
+
+/**
+ * All message deserializers and message handlers should return this type via
+ * the above macros. We use a less generic name here to avoid conflict with
+ * `mozilla::Result` because we have quite a few `using namespace mozilla::ipc;`
+ * in the code base.
+ *
+ * Note that merely constructing a failure-result, whether directly or via the
+ * IPC_FAIL macros, causes the associated error message to be processed
+ * immediately.
+ */
+class IPCResult {
+ public:
+ static IPCResult Ok() { return IPCResult(true); }
+
+ // IPC failure messages can sometimes end up in telemetry. As such, to avoid
+ // accidentally exfiltrating sensitive information without a data review, we
+ // require that they be constant strings.
+ template <size_t N, size_t M>
+ static IPCResult Fail(NotNull<IProtocol*> aActor, const char (&aWhere)[N],
+ const char (&aWhy)[M]) {
+ return FailImpl(aActor, aWhere, aWhy);
+ }
+ template <size_t N>
+ static IPCResult Fail(NotNull<IProtocol*> aActor, const char (&aWhere)[N]) {
+ return FailImpl(aActor, aWhere, "");
+ }
+
+ MOZ_IMPLICIT operator bool() const { return mSuccess; }
+
+ // Only used by IPC_FAIL_UNSAFE_PRINTF (q.v.). Do not call this directly. (Or
+ // at least get data-review's approval if you do.)
+ template <size_t N>
+ static IPCResult FailUnsafePrintfImpl(NotNull<IProtocol*> aActor,
+ const char (&aWhere)[N],
+ nsPrintfCString const& aWhy) {
+ return FailImpl(aActor, aWhere, aWhy.get());
+ }
+
+ private:
+ static IPCResult FailImpl(NotNull<IProtocol*> aActor, const char* aWhere,
+ const char* aWhy);
+
+ explicit IPCResult(bool aResult) : mSuccess(aResult) {}
+ bool mSuccess;
+};
+
+class UntypedEndpoint;
+
+template <class PFooSide>
+class Endpoint;
+
+template <class PFooSide>
+class ManagedEndpoint;
+
+/**
+ * All refcounted protocols should inherit this class.
+ */
+class IRefCountedProtocol : public IProtocol {
+ public:
+ NS_INLINE_DECL_PURE_VIRTUAL_REFCOUNTING
+
+ using IProtocol::IProtocol;
+};
+
+/**
+ * All top-level protocols should inherit this class.
+ *
+ * IToplevelProtocol tracks all top-level protocol actors created from
+ * this protocol actor.
+ */
+class IToplevelProtocol : public IRefCountedProtocol {
+ template <class PFooSide>
+ friend class Endpoint;
+
+ protected:
+ explicit IToplevelProtocol(const char* aName, ProtocolId aProtoId,
+ Side aSide);
+ ~IToplevelProtocol() = default;
+
+ public:
+ // Shadow methods on IProtocol which are implemented directly on toplevel
+ // actors.
+ int32_t Register(IProtocol* aRouted);
+ int32_t RegisterID(IProtocol* aRouted, int32_t aId);
+ IProtocol* Lookup(int32_t aId);
+ void Unregister(int32_t aId);
+
+ Shmem::SharedMemory* CreateSharedMemory(size_t aSize, bool aUnsafe,
+ int32_t* aId);
+ Shmem::SharedMemory* LookupSharedMemory(int32_t aId);
+ bool IsTrackingSharedMemory(Shmem::SharedMemory* aSegment);
+ bool DestroySharedMemory(Shmem& aShmem);
+
+ MessageChannel* GetIPCChannel() { return &mChannel; }
+ const MessageChannel* GetIPCChannel() const { return &mChannel; }
+
+ void SetOtherProcessId(base::ProcessId aOtherPid);
+
+ virtual void OnChannelClose() = 0;
+ virtual void OnChannelError() = 0;
+ virtual void ProcessingError(Result aError, const char* aMsgName) {}
+
+ bool Open(ScopedPort aPort, const nsID& aMessageChannelId,
+ base::ProcessId aOtherPid,
+ nsISerialEventTarget* aEventTarget = nullptr);
+
+ bool Open(IToplevelProtocol* aTarget, nsISerialEventTarget* aEventTarget,
+ mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
+
+ // Open a toplevel actor such that both ends of the actor's channel are on
+ // the same thread. This method should be called on the thread to perform
+ // the link.
+ //
+ // WARNING: Attempting to send a sync or intr message on the same thread
+ // will crash.
+ bool OpenOnSameThread(IToplevelProtocol* aTarget,
+ mozilla::ipc::Side aSide = mozilla::ipc::UnknownSide);
+
+ /**
+ * This sends a special message that is processed on the IO thread, so that
+ * other actors can know that the process will soon shutdown.
+ */
+ void NotifyImpendingShutdown();
+
+ void Close();
+
+ void SetReplyTimeoutMs(int32_t aTimeoutMs);
+
+ void DeallocShmems();
+ bool ShmemCreated(const Message& aMsg);
+ bool ShmemDestroyed(const Message& aMsg);
+
+ virtual bool ShouldContinueFromReplyTimeout() { return false; }
+
+ // WARNING: This function is called with the MessageChannel monitor held.
+ virtual void IntentionalCrash() { MOZ_CRASH("Intentional IPDL crash"); }
+
+ // The code here is only useful for fuzzing. It should not be used for any
+ // other purpose.
+#ifdef DEBUG
+ // Returns true if we should simulate a timeout.
+ // WARNING: This is a testing-only function that is called with the
+ // MessageChannel monitor held. Don't do anything fancy here or we could
+ // deadlock.
+ virtual bool ArtificialTimeout() { return false; }
+
+ // Returns true if we want to cause the worker thread to sleep with the
+ // monitor unlocked.
+ virtual bool NeedArtificialSleep() { return false; }
+
+ // This function should be implemented to sleep for some amount of time on
+ // the worker thread. Will only be called if NeedArtificialSleep() returns
+ // true.
+ virtual void ArtificialSleep() {}
+#else
+ bool ArtificialTimeout() { return false; }
+ bool NeedArtificialSleep() { return false; }
+ void ArtificialSleep() {}
+#endif
+
+ bool IsOnCxxStack() const;
+
+ virtual void ProcessRemoteNativeEventsInInterruptCall() {}
+
+ virtual void OnChannelReceivedMessage(const Message& aMsg) {}
+
+ void OnIPCChannelOpened() { ActorConnected(); }
+
+ base::ProcessId OtherPidMaybeInvalid() const { return mOtherPid; }
+
+ private:
+ int32_t NextId();
+
+ template <class T>
+ using IDMap = nsTHashMap<nsUint32HashKey, T>;
+
+ base::ProcessId mOtherPid;
+
+ // NOTE NOTE NOTE
+ // Used to be on mState
+ int32_t mLastLocalId;
+ IDMap<IProtocol*> mActorMap;
+ IDMap<RefPtr<Shmem::SharedMemory>> mShmemMap;
+
+ MessageChannel mChannel;
+};
+
+class IShmemAllocator {
+ public:
+ virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) = 0;
+ virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) = 0;
+ virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) = 0;
+};
+
+#define FORWARD_SHMEM_ALLOCATOR_TO(aImplClass) \
+ virtual bool AllocShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
+ override { \
+ return aImplClass::AllocShmem(aSize, aShmem); \
+ } \
+ virtual bool AllocUnsafeShmem(size_t aSize, mozilla::ipc::Shmem* aShmem) \
+ override { \
+ return aImplClass::AllocUnsafeShmem(aSize, aShmem); \
+ } \
+ virtual bool DeallocShmem(mozilla::ipc::Shmem& aShmem) override { \
+ return aImplClass::DeallocShmem(aShmem); \
+ }
+
+inline bool LoggingEnabled() {
+#if defined(DEBUG) || defined(FUZZING)
+ return !!PR_GetEnv("MOZ_IPC_MESSAGE_LOG");
+#else
+ return false;
+#endif
+}
+
+#if defined(DEBUG) || defined(FUZZING)
+bool LoggingEnabledFor(const char* aTopLevelProtocol, mozilla::ipc::Side aSide,
+ const char* aFilter);
+#endif
+
+inline bool LoggingEnabledFor(const char* aTopLevelProtocol,
+ mozilla::ipc::Side aSide) {
+#if defined(DEBUG) || defined(FUZZING)
+ return LoggingEnabledFor(aTopLevelProtocol, aSide,
+ PR_GetEnv("MOZ_IPC_MESSAGE_LOG"));
+#else
+ return false;
+#endif
+}
+
+MOZ_NEVER_INLINE void LogMessageForProtocol(const char* aTopLevelProtocol,
+ base::ProcessId aOtherPid,
+ const char* aContextDescription,
+ uint32_t aMessageId,
+ MessageDirection aDirection);
+
+MOZ_NEVER_INLINE void ProtocolErrorBreakpoint(const char* aMsg);
+
+// IPC::MessageReader and IPC::MessageWriter call this function for FatalError
+// calls which come from serialization/deserialization.
+MOZ_NEVER_INLINE void PickleFatalError(const char* aMsg, IProtocol* aActor);
+
+// The code generator calls this function for errors which come from the
+// methods of protocols. Doing this saves codesize by making the error
+// cases significantly smaller.
+MOZ_NEVER_INLINE void FatalError(const char* aMsg, bool aIsParent);
+
+// The code generator calls this function for errors which are not
+// protocol-specific: errors in generated struct methods or errors in
+// transition functions, for instance. Doing this saves codesize by
+// by making the error cases significantly smaller.
+MOZ_NEVER_INLINE void LogicError(const char* aMsg);
+
+MOZ_NEVER_INLINE void ActorIdReadError(const char* aActorDescription);
+
+MOZ_NEVER_INLINE void BadActorIdError(const char* aActorDescription);
+
+MOZ_NEVER_INLINE void ActorLookupError(const char* aActorDescription);
+
+MOZ_NEVER_INLINE void MismatchedActorTypeError(const char* aActorDescription);
+
+MOZ_NEVER_INLINE void UnionTypeReadError(const char* aUnionName);
+
+MOZ_NEVER_INLINE void ArrayLengthReadError(const char* aElementName);
+
+MOZ_NEVER_INLINE void SentinelReadError(const char* aElementName);
+
+/**
+ * Annotate the crash reporter with the error code from the most recent system
+ * call. Returns the system error.
+ */
+void AnnotateSystemError();
+
+// The ActorLifecycleProxy is a helper type used internally by IPC to maintain a
+// maybe-owning reference to an IProtocol object. For well-behaved actors
+// which are not freed until after their `Dealloc` method is called, a
+// reference to an actor's `ActorLifecycleProxy` object is an owning one, as the
+// `Dealloc` method will only be called when all references to the
+// `ActorLifecycleProxy` are released.
+//
+// Unfortunately, some actors may be destroyed before their `Dealloc` method
+// is called. For these actors, `ActorLifecycleProxy` acts as a weak pointer,
+// and will begin to return `nullptr` from its `Get()` method once the
+// corresponding actor object has been destroyed.
+//
+// When calling a `Recv` method, IPC will hold a `ActorLifecycleProxy` reference
+// to the target actor, meaning that well-behaved actors can behave as though a
+// strong reference is being held.
+//
+// Generic IPC code MUST treat ActorLifecycleProxy references as weak
+// references!
+class ActorLifecycleProxy {
+ public:
+ NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ActorLifecycleProxy)
+
+ IProtocol* Get() { return mActor; }
+
+ WeakActorLifecycleProxy* GetWeakProxy();
+
+ private:
+ friend class IProtocol;
+
+ explicit ActorLifecycleProxy(IProtocol* aActor);
+ ~ActorLifecycleProxy();
+
+ ActorLifecycleProxy(const ActorLifecycleProxy&) = delete;
+ ActorLifecycleProxy& operator=(const ActorLifecycleProxy&) = delete;
+
+ IProtocol* MOZ_NON_OWNING_REF mActor;
+
+ // Hold a reference to the actor's manager's ActorLifecycleProxy to help
+ // prevent it from dying while we're still alive!
+ RefPtr<ActorLifecycleProxy> mManager;
+
+ // When requested, the current self-referencing weak reference for this
+ // ActorLifecycleProxy.
+ RefPtr<WeakActorLifecycleProxy> mWeakProxy;
+};
+
+// Unlike ActorLifecycleProxy, WeakActorLifecycleProxy only holds a weak
+// reference to both the proxy and the actual actor, meaning that holding this
+// type will not attempt to keep the actor object alive.
+//
+// This type is safe to hold on threads other than the actor's thread, but is
+// _NOT_ safe to access on other threads, as actors and ActorLifecycleProxy
+// objects are not threadsafe.
+class WeakActorLifecycleProxy final {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(WeakActorLifecycleProxy)
+
+ // May only be called on the actor's event target.
+ // Will return `nullptr` if the actor has already been destroyed from IPC's
+ // point of view.
+ IProtocol* Get() const;
+
+ // Safe to call on any thread.
+ nsISerialEventTarget* ActorEventTarget() const { return mActorEventTarget; }
+
+ private:
+ friend class ActorLifecycleProxy;
+
+ explicit WeakActorLifecycleProxy(ActorLifecycleProxy* aProxy);
+ ~WeakActorLifecycleProxy();
+
+ WeakActorLifecycleProxy(const WeakActorLifecycleProxy&) = delete;
+ WeakActorLifecycleProxy& operator=(const WeakActorLifecycleProxy&) = delete;
+
+ // This field may only be accessed on the actor's thread, and will be
+ // automatically cleared when the ActorLifecycleProxy is destroyed.
+ ActorLifecycleProxy* MOZ_NON_OWNING_REF mProxy;
+
+ // The serial event target which owns the actor, and is the only thread where
+ // it is OK to access the ActorLifecycleProxy.
+ const nsCOMPtr<nsISerialEventTarget> mActorEventTarget;
+};
+
+class IPDLResolverInner final {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING_WITH_DESTROY(IPDLResolverInner,
+ Destroy())
+
+ explicit IPDLResolverInner(UniquePtr<IPC::Message> aReply, IProtocol* aActor);
+
+ template <typename F>
+ void Resolve(F&& aWrite) {
+ ResolveOrReject(true, std::forward<F>(aWrite));
+ }
+
+ private:
+ void ResolveOrReject(bool aResolve,
+ FunctionRef<void(IPC::Message*, IProtocol*)> aWrite);
+
+ void Destroy();
+ ~IPDLResolverInner();
+
+ UniquePtr<IPC::Message> mReply;
+ RefPtr<WeakActorLifecycleProxy> mWeakProxy;
+};
+
+} // namespace ipc
+
+template <typename Protocol>
+class ManagedContainer {
+ public:
+ using iterator = typename nsTArray<Protocol*>::const_iterator;
+
+ iterator begin() const { return mArray.begin(); }
+ iterator end() const { return mArray.end(); }
+ iterator cbegin() const { return begin(); }
+ iterator cend() const { return end(); }
+
+ bool IsEmpty() const { return mArray.IsEmpty(); }
+ uint32_t Count() const { return mArray.Length(); }
+
+ void ToArray(nsTArray<Protocol*>& aArray) const {
+ aArray.AppendElements(mArray);
+ }
+
+ bool EnsureRemoved(Protocol* aElement) {
+ return mArray.RemoveElementSorted(aElement);
+ }
+
+ void Insert(Protocol* aElement) {
+ // Equivalent to `InsertElementSorted`, avoiding inserting a duplicate
+ // element.
+ size_t index = mArray.IndexOfFirstElementGt(aElement);
+ if (index == 0 || mArray[index - 1] != aElement) {
+ mArray.InsertElementAt(index, aElement);
+ }
+ }
+
+ void Clear() { mArray.Clear(); }
+
+ private:
+ nsTArray<Protocol*> mArray;
+};
+
+template <typename Protocol>
+Protocol* LoneManagedOrNullAsserts(
+ const ManagedContainer<Protocol>& aManagees) {
+ if (aManagees.IsEmpty()) {
+ return nullptr;
+ }
+ MOZ_ASSERT(aManagees.Count() == 1);
+ return *aManagees.cbegin();
+}
+
+template <typename Protocol>
+Protocol* SingleManagedOrNull(const ManagedContainer<Protocol>& aManagees) {
+ if (aManagees.Count() != 1) {
+ return nullptr;
+ }
+ return *aManagees.cbegin();
+}
+
+} // namespace mozilla
+
+#endif // mozilla_ipc_ProtocolUtils_h
diff --git a/ipc/glue/RandomAccessStreamParams.ipdlh b/ipc/glue/RandomAccessStreamParams.ipdlh
new file mode 100644
index 0000000000..8bcf528af2
--- /dev/null
+++ b/ipc/glue/RandomAccessStreamParams.ipdlh
@@ -0,0 +1,32 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include IPCQuotaObject;
+
+namespace mozilla {
+namespace ipc {
+
+// Use RandomAccessStreamParams in your ipdl to represent serialized
+// nsIRandomAccessStreams. Then use SerializeRandomAccessStream from
+// RandomAccessStreamUtils.h to perform the serialization.
+struct FileRandomAccessStreamParams
+{
+ FileDescriptor fileDescriptor;
+ int32_t behaviorFlags;
+};
+
+struct LimitingFileRandomAccessStreamParams
+{
+ FileRandomAccessStreamParams fileRandomAccessStreamParams;
+ IPCQuotaObject quotaObject;
+};
+
+union RandomAccessStreamParams
+{
+ FileRandomAccessStreamParams;
+ LimitingFileRandomAccessStreamParams;
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/RandomAccessStreamUtils.cpp b/ipc/glue/RandomAccessStreamUtils.cpp
new file mode 100644
index 0000000000..d5e66daae6
--- /dev/null
+++ b/ipc/glue/RandomAccessStreamUtils.cpp
@@ -0,0 +1,88 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "RandomAccessStreamUtils.h"
+
+#include "mozilla/NotNull.h"
+#include "mozilla/Result.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/dom/quota/FileStreams.h"
+#include "mozilla/ipc/RandomAccessStreamParams.h"
+#include "nsFileStreams.h"
+#include "nsIInterfaceRequestor.h"
+#include "nsIRandomAccessStream.h"
+
+namespace mozilla::ipc {
+
+RandomAccessStreamParams SerializeRandomAccessStream(
+ MovingNotNull<nsCOMPtr<nsIRandomAccessStream>> aStream,
+ nsIInterfaceRequestor* aCallbacks) {
+ NotNull<nsCOMPtr<nsIRandomAccessStream>> stream = std::move(aStream);
+
+ RandomAccessStreamParams streamParams = stream->Serialize(aCallbacks);
+
+ MOZ_ASSERT(streamParams.type() != RandomAccessStreamParams::T__None);
+
+ return streamParams;
+}
+
+Maybe<RandomAccessStreamParams> SerializeRandomAccessStream(
+ nsCOMPtr<nsIRandomAccessStream> aStream,
+ nsIInterfaceRequestor* aCallbacks) {
+ if (!aStream) {
+ return Nothing();
+ }
+
+ return Some(SerializeRandomAccessStream(
+ WrapMovingNotNullUnchecked(std::move(aStream)), aCallbacks));
+}
+
+Result<MovingNotNull<nsCOMPtr<nsIRandomAccessStream>>, bool>
+DeserializeRandomAccessStream(RandomAccessStreamParams& aStreamParams) {
+ nsCOMPtr<nsIRandomAccessStream> stream;
+
+ switch (aStreamParams.type()) {
+ case RandomAccessStreamParams::TFileRandomAccessStreamParams:
+ nsFileRandomAccessStream::Create(NS_GET_IID(nsIFileRandomAccessStream),
+ getter_AddRefs(stream));
+ break;
+
+ case RandomAccessStreamParams::TLimitingFileRandomAccessStreamParams:
+ stream = new dom::quota::FileRandomAccessStream();
+ break;
+
+ default:
+ MOZ_ASSERT_UNREACHABLE("Unknown params!");
+ return Err(false);
+ }
+
+ MOZ_ASSERT(stream);
+
+ if (!stream->Deserialize(aStreamParams)) {
+ MOZ_ASSERT_UNREACHABLE("Deserialize failed!");
+ return Err(false);
+ }
+
+ return WrapMovingNotNullUnchecked(std::move(stream));
+}
+
+Result<nsCOMPtr<nsIRandomAccessStream>, bool> DeserializeRandomAccessStream(
+ Maybe<RandomAccessStreamParams>& aStreamParams) {
+ if (aStreamParams.isNothing()) {
+ return nsCOMPtr<nsIRandomAccessStream>();
+ }
+
+ auto res = DeserializeRandomAccessStream(aStreamParams.ref());
+ if (res.isErr()) {
+ return res.propagateErr();
+ }
+
+ MovingNotNull<nsCOMPtr<nsIRandomAccessStream>> stream = res.unwrap();
+
+ return std::move(stream).unwrapBasePtr();
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/RandomAccessStreamUtils.h b/ipc/glue/RandomAccessStreamUtils.h
new file mode 100644
index 0000000000..3ca79537eb
--- /dev/null
+++ b/ipc/glue/RandomAccessStreamUtils.h
@@ -0,0 +1,50 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_RandomAccessStreamUtils_h
+#define mozilla_ipc_RandomAccessStreamUtils_h
+
+template <class T>
+class nsCOMPtr;
+
+class nsIInterfaceRequestor;
+class nsIRandomAccessStream;
+
+namespace mozilla {
+
+template <class T>
+class Maybe;
+
+template <typename T>
+class MovingNotNull;
+
+template <typename V, typename E>
+class Result;
+
+namespace ipc {
+
+class RandomAccessStreamParams;
+
+// Serialize an nsIRandomAccessStream to be sent over IPC infallibly.
+RandomAccessStreamParams SerializeRandomAccessStream(
+ MovingNotNull<nsCOMPtr<nsIRandomAccessStream>> aStream,
+ nsIInterfaceRequestor* aCallbacks);
+
+Maybe<RandomAccessStreamParams> SerializeRandomAccessStream(
+ nsCOMPtr<nsIRandomAccessStream> aStream, nsIInterfaceRequestor* aCallbacks);
+
+// Deserialize an nsIRandomAccessStream received from an actor call. These
+// methods work in both the child and parent.
+Result<MovingNotNull<nsCOMPtr<nsIRandomAccessStream>>, bool>
+DeserializeRandomAccessStream(RandomAccessStreamParams& aStreamParams);
+
+Result<nsCOMPtr<nsIRandomAccessStream>, bool> DeserializeRandomAccessStream(
+ Maybe<RandomAccessStreamParams>& aStreamParams);
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_RandomAccessStreamUtils_h
diff --git a/ipc/glue/RawShmem.cpp b/ipc/glue/RawShmem.cpp
new file mode 100644
index 0000000000..f700804301
--- /dev/null
+++ b/ipc/glue/RawShmem.cpp
@@ -0,0 +1,108 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "RawShmem.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+namespace mozilla::ipc {
+
+UnsafeSharedMemoryHandle::UnsafeSharedMemoryHandle()
+ : mHandle(ipc::SharedMemoryBasic::NULLHandle()), mSize(0) {}
+
+UnsafeSharedMemoryHandle::UnsafeSharedMemoryHandle(
+ UnsafeSharedMemoryHandle&& aOther) noexcept
+ : mHandle(std::move(aOther.mHandle)), mSize(aOther.mSize) {
+ aOther.mHandle = ipc::SharedMemoryBasic::NULLHandle();
+ aOther.mSize = 0;
+}
+
+UnsafeSharedMemoryHandle& UnsafeSharedMemoryHandle::operator=(
+ UnsafeSharedMemoryHandle&& aOther) noexcept {
+ if (this == &aOther) {
+ return *this;
+ }
+
+ mHandle = std::move(aOther.mHandle);
+ mSize = aOther.mSize;
+ aOther.mHandle = ipc::SharedMemoryBasic::NULLHandle();
+ aOther.mSize = 0;
+ return *this;
+}
+
+Maybe<std::pair<UnsafeSharedMemoryHandle, WritableSharedMemoryMapping>>
+UnsafeSharedMemoryHandle::CreateAndMap(size_t aSize) {
+ if (aSize == 0) {
+ return Some(std::make_pair(UnsafeSharedMemoryHandle(),
+ WritableSharedMemoryMapping()));
+ }
+
+ RefPtr<ipc::SharedMemoryBasic> shm = MakeAndAddRef<ipc::SharedMemoryBasic>();
+ if (NS_WARN_IF(!shm->Create(aSize)) || NS_WARN_IF(!shm->Map(aSize))) {
+ return Nothing();
+ }
+
+ auto handle = shm->TakeHandle();
+
+ auto size = shm->Size();
+
+ return Some(std::make_pair(UnsafeSharedMemoryHandle(std::move(handle), size),
+ WritableSharedMemoryMapping(std::move(shm))));
+}
+
+WritableSharedMemoryMapping::WritableSharedMemoryMapping(
+ RefPtr<ipc::SharedMemoryBasic>&& aRef)
+ : mRef(aRef) {}
+
+Maybe<WritableSharedMemoryMapping> WritableSharedMemoryMapping::Open(
+ UnsafeSharedMemoryHandle aHandle) {
+ if (aHandle.mSize == 0) {
+ return Some(WritableSharedMemoryMapping(nullptr));
+ }
+
+ RefPtr<ipc::SharedMemoryBasic> shm = MakeAndAddRef<ipc::SharedMemoryBasic>();
+ if (NS_WARN_IF(!shm->SetHandle(std::move(aHandle.mHandle),
+ ipc::SharedMemory::RightsReadWrite)) ||
+ NS_WARN_IF(!shm->Map(aHandle.mSize))) {
+ return Nothing();
+ }
+
+ shm->CloseHandle();
+
+ return Some(WritableSharedMemoryMapping(std::move(shm)));
+}
+
+size_t WritableSharedMemoryMapping::Size() const {
+ if (!mRef) {
+ return 0;
+ }
+
+ return mRef->Size();
+}
+
+Span<uint8_t> WritableSharedMemoryMapping::Bytes() {
+ if (!mRef) {
+ return Span<uint8_t>();
+ }
+
+ uint8_t* mem = static_cast<uint8_t*>(mRef->memory());
+ return Span(mem, mRef->Size());
+}
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+auto ParamTraits<mozilla::ipc::UnsafeSharedMemoryHandle>::Write(
+ IPC::MessageWriter* aWriter, paramType&& aVar) -> void {
+ IPC::WriteParam(aWriter, std::move(aVar.mHandle));
+ IPC::WriteParam(aWriter, aVar.mSize);
+}
+
+auto ParamTraits<mozilla::ipc::UnsafeSharedMemoryHandle>::Read(
+ IPC::MessageReader* aReader, paramType* aVar) -> bool {
+ return IPC::ReadParam(aReader, &aVar->mHandle) &&
+ IPC::ReadParam(aReader, &aVar->mSize);
+}
+
+} // namespace IPC
diff --git a/ipc/glue/RawShmem.h b/ipc/glue/RawShmem.h
new file mode 100644
index 0000000000..cebc59e924
--- /dev/null
+++ b/ipc/glue/RawShmem.h
@@ -0,0 +1,113 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef MOZILLA_IPC_RAWSHMEM_H_
+#define MOZILLA_IPC_RAWSHMEM_H_
+
+#include "mozilla/ipc/SharedMemoryBasic.h"
+#include "mozilla/Span.h"
+#include <utility>
+
+namespace mozilla::ipc {
+
+class WritableSharedMemoryMapping;
+
+/// A handle to shared memory.
+///
+/// See the doc comment for `WritableSharedMemoryMapping` below.
+class UnsafeSharedMemoryHandle {
+ friend class WritableSharedMemoryMapping;
+ friend struct IPC::ParamTraits<UnsafeSharedMemoryHandle>;
+
+ public:
+ UnsafeSharedMemoryHandle();
+ UnsafeSharedMemoryHandle(UnsafeSharedMemoryHandle&& aOther) noexcept;
+ UnsafeSharedMemoryHandle& operator=(
+ UnsafeSharedMemoryHandle&& aOther) noexcept;
+
+ /// Attempts to allocate a shmem.
+ ///
+ /// Returns `Nothing()` if allocation fails.
+ /// If `aSize` is zero, a valid empty WritableSharedMemoryMapping is returned.
+ static Maybe<std::pair<UnsafeSharedMemoryHandle, WritableSharedMemoryMapping>>
+ CreateAndMap(size_t aSize);
+
+ private:
+ UnsafeSharedMemoryHandle(SharedMemoryBasic::Handle&& aHandle, uint64_t aSize)
+ : mHandle(std::move(aHandle)), mSize(aSize) {}
+
+ SharedMemoryBasic::Handle mHandle;
+ uint64_t mSize;
+};
+
+/// A Shared memory buffer mapping.
+///
+/// Unlike `ipc::Shmem`, the underlying shared memory buffer on each side of
+/// the process boundary is only deallocated with there respective
+/// `WritableSharedMemoryMapping`.
+///
+/// ## Usage
+///
+/// Typical usage goes as follows:
+/// - Allocate the memory using `UnsafeSharedMemoryHandle::Create`, returning a
+/// handle and a mapping.
+/// - Send the handle to the other process using an IPDL message.
+/// - On the other process, map the shared memory by creating
+/// WritableSharedMemoryMapping via `WritableSharedMemoryMapping::Open` and
+/// the received handle.
+///
+/// Do not send the shared memory handle again, it is only intended to establish
+/// the mapping on each side during initialization. The user of this class is
+/// responsible for managing the lifetime of the buffers on each side, as well
+/// as their identity, by for example storing them in hash map and referring to
+/// them via IDs in IPDL message if need be.
+///
+/// ## Empty shmems
+///
+/// An empty WritableSharedMemoryMapping is one that was created with size zero.
+/// It is analogous to a null RefPtr. It can be used like a non-empty shmem,
+/// including sending the handle and openning it on another process (resulting
+/// in an empty mapping on the other side).
+class WritableSharedMemoryMapping {
+ friend class UnsafeSharedMemoryHandle;
+
+ public:
+ WritableSharedMemoryMapping() = default;
+
+ WritableSharedMemoryMapping(WritableSharedMemoryMapping&& aMoved) = default;
+
+ WritableSharedMemoryMapping& operator=(WritableSharedMemoryMapping&& aMoved) =
+ default;
+
+ /// Open the shmem and immediately close the handle.
+ static Maybe<WritableSharedMemoryMapping> Open(
+ UnsafeSharedMemoryHandle aHandle);
+
+ // Returns the size in bytes.
+ size_t Size() const;
+
+ // Returns the shared memory as byte range.
+ Span<uint8_t> Bytes();
+
+ private:
+ explicit WritableSharedMemoryMapping(
+ RefPtr<mozilla::ipc::SharedMemoryBasic>&& aRef);
+
+ RefPtr<mozilla::ipc::SharedMemoryBasic> mRef;
+};
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+template <>
+struct ParamTraits<mozilla::ipc::UnsafeSharedMemoryHandle> {
+ typedef mozilla::ipc::UnsafeSharedMemoryHandle paramType;
+ static void Write(IPC::MessageWriter* aWriter, paramType&& aVar);
+ static bool Read(IPC::MessageReader* aReader, paramType* aVar);
+};
+
+} // namespace IPC
+
+#endif
diff --git a/ipc/glue/ScopedPort.cpp b/ipc/glue/ScopedPort.cpp
new file mode 100644
index 0000000000..e874796fb2
--- /dev/null
+++ b/ipc/glue/ScopedPort.cpp
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/ScopedPort.h"
+#include "mozilla/ipc/NodeController.h"
+#include "chrome/common/ipc_message_utils.h"
+
+namespace mozilla::ipc {
+
+void ScopedPort::Reset() {
+ if (mValid) {
+ mController->ClosePort(mPort);
+ }
+ mValid = false;
+ mPort = {};
+ mController = nullptr;
+}
+
+auto ScopedPort::Release() -> PortRef {
+ if (!mValid) {
+ return {};
+ }
+ mValid = false;
+ mController = nullptr;
+ return std::exchange(mPort, PortRef{});
+}
+
+ScopedPort::ScopedPort() = default;
+
+ScopedPort::~ScopedPort() { Reset(); }
+
+ScopedPort::ScopedPort(PortRef aPort, NodeController* aController)
+ : mValid(true), mPort(std::move(aPort)), mController(aController) {
+ MOZ_ASSERT(mPort.is_valid() && mController);
+}
+
+ScopedPort::ScopedPort(ScopedPort&& aOther)
+ : mValid(std::exchange(aOther.mValid, false)),
+ mPort(std::move(aOther.mPort)),
+ mController(std::move(aOther.mController)) {}
+
+ScopedPort& ScopedPort::operator=(ScopedPort&& aOther) {
+ if (this != &aOther) {
+ Reset();
+ mValid = std::exchange(aOther.mValid, false);
+ mPort = std::move(aOther.mPort);
+ mController = std::move(aOther.mController);
+ }
+ return *this;
+}
+
+} // namespace mozilla::ipc
+
+void IPC::ParamTraits<mozilla::ipc::ScopedPort>::Write(MessageWriter* aWriter,
+ paramType&& aParam) {
+ aWriter->WriteBool(aParam.IsValid());
+ if (!aParam.IsValid()) {
+ return;
+ }
+ aWriter->WritePort(std::move(aParam));
+}
+
+bool IPC::ParamTraits<mozilla::ipc::ScopedPort>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ bool isValid = false;
+ if (!aReader->ReadBool(&isValid)) {
+ return false;
+ }
+ if (!isValid) {
+ *aResult = {};
+ return true;
+ }
+ return aReader->ConsumePort(aResult);
+}
diff --git a/ipc/glue/ScopedPort.h b/ipc/glue/ScopedPort.h
new file mode 100644
index 0000000000..e683ba894e
--- /dev/null
+++ b/ipc/glue/ScopedPort.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_RawEndpoint_h
+#define mozilla_ipc_RawEndpoint_h
+
+#include "mojo/core/ports/port_ref.h"
+
+namespace mozilla::ipc {
+
+class NodeController;
+
+/// A uniquely owned raw IPC endpoint, connected to our peers over the node
+/// controller. This type can be sent over IPC channels to establish
+/// connections.
+///
+/// In general, prefer using Endpoint over ScopedPort for type safety reasons.
+class ScopedPort {
+ using PortName = mojo::core::ports::PortName;
+ using PortRef = mojo::core::ports::PortRef;
+
+ public:
+ ScopedPort();
+ ~ScopedPort();
+
+ ScopedPort(PortRef aPort, NodeController* aController);
+
+ ScopedPort(ScopedPort&& aOther);
+ ScopedPort(const ScopedPort&) = delete;
+
+ ScopedPort& operator=(ScopedPort&& aOther);
+ ScopedPort& operator=(const ScopedPort&) = delete;
+
+ // Allow checking if this `ScopedPort` is valid or not.
+ bool IsValid() const { return mValid; }
+ explicit operator bool() const { return IsValid(); }
+
+ // Underlying port and controller which are used by this ScopedPort.
+ const PortName& Name() const { return mPort.name(); }
+ const PortRef& Port() const { return mPort; }
+ NodeController* Controller() const { return mController; }
+
+ // Release ownership over the contained `ScopedPort`, meaning that it will
+ // not be closed when this ScopedPort is destroyed. This will make the
+ // endpoint invalid.
+ PortRef Release();
+
+ private:
+ void Reset();
+
+ bool mValid = false;
+ PortRef mPort;
+ RefPtr<NodeController> mController;
+
+ // NOTE: This type does not contain PID information about the other process,
+ // which will need to be sent separately if necessary.
+};
+
+} // namespace mozilla::ipc
+
+namespace IPC {
+
+template <typename T>
+struct ParamTraits;
+
+template <>
+struct ParamTraits<mozilla::ipc::ScopedPort> {
+ using paramType = mozilla::ipc::ScopedPort;
+
+ static void Write(MessageWriter* aWriter, paramType&& aParam);
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+} // namespace IPC
+
+#endif
diff --git a/ipc/glue/SerializedStructuredCloneBuffer.cpp b/ipc/glue/SerializedStructuredCloneBuffer.cpp
new file mode 100644
index 0000000000..9cad1ed826
--- /dev/null
+++ b/ipc/glue/SerializedStructuredCloneBuffer.cpp
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/SerializedStructuredCloneBuffer.h"
+#include "js/StructuredClone.h"
+
+namespace IPC {
+
+void ParamTraits<JSStructuredCloneData>::Write(MessageWriter* aWriter,
+ const paramType& aParam) {
+ MOZ_ASSERT(!(aParam.Size() % sizeof(uint64_t)));
+
+ // We can only construct shared memory regions up to 4Gb in size, making that
+ // the maximum possible JSStructuredCloneData size.
+ mozilla::CheckedUint32 size = aParam.Size();
+ if (!size.isValid()) {
+ aWriter->FatalError("JSStructuredCloneData over 4Gb in size");
+ return;
+ }
+ WriteParam(aWriter, size.value());
+
+ MessageBufferWriter bufWriter(aWriter, size.value());
+ aParam.ForEachDataChunk([&](const char* aData, size_t aSize) {
+ return bufWriter.WriteBytes(aData, aSize);
+ });
+}
+
+bool ParamTraits<JSStructuredCloneData>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ uint32_t length = 0;
+ if (!ReadParam(aReader, &length)) {
+ aReader->FatalError("JSStructuredCloneData length read failed");
+ return false;
+ }
+ MOZ_ASSERT(!(length % sizeof(uint64_t)));
+
+ // Borrowing is not suitable to use for IPC to hand out data because we often
+ // want to store the data somewhere for processing after IPC has released the
+ // underlying buffers.
+ //
+ // This deserializer previously used a mechanism to transfer ownership over
+ // the underlying buffers from IPC into the JSStructuredCloneData. This was
+ // removed when support for serializing over shared memory was added, as the
+ // benefit for avoiding copies was limited due to it only functioning for
+ // buffers under 64k in size (as larger buffers would be serialized using
+ // shared memory), and it added substantial complexity to the BufferList type
+ // and the IPC serialization layer due to things like buffer alignment. This
+ // can be revisited in the future if it turns out to be a noticable
+ // performance regression. (bug 1783242)
+
+ mozilla::BufferList<js::SystemAllocPolicy> buffers(0, 0, 4096);
+ MessageBufferReader bufReader(aReader, length);
+ uint32_t read = 0;
+ while (read < length) {
+ size_t bufLen;
+ char* buf = buffers.AllocateBytes(length - read, &bufLen);
+ if (!buf) {
+ // Would be nice to allow actor to control behaviour here (bug 1784307)
+ NS_ABORT_OOM(length - read);
+ return false;
+ }
+ if (!bufReader.ReadBytesInto(buf, bufLen)) {
+ aReader->FatalError("JSStructuredCloneData ReadBytesInto failed");
+ return false;
+ }
+ read += bufLen;
+ }
+
+ MOZ_ASSERT(read == length);
+ *aResult = JSStructuredCloneData(
+ std::move(buffers), JS::StructuredCloneScope::DifferentProcess,
+ OwnTransferablePolicy::IgnoreTransferablesIfAny);
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/glue/SerializedStructuredCloneBuffer.h b/ipc/glue/SerializedStructuredCloneBuffer.h
new file mode 100644
index 0000000000..ed4e404dbc
--- /dev/null
+++ b/ipc/glue/SerializedStructuredCloneBuffer.h
@@ -0,0 +1,87 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef __IPC_GLUE_SERIALIZEDSTRUCTUREDCLONEBUFFER_H__
+#define __IPC_GLUE_SERIALIZEDSTRUCTUREDCLONEBUFFER_H__
+
+#include <algorithm>
+#include <cstdint>
+#include <cstdlib>
+#include <string>
+#include <utility>
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "js/AllocPolicy.h"
+#include "js/StructuredClone.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/BufferList.h"
+#include "mozilla/Vector.h"
+#include "mozilla/mozalloc.h"
+class PickleIterator;
+
+namespace mozilla {
+template <typename...>
+class Variant;
+
+namespace detail {
+template <typename...>
+struct VariantTag;
+}
+} // namespace mozilla
+
+namespace mozilla {
+
+struct SerializedStructuredCloneBuffer final {
+ SerializedStructuredCloneBuffer() = default;
+
+ SerializedStructuredCloneBuffer(SerializedStructuredCloneBuffer&&) = default;
+ SerializedStructuredCloneBuffer& operator=(
+ SerializedStructuredCloneBuffer&&) = default;
+
+ SerializedStructuredCloneBuffer(const SerializedStructuredCloneBuffer&) =
+ delete;
+ SerializedStructuredCloneBuffer& operator=(
+ const SerializedStructuredCloneBuffer& aOther) = delete;
+
+ bool operator==(const SerializedStructuredCloneBuffer& aOther) const {
+ // The copy assignment operator and the equality operator are
+ // needed by the IPDL generated code. We relied on the copy
+ // assignment operator at some places but we never use the
+ // equality operator.
+ return false;
+ }
+
+ JSStructuredCloneData data{JS::StructuredCloneScope::Unassigned};
+};
+
+} // namespace mozilla
+
+namespace IPC {
+template <>
+struct ParamTraits<JSStructuredCloneData> {
+ typedef JSStructuredCloneData paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam);
+
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+template <>
+struct ParamTraits<mozilla::SerializedStructuredCloneBuffer> {
+ typedef mozilla::SerializedStructuredCloneBuffer paramType;
+
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.data);
+ }
+
+ static bool Read(MessageReader* aReader, paramType* aResult) {
+ return ReadParam(aReader, &aResult->data);
+ }
+};
+
+} // namespace IPC
+
+#endif /* __IPC_GLUE_SERIALIZEDSTRUCTUREDCLONEBUFFER_H__ */
diff --git a/ipc/glue/SetProcessTitle.cpp b/ipc/glue/SetProcessTitle.cpp
new file mode 100644
index 0000000000..4d929fb53c
--- /dev/null
+++ b/ipc/glue/SetProcessTitle.cpp
@@ -0,0 +1,51 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/SetProcessTitle.h"
+
+#include "nsString.h"
+
+#ifdef XP_LINUX
+
+# include "base/set_process_title_linux.h"
+# define HAVE_SETPROCTITLE
+# define HAVE_SETPROCTITLE_INIT
+
+#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || \
+ defined(__DragonFly__)
+
+# include <sys/types.h>
+# include <unistd.h>
+# define HAVE_SETPROCTITLE
+
+#endif
+
+namespace mozilla {
+
+void SetProcessTitle(const std::vector<std::string>& aNewArgv) {
+#ifdef HAVE_SETPROCTITLE
+ nsAutoCStringN<1024> buf;
+
+ bool firstArg = true;
+ for (const std::string& arg : aNewArgv) {
+ if (firstArg) {
+ firstArg = false;
+ } else {
+ buf.Append(' ');
+ }
+ buf.Append(arg.c_str());
+ }
+
+ setproctitle("-%s", buf.get());
+#endif
+}
+
+void SetProcessTitleInit(char** aOrigArgv) {
+#ifdef HAVE_SETPROCTITLE_INIT
+ setproctitle_init(aOrigArgv);
+#endif
+}
+
+} // namespace mozilla
diff --git a/ipc/glue/SetProcessTitle.h b/ipc/glue/SetProcessTitle.h
new file mode 100644
index 0000000000..01b8caa3ce
--- /dev/null
+++ b/ipc/glue/SetProcessTitle.h
@@ -0,0 +1,19 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SetProcessTitle_h
+#define mozilla_ipc_SetProcessTitle_h
+
+#include <string>
+#include <vector>
+
+namespace mozilla {
+
+void SetProcessTitle(const std::vector<std::string>& aNewArgv);
+void SetProcessTitleInit(char** aOrigArgv);
+
+} // namespace mozilla
+
+#endif // mozilla_ipc_SetProcessTitle_h
diff --git a/ipc/glue/SharedMemory.cpp b/ipc/glue/SharedMemory.cpp
new file mode 100644
index 0000000000..4761746658
--- /dev/null
+++ b/ipc/glue/SharedMemory.cpp
@@ -0,0 +1,84 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <math.h>
+
+#include "nsString.h"
+#include "nsIMemoryReporter.h"
+#include "mozilla/ipc/SharedMemory.h"
+#include "mozilla/Atomics.h"
+
+namespace mozilla {
+namespace ipc {
+
+static Atomic<size_t> gShmemAllocated;
+static Atomic<size_t> gShmemMapped;
+
+class ShmemReporter final : public nsIMemoryReporter {
+ ~ShmemReporter() = default;
+
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ NS_IMETHOD
+ CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData,
+ bool aAnonymize) override {
+ MOZ_COLLECT_REPORT(
+ "shmem-allocated", KIND_OTHER, UNITS_BYTES, gShmemAllocated,
+ "Memory shared with other processes that is accessible (but not "
+ "necessarily mapped).");
+
+ MOZ_COLLECT_REPORT(
+ "shmem-mapped", KIND_OTHER, UNITS_BYTES, gShmemMapped,
+ "Memory shared with other processes that is mapped into the address "
+ "space.");
+
+ return NS_OK;
+ }
+};
+
+NS_IMPL_ISUPPORTS(ShmemReporter, nsIMemoryReporter)
+
+SharedMemory::SharedMemory() : mAllocSize(0), mMappedSize(0) {
+ static Atomic<bool> registered;
+ if (registered.compareExchange(false, true)) {
+ RegisterStrongMemoryReporter(new ShmemReporter());
+ }
+}
+
+/*static*/
+size_t SharedMemory::PageAlignedSize(size_t aSize) {
+ size_t pageSize = SystemPageSize();
+ size_t nPagesNeeded = size_t(ceil(double(aSize) / double(pageSize)));
+ return pageSize * nPagesNeeded;
+}
+
+void SharedMemory::Created(size_t aNBytes) {
+ mAllocSize = aNBytes;
+ gShmemAllocated += mAllocSize;
+}
+
+void SharedMemory::Mapped(size_t aNBytes) {
+ mMappedSize = aNBytes;
+ gShmemMapped += mMappedSize;
+}
+
+void SharedMemory::Unmapped() {
+ MOZ_ASSERT(gShmemMapped >= mMappedSize, "Can't unmap more than mapped");
+ gShmemMapped -= mMappedSize;
+ mMappedSize = 0;
+}
+
+/*static*/
+void SharedMemory::Destroyed() {
+ MOZ_ASSERT(gShmemAllocated >= mAllocSize,
+ "Can't destroy more than allocated");
+ gShmemAllocated -= mAllocSize;
+ mAllocSize = 0;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/SharedMemory.h b/ipc/glue/SharedMemory.h
new file mode 100644
index 0000000000..818fad5e69
--- /dev/null
+++ b/ipc/glue/SharedMemory.h
@@ -0,0 +1,142 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SharedMemory_h
+#define mozilla_ipc_SharedMemory_h
+
+#include "nsDebug.h"
+#include "nsISupportsImpl.h" // NS_INLINE_DECL_REFCOUNTING
+#include "mozilla/Attributes.h"
+
+#include "base/process.h"
+#include "chrome/common/ipc_message_utils.h"
+
+//
+// This is a low-level wrapper around platform shared memory. Don't
+// use it directly; use Shmem allocated through IPDL interfaces.
+//
+namespace {
+enum Rights { RightsNone = 0, RightsRead = 1 << 0, RightsWrite = 1 << 1 };
+} // namespace
+
+namespace mozilla {
+
+namespace ipc {
+class SharedMemory;
+} // namespace ipc
+
+namespace ipc {
+
+class SharedMemory {
+ protected:
+ virtual ~SharedMemory() {
+ Unmapped();
+ Destroyed();
+ }
+
+ public:
+ enum OpenRights {
+ RightsReadOnly = RightsRead,
+ RightsReadWrite = RightsRead | RightsWrite,
+ };
+
+ size_t Size() const { return mMappedSize; }
+
+ virtual void* memory() const = 0;
+
+ virtual bool Create(size_t size) = 0;
+ virtual bool Map(size_t nBytes, void* fixed_address = nullptr) = 0;
+ virtual void Unmap() = 0;
+
+ virtual void CloseHandle() = 0;
+
+ virtual bool WriteHandle(IPC::MessageWriter* aWriter) = 0;
+ virtual bool ReadHandle(IPC::MessageReader* aReader) = 0;
+
+ void Protect(char* aAddr, size_t aSize, int aRights) {
+ char* memStart = reinterpret_cast<char*>(memory());
+ if (!memStart) MOZ_CRASH("SharedMemory region points at NULL!");
+ char* memEnd = memStart + Size();
+
+ char* protStart = aAddr;
+ if (!protStart) MOZ_CRASH("trying to Protect() a NULL region!");
+ char* protEnd = protStart + aSize;
+
+ if (!(memStart <= protStart && protEnd <= memEnd))
+ MOZ_CRASH("attempt to Protect() a region outside this SharedMemory");
+
+ // checks alignment etc.
+ SystemProtect(aAddr, aSize, aRights);
+ }
+
+ // bug 1168843, compositor thread may create shared memory instances that are
+ // destroyed by main thread on shutdown, so this must use thread-safe RC to
+ // avoid hitting assertion
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(SharedMemory)
+
+ static void SystemProtect(char* aAddr, size_t aSize, int aRights);
+ [[nodiscard]] static bool SystemProtectFallible(char* aAddr, size_t aSize,
+ int aRights);
+ static size_t SystemPageSize();
+ static size_t PageAlignedSize(size_t aSize);
+
+ protected:
+ SharedMemory();
+
+ // Implementations should call these methods on shmem usage changes,
+ // but *only if* the OS-specific calls are known to have succeeded.
+ // The methods are expected to be called in the pattern
+ //
+ // Created (Mapped Unmapped)* Destroy
+ //
+ // but this isn't checked.
+ void Created(size_t aNBytes);
+ void Mapped(size_t aNBytes);
+ void Unmapped();
+ void Destroyed();
+
+ // The size of the shmem region requested in Create(), if
+ // successful. SharedMemory instances that are opened from a
+ // foreign handle have an alloc size of 0, even though they have
+ // access to the alloc-size information.
+ size_t mAllocSize;
+ // The size of the region mapped in Map(), if successful. All
+ // SharedMemorys that are mapped have a non-zero mapped size.
+ size_t mMappedSize;
+};
+
+template <typename HandleImpl>
+class SharedMemoryCommon : public SharedMemory {
+ public:
+ typedef HandleImpl Handle;
+
+ virtual Handle CloneHandle() = 0;
+ virtual Handle TakeHandle() = 0;
+ virtual bool IsHandleValid(const Handle& aHandle) const = 0;
+ virtual bool SetHandle(Handle aHandle, OpenRights aRights) = 0;
+
+ virtual void CloseHandle() override { TakeHandle(); }
+
+ virtual bool WriteHandle(IPC::MessageWriter* aWriter) override {
+ Handle handle = CloneHandle();
+ if (!handle) {
+ return false;
+ }
+ IPC::WriteParam(aWriter, std::move(handle));
+ return true;
+ }
+
+ virtual bool ReadHandle(IPC::MessageReader* aReader) override {
+ Handle handle;
+ return IPC::ReadParam(aReader, &handle) && IsHandleValid(handle) &&
+ SetHandle(std::move(handle), RightsReadWrite);
+ }
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_SharedMemory_h
diff --git a/ipc/glue/SharedMemoryBasic.h b/ipc/glue/SharedMemoryBasic.h
new file mode 100644
index 0000000000..2f07ae4402
--- /dev/null
+++ b/ipc/glue/SharedMemoryBasic.h
@@ -0,0 +1,16 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SharedMemoryBasic_h
+#define mozilla_ipc_SharedMemoryBasic_h
+
+#ifdef XP_DARWIN
+# include "mozilla/ipc/SharedMemoryBasic_mach.h"
+#else
+# include "mozilla/ipc/SharedMemoryBasic_chromium.h"
+#endif
+
+#endif // ifndef mozilla_ipc_SharedMemoryBasic_h
diff --git a/ipc/glue/SharedMemoryBasic_chromium.h b/ipc/glue/SharedMemoryBasic_chromium.h
new file mode 100644
index 0000000000..8d65e7f189
--- /dev/null
+++ b/ipc/glue/SharedMemoryBasic_chromium.h
@@ -0,0 +1,89 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SharedMemoryBasic_chromium_h
+#define mozilla_ipc_SharedMemoryBasic_chromium_h
+
+#include "base/shared_memory.h"
+#include "mozilla/ipc/SharedMemory.h"
+
+#ifdef FUZZING
+# include "mozilla/ipc/SharedMemoryFuzzer.h"
+#endif
+
+#include "nsDebug.h"
+
+//
+// This is a low-level wrapper around platform shared memory. Don't
+// use it directly; use Shmem allocated through IPDL interfaces.
+//
+
+namespace mozilla {
+namespace ipc {
+
+class SharedMemoryBasic final
+ : public SharedMemoryCommon<base::SharedMemoryHandle> {
+ public:
+ SharedMemoryBasic() = default;
+
+ virtual bool SetHandle(Handle aHandle, OpenRights aRights) override {
+ return mSharedMemory.SetHandle(std::move(aHandle),
+ aRights == RightsReadOnly);
+ }
+
+ virtual bool Create(size_t aNbytes) override {
+ bool ok = mSharedMemory.Create(aNbytes);
+ if (ok) {
+ Created(aNbytes);
+ }
+ return ok;
+ }
+
+ virtual bool Map(size_t nBytes, void* fixed_address = nullptr) override {
+ bool ok = mSharedMemory.Map(nBytes, fixed_address);
+ if (ok) {
+ Mapped(nBytes);
+ }
+ return ok;
+ }
+
+ virtual void Unmap() override { mSharedMemory.Unmap(); }
+
+ virtual void* memory() const override {
+#ifdef FUZZING
+ return SharedMemoryFuzzer::MutateSharedMemory(mSharedMemory.memory(),
+ mAllocSize);
+#else
+ return mSharedMemory.memory();
+#endif
+ }
+
+ static Handle NULLHandle() { return base::SharedMemory::NULLHandle(); }
+
+ virtual bool IsHandleValid(const Handle& aHandle) const override {
+ return base::SharedMemory::IsHandleValid(aHandle);
+ }
+
+ virtual Handle CloneHandle() override { return mSharedMemory.CloneHandle(); }
+
+ virtual Handle TakeHandle() override {
+ return mSharedMemory.TakeHandle(false);
+ }
+
+ static void* FindFreeAddressSpace(size_t size) {
+ return base::SharedMemory::FindFreeAddressSpace(size);
+ }
+
+ private:
+ ~SharedMemoryBasic() = default;
+
+ base::SharedMemory mSharedMemory;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_SharedMemoryBasic_chromium_h
diff --git a/ipc/glue/SharedMemoryBasic_mach.h b/ipc/glue/SharedMemoryBasic_mach.h
new file mode 100644
index 0000000000..d7ea9b2c39
--- /dev/null
+++ b/ipc/glue/SharedMemoryBasic_mach.h
@@ -0,0 +1,75 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SharedMemoryBasic_mach_h
+#define mozilla_ipc_SharedMemoryBasic_mach_h
+
+#include "base/process.h"
+
+#include "mozilla/UniquePtrExtensions.h"
+#include "mozilla/ipc/SharedMemory.h"
+#include <mach/port.h>
+
+#ifdef FUZZING
+# include "mozilla/ipc/SharedMemoryFuzzer.h"
+#endif
+
+//
+// This is a low-level wrapper around platform shared memory. Don't
+// use it directly; use Shmem allocated through IPDL interfaces.
+//
+
+class MachPortSender;
+class ReceivePort;
+
+namespace mozilla {
+namespace ipc {
+
+class SharedMemoryBasic final
+ : public SharedMemoryCommon<mozilla::UniqueMachSendRight> {
+ public:
+ SharedMemoryBasic();
+
+ virtual bool SetHandle(Handle aHandle, OpenRights aRights) override;
+
+ virtual bool Create(size_t aNbytes) override;
+
+ virtual bool Map(size_t nBytes, void* fixed_address = nullptr) override;
+
+ virtual void Unmap() override;
+
+ virtual void* memory() const override {
+#ifdef FUZZING
+ return SharedMemoryFuzzer::MutateSharedMemory(mMemory, mAllocSize);
+#else
+ return mMemory;
+#endif
+ }
+
+ static Handle NULLHandle() { return Handle(); }
+
+ static void* FindFreeAddressSpace(size_t aSize);
+
+ virtual bool IsHandleValid(const Handle& aHandle) const override;
+
+ virtual Handle CloneHandle() override;
+
+ virtual Handle TakeHandle() override;
+
+ private:
+ ~SharedMemoryBasic();
+
+ mozilla::UniqueMachSendRight mPort;
+ // Pointer to mapped region, null if unmapped.
+ void* mMemory;
+ // Access rights to map an existing region with.
+ OpenRights mOpenRights;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_SharedMemoryBasic_mach_h
diff --git a/ipc/glue/SharedMemoryBasic_mach.mm b/ipc/glue/SharedMemoryBasic_mach.mm
new file mode 100644
index 0000000000..d9992792e9
--- /dev/null
+++ b/ipc/glue/SharedMemoryBasic_mach.mm
@@ -0,0 +1,175 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=8 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <map>
+
+#include <mach/vm_map.h>
+#include <mach/mach_port.h>
+#if defined(XP_IOS)
+# include <mach/vm_map.h>
+# define mach_vm_address_t vm_address_t
+# define mach_vm_map vm_map
+# define mach_vm_read vm_read
+# define mach_vm_region_recurse vm_region_recurse_64
+# define mach_vm_size_t vm_size_t
+#else
+# include <mach/mach_vm.h>
+#endif
+#include <pthread.h>
+#include <unistd.h>
+#include "SharedMemoryBasic.h"
+
+#include "mozilla/IntegerPrintfMacros.h"
+#include "mozilla/Printf.h"
+#include "mozilla/StaticMutex.h"
+
+#ifdef DEBUG
+# define LOG_ERROR(str, args...) \
+ PR_BEGIN_MACRO \
+ mozilla::SmprintfPointer msg = mozilla::Smprintf(str, ##args); \
+ NS_WARNING(msg.get()); \
+ PR_END_MACRO
+#else
+# define LOG_ERROR(str, args...) \
+ do { /* nothing */ \
+ } while (0)
+#endif
+
+namespace mozilla {
+namespace ipc {
+
+SharedMemoryBasic::SharedMemoryBasic()
+ : mPort(MACH_PORT_NULL), mMemory(nullptr), mOpenRights(RightsReadWrite) {}
+
+SharedMemoryBasic::~SharedMemoryBasic() {
+ Unmap();
+ CloseHandle();
+}
+
+bool SharedMemoryBasic::SetHandle(Handle aHandle, OpenRights aRights) {
+ MOZ_ASSERT(mPort == MACH_PORT_NULL, "already initialized");
+
+ mPort = std::move(aHandle);
+ mOpenRights = aRights;
+ return true;
+}
+
+static inline void* toPointer(mach_vm_address_t address) {
+ return reinterpret_cast<void*>(static_cast<uintptr_t>(address));
+}
+
+static inline mach_vm_address_t toVMAddress(void* pointer) {
+ return static_cast<mach_vm_address_t>(reinterpret_cast<uintptr_t>(pointer));
+}
+
+bool SharedMemoryBasic::Create(size_t size) {
+ MOZ_ASSERT(mPort == MACH_PORT_NULL, "already initialized");
+
+ memory_object_size_t memoryObjectSize = round_page(size);
+
+ kern_return_t kr =
+ mach_make_memory_entry_64(mach_task_self(), &memoryObjectSize, 0,
+ MAP_MEM_NAMED_CREATE | VM_PROT_DEFAULT,
+ getter_Transfers(mPort), MACH_PORT_NULL);
+ if (kr != KERN_SUCCESS || memoryObjectSize < round_page(size)) {
+ LOG_ERROR("Failed to make memory entry (%zu bytes). %s (%x)\n", size,
+ mach_error_string(kr), kr);
+ CloseHandle();
+ return false;
+ }
+
+ Created(size);
+ return true;
+}
+
+bool SharedMemoryBasic::Map(size_t size, void* fixed_address) {
+ MOZ_ASSERT(mMemory == nullptr);
+
+ if (MACH_PORT_NULL == mPort) {
+ return false;
+ }
+
+ kern_return_t kr;
+ mach_vm_address_t address = toVMAddress(fixed_address);
+
+ vm_prot_t vmProtection = VM_PROT_READ;
+ if (mOpenRights == RightsReadWrite) {
+ vmProtection |= VM_PROT_WRITE;
+ }
+
+ kr = mach_vm_map(mach_task_self(), &address, round_page(size), 0,
+ fixed_address ? VM_FLAGS_FIXED : VM_FLAGS_ANYWHERE,
+ mPort.get(), 0, false, vmProtection, vmProtection,
+ VM_INHERIT_NONE);
+ if (kr != KERN_SUCCESS) {
+ if (!fixed_address) {
+ LOG_ERROR(
+ "Failed to map shared memory (%zu bytes) into %x, port %x. %s (%x)\n",
+ size, mach_task_self(), mach_port_t(mPort.get()),
+ mach_error_string(kr), kr);
+ }
+ return false;
+ }
+
+ if (fixed_address && fixed_address != toPointer(address)) {
+ kr = vm_deallocate(mach_task_self(), address, size);
+ if (kr != KERN_SUCCESS) {
+ LOG_ERROR("Failed to unmap shared memory at unsuitable address "
+ "(%zu bytes) from %x, port %x. %s (%x)\n",
+ size, mach_task_self(), mach_port_t(mPort.get()),
+ mach_error_string(kr), kr);
+ }
+ return false;
+ }
+
+ mMemory = toPointer(address);
+ Mapped(size);
+ return true;
+}
+
+void* SharedMemoryBasic::FindFreeAddressSpace(size_t size) {
+ mach_vm_address_t address = 0;
+ size = round_page(size);
+ if (mach_vm_map(mach_task_self(), &address, size, 0, VM_FLAGS_ANYWHERE,
+ MEMORY_OBJECT_NULL, 0, false, VM_PROT_NONE, VM_PROT_NONE,
+ VM_INHERIT_NONE) != KERN_SUCCESS ||
+ vm_deallocate(mach_task_self(), address, size) != KERN_SUCCESS) {
+ return nullptr;
+ }
+ return toPointer(address);
+}
+
+auto SharedMemoryBasic::CloneHandle() -> Handle {
+ return mozilla::RetainMachSendRight(mPort.get());
+}
+
+auto SharedMemoryBasic::TakeHandle() -> Handle {
+ mOpenRights = RightsReadWrite;
+ return std::move(mPort);
+}
+
+void SharedMemoryBasic::Unmap() {
+ if (!mMemory) {
+ return;
+ }
+ vm_address_t address = toVMAddress(mMemory);
+ kern_return_t kr =
+ vm_deallocate(mach_task_self(), address, round_page(mMappedSize));
+ if (kr != KERN_SUCCESS) {
+ LOG_ERROR("Failed to deallocate shared memory. %s (%x)\n",
+ mach_error_string(kr), kr);
+ return;
+ }
+ mMemory = nullptr;
+}
+
+bool SharedMemoryBasic::IsHandleValid(const Handle& aHandle) const {
+ return aHandle != nullptr;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/SharedMemory_posix.cpp b/ipc/glue/SharedMemory_posix.cpp
new file mode 100644
index 0000000000..b634058945
--- /dev/null
+++ b/ipc/glue/SharedMemory_posix.cpp
@@ -0,0 +1,55 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <sys/mman.h> // mprotect
+#include <unistd.h> // sysconf
+
+#include "mozilla/ipc/SharedMemory.h"
+
+#if defined(XP_MACOSX) && defined(__x86_64__)
+# include "prenv.h"
+#endif
+
+namespace mozilla {
+namespace ipc {
+
+#if defined(XP_MACOSX) && defined(__x86_64__)
+std::atomic<size_t> sPageSizeOverride = 0;
+#endif
+
+void SharedMemory::SystemProtect(char* aAddr, size_t aSize, int aRights) {
+ if (!SystemProtectFallible(aAddr, aSize, aRights)) {
+ MOZ_CRASH("can't mprotect()");
+ }
+}
+
+bool SharedMemory::SystemProtectFallible(char* aAddr, size_t aSize,
+ int aRights) {
+ int flags = 0;
+ if (aRights & RightsRead) flags |= PROT_READ;
+ if (aRights & RightsWrite) flags |= PROT_WRITE;
+ if (RightsNone == aRights) flags = PROT_NONE;
+
+ return 0 == mprotect(aAddr, aSize, flags);
+}
+
+size_t SharedMemory::SystemPageSize() {
+#if defined(XP_MACOSX) && defined(__x86_64__)
+ if (sPageSizeOverride == 0) {
+ if (PR_GetEnv("MOZ_SHMEM_PAGESIZE_16K")) {
+ sPageSizeOverride = 16 * 1024;
+ } else {
+ sPageSizeOverride = sysconf(_SC_PAGESIZE);
+ }
+ }
+ return sPageSizeOverride;
+#else
+ return sysconf(_SC_PAGESIZE);
+#endif
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/SharedMemory_windows.cpp b/ipc/glue/SharedMemory_windows.cpp
new file mode 100644
index 0000000000..1cc93687af
--- /dev/null
+++ b/ipc/glue/SharedMemory_windows.cpp
@@ -0,0 +1,41 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include <windows.h>
+
+#include "mozilla/ipc/SharedMemory.h"
+
+namespace mozilla {
+namespace ipc {
+
+void SharedMemory::SystemProtect(char* aAddr, size_t aSize, int aRights) {
+ if (!SystemProtectFallible(aAddr, aSize, aRights)) {
+ MOZ_CRASH("can't VirtualProtect()");
+ }
+}
+
+bool SharedMemory::SystemProtectFallible(char* aAddr, size_t aSize,
+ int aRights) {
+ DWORD flags;
+ if ((aRights & RightsRead) && (aRights & RightsWrite))
+ flags = PAGE_READWRITE;
+ else if (aRights & RightsRead)
+ flags = PAGE_READONLY;
+ else
+ flags = PAGE_NOACCESS;
+
+ DWORD oldflags;
+ return VirtualProtect(aAddr, aSize, flags, &oldflags);
+}
+
+size_t SharedMemory::SystemPageSize() {
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwPageSize;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/Shmem.cpp b/ipc/glue/Shmem.cpp
new file mode 100644
index 0000000000..442c6fb73c
--- /dev/null
+++ b/ipc/glue/Shmem.cpp
@@ -0,0 +1,248 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "Shmem.h"
+
+#include "ProtocolUtils.h"
+#include "SharedMemoryBasic.h"
+#include "ShmemMessageUtils.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "mozilla/Unused.h"
+
+namespace mozilla {
+namespace ipc {
+
+class ShmemCreated : public IPC::Message {
+ private:
+ typedef Shmem::id_t id_t;
+
+ public:
+ ShmemCreated(int32_t routingId, id_t aIPDLId, size_t aSize)
+ : IPC::Message(
+ routingId, SHMEM_CREATED_MESSAGE_TYPE, 0,
+ HeaderFlags(NESTED_INSIDE_CPOW, CONTROL_PRIORITY, COMPRESSION_NONE,
+ LAZY_SEND, NOT_CONSTRUCTOR, ASYNC, NOT_REPLY)) {
+ MOZ_RELEASE_ASSERT(aSize < std::numeric_limits<uint32_t>::max(),
+ "Tried to create Shmem with size larger than 4GB");
+ IPC::MessageWriter writer(*this);
+ IPC::WriteParam(&writer, aIPDLId);
+ IPC::WriteParam(&writer, uint32_t(aSize));
+ }
+
+ static bool ReadInfo(IPC::MessageReader* aReader, id_t* aIPDLId,
+ size_t* aSize) {
+ uint32_t size = 0;
+ if (!IPC::ReadParam(aReader, aIPDLId) || !IPC::ReadParam(aReader, &size)) {
+ return false;
+ }
+ *aSize = size;
+ return true;
+ }
+
+ void Log(const std::string& aPrefix, FILE* aOutf) const {
+ fputs("(special ShmemCreated msg)", aOutf);
+ }
+};
+
+class ShmemDestroyed : public IPC::Message {
+ private:
+ typedef Shmem::id_t id_t;
+
+ public:
+ ShmemDestroyed(int32_t routingId, id_t aIPDLId)
+ : IPC::Message(
+ routingId, SHMEM_DESTROYED_MESSAGE_TYPE, 0,
+ HeaderFlags(NOT_NESTED, NORMAL_PRIORITY, COMPRESSION_NONE,
+ LAZY_SEND, NOT_CONSTRUCTOR, ASYNC, NOT_REPLY)) {
+ IPC::MessageWriter writer(*this);
+ IPC::WriteParam(&writer, aIPDLId);
+ }
+};
+
+static already_AddRefed<SharedMemory> NewSegment() {
+ return MakeAndAddRef<SharedMemoryBasic>();
+}
+
+static already_AddRefed<SharedMemory> CreateSegment(size_t aNBytes) {
+ if (!aNBytes) {
+ return nullptr;
+ }
+ RefPtr<SharedMemory> segment = NewSegment();
+ if (!segment) {
+ return nullptr;
+ }
+ size_t size = SharedMemory::PageAlignedSize(aNBytes);
+ if (!segment->Create(size) || !segment->Map(size)) {
+ return nullptr;
+ }
+ return segment.forget();
+}
+
+static already_AddRefed<SharedMemory> ReadSegment(
+ const IPC::Message& aDescriptor, Shmem::id_t* aId, size_t* aNBytes) {
+ if (SHMEM_CREATED_MESSAGE_TYPE != aDescriptor.type()) {
+ NS_ERROR("expected 'shmem created' message");
+ return nullptr;
+ }
+ IPC::MessageReader reader(aDescriptor);
+ if (!ShmemCreated::ReadInfo(&reader, aId, aNBytes)) {
+ return nullptr;
+ }
+ RefPtr<SharedMemory> segment = NewSegment();
+ if (!segment) {
+ return nullptr;
+ }
+ if (!segment->ReadHandle(&reader)) {
+ NS_ERROR("trying to open invalid handle");
+ return nullptr;
+ }
+ reader.EndRead();
+ if (!*aNBytes) {
+ return nullptr;
+ }
+ size_t size = SharedMemory::PageAlignedSize(*aNBytes);
+ if (!segment->Map(size)) {
+ return nullptr;
+ }
+ // close the handle to the segment after it is mapped
+ segment->CloseHandle();
+ return segment.forget();
+}
+
+#if defined(DEBUG)
+
+static void Protect(SharedMemory* aSegment) {
+ MOZ_ASSERT(aSegment, "null segment");
+ aSegment->Protect(reinterpret_cast<char*>(aSegment->memory()),
+ aSegment->Size(), RightsNone);
+}
+
+static void Unprotect(SharedMemory* aSegment) {
+ MOZ_ASSERT(aSegment, "null segment");
+ aSegment->Protect(reinterpret_cast<char*>(aSegment->memory()),
+ aSegment->Size(), RightsRead | RightsWrite);
+}
+
+void Shmem::AssertInvariants() const {
+ MOZ_ASSERT(mSegment, "null segment");
+ MOZ_ASSERT(mData, "null data pointer");
+ MOZ_ASSERT(mSize > 0, "invalid size");
+ // if the segment isn't owned by the current process, these will
+ // trigger SIGSEGV
+ char checkMappingFront = *reinterpret_cast<char*>(mData);
+ char checkMappingBack = *(reinterpret_cast<char*>(mData) + mSize - 1);
+
+ // avoid "unused" warnings for these variables:
+ Unused << checkMappingFront;
+ Unused << checkMappingBack;
+}
+
+void Shmem::RevokeRights() {
+ AssertInvariants();
+
+ // When sending a non-unsafe shmem, remove read/write rights from the local
+ // mapping of the segment.
+ if (!mUnsafe) {
+ Protect(mSegment);
+ }
+}
+
+#endif // if defined(DEBUG)
+
+Shmem::Shmem(SharedMemory* aSegment, id_t aId, size_t aSize, bool aUnsafe)
+ : mSegment(aSegment), mData(aSegment->memory()), mSize(aSize), mId(aId) {
+#ifdef DEBUG
+ mUnsafe = aUnsafe;
+ Unprotect(mSegment);
+#endif
+
+ MOZ_RELEASE_ASSERT(mSegment->Size() >= mSize,
+ "illegal size in shared memory segment");
+}
+
+// static
+already_AddRefed<Shmem::SharedMemory> Shmem::Alloc(size_t aNBytes) {
+ RefPtr<SharedMemory> segment = CreateSegment(aNBytes);
+ if (!segment) {
+ return nullptr;
+ }
+
+ return segment.forget();
+}
+
+// static
+already_AddRefed<Shmem::SharedMemory> Shmem::OpenExisting(
+ const IPC::Message& aDescriptor, id_t* aId, bool /*unused*/) {
+ size_t size;
+ RefPtr<SharedMemory> segment = ReadSegment(aDescriptor, aId, &size);
+ if (!segment) {
+ return nullptr;
+ }
+
+ return segment.forget();
+}
+
+UniquePtr<IPC::Message> Shmem::MkCreatedMessage(int32_t routingId) {
+ AssertInvariants();
+
+ auto msg = MakeUnique<ShmemCreated>(routingId, mId, mSize);
+ IPC::MessageWriter writer(*msg);
+ if (!mSegment->WriteHandle(&writer)) {
+ return nullptr;
+ }
+ // close the handle to the segment after it is shared
+ mSegment->CloseHandle();
+ return msg;
+}
+
+UniquePtr<IPC::Message> Shmem::MkDestroyedMessage(int32_t routingId) {
+ AssertInvariants();
+ return MakeUnique<ShmemDestroyed>(routingId, mId);
+}
+
+void IPDLParamTraits<Shmem>::Write(IPC::MessageWriter* aWriter,
+ IProtocol* aActor, Shmem&& aParam) {
+ WriteIPDLParam(aWriter, aActor, aParam.mId);
+ WriteIPDLParam(aWriter, aActor, uint32_t(aParam.mSize));
+#ifdef DEBUG
+ WriteIPDLParam(aWriter, aActor, aParam.mUnsafe);
+#endif
+
+ aParam.RevokeRights();
+ aParam.forget();
+}
+
+bool IPDLParamTraits<Shmem>::Read(IPC::MessageReader* aReader,
+ IProtocol* aActor, paramType* aResult) {
+ paramType::id_t id;
+ uint32_t size;
+ if (!ReadIPDLParam(aReader, aActor, &id) ||
+ !ReadIPDLParam(aReader, aActor, &size)) {
+ return false;
+ }
+
+ bool unsafe = false;
+#ifdef DEBUG
+ if (!ReadIPDLParam(aReader, aActor, &unsafe)) {
+ return false;
+ }
+#endif
+
+ Shmem::SharedMemory* rawmem = aActor->LookupSharedMemory(id);
+ if (rawmem) {
+ if (size > rawmem->Size()) {
+ return false;
+ }
+
+ *aResult = Shmem(rawmem, id, size, unsafe);
+ return true;
+ }
+ *aResult = Shmem();
+ return true;
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/Shmem.h b/ipc/glue/Shmem.h
new file mode 100644
index 0000000000..657d5efbdd
--- /dev/null
+++ b/ipc/glue/Shmem.h
@@ -0,0 +1,190 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_Shmem_h
+#define mozilla_ipc_Shmem_h
+
+#include "mozilla/Attributes.h"
+
+#include "base/basictypes.h"
+#include "base/process.h"
+
+#include "nscore.h"
+#include "nsDebug.h"
+
+#include "mozilla/ipc/SharedMemory.h"
+#include "mozilla/Range.h"
+#include "mozilla/UniquePtr.h"
+
+/**
+ * |Shmem| is one agent in the IPDL shared memory scheme. The way it
+ works is essentially
+ *
+ * (1) C++ code calls, say, |parentActor->AllocShmem(size)|
+
+ * (2) IPDL-generated code creates a |mozilla::ipc::SharedMemory|
+ * wrapping the bare OS shmem primitives. The code then adds the new
+ * SharedMemory to the set of shmem segments being managed by IPDL.
+ *
+ * (3) IPDL-generated code "shares" the new SharedMemory to the child
+ * process, and then sends a special asynchronous IPC message to the
+ * child notifying it of the creation of the segment. (What this
+ * means is OS specific.)
+ *
+ * (4a) The child receives the special IPC message, and using the
+ * |SharedMemory{Basic}::Handle| it was passed, creates a
+ * |mozilla::ipc::SharedMemory| in the child
+ * process.
+ *
+ * (4b) After sending the "shmem-created" IPC message, IPDL-generated
+ * code in the parent returns a |mozilla::ipc::Shmem| back to the C++
+ * caller of |parentActor->AllocShmem()|. The |Shmem| is a "weak
+ * reference" to the underlying |SharedMemory|, which is managed by
+ * IPDL-generated code. C++ consumers of |Shmem| can't get at the
+ * underlying |SharedMemory|.
+ *
+ * If parent code wants to give access rights to the Shmem to the
+ * child, it does so by sending its |Shmem| to the child, in an IPDL
+ * message. The parent's |Shmem| then "dies", i.e. becomes
+ * inaccessible. This process could be compared to passing a
+ * "shmem-access baton" between parent and child.
+ */
+
+namespace mozilla::ipc {
+
+class IProtocol;
+class IToplevelProtocol;
+
+template <typename P>
+struct IPDLParamTraits;
+
+class Shmem final {
+ friend struct IPDLParamTraits<mozilla::ipc::Shmem>;
+ friend class mozilla::ipc::IProtocol;
+ friend class mozilla::ipc::IToplevelProtocol;
+
+ public:
+ typedef int32_t id_t;
+ // Low-level wrapper around platform shmem primitives.
+ typedef mozilla::ipc::SharedMemory SharedMemory;
+
+ Shmem() : mSegment(nullptr), mData(nullptr), mSize(0), mId(0) {}
+
+ Shmem(const Shmem& aOther) = default;
+
+ ~Shmem() {
+ // Shmem only holds a "weak ref" to the actual segment, which is
+ // owned by IPDL. So there's nothing interesting to be done here
+ forget();
+ }
+
+ Shmem& operator=(const Shmem& aRhs) = default;
+
+ bool operator==(const Shmem& aRhs) const { return mSegment == aRhs.mSegment; }
+
+ // Returns whether this Shmem is writable by you, and thus whether you can
+ // transfer writability to another actor.
+ bool IsWritable() const { return mSegment != nullptr; }
+
+ // Returns whether this Shmem is readable by you, and thus whether you can
+ // transfer readability to another actor.
+ bool IsReadable() const { return mSegment != nullptr; }
+
+ // Return a pointer to the user-visible data segment.
+ template <typename T>
+ T* get() const {
+ AssertInvariants();
+ AssertAligned<T>();
+
+ return reinterpret_cast<T*>(mData);
+ }
+
+ // Return the size of the segment as requested when this shmem
+ // segment was allocated, in units of T. The underlying mapping may
+ // actually be larger because of page alignment and private data,
+ // but this isn't exposed to clients.
+ template <typename T>
+ size_t Size() const {
+ AssertInvariants();
+ AssertAligned<T>();
+
+ return mSize / sizeof(T);
+ }
+
+ template <typename T>
+ Range<T> Range() const {
+ return {get<T>(), Size<T>()};
+ }
+
+ private:
+ // These shouldn't be used directly, use the IPDL interface instead.
+
+ Shmem(SharedMemory* aSegment, id_t aId, size_t aSize, bool aUnsafe);
+
+ id_t Id() const { return mId; }
+
+ SharedMemory* Segment() const { return mSegment; }
+
+#ifndef DEBUG
+ void RevokeRights() {}
+#else
+ void RevokeRights();
+#endif
+
+ void forget() {
+ mSegment = nullptr;
+ mData = nullptr;
+ mSize = 0;
+ mId = 0;
+#ifdef DEBUG
+ mUnsafe = false;
+#endif
+ }
+
+ static already_AddRefed<Shmem::SharedMemory> Alloc(size_t aNBytes);
+
+ // Prepare this to be shared with another process. Return an IPC message that
+ // contains enough information for the other process to map this segment in
+ // OpenExisting() below. Return a new message if successful (owned by the
+ // caller), nullptr if not.
+ UniquePtr<IPC::Message> MkCreatedMessage(int32_t routingId);
+
+ // Stop sharing this with another process. Return an IPC message that
+ // contains enough information for the other process to unmap this
+ // segment. Return a new message if successful (owned by the
+ // caller), nullptr if not.
+ UniquePtr<IPC::Message> MkDestroyedMessage(int32_t routingId);
+
+ // Return a SharedMemory instance in this process using the descriptor shared
+ // to us by the process that created the underlying OS shmem resource. The
+ // contents of the descriptor depend on the type of SharedMemory that was
+ // passed to us.
+ static already_AddRefed<SharedMemory> OpenExisting(
+ const IPC::Message& aDescriptor, id_t* aId, bool aProtect = false);
+
+ template <typename T>
+ void AssertAligned() const {
+ if (0 != (mSize % sizeof(T))) MOZ_CRASH("shmem is not T-aligned");
+ }
+
+#if !defined(DEBUG)
+ void AssertInvariants() const {}
+#else
+ void AssertInvariants() const;
+#endif
+
+ RefPtr<SharedMemory> mSegment;
+ void* mData;
+ size_t mSize;
+ id_t mId;
+#ifdef DEBUG
+ bool mUnsafe = false;
+#endif
+};
+
+} // namespace mozilla::ipc
+
+#endif // ifndef mozilla_ipc_Shmem_h
diff --git a/ipc/glue/ShmemMessageUtils.h b/ipc/glue/ShmemMessageUtils.h
new file mode 100644
index 0000000000..c0f8c40215
--- /dev/null
+++ b/ipc/glue/ShmemMessageUtils.h
@@ -0,0 +1,30 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_ShmemMessageUtils_h
+#define mozilla_ipc_ShmemMessageUtils_h
+
+#include "ipc/IPCMessageUtils.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "mozilla/ipc/Shmem.h"
+
+namespace mozilla {
+namespace ipc {
+
+template <>
+struct IPDLParamTraits<Shmem> {
+ typedef Shmem paramType;
+
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ paramType&& aParam);
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ paramType* aResult);
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_ShmemMessageUtils_h
diff --git a/ipc/glue/SideVariant.h b/ipc/glue/SideVariant.h
new file mode 100644
index 0000000000..3082feebde
--- /dev/null
+++ b/ipc/glue/SideVariant.h
@@ -0,0 +1,187 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_SidedVariant_h
+#define mozilla_ipc_SidedVariant_h
+
+#include <variant>
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "ipc/IPCMessageUtils.h"
+
+namespace mozilla {
+namespace ipc {
+
+/**
+ * Helper type used by IPDL structs and unions to hold actor pointers with a
+ * dynamic side.
+ *
+ * When sent over IPC, ParentSide will be used for send/recv on parent actors,
+ * and ChildSide will be used for send/recv on child actors.
+ */
+template <typename ParentSide, typename ChildSide>
+struct SideVariant {
+ public:
+ SideVariant() = default;
+ template <typename U,
+ std::enable_if_t<std::is_convertible_v<U&&, ParentSide>, int> = 0>
+ MOZ_IMPLICIT SideVariant(U&& aParent) : mParent(std::forward<U>(aParent)) {}
+ template <typename U,
+ std::enable_if_t<std::is_convertible_v<U&&, ChildSide>, int> = 0>
+ MOZ_IMPLICIT SideVariant(U&& aChild) : mChild(std::forward<U>(aChild)) {}
+ MOZ_IMPLICIT SideVariant(std::nullptr_t) {}
+
+ MOZ_IMPLICIT SideVariant& operator=(ParentSide aParent) {
+ mParent = aParent;
+ mChild = nullptr;
+ return *this;
+ }
+ MOZ_IMPLICIT SideVariant& operator=(ChildSide aChild) {
+ mChild = aChild;
+ mParent = nullptr;
+ return *this;
+ }
+ MOZ_IMPLICIT SideVariant& operator=(std::nullptr_t) {
+ mChild = nullptr;
+ mParent = nullptr;
+ return *this;
+ }
+
+ MOZ_IMPLICIT operator bool() const { return mParent || mChild; }
+
+ bool IsNull() const { return !operator bool(); }
+ bool IsParent() const { return mParent; }
+ bool IsChild() const { return mChild; }
+
+ ParentSide AsParent() const {
+ MOZ_ASSERT(IsNull() || IsParent());
+ return mParent;
+ }
+ ChildSide AsChild() const {
+ MOZ_ASSERT(IsNull() || IsChild());
+ return mChild;
+ }
+
+ private:
+ // As the values are both pointers, this is the same size as a variant would
+ // be, but has less risk of type confusion, and supports an overall `nullptr`
+ // value which is neither parent nor child.
+ ParentSide mParent = nullptr;
+ ChildSide mChild = nullptr;
+};
+
+} // namespace ipc
+
+// NotNull specialization to expose AsChild and AsParent on the NotNull itself
+// avoiding unnecessary unwrapping.
+template <typename ParentSide, typename ChildSide>
+class NotNull<mozilla::ipc::SideVariant<ParentSide, ChildSide>> {
+ template <typename U>
+ friend constexpr NotNull<U> WrapNotNull(U aBasePtr);
+ template <typename U>
+ friend constexpr NotNull<U> WrapNotNullUnchecked(U aBasePtr);
+ template <typename U>
+ friend class NotNull;
+
+ using BasePtr = mozilla::ipc::SideVariant<ParentSide, ChildSide>;
+
+ BasePtr mBasePtr;
+
+ // This constructor is only used by WrapNotNull() and MakeNotNull<U>().
+ template <typename U>
+ constexpr explicit NotNull(U aBasePtr) : mBasePtr(aBasePtr) {}
+
+ public:
+ // Disallow default construction.
+ NotNull() = delete;
+
+ // Construct/assign from another NotNull with a compatible base pointer type.
+ template <typename U, typename = std::enable_if_t<
+ std::is_convertible_v<const U&, BasePtr>>>
+ constexpr MOZ_IMPLICIT NotNull(const NotNull<U>& aOther)
+ : mBasePtr(aOther.get()) {
+ static_assert(sizeof(BasePtr) == sizeof(NotNull<BasePtr>),
+ "NotNull must have zero space overhead.");
+ static_assert(offsetof(NotNull<BasePtr>, mBasePtr) == 0,
+ "mBasePtr must have zero offset.");
+ }
+
+ template <typename U,
+ typename = std::enable_if_t<std::is_convertible_v<U&&, BasePtr>>>
+ constexpr MOZ_IMPLICIT NotNull(MovingNotNull<U>&& aOther)
+ : mBasePtr(NotNull{std::move(aOther)}) {}
+
+ // Disallow null checks, which are unnecessary for this type.
+ explicit operator bool() const = delete;
+
+ // Explicit conversion to a base pointer. Use only to resolve ambiguity or to
+ // get a castable pointer.
+ constexpr const BasePtr& get() const { return mBasePtr; }
+
+ // Implicit conversion to a base pointer. Preferable to get().
+ constexpr operator const BasePtr&() const { return get(); }
+
+ bool IsParent() const { return get().IsParent(); }
+ bool IsChild() const { return get().IsChild(); }
+
+ NotNull<ParentSide> AsParent() const { return WrapNotNull(get().AsParent()); }
+ NotNull<ChildSide> AsChild() const { return WrapNotNull(get().AsChild()); }
+};
+
+} // namespace mozilla
+
+namespace IPC {
+
+template <typename ParentSide, typename ChildSide>
+struct ParamTraits<mozilla::ipc::SideVariant<ParentSide, ChildSide>> {
+ typedef mozilla::ipc::SideVariant<ParentSide, ChildSide> paramType;
+
+ static void Write(IPC::MessageWriter* aWriter, const paramType& aParam) {
+ if (!aWriter->GetActor()) {
+ aWriter->FatalError("actor required to serialize this type");
+ return;
+ }
+
+ if (aWriter->GetActor()->GetSide() == mozilla::ipc::ParentSide) {
+ if (aParam && !aParam.IsParent()) {
+ aWriter->FatalError("invalid side");
+ return;
+ }
+ WriteParam(aWriter, aParam.AsParent());
+ } else {
+ if (aParam && !aParam.IsChild()) {
+ aWriter->FatalError("invalid side");
+ return;
+ }
+ WriteParam(aWriter, aParam.AsChild());
+ }
+ }
+
+ static ReadResult<paramType> Read(IPC::MessageReader* aReader) {
+ if (!aReader->GetActor()) {
+ aReader->FatalError("actor required to deserialize this type");
+ return {};
+ }
+
+ if (aReader->GetActor()->GetSide() == mozilla::ipc::ParentSide) {
+ auto parentSide = ReadParam<ParentSide>(aReader);
+ if (!parentSide) {
+ return {};
+ }
+ return std::move(*parentSide);
+ }
+ auto childSide = ReadParam<ChildSide>(aReader);
+ if (!childSide) {
+ return {};
+ }
+ return std::move(*childSide);
+ }
+};
+
+} // namespace IPC
+
+#endif // mozilla_ipc_SidedVariant_h
diff --git a/ipc/glue/StringUtil.cpp b/ipc/glue/StringUtil.cpp
new file mode 100644
index 0000000000..af589bb720
--- /dev/null
+++ b/ipc/glue/StringUtil.cpp
@@ -0,0 +1,86 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "base/string_util.h"
+
+// Copyright (c) 2006-2008 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.
+
+#include "base/sys_string_conversions.h"
+
+#include "base/string_piece.h"
+#include "base/string_util.h"
+
+// FIXME/cjones: these really only pertain to the linux sys string
+// converters.
+#ifdef XP_WIN
+# define ICONV_WCHAR_T_ENCODING "UTF-16"
+#else
+# define ICONV_WCHAR_T_ENCODING "WCHAR_T"
+#endif
+
+// FIXME/cjones: BIG assumption here that std::string is a good
+// container of UTF8-encoded strings. this is probably wrong, as its
+// API doesn't really make sense for UTF8.
+
+namespace base {
+
+// FIXME/cjones: as its name implies, this function is a hack.
+template <typename FromType, typename ToType>
+ToType HackyStringConvert(const FromType& in) {
+ // FIXME/cjones: assumes no non-ASCII characters in |in|
+ ToType out;
+ out.resize(in.length());
+ for (int i = 0; i < static_cast<int>(in.length()); ++i)
+ out[i] = static_cast<typename ToType::value_type>(in[i]);
+ return out;
+}
+
+} // namespace base
+
+// Implement functions that were in the chromium ICU library, which
+// we're not taking.
+
+std::string WideToUTF8(const std::wstring& wide) {
+ return base::SysWideToUTF8(wide);
+}
+
+std::wstring UTF8ToWide(const StringPiece& utf8) {
+ return base::SysUTF8ToWide(utf8);
+}
+
+namespace base {
+
+// FIXME/cjones: here we're entirely replacing the linux string
+// converters, and implementing the one that doesn't exist for OS X
+// and Windows.
+
+#if !defined(XP_DARWIN) && !defined(XP_WIN)
+std::string SysWideToUTF8(const std::wstring& wide) {
+ // FIXME/cjones: do this with iconv
+ return HackyStringConvert<std::wstring, std::string>(wide);
+}
+#endif
+
+#if !defined(XP_DARWIN) && !defined(XP_WIN)
+std::wstring SysUTF8ToWide(const StringPiece& utf8) {
+ // FIXME/cjones: do this with iconv
+ return HackyStringConvert<StringPiece, std::wstring>(utf8);
+}
+
+std::string SysWideToNativeMB(const std::wstring& wide) {
+ // TODO(evanm): we can't assume Linux is UTF-8.
+ return SysWideToUTF8(wide);
+}
+
+std::wstring SysNativeMBToWide(const StringPiece& native_mb) {
+ // TODO(evanm): we can't assume Linux is UTF-8.
+ return SysUTF8ToWide(native_mb);
+}
+#endif
+
+} // namespace base
diff --git a/ipc/glue/TaintingIPCUtils.h b/ipc/glue/TaintingIPCUtils.h
new file mode 100644
index 0000000000..d4f61d95b5
--- /dev/null
+++ b/ipc/glue/TaintingIPCUtils.h
@@ -0,0 +1,41 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_Tainting_h
+#define mozilla_ipc_Tainting_h
+
+#include "mozilla/Tainting.h"
+
+#include "base/basictypes.h"
+#include "base/process.h"
+
+#include "mozilla/ipc/IPDLParamTraits.h"
+
+namespace mozilla {
+namespace ipc {
+
+template <typename T>
+struct IPDLParamTraits<mozilla::Tainted<T>> {
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ const mozilla::Tainted<T>& aParam) {
+ WriteIPDLParam(aWriter, aActor, aParam.mValue);
+ }
+
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ mozilla::Tainted<T>&& aParam) {
+ WriteIPDLParam(aWriter, aActor, std::move(aParam.mValue));
+ }
+
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ mozilla::Tainted<T>* aResult) {
+ return ReadIPDLParam(aReader, aActor, &(aResult->mValue));
+ }
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipc_Tainting_h
diff --git a/ipc/glue/TaskFactory.h b/ipc/glue/TaskFactory.h
new file mode 100644
index 0000000000..af63244cf0
--- /dev/null
+++ b/ipc/glue/TaskFactory.h
@@ -0,0 +1,97 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_plugins_TaskFactory_h
+#define mozilla_plugins_TaskFactory_h
+
+#include <base/task.h>
+
+#include <utility>
+
+/*
+ * This is based on the ScopedRunnableMethodFactory from
+ * ipc/chromium/src/base/task.h Chromium's factories assert if tasks are created
+ * and run on different threads, which is something we need to do in
+ * PluginModuleParent (hang UI vs. main thread). TaskFactory just provides
+ * cancellable tasks that don't assert this. This version also allows both
+ * ScopedMethod and regular Tasks to be generated by the same Factory object.
+ */
+
+namespace mozilla {
+namespace ipc {
+
+template <class T>
+class TaskFactory : public RevocableStore {
+ private:
+ template <class TaskType>
+ class TaskWrapper : public TaskType {
+ public:
+ template <typename... Args>
+ explicit TaskWrapper(RevocableStore* store, Args&&... args)
+ : TaskType(std::forward<Args>(args)...), revocable_(store) {}
+
+ NS_IMETHOD Run() override {
+ if (!revocable_.revoked()) TaskType::Run();
+ return NS_OK;
+ }
+
+ private:
+ Revocable revocable_;
+ };
+
+ public:
+ explicit TaskFactory(T* object) : object_(object) {}
+
+ template <typename TaskParamType, typename... Args>
+ inline already_AddRefed<TaskParamType> NewTask(Args&&... args) {
+ typedef TaskWrapper<TaskParamType> TaskWrapper;
+ RefPtr<TaskWrapper> task =
+ new TaskWrapper(this, std::forward<Args>(args)...);
+ return task.forget();
+ }
+
+ template <class Method, typename... Args>
+ inline already_AddRefed<Runnable> NewRunnableMethod(Method method,
+ Args&&... args) {
+ typedef decltype(base::MakeTuple(std::forward<Args>(args)...)) ArgTuple;
+ typedef RunnableMethod<Method, ArgTuple> RunnableMethod;
+ typedef TaskWrapper<RunnableMethod> TaskWrapper;
+
+ RefPtr<TaskWrapper> task = new TaskWrapper(
+ this, object_, method, base::MakeTuple(std::forward<Args>(args)...));
+
+ return task.forget();
+ }
+
+ protected:
+ template <class Method, class Params>
+ class RunnableMethod : public Runnable {
+ public:
+ RunnableMethod(T* obj, Method meth, const Params& params)
+ : Runnable("ipc::TaskFactory::RunnableMethod"),
+ obj_(obj),
+ meth_(meth),
+ params_(params) {}
+
+ NS_IMETHOD Run() override {
+ DispatchToMethod(obj_, meth_, params_);
+ return NS_OK;
+ }
+
+ private:
+ T* obj_;
+ Method meth_;
+ Params params_;
+ };
+
+ private:
+ T* object_;
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_plugins_TaskFactory_h
diff --git a/ipc/glue/ToplevelActorHolder.h b/ipc/glue/ToplevelActorHolder.h
new file mode 100644
index 0000000000..6e95ef8565
--- /dev/null
+++ b/ipc/glue/ToplevelActorHolder.h
@@ -0,0 +1,45 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef MOZILLA_IPC_TOPLEVELACTORHOLDER_H
+#define MOZILLA_IPC_TOPLEVELACTORHOLDER_H
+
+#include "nsISupports.h"
+
+namespace mozilla::ipc {
+
+// Class to let us close the actor when we're not using it anymore. You
+// should create a single instance of this, and when you have no more
+// references it will be destroyed and will Close() the underlying
+// top-level channel.
+// When you want to send something, you use something like
+// aActor->Actor()->SendFoo()
+
+// You can avoid calling Close() on an un-connected Actor (for example if
+// Bind() fails) by calling RemoveActor();
+template <typename T>
+class ToplevelActorHolder final {
+ public:
+ NS_INLINE_DECL_REFCOUNTING_ONEVENTTARGET(ToplevelActorHolder)
+
+ explicit ToplevelActorHolder(T* aActor) : mActor(aActor) {}
+
+ constexpr T* Actor() const { return mActor; }
+ inline void RemoveActor() { mActor = nullptr; }
+
+ private:
+ inline ~ToplevelActorHolder() {
+ if (mActor) {
+ mActor->Close();
+ }
+ }
+
+ RefPtr<T> mActor;
+};
+
+} // namespace mozilla::ipc
+
+#endif // MOZILLA_IPC_TOPLEVELACTORHOLDER_H
diff --git a/ipc/glue/TransportSecurityInfoUtils.cpp b/ipc/glue/TransportSecurityInfoUtils.cpp
new file mode 100644
index 0000000000..9898e2b579
--- /dev/null
+++ b/ipc/glue/TransportSecurityInfoUtils.cpp
@@ -0,0 +1,78 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "TransportSecurityInfoUtils.h"
+
+#include "ipc/IPCMessageUtils.h"
+#include "mozilla/psm/TransportSecurityInfo.h"
+#include "nsNSSCertificate.h"
+
+namespace IPC {
+
+void ParamTraits<nsITransportSecurityInfo*>::Write(
+ MessageWriter* aWriter, nsITransportSecurityInfo* aParam) {
+ bool nonNull = !!aParam;
+ WriteParam(aWriter, nonNull);
+ if (!nonNull) {
+ return;
+ }
+
+ aParam->SerializeToIPC(aWriter);
+}
+
+bool ParamTraits<nsITransportSecurityInfo*>::Read(
+ MessageReader* aReader, RefPtr<nsITransportSecurityInfo>* aResult) {
+ *aResult = nullptr;
+
+ bool nonNull = false;
+ if (!ReadParam(aReader, &nonNull)) {
+ return false;
+ }
+
+ if (!nonNull) {
+ return true;
+ }
+
+ if (!mozilla::psm::TransportSecurityInfo::DeserializeFromIPC(aReader,
+ aResult)) {
+ return false;
+ }
+
+ return true;
+}
+
+void ParamTraits<nsIX509Cert*>::Write(MessageWriter* aWriter,
+ nsIX509Cert* aParam) {
+ bool nonNull = !!aParam;
+ WriteParam(aWriter, nonNull);
+ if (!nonNull) {
+ return;
+ }
+
+ aParam->SerializeToIPC(aWriter);
+}
+
+bool ParamTraits<nsIX509Cert*>::Read(MessageReader* aReader,
+ RefPtr<nsIX509Cert>* aResult) {
+ *aResult = nullptr;
+
+ bool nonNull = false;
+ if (!ReadParam(aReader, &nonNull)) {
+ return false;
+ }
+
+ if (!nonNull) {
+ return true;
+ }
+
+ RefPtr<nsIX509Cert> cert = new nsNSSCertificate();
+ if (!cert->DeserializeFromIPC(aReader)) {
+ return false;
+ }
+
+ *aResult = std::move(cert);
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/glue/TransportSecurityInfoUtils.h b/ipc/glue/TransportSecurityInfoUtils.h
new file mode 100644
index 0000000000..009db8e162
--- /dev/null
+++ b/ipc/glue/TransportSecurityInfoUtils.h
@@ -0,0 +1,43 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_TransportSecurityInfoUtils_h
+#define mozilla_ipc_TransportSecurityInfoUtils_h
+
+#include "ipc/EnumSerializer.h"
+#include "mozilla/RefPtr.h"
+#include "nsITransportSecurityInfo.h"
+#include "nsIX509Cert.h"
+
+class MessageReader;
+class MessageWriter;
+
+namespace IPC {
+
+template <typename>
+struct ParamTraits;
+
+template <>
+struct ParamTraits<nsITransportSecurityInfo*> {
+ static void Write(MessageWriter* aWriter, nsITransportSecurityInfo* aParam);
+ static bool Read(MessageReader* aReader,
+ RefPtr<nsITransportSecurityInfo>* aResult);
+};
+
+template <>
+struct ParamTraits<nsIX509Cert*> {
+ static void Write(MessageWriter* aWriter, nsIX509Cert* aCert);
+ static bool Read(MessageReader* aReader, RefPtr<nsIX509Cert>* aResult);
+};
+
+template <>
+struct ParamTraits<nsITransportSecurityInfo::OverridableErrorCategory>
+ : public ContiguousEnumSerializerInclusive<
+ nsITransportSecurityInfo::OverridableErrorCategory,
+ nsITransportSecurityInfo::OverridableErrorCategory::ERROR_UNSET,
+ nsITransportSecurityInfo::OverridableErrorCategory::ERROR_TIME> {};
+
+} // namespace IPC
+
+#endif // mozilla_ipc_TransportSecurityInfoUtils_h
diff --git a/ipc/glue/URIParams.ipdlh b/ipc/glue/URIParams.ipdlh
new file mode 100644
index 0000000000..99b18afd0f
--- /dev/null
+++ b/ipc/glue/URIParams.ipdlh
@@ -0,0 +1,117 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+
+include PBackgroundSharedTypes;
+
+namespace mozilla {
+namespace ipc {
+
+struct SimpleURIParams
+{
+ nsCString scheme;
+ nsCString path;
+ nsCString ref;
+ nsCString query;
+};
+
+struct DefaultURIParams
+{
+ nsCString spec;
+};
+
+struct StandardURLSegment
+{
+ uint32_t position;
+ int32_t length;
+};
+
+struct StandardURLParams
+{
+ uint32_t urlType;
+ int32_t port;
+ int32_t defaultPort;
+ nsCString spec;
+ StandardURLSegment scheme;
+ StandardURLSegment authority;
+ StandardURLSegment username;
+ StandardURLSegment password;
+ StandardURLSegment host;
+ StandardURLSegment path;
+ StandardURLSegment filePath;
+ StandardURLSegment directory;
+ StandardURLSegment baseName;
+ StandardURLSegment extension;
+ StandardURLSegment query;
+ StandardURLSegment ref;
+ bool supportsFileURL;
+ bool isSubstituting;
+};
+
+struct JARURIParams
+{
+ URIParams jarFile;
+ URIParams jarEntry;
+ nsCString charset;
+};
+
+struct IconURIParams
+{
+ URIParams? uri;
+ uint32_t size;
+ nsCString contentType;
+ nsCString fileName;
+ nsCString stockIcon;
+ int32_t iconSize;
+ int32_t iconState;
+};
+
+struct HostObjectURIParams
+{
+ SimpleURIParams simpleParams;
+ bool revoked;
+};
+
+union URIParams
+{
+ SimpleURIParams;
+ StandardURLParams;
+ JARURIParams;
+ IconURIParams;
+ JSURIParams;
+ SimpleNestedURIParams;
+ HostObjectURIParams;
+ DefaultURIParams;
+ NestedAboutURIParams;
+ SubstitutingJARURIParams;
+};
+
+struct JSURIParams
+{
+ SimpleURIParams simpleParams;
+ URIParams? baseURI;
+};
+
+struct SimpleNestedURIParams
+{
+ SimpleURIParams simpleParams;
+ URIParams innerURI;
+};
+
+struct NestedAboutURIParams
+{
+ SimpleNestedURIParams nestedParams;
+ URIParams? baseURI;
+};
+
+struct SubstitutingJARURIParams
+{
+ URIParams source;
+ JARURIParams resolved;
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/URIUtils.cpp b/ipc/glue/URIUtils.cpp
new file mode 100644
index 0000000000..690509cecc
--- /dev/null
+++ b/ipc/glue/URIUtils.cpp
@@ -0,0 +1,140 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "URIUtils.h"
+
+#include "mozilla/ArrayUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/dom/BlobURL.h"
+#include "mozilla/net/DefaultURI.h"
+#include "mozilla/net/SubstitutingJARURI.h"
+#include "mozilla/net/SubstitutingURL.h"
+#include "nsAboutProtocolHandler.h"
+#include "nsComponentManagerUtils.h"
+#include "nsDebug.h"
+#include "nsID.h"
+#include "nsJARURI.h"
+#include "nsIIconURI.h"
+#include "nsJSProtocolHandler.h"
+#include "nsNetCID.h"
+#include "nsSimpleNestedURI.h"
+#include "nsThreadUtils.h"
+#include "nsIURIMutator.h"
+
+using namespace mozilla::ipc;
+using mozilla::ArrayLength;
+
+namespace {
+
+NS_DEFINE_CID(kSimpleURIMutatorCID, NS_SIMPLEURIMUTATOR_CID);
+NS_DEFINE_CID(kStandardURLMutatorCID, NS_STANDARDURLMUTATOR_CID);
+NS_DEFINE_CID(kJARURIMutatorCID, NS_JARURIMUTATOR_CID);
+NS_DEFINE_CID(kIconURIMutatorCID, NS_MOZICONURIMUTATOR_CID);
+
+} // namespace
+
+namespace mozilla {
+namespace ipc {
+
+void SerializeURI(nsIURI* aURI, URIParams& aParams) {
+ MOZ_ASSERT(aURI);
+
+ aURI->Serialize(aParams);
+ if (aParams.type() == URIParams::T__None) {
+ MOZ_CRASH("Serialize failed!");
+ }
+}
+
+void SerializeURI(nsIURI* aURI, Maybe<URIParams>& aParams) {
+ if (aURI) {
+ URIParams params;
+ SerializeURI(aURI, params);
+ aParams = Some(std::move(params));
+ } else {
+ aParams = Nothing();
+ }
+}
+
+already_AddRefed<nsIURI> DeserializeURI(const URIParams& aParams) {
+ nsCOMPtr<nsIURIMutator> mutator;
+
+ switch (aParams.type()) {
+ case URIParams::TSimpleURIParams:
+ mutator = do_CreateInstance(kSimpleURIMutatorCID);
+ break;
+
+ case URIParams::TStandardURLParams:
+ if (aParams.get_StandardURLParams().isSubstituting()) {
+ mutator = new net::SubstitutingURL::Mutator();
+ } else {
+ mutator = do_CreateInstance(kStandardURLMutatorCID);
+ }
+ break;
+
+ case URIParams::TJARURIParams:
+ mutator = do_CreateInstance(kJARURIMutatorCID);
+ break;
+
+ case URIParams::TJSURIParams:
+ mutator = new nsJSURI::Mutator();
+ break;
+
+ case URIParams::TIconURIParams:
+ mutator = do_CreateInstance(kIconURIMutatorCID);
+ break;
+
+ case URIParams::TSimpleNestedURIParams:
+ mutator = new net::nsSimpleNestedURI::Mutator();
+ break;
+
+ case URIParams::THostObjectURIParams:
+ mutator = new mozilla::dom::BlobURL::Mutator();
+ break;
+
+ case URIParams::TDefaultURIParams:
+ mutator = new mozilla::net::DefaultURI::Mutator();
+ break;
+
+ case URIParams::TNestedAboutURIParams:
+ mutator = new net::nsNestedAboutURI::Mutator();
+ break;
+
+ case URIParams::TSubstitutingJARURIParams:
+ mutator = new net::SubstitutingJARURI::Mutator();
+ break;
+
+ default:
+ MOZ_CRASH("Unknown params!");
+ }
+
+ MOZ_ASSERT(mutator);
+
+ nsresult rv = mutator->Deserialize(aParams);
+ if (NS_FAILED(rv)) {
+ MOZ_ASSERT(false, "Deserialize failed!");
+ return nullptr;
+ }
+
+ nsCOMPtr<nsIURI> uri;
+ DebugOnly<nsresult> rv2 = mutator->Finalize(getter_AddRefs(uri));
+ MOZ_ASSERT(uri);
+ MOZ_ASSERT(NS_SUCCEEDED(rv2));
+
+ return uri.forget();
+}
+
+already_AddRefed<nsIURI> DeserializeURI(const Maybe<URIParams>& aParams) {
+ nsCOMPtr<nsIURI> uri;
+
+ if (aParams.isSome()) {
+ uri = DeserializeURI(aParams.ref());
+ }
+
+ return uri.forget();
+}
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/glue/URIUtils.h b/ipc/glue/URIUtils.h
new file mode 100644
index 0000000000..7cb8687bbe
--- /dev/null
+++ b/ipc/glue/URIUtils.h
@@ -0,0 +1,49 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_URIUtils_h
+#define mozilla_ipc_URIUtils_h
+
+#include "mozilla/ipc/URIParams.h"
+#include "mozilla/ipc/IPDLParamTraits.h"
+#include "nsCOMPtr.h"
+#include "nsIURI.h"
+
+namespace mozilla {
+namespace ipc {
+
+void SerializeURI(nsIURI* aURI, URIParams& aParams);
+
+void SerializeURI(nsIURI* aURI, Maybe<URIParams>& aParams);
+
+already_AddRefed<nsIURI> DeserializeURI(const URIParams& aParams);
+
+already_AddRefed<nsIURI> DeserializeURI(const Maybe<URIParams>& aParams);
+
+template <>
+struct IPDLParamTraits<nsIURI*> {
+ static void Write(IPC::MessageWriter* aWriter, IProtocol* aActor,
+ nsIURI* aParam) {
+ Maybe<URIParams> params;
+ SerializeURI(aParam, params);
+ WriteIPDLParam(aWriter, aActor, params);
+ }
+
+ static bool Read(IPC::MessageReader* aReader, IProtocol* aActor,
+ RefPtr<nsIURI>* aResult) {
+ Maybe<URIParams> params;
+ if (!ReadIPDLParam(aReader, aActor, &params)) {
+ return false;
+ }
+ *aResult = DeserializeURI(params);
+ return true;
+ }
+};
+
+} // namespace ipc
+} // namespace mozilla
+
+#endif // mozilla_ipc_URIUtils_h
diff --git a/ipc/glue/UtilityAudioDecoder.cpp b/ipc/glue/UtilityAudioDecoder.cpp
new file mode 100644
index 0000000000..0b28fd601e
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoder.cpp
@@ -0,0 +1,41 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ProcInfo.h"
+#include "mozilla/ipc/UtilityAudioDecoder.h"
+#include "mozilla/ipc/UtilityProcessChild.h"
+
+namespace mozilla::ipc {
+
+UtilityActorName GetAudioActorName(const SandboxingKind aSandbox) {
+ switch (aSandbox) {
+ case GENERIC_UTILITY:
+ return UtilityActorName::AudioDecoder_Generic;
+#ifdef MOZ_APPLEMEDIA
+ case UTILITY_AUDIO_DECODING_APPLE_MEDIA:
+ return UtilityActorName::AudioDecoder_AppleMedia;
+#endif
+#ifdef XP_WIN
+ case UTILITY_AUDIO_DECODING_WMF:
+ return UtilityActorName::AudioDecoder_WMF;
+#endif
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ case MF_MEDIA_ENGINE_CDM:
+ return UtilityActorName::MfMediaEngineCDM;
+#endif
+ default:
+ MOZ_CRASH("Unexpected mSandbox for GetActorName()");
+ }
+}
+
+nsCString GetChildAudioActorName() {
+ RefPtr<ipc::UtilityProcessChild> s = ipc::UtilityProcessChild::Get();
+ MOZ_ASSERT(s, "Has UtilityProcessChild");
+ return nsCString(dom::WebIDLUtilityActorNameValues::GetString(
+ GetAudioActorName(s->mSandbox)));
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityAudioDecoder.h b/ipc/glue/UtilityAudioDecoder.h
new file mode 100644
index 0000000000..4fed9aab64
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoder.h
@@ -0,0 +1,21 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityAudioDecoder_h__
+#define _include_ipc_glue_UtilityAudioDecoder_h__
+
+#include "mozilla/dom/ChromeUtilsBinding.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+
+namespace mozilla::ipc {
+
+using UtilityActorName = mozilla::dom::WebIDLUtilityActorName;
+
+UtilityActorName GetAudioActorName(const SandboxingKind aSandbox);
+nsCString GetChildAudioActorName();
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityAudioDecoder_h__
diff --git a/ipc/glue/UtilityAudioDecoderChild.cpp b/ipc/glue/UtilityAudioDecoderChild.cpp
new file mode 100644
index 0000000000..88124a1f8b
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoderChild.cpp
@@ -0,0 +1,232 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "UtilityAudioDecoderChild.h"
+
+#include "base/basictypes.h"
+#include "mozilla/AppShutdown.h"
+#include "mozilla/dom/ContentParent.h"
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+# include "mozilla/StaticPrefs_media.h"
+# include "mozilla/gfx/GPUProcessManager.h"
+# include "mozilla/gfx/gfxVars.h"
+# include "mozilla/ipc/UtilityProcessManager.h"
+# include "mozilla/layers/PVideoBridge.h"
+# include "mozilla/layers/VideoBridgeUtils.h"
+#endif
+
+#ifdef MOZ_WMF_CDM
+# include "mozilla/dom/Promise.h"
+# include "mozilla/EMEUtils.h"
+# include "mozilla/PMFCDM.h"
+#endif
+
+namespace mozilla::ipc {
+
+NS_IMETHODIMP UtilityAudioDecoderChildShutdownObserver::Observe(
+ nsISupports* aSubject, const char* aTopic, const char16_t* aData) {
+ MOZ_ASSERT(strcmp(aTopic, "ipc:utility-shutdown") == 0);
+
+ nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
+ if (observerService) {
+ observerService->RemoveObserver(this, "ipc:utility-shutdown");
+ }
+
+ UtilityAudioDecoderChild::Shutdown(mSandbox);
+ return NS_OK;
+}
+
+NS_IMPL_ISUPPORTS(UtilityAudioDecoderChildShutdownObserver, nsIObserver);
+
+static EnumeratedArray<SandboxingKind, SandboxingKind::COUNT,
+ StaticRefPtr<UtilityAudioDecoderChild>>
+ sAudioDecoderChilds;
+
+UtilityAudioDecoderChild::UtilityAudioDecoderChild(SandboxingKind aKind)
+ : mSandbox(aKind), mAudioDecoderChildStart(TimeStamp::Now()) {
+ MOZ_ASSERT(NS_IsMainThread());
+ nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
+ if (observerService) {
+ auto* obs = new UtilityAudioDecoderChildShutdownObserver(aKind);
+ observerService->AddObserver(obs, "ipc:utility-shutdown", false);
+ }
+}
+
+void UtilityAudioDecoderChild::ActorDestroy(ActorDestroyReason aReason) {
+ MOZ_ASSERT(NS_IsMainThread());
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ if (mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ gfx::gfxVars::RemoveReceiver(this);
+ }
+#endif
+ Shutdown(mSandbox);
+}
+
+void UtilityAudioDecoderChild::Bind(
+ Endpoint<PUtilityAudioDecoderChild>&& aEndpoint) {
+ MOZ_ASSERT(NS_IsMainThread());
+ if (NS_WARN_IF(!aEndpoint.Bind(this))) {
+ MOZ_ASSERT_UNREACHABLE("Failed to bind UtilityAudioDecoderChild!");
+ return;
+ }
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ if (mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ gfx::gfxVars::AddReceiver(this);
+ }
+#endif
+}
+
+/* static */
+void UtilityAudioDecoderChild::Shutdown(SandboxingKind aKind) {
+ sAudioDecoderChilds[aKind] = nullptr;
+}
+
+/* static */
+RefPtr<UtilityAudioDecoderChild> UtilityAudioDecoderChild::GetSingleton(
+ SandboxingKind aKind) {
+ MOZ_ASSERT(NS_IsMainThread());
+ bool shutdown = AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMWillShutdown);
+ if (!sAudioDecoderChilds[aKind] && !shutdown) {
+ sAudioDecoderChilds[aKind] = new UtilityAudioDecoderChild(aKind);
+ }
+ return sAudioDecoderChilds[aKind];
+}
+
+mozilla::ipc::IPCResult
+UtilityAudioDecoderChild::RecvUpdateMediaCodecsSupported(
+ const RemoteDecodeIn& aLocation,
+ const media::MediaCodecsSupported& aSupported) {
+ dom::ContentParent::BroadcastMediaCodecsSupportedUpdate(aLocation,
+ aSupported);
+ return IPC_OK();
+}
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+mozilla::ipc::IPCResult
+UtilityAudioDecoderChild::RecvCompleteCreatedVideoBridge() {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ mHasCreatedVideoBridge = true;
+ return IPC_OK();
+}
+
+bool UtilityAudioDecoderChild::HasCreatedVideoBridge() const {
+ MOZ_ASSERT(NS_IsMainThread());
+ return mHasCreatedVideoBridge;
+}
+
+void UtilityAudioDecoderChild::OnVarChanged(const gfx::GfxVarUpdate& aVar) {
+ MOZ_ASSERT(mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ SendUpdateVar(aVar);
+}
+
+void UtilityAudioDecoderChild::OnCompositorUnexpectedShutdown() {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ mHasCreatedVideoBridge = false;
+ CreateVideoBridge();
+}
+
+bool UtilityAudioDecoderChild::CreateVideoBridge() {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(mSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+
+ if (HasCreatedVideoBridge()) {
+ return true;
+ }
+
+ // Build content device data first; this ensure that the GPU process is fully
+ // ready.
+ gfx::ContentDeviceData contentDeviceData;
+ gfxPlatform::GetPlatform()->BuildContentDeviceData(&contentDeviceData);
+
+ gfx::GPUProcessManager* gpuManager = gfx::GPUProcessManager::Get();
+ if (!gpuManager) {
+ NS_WARNING("Failed to get a gpu mananger!");
+ return false;
+ }
+
+ // The child end is the producer of video frames; the parent end is the
+ // consumer.
+ base::ProcessId childPid = UtilityProcessManager::GetSingleton()
+ ->GetProcessParent(mSandbox)
+ ->OtherPid();
+ base::ProcessId parentPid = gpuManager->GPUProcessPid();
+ if (parentPid == base::kInvalidProcessId) {
+ NS_WARNING("GPU process Id is invald!");
+ return false;
+ }
+
+ ipc::Endpoint<layers::PVideoBridgeParent> parentPipe;
+ ipc::Endpoint<layers::PVideoBridgeChild> childPipe;
+ nsresult rv = layers::PVideoBridge::CreateEndpoints(parentPid, childPid,
+ &parentPipe, &childPipe);
+ if (NS_FAILED(rv)) {
+ NS_WARNING("Failed to create endpoints for video bridge!");
+ return false;
+ }
+
+ nsTArray<gfx::GfxVarUpdate> updates = gfx::gfxVars::FetchNonDefaultVars();
+ gpuManager->InitVideoBridge(
+ std::move(parentPipe),
+ layers::VideoBridgeSource::MFMediaEngineCDMProcess);
+ SendInitVideoBridge(std::move(childPipe), updates, contentDeviceData);
+ return true;
+}
+#endif
+
+#ifdef MOZ_WMF_CDM
+void UtilityAudioDecoderChild::GetKeySystemCapabilities(
+ dom::Promise* aPromise) {
+ EME_LOG("Ask capabilities for all supported CDMs");
+ SendGetKeySystemCapabilities()->Then(
+ NS_GetCurrentThread(), __func__,
+ [promise = RefPtr<dom::Promise>(aPromise)](
+ CopyableTArray<MFCDMCapabilitiesIPDL>&& result) {
+ FallibleTArray<dom::CDMInformation> cdmInfo;
+ for (const auto& capabilities : result) {
+ EME_LOG("Received capabilities for %s",
+ NS_ConvertUTF16toUTF8(capabilities.keySystem()).get());
+ for (const auto& v : capabilities.videoCapabilities()) {
+ EME_LOG(" capabilities: video=%s",
+ NS_ConvertUTF16toUTF8(v.contentType()).get());
+ }
+ for (const auto& a : capabilities.audioCapabilities()) {
+ EME_LOG(" capabilities: audio=%s",
+ NS_ConvertUTF16toUTF8(a.contentType()).get());
+ }
+ for (const auto& e : capabilities.encryptionSchemes()) {
+ EME_LOG(" capabilities: encryptionScheme=%s",
+ EncryptionSchemeStr(e));
+ }
+ auto* info = cdmInfo.AppendElement(fallible);
+ if (!info) {
+ promise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
+ return;
+ }
+ info->mKeySystemName = capabilities.keySystem();
+
+ KeySystemConfig config;
+ MFCDMCapabilitiesIPDLToKeySystemConfig(capabilities, config);
+ info->mCapabilities = config.GetDebugInfo();
+ info->mClearlead =
+ DoesKeySystemSupportClearLead(info->mKeySystemName);
+ if (capabilities.isHDCP22Compatible()) {
+ info->mIsHDCP22Compatible = true;
+ }
+ }
+ promise->MaybeResolve(cdmInfo);
+ },
+ [promise = RefPtr<dom::Promise>(aPromise)](
+ const mozilla::ipc::ResponseRejectReason& aReason) {
+ EME_LOG("IPC failure for GetKeySystemCapabilities!");
+ promise->MaybeReject(NS_ERROR_DOM_MEDIA_CDM_ERR);
+ });
+}
+#endif
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityAudioDecoderChild.h b/ipc/glue/UtilityAudioDecoderChild.h
new file mode 100644
index 0000000000..4e6a7792b0
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoderChild.h
@@ -0,0 +1,131 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityAudioDecoderChild_h__
+#define _include_ipc_glue_UtilityAudioDecoderChild_h__
+
+#include "mozilla/ProcInfo.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "mozilla/RefPtr.h"
+
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/UtilityProcessParent.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/ipc/UtilityAudioDecoder.h"
+#include "mozilla/ipc/PUtilityAudioDecoderChild.h"
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+# include "mozilla/gfx/GPUProcessListener.h"
+# include "mozilla/gfx/gfxVarReceiver.h"
+#endif
+
+#include "PDMFactory.h"
+
+namespace mozilla::ipc {
+
+class UtilityAudioDecoderChildShutdownObserver : public nsIObserver {
+ public:
+ explicit UtilityAudioDecoderChildShutdownObserver(SandboxingKind aKind)
+ : mSandbox(aKind){};
+
+ NS_DECL_ISUPPORTS
+
+ NS_IMETHOD Observe(nsISupports* aSubject, const char* aTopic,
+ const char16_t* aData) override;
+
+ private:
+ virtual ~UtilityAudioDecoderChildShutdownObserver() = default;
+
+ const SandboxingKind mSandbox;
+};
+
+// This controls performing audio decoding on the utility process and it is
+// intended to live on the main process side
+class UtilityAudioDecoderChild final : public PUtilityAudioDecoderChild
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ ,
+ public gfx::gfxVarReceiver,
+ public gfx::GPUProcessListener
+#endif
+{
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityAudioDecoderChild, override);
+ mozilla::ipc::IPCResult RecvUpdateMediaCodecsSupported(
+ const RemoteDecodeIn& aLocation,
+ const media::MediaCodecsSupported& aSupported);
+
+ UtilityActorName GetActorName() { return GetAudioActorName(mSandbox); }
+
+ nsresult BindToUtilityProcess(RefPtr<UtilityProcessParent> aUtilityParent) {
+ Endpoint<PUtilityAudioDecoderChild> utilityAudioDecoderChildEnd;
+ Endpoint<PUtilityAudioDecoderParent> utilityAudioDecoderParentEnd;
+ nsresult rv = PUtilityAudioDecoder::CreateEndpoints(
+ aUtilityParent->OtherPid(), base::GetCurrentProcId(),
+ &utilityAudioDecoderParentEnd, &utilityAudioDecoderChildEnd);
+
+ if (NS_FAILED(rv)) {
+ MOZ_ASSERT(false, "Protocol endpoints failure");
+ return NS_ERROR_FAILURE;
+ }
+
+ if (!aUtilityParent->SendStartUtilityAudioDecoderService(
+ std::move(utilityAudioDecoderParentEnd))) {
+ MOZ_ASSERT(false, "StartUtilityAudioDecoder service failure");
+ return NS_ERROR_FAILURE;
+ }
+
+ Bind(std::move(utilityAudioDecoderChildEnd));
+
+ PROFILER_MARKER_UNTYPED(
+ "UtilityAudioDecoderChild::BindToUtilityProcess", IPC,
+ MarkerOptions(
+ MarkerTiming::IntervalUntilNowFrom(mAudioDecoderChildStart)));
+ return NS_OK;
+ }
+
+ void ActorDestroy(ActorDestroyReason aReason) override;
+
+ void Bind(Endpoint<PUtilityAudioDecoderChild>&& aEndpoint);
+
+ static void Shutdown(SandboxingKind aKind);
+
+ static RefPtr<UtilityAudioDecoderChild> GetSingleton(SandboxingKind aKind);
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ mozilla::ipc::IPCResult RecvCompleteCreatedVideoBridge();
+
+ bool HasCreatedVideoBridge() const;
+
+ void OnVarChanged(const gfx::GfxVarUpdate& aVar) override;
+
+ void OnCompositorUnexpectedShutdown() override;
+
+ // True if creating a video bridge sucessfully. Currently only used for media
+ // engine cdm.
+ bool CreateVideoBridge();
+#endif
+
+#ifdef MOZ_WMF_CDM
+ void GetKeySystemCapabilities(dom::Promise* aPromise);
+#endif
+
+ private:
+ explicit UtilityAudioDecoderChild(SandboxingKind aKind);
+ ~UtilityAudioDecoderChild() = default;
+
+ const SandboxingKind mSandbox;
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ // True if the utility process has created a video bridge with the GPU prcess.
+ // Currently only used for media egine cdm. Main thread only.
+ bool mHasCreatedVideoBridge = false;
+#endif
+
+ TimeStamp mAudioDecoderChildStart;
+};
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityAudioDecoderChild_h__
diff --git a/ipc/glue/UtilityAudioDecoderParent.cpp b/ipc/glue/UtilityAudioDecoderParent.cpp
new file mode 100644
index 0000000000..2eb0936a38
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoderParent.cpp
@@ -0,0 +1,205 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "UtilityAudioDecoderParent.h"
+
+#include "GeckoProfiler.h"
+#include "nsDebugImpl.h"
+
+#include "mozilla/RemoteDecoderManagerParent.h"
+#include "PDMFactory.h"
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+# include "WMF.h"
+# include "WMFDecoderModule.h"
+# include "WMFUtils.h"
+
+# include "mozilla/sandboxTarget.h"
+# include "mozilla/ipc/UtilityProcessImpl.h"
+#endif // defined(XP_WIN) && defined(MOZ_SANDBOX)
+
+#ifdef MOZ_WIDGET_ANDROID
+# include "mozilla/StaticPrefs_media.h"
+# include "AndroidDecoderModule.h"
+#endif
+
+#include "mozilla/ipc/UtilityProcessChild.h"
+#include "mozilla/RemoteDecodeUtils.h"
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+# include "mozilla/gfx/DeviceManagerDx.h"
+# include "mozilla/gfx/gfxVars.h"
+# include "gfxConfig.h"
+#endif
+
+#ifdef MOZ_WMF_CDM
+# include "mozilla/MFCDMParent.h"
+# include "mozilla/PMFCDM.h"
+#endif
+
+namespace mozilla::ipc {
+
+UtilityAudioDecoderParent::UtilityAudioDecoderParent()
+ : mKind(GetCurrentSandboxingKind()),
+ mAudioDecoderParentStart(TimeStamp::Now()) {
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ if (mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ nsDebugImpl::SetMultiprocessMode("MF Media Engine CDM");
+ profiler_set_process_name(nsCString("MF Media Engine CDM"));
+ gfx::gfxConfig::Init();
+ gfx::gfxVars::Initialize();
+ gfx::DeviceManagerDx::Init();
+ return;
+ }
+#endif
+ if (GetCurrentSandboxingKind() != SandboxingKind::GENERIC_UTILITY) {
+ nsDebugImpl::SetMultiprocessMode("Utility AudioDecoder");
+ profiler_set_process_name(nsCString("Utility AudioDecoder"));
+ }
+}
+
+UtilityAudioDecoderParent::~UtilityAudioDecoderParent() {
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ if (mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ gfx::gfxConfig::Shutdown();
+ gfx::gfxVars::Shutdown();
+ gfx::DeviceManagerDx::Shutdown();
+ }
+#endif
+#ifdef MOZ_WMF_CDM
+ if (mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ MFCDMParent::Shutdown();
+ }
+#endif
+}
+
+/* static */
+void UtilityAudioDecoderParent::GenericPreloadForSandbox() {
+#if defined(MOZ_SANDBOX) && defined(XP_WIN) && defined(MOZ_FFVPX)
+ // Preload AV dlls so we can enable Binary Signature Policy
+ // to restrict further dll loads.
+ UtilityProcessImpl::LoadLibraryOrCrash(L"mozavcodec.dll");
+ UtilityProcessImpl::LoadLibraryOrCrash(L"mozavutil.dll");
+#endif // defined(MOZ_SANDBOX) && defined(XP_WIN) && defined(MOZ_FFVPX)
+}
+
+/* static */
+void UtilityAudioDecoderParent::WMFPreloadForSandbox() {
+#if defined(MOZ_SANDBOX) && defined(XP_WIN)
+ // mfplat.dll and mf.dll will be preloaded by
+ // wmf::MediaFoundationInitializer::HasInitialized()
+
+# if defined(NS_FREE_PERMANENT_DATA)
+ // WMF Shutdown requires this or it will badly crash
+ UtilityProcessImpl::LoadLibraryOrCrash(L"ole32.dll");
+# endif // defined(NS_FREE_PERMANENT_DATA)
+
+ auto rv = wmf::MediaFoundationInitializer::HasInitialized();
+ if (!rv) {
+ NS_WARNING("Failed to init Media Foundation in the Utility process");
+ return;
+ }
+#endif // defined(MOZ_SANDBOX) && defined(XP_WIN)
+}
+
+void UtilityAudioDecoderParent::Start(
+ Endpoint<PUtilityAudioDecoderParent>&& aEndpoint) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ DebugOnly<bool> ok = std::move(aEndpoint).Bind(this);
+ MOZ_ASSERT(ok);
+
+#ifdef MOZ_WIDGET_ANDROID
+ if (StaticPrefs::media_utility_android_media_codec_enabled()) {
+ AndroidDecoderModule::SetSupportedMimeTypes();
+ }
+#endif
+
+ auto supported = PDMFactory::Supported();
+ Unused << SendUpdateMediaCodecsSupported(GetRemoteDecodeInFromKind(mKind),
+ supported);
+ PROFILER_MARKER_UNTYPED("UtilityAudioDecoderParent::Start", IPC,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(
+ mAudioDecoderParentStart)));
+}
+
+mozilla::ipc::IPCResult
+UtilityAudioDecoderParent::RecvNewContentRemoteDecoderManager(
+ Endpoint<PRemoteDecoderManagerParent>&& aEndpoint,
+ const ContentParentId& aParentId) {
+ MOZ_ASSERT(NS_IsMainThread());
+ if (!RemoteDecoderManagerParent::CreateForContent(std::move(aEndpoint),
+ aParentId)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+mozilla::ipc::IPCResult UtilityAudioDecoderParent::RecvInitVideoBridge(
+ Endpoint<PVideoBridgeChild>&& aEndpoint,
+ nsTArray<gfx::GfxVarUpdate>&& aUpdates,
+ const ContentDeviceData& aContentDeviceData) {
+ MOZ_ASSERT(mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ if (!RemoteDecoderManagerParent::CreateVideoBridgeToOtherProcess(
+ std::move(aEndpoint))) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ for (const auto& update : aUpdates) {
+ gfx::gfxVars::ApplyUpdate(update);
+ }
+
+ gfx::gfxConfig::Inherit(
+ {
+ gfx::Feature::HW_COMPOSITING,
+ gfx::Feature::D3D11_COMPOSITING,
+ gfx::Feature::OPENGL_COMPOSITING,
+ gfx::Feature::DIRECT2D,
+ },
+ aContentDeviceData.prefs());
+
+ if (gfx::gfxConfig::IsEnabled(gfx::Feature::D3D11_COMPOSITING)) {
+ if (auto* devmgr = gfx::DeviceManagerDx::Get()) {
+ devmgr->ImportDeviceInfo(aContentDeviceData.d3d11());
+ }
+ }
+
+ Unused << SendCompleteCreatedVideoBridge();
+ return IPC_OK();
+}
+
+IPCResult UtilityAudioDecoderParent::RecvUpdateVar(
+ const GfxVarUpdate& aUpdate) {
+ MOZ_ASSERT(mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ gfx::gfxVars::ApplyUpdate(aUpdate);
+ return IPC_OK();
+}
+#endif
+
+#ifdef MOZ_WMF_CDM
+IPCResult UtilityAudioDecoderParent::RecvGetKeySystemCapabilities(
+ GetKeySystemCapabilitiesResolver&& aResolver) {
+ MOZ_ASSERT(mKind == SandboxingKind::MF_MEDIA_ENGINE_CDM);
+ MFCDMParent::GetAllKeySystemsCapabilities()->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [aResolver](CopyableTArray<MFCDMCapabilitiesIPDL>&& aCapabilities) {
+ aResolver(std::move(aCapabilities));
+ },
+ [aResolver](nsresult) {
+ aResolver(CopyableTArray<MFCDMCapabilitiesIPDL>());
+ });
+ return IPC_OK();
+}
+
+IPCResult UtilityAudioDecoderParent::RecvUpdateWidevineL1Path(
+ const nsString& aPath) {
+ MFCDMParent::SetWidevineL1Path(NS_ConvertUTF16toUTF8(aPath).get());
+ return IPC_OK();
+}
+#endif
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityAudioDecoderParent.h b/ipc/glue/UtilityAudioDecoderParent.h
new file mode 100644
index 0000000000..6996fa0538
--- /dev/null
+++ b/ipc/glue/UtilityAudioDecoderParent.h
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityAudioDecoderParent_h_
+#define _include_ipc_glue_UtilityAudioDecoderParent_h_
+
+#include "mozilla/PRemoteDecoderManagerParent.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "mozilla/UniquePtr.h"
+
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/PUtilityAudioDecoderParent.h"
+
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+
+#include "nsThreadManager.h"
+
+namespace mozilla::ipc {
+
+// This is in charge of handling the utility child process side to perform
+// audio decoding
+class UtilityAudioDecoderParent final : public PUtilityAudioDecoderParent {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityAudioDecoderParent, override);
+
+ UtilityAudioDecoderParent();
+
+ static void GenericPreloadForSandbox();
+ static void WMFPreloadForSandbox();
+
+ void Start(Endpoint<PUtilityAudioDecoderParent>&& aEndpoint);
+
+ mozilla::ipc::IPCResult RecvNewContentRemoteDecoderManager(
+ Endpoint<PRemoteDecoderManagerParent>&& aEndpoint,
+ const ContentParentId& aParentId);
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ mozilla::ipc::IPCResult RecvInitVideoBridge(
+ Endpoint<PVideoBridgeChild>&& aEndpoint,
+ nsTArray<mozilla::gfx::GfxVarUpdate>&& aUpdates,
+ const ContentDeviceData& aContentDeviceData);
+
+ IPCResult RecvUpdateVar(const mozilla::gfx::GfxVarUpdate& aUpdate);
+#endif
+
+#ifdef MOZ_WMF_CDM
+ IPCResult RecvGetKeySystemCapabilities(
+ GetKeySystemCapabilitiesResolver&& aResolver);
+
+ IPCResult RecvUpdateWidevineL1Path(const nsString& aPath);
+#endif
+
+ private:
+ ~UtilityAudioDecoderParent();
+
+ const SandboxingKind mKind;
+ TimeStamp mAudioDecoderParentStart;
+};
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityAudioDecoderParent_h_
diff --git a/ipc/glue/UtilityProcessChild.cpp b/ipc/glue/UtilityProcessChild.cpp
new file mode 100644
index 0000000000..cda3dbc817
--- /dev/null
+++ b/ipc/glue/UtilityProcessChild.cpp
@@ -0,0 +1,401 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "UtilityProcessChild.h"
+
+#include "mozilla/AppShutdown.h"
+#include "mozilla/Logging.h"
+#include "mozilla/dom/ContentParent.h"
+#include "mozilla/dom/JSOracleChild.h"
+#include "mozilla/dom/MemoryReportRequest.h"
+#include "mozilla/ipc/CrashReporterClient.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/UtilityProcessManager.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/Preferences.h"
+#include "mozilla/RemoteDecoderManagerParent.h"
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/Sandbox.h"
+#endif
+
+#if defined(XP_OPENBSD) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxSettings.h"
+#endif
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+# include "mozilla/SandboxTestingChild.h"
+#endif
+
+#include "mozilla/Telemetry.h"
+
+#if defined(XP_WIN)
+# include "mozilla/WinDllServices.h"
+# include "mozilla/dom/WindowsUtilsChild.h"
+# include "mozilla/widget/filedialog/WinFileDialogChild.h"
+#endif
+
+#include "nsDebugImpl.h"
+#include "nsIXULRuntime.h"
+#include "nsThreadManager.h"
+#include "GeckoProfiler.h"
+
+#include "mozilla/ipc/ProcessChild.h"
+#include "mozilla/FOGIPC.h"
+#include "mozilla/glean/GleanMetrics.h"
+
+#include "mozilla/Services.h"
+
+namespace mozilla::ipc {
+
+using namespace layers;
+
+static StaticMutex sUtilityProcessChildMutex;
+static StaticRefPtr<UtilityProcessChild> sUtilityProcessChild
+ MOZ_GUARDED_BY(sUtilityProcessChildMutex);
+
+UtilityProcessChild::UtilityProcessChild() : mChildStartTime(TimeStamp::Now()) {
+ nsDebugImpl::SetMultiprocessMode("Utility");
+}
+
+UtilityProcessChild::~UtilityProcessChild() = default;
+
+/* static */
+RefPtr<UtilityProcessChild> UtilityProcessChild::GetSingleton() {
+ MOZ_ASSERT(XRE_IsUtilityProcess());
+ if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownFinal)) {
+ return nullptr;
+ }
+ StaticMutexAutoLock lock(sUtilityProcessChildMutex);
+ if (!sUtilityProcessChild) {
+ sUtilityProcessChild = new UtilityProcessChild();
+ }
+ return sUtilityProcessChild;
+}
+
+/* static */
+RefPtr<UtilityProcessChild> UtilityProcessChild::Get() {
+ StaticMutexAutoLock lock(sUtilityProcessChildMutex);
+ return sUtilityProcessChild;
+}
+
+bool UtilityProcessChild::Init(mozilla::ipc::UntypedEndpoint&& aEndpoint,
+ const nsCString& aParentBuildID,
+ uint64_t aSandboxingKind) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ // Initialize the thread manager before starting IPC. Otherwise, messages
+ // may be posted to the main thread and we won't be able to process them.
+ if (NS_WARN_IF(NS_FAILED(nsThreadManager::get().Init()))) {
+ return false;
+ }
+
+ // Now it's safe to start IPC.
+ if (NS_WARN_IF(!aEndpoint.Bind(this))) {
+ return false;
+ }
+
+ // This must be checked before any IPDL message, which may hit sentinel
+ // errors due to parent and content processes having different
+ // versions.
+ MessageChannel* channel = GetIPCChannel();
+ if (channel && !channel->SendBuildIDsMatchMessage(aParentBuildID.get())) {
+ // We need to quit this process if the buildID doesn't match the parent's.
+ // This can occur when an update occurred in the background.
+ ipc::ProcessChild::QuickExit();
+ }
+
+ // Init crash reporter support.
+ ipc::CrashReporterClient::InitSingleton(this);
+
+ if (NS_FAILED(NS_InitMinimalXPCOM())) {
+ return false;
+ }
+
+ mSandbox = (SandboxingKind)aSandboxingKind;
+
+ // At the moment, only ORB uses JSContext in the
+ // Utility Process and ORB uses GENERIC_UTILITY
+ if (mSandbox == SandboxingKind::GENERIC_UTILITY) {
+ if (!JS_FrontendOnlyInit()) {
+ return false;
+ }
+#if defined(__OpenBSD__) && defined(MOZ_SANDBOX)
+ // Bug 1823458: delay pledge initialization, otherwise
+ // JS_FrontendOnlyInit triggers sysctl(KERN_PROC_ID) which isnt
+ // permitted with the current pledge.utility config
+ StartOpenBSDSandbox(GeckoProcessType_Utility, mSandbox);
+#endif
+ }
+
+ profiler_set_process_name(nsCString("Utility Process"));
+
+ // Notify the parent process that we have finished our init and that it can
+ // now resolve the pending promise of process startup
+ SendInitCompleted();
+
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::SendInitCompleted", IPC,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+
+ RunOnShutdown(
+ [sandboxKind = mSandbox] {
+ StaticMutexAutoLock lock(sUtilityProcessChildMutex);
+ sUtilityProcessChild = nullptr;
+ if (sandboxKind == SandboxingKind::GENERIC_UTILITY) {
+ JS_FrontendOnlyShutDown();
+ }
+ },
+ ShutdownPhase::XPCOMShutdownFinal);
+
+ return true;
+}
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+extern "C" {
+void CGSShutdownServerConnections();
+};
+#endif
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvInit(
+ const Maybe<FileDescriptor>& aBrokerFd,
+ const bool& aCanRecordReleaseTelemetry,
+ const bool& aIsReadyForBackgroundProcessing) {
+ // Do this now (before closing WindowServer on macOS) to avoid risking
+ // blocking in GetCurrentProcess() called on that platform
+ mozilla::ipc::SetThisProcessName("Utility Process");
+
+#if defined(MOZ_SANDBOX)
+# if defined(XP_MACOSX)
+ // Close all current connections to the WindowServer. This ensures that the
+ // Activity Monitor will not label the content process as "Not responding"
+ // because it's not running a native event loop. See bug 1384336.
+ CGSShutdownServerConnections();
+
+# elif defined(XP_LINUX)
+ int fd = -1;
+ if (aBrokerFd.isSome()) {
+ fd = aBrokerFd.value().ClonePlatformHandle().release();
+ }
+
+ SetUtilitySandbox(fd, mSandbox);
+
+# endif // XP_MACOSX/XP_LINUX
+#endif // MOZ_SANDBOX
+
+#if defined(XP_WIN)
+ if (aCanRecordReleaseTelemetry) {
+ RefPtr<DllServices> dllSvc(DllServices::Get());
+ dllSvc->StartUntrustedModulesProcessor(aIsReadyForBackgroundProcessing);
+ }
+#endif // defined(XP_WIN)
+
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::RecvInit", IPC,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvPreferenceUpdate(
+ const Pref& aPref) {
+ Preferences::SetPreference(aPref);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvInitProfiler(
+ Endpoint<PProfilerChild>&& aEndpoint) {
+ mProfilerController = ChildProfilerController::Create(std::move(aEndpoint));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvRequestMemoryReport(
+ const uint32_t& aGeneration, const bool& aAnonymize,
+ const bool& aMinimizeMemoryUsage, const Maybe<FileDescriptor>& aDMDFile,
+ const RequestMemoryReportResolver& aResolver) {
+ nsPrintfCString processName("Utility (pid %" PRIPID
+ ", sandboxingKind %" PRIu64 ")",
+ base::GetCurrentProcId(), mSandbox);
+
+ mozilla::dom::MemoryReportRequestClient::Start(
+ aGeneration, aAnonymize, aMinimizeMemoryUsage, aDMDFile, processName,
+ [&](const MemoryReport& aReport) {
+ Unused << GetSingleton()->SendAddMemoryReport(aReport);
+ },
+ aResolver);
+ return IPC_OK();
+}
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+mozilla::ipc::IPCResult UtilityProcessChild::RecvInitSandboxTesting(
+ Endpoint<PSandboxTestingChild>&& aEndpoint) {
+ if (!SandboxTestingChild::Initialize(std::move(aEndpoint))) {
+ return IPC_FAIL(
+ this, "InitSandboxTesting failed to initialise the child process.");
+ }
+ return IPC_OK();
+}
+#endif
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvFlushFOGData(
+ FlushFOGDataResolver&& aResolver) {
+ glean::FlushFOGData(std::move(aResolver));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvTestTriggerMetrics(
+ TestTriggerMetricsResolver&& aResolve) {
+ mozilla::glean::test_only_ipc::a_counter.Add(
+ nsIXULRuntime::PROCESS_TYPE_UTILITY);
+ aResolve(true);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvTestTelemetryProbes() {
+ const uint32_t kExpectedUintValue = 42;
+ Telemetry::ScalarSet(Telemetry::ScalarID::TELEMETRY_TEST_UTILITY_ONLY_UINT,
+ kExpectedUintValue);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+UtilityProcessChild::RecvStartUtilityAudioDecoderService(
+ Endpoint<PUtilityAudioDecoderParent>&& aEndpoint) {
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::RecvStartUtilityAudioDecoderService", MEDIA,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+ mUtilityAudioDecoderInstance = new UtilityAudioDecoderParent();
+ if (!mUtilityAudioDecoderInstance) {
+ return IPC_FAIL(this, "Failed to create UtilityAudioDecoderParent");
+ }
+
+ mUtilityAudioDecoderInstance->Start(std::move(aEndpoint));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvStartJSOracleService(
+ Endpoint<PJSOracleChild>&& aEndpoint) {
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::RecvStartJSOracleService", JS,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+ mJSOracleInstance = new mozilla::dom::JSOracleChild();
+ if (!mJSOracleInstance) {
+ return IPC_FAIL(this, "Failed to create JSOracleParent");
+ }
+
+ mJSOracleInstance->Start(std::move(aEndpoint));
+ return IPC_OK();
+}
+
+#if defined(XP_WIN)
+mozilla::ipc::IPCResult UtilityProcessChild::RecvStartWindowsUtilsService(
+ Endpoint<dom::PWindowsUtilsChild>&& aEndpoint) {
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::RecvStartWindowsUtilsService", OTHER,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+ mWindowsUtilsInstance = new dom::WindowsUtilsChild();
+ if (!mWindowsUtilsInstance) {
+ return IPC_FAIL(this, "Failed to create WindowsUtilsChild");
+ }
+
+ [[maybe_unused]] bool ok = std::move(aEndpoint).Bind(mWindowsUtilsInstance);
+ MOZ_ASSERT(ok);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvStartWinFileDialogService(
+ Endpoint<widget::filedialog::PWinFileDialogChild>&& aEndpoint) {
+ PROFILER_MARKER_UNTYPED(
+ "UtilityProcessChild::RecvStartWinFileDialogService", OTHER,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(mChildStartTime)));
+
+ auto instance = MakeRefPtr<widget::filedialog::WinFileDialogChild>();
+ if (!instance) {
+ return IPC_FAIL(this, "Failed to create WinFileDialogChild");
+ }
+
+ bool const ok = std::move(aEndpoint).Bind(instance.get());
+ if (!ok) {
+ return IPC_FAIL(this, "Failed to bind created WinFileDialogChild");
+ }
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessChild::RecvGetUntrustedModulesData(
+ GetUntrustedModulesDataResolver&& aResolver) {
+ RefPtr<DllServices> dllSvc(DllServices::Get());
+ dllSvc->GetUntrustedModulesData()->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [aResolver](Maybe<UntrustedModulesData>&& aData) {
+ aResolver(std::move(aData));
+ },
+ [aResolver](nsresult aReason) { aResolver(Nothing()); });
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+UtilityProcessChild::RecvUnblockUntrustedModulesThread() {
+ if (nsCOMPtr<nsIObserverService> obs =
+ mozilla::services::GetObserverService()) {
+ obs->NotifyObservers(nullptr, "unblock-untrusted-modules-thread", nullptr);
+ }
+ return IPC_OK();
+}
+#endif // defined(XP_WIN)
+
+void UtilityProcessChild::ActorDestroy(ActorDestroyReason aWhy) {
+ if (AbnormalShutdown == aWhy) {
+ NS_WARNING("Shutting down Utility process early due to a crash!");
+ ipc::ProcessChild::QuickExit();
+ }
+
+ // Send the last bits of Glean data over to the main process.
+ glean::FlushFOGData(
+ [](ByteBuf&& aBuf) { glean::SendFOGData(std::move(aBuf)); });
+
+#ifndef NS_FREE_PERMANENT_DATA
+ ProcessChild::QuickExit();
+#else
+
+ if (mProfilerController) {
+ mProfilerController->Shutdown();
+ mProfilerController = nullptr;
+ }
+
+ uint32_t timeout = 0;
+ if (mUtilityAudioDecoderInstance) {
+ mUtilityAudioDecoderInstance = nullptr;
+ timeout = 10 * 1000;
+ }
+
+ mJSOracleInstance = nullptr;
+
+# ifdef XP_WIN
+ mWindowsUtilsInstance = nullptr;
+# endif
+
+ // Wait until all RemoteDecoderManagerParent have closed.
+ // It is still possible some may not have clean up yet, and we might hit
+ // timeout. Our xpcom-shutdown listener should take care of cleaning the
+ // reference of our singleton.
+ //
+ // FIXME: Should move from using AsyncBlockers to proper
+ // nsIAsyncShutdownService once it is not JS, see bug 1760855
+ mShutdownBlockers.WaitUntilClear(timeout)->Then(
+ GetCurrentSerialEventTarget(), __func__, [&]() {
+# ifdef XP_WIN
+ {
+ RefPtr<DllServices> dllSvc(DllServices::Get());
+ dllSvc->DisableFull();
+ }
+# endif // defined(XP_WIN)
+
+ ipc::CrashReporterClient::DestroySingleton();
+ XRE_ShutdownChildProcess();
+ });
+#endif // NS_FREE_PERMANENT_DATA
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessChild.h b/ipc/glue/UtilityProcessChild.h
new file mode 100644
index 0000000000..db6db6bba6
--- /dev/null
+++ b/ipc/glue/UtilityProcessChild.h
@@ -0,0 +1,110 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessChild_h_
+#define _include_ipc_glue_UtilityProcessChild_h_
+#include "mozilla/ipc/PUtilityProcessChild.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/ipc/UtilityAudioDecoderParent.h"
+#include "mozilla/UniquePtr.h"
+#include "ChildProfilerController.h"
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+# include "mozilla/PSandboxTestingChild.h"
+#endif
+#include "mozilla/PRemoteDecoderManagerParent.h"
+#include "mozilla/ipc/AsyncBlockers.h"
+#include "mozilla/dom/JSOracleChild.h"
+#include "mozilla/ProfilerMarkers.h"
+
+namespace mozilla::dom {
+class PJSOracleChild;
+} // namespace mozilla::dom
+
+namespace mozilla::ipc {
+
+class UtilityProcessHost;
+
+class UtilityProcessChild final : public PUtilityProcessChild {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityProcessChild, override);
+
+ UtilityProcessChild();
+
+ static RefPtr<UtilityProcessChild> GetSingleton();
+ static RefPtr<UtilityProcessChild> Get();
+
+ SandboxingKind mSandbox{};
+
+ bool Init(mozilla::ipc::UntypedEndpoint&& aEndpoint,
+ const nsCString& aParentBuildID, uint64_t aSandboxingKind);
+
+ mozilla::ipc::IPCResult RecvInit(const Maybe<ipc::FileDescriptor>& aBrokerFd,
+ const bool& aCanRecordReleaseTelemetry,
+ const bool& aIsReadyForBackgroundProcessing);
+ mozilla::ipc::IPCResult RecvInitProfiler(
+ Endpoint<PProfilerChild>&& aEndpoint);
+
+ mozilla::ipc::IPCResult RecvPreferenceUpdate(const Pref& pref);
+
+ mozilla::ipc::IPCResult RecvRequestMemoryReport(
+ const uint32_t& generation, const bool& anonymize,
+ const bool& minimizeMemoryUsage,
+ const Maybe<ipc::FileDescriptor>& DMDFile,
+ const RequestMemoryReportResolver& aResolver);
+
+ mozilla::ipc::IPCResult RecvFlushFOGData(FlushFOGDataResolver&& aResolver);
+
+ mozilla::ipc::IPCResult RecvTestTriggerMetrics(
+ TestTriggerMetricsResolver&& aResolve);
+
+ mozilla::ipc::IPCResult RecvTestTelemetryProbes();
+
+ mozilla::ipc::IPCResult RecvStartUtilityAudioDecoderService(
+ Endpoint<PUtilityAudioDecoderParent>&& aEndpoint);
+
+ mozilla::ipc::IPCResult RecvStartJSOracleService(
+ Endpoint<dom::PJSOracleChild>&& aEndpoint);
+
+#if defined(XP_WIN)
+ mozilla::ipc::IPCResult RecvStartWindowsUtilsService(
+ Endpoint<PWindowsUtilsChild>&& aEndpoint);
+
+ mozilla::ipc::IPCResult RecvStartWinFileDialogService(
+ Endpoint<PWinFileDialogChild>&& aEndpoint);
+
+ mozilla::ipc::IPCResult RecvGetUntrustedModulesData(
+ GetUntrustedModulesDataResolver&& aResolver);
+ mozilla::ipc::IPCResult RecvUnblockUntrustedModulesThread();
+#endif // defined(XP_WIN)
+
+ AsyncBlockers& AsyncShutdownService() { return mShutdownBlockers; }
+
+ void ActorDestroy(ActorDestroyReason aWhy) override;
+
+#if defined(MOZ_SANDBOX) && defined(MOZ_DEBUG) && defined(ENABLE_TESTS)
+ mozilla::ipc::IPCResult RecvInitSandboxTesting(
+ Endpoint<PSandboxTestingChild>&& aEndpoint);
+#endif
+
+ protected:
+ friend class UtilityProcessImpl;
+ ~UtilityProcessChild();
+
+ private:
+ TimeStamp mChildStartTime;
+ RefPtr<ChildProfilerController> mProfilerController;
+ RefPtr<UtilityAudioDecoderParent> mUtilityAudioDecoderInstance{};
+ RefPtr<dom::JSOracleChild> mJSOracleInstance{};
+#ifdef XP_WIN
+ RefPtr<PWindowsUtilsChild> mWindowsUtilsInstance;
+#endif
+
+ AsyncBlockers mShutdownBlockers;
+};
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityProcessChild_h_
diff --git a/ipc/glue/UtilityProcessHost.cpp b/ipc/glue/UtilityProcessHost.cpp
new file mode 100644
index 0000000000..6b8a84966e
--- /dev/null
+++ b/ipc/glue/UtilityProcessHost.cpp
@@ -0,0 +1,431 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "UtilityProcessHost.h"
+
+#include "mozilla/dom/ContentParent.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/UtilityProcessManager.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/Telemetry.h"
+
+#include "chrome/common/process_watcher.h"
+#include "mozilla/Preferences.h"
+#include "mozilla/StaticPrefs_general.h"
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+# include "mozilla/Sandbox.h"
+#endif
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxBrokerPolicyFactory.h"
+#endif
+
+#if defined(XP_WIN)
+# include "mozilla/WinDllServices.h"
+#endif // defined(XP_WIN)
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX) && !defined(MOZ_ASAN)
+# define MOZ_WMF_CDM_LPAC_SANDBOX true
+#endif
+
+#ifdef MOZ_WMF_CDM_LPAC_SANDBOX
+# include "GMPServiceParent.h"
+# include "mozilla/dom/KeySystemNames.h"
+# include "mozilla/GeckoArgs.h"
+# include "mozilla/MFMediaEngineUtils.h"
+# include "mozilla/StaticPrefs_media.h"
+# include "nsIFile.h"
+# include "sandboxBroker.h"
+#endif
+
+#include "ProfilerParent.h"
+#include "mozilla/PProfilerChild.h"
+
+namespace mozilla::ipc {
+
+LazyLogModule gUtilityProcessLog("utilityproc");
+#define LOGD(...) MOZ_LOG(gUtilityProcessLog, LogLevel::Debug, (__VA_ARGS__))
+
+#ifdef MOZ_WMF_CDM_LPAC_SANDBOX
+# define WMF_LOG(msg, ...) \
+ MOZ_LOG(gMFMediaEngineLog, LogLevel::Debug, \
+ ("UtilityProcessHost=%p, " msg, this, ##__VA_ARGS__))
+#endif
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+bool UtilityProcessHost::sLaunchWithMacSandbox = false;
+#endif
+
+UtilityProcessHost::UtilityProcessHost(SandboxingKind aSandbox,
+ RefPtr<Listener> aListener)
+ : GeckoChildProcessHost(GeckoProcessType_Utility),
+ mListener(std::move(aListener)),
+ mLiveToken(new media::Refcountable<bool>(true)),
+ mLaunchPromise(
+ MakeRefPtr<GenericNonExclusivePromise::Private>(__func__)) {
+ MOZ_COUNT_CTOR(UtilityProcessHost);
+ LOGD("[%p] UtilityProcessHost::UtilityProcessHost sandboxingKind=%" PRIu64,
+ this, aSandbox);
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ if (!sLaunchWithMacSandbox) {
+ sLaunchWithMacSandbox = IsUtilitySandboxEnabled(aSandbox);
+ }
+ mDisableOSActivityMode = sLaunchWithMacSandbox;
+#endif
+#if defined(MOZ_SANDBOX)
+ mSandbox = aSandbox;
+#endif
+}
+
+UtilityProcessHost::~UtilityProcessHost() {
+ MOZ_COUNT_DTOR(UtilityProcessHost);
+#if defined(MOZ_SANDBOX)
+ LOGD("[%p] UtilityProcessHost::~UtilityProcessHost sandboxingKind=%" PRIu64,
+ this, mSandbox);
+#else
+ LOGD("[%p] UtilityProcessHost::~UtilityProcessHost", this);
+#endif
+}
+
+bool UtilityProcessHost::Launch(StringVector aExtraOpts) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ MOZ_ASSERT(mLaunchPhase == LaunchPhase::Unlaunched);
+ MOZ_ASSERT(!mUtilityProcessParent);
+
+ LOGD("[%p] UtilityProcessHost::Launch", this);
+
+ mPrefSerializer = MakeUnique<ipc::SharedPreferenceSerializer>();
+ if (!mPrefSerializer->SerializeToSharedMemory(GeckoProcessType_Utility,
+ /* remoteType */ ""_ns)) {
+ return false;
+ }
+ mPrefSerializer->AddSharedPrefCmdLineArgs(*this, aExtraOpts);
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ mSandboxLevel = Preferences::GetInt("security.sandbox.utility.level");
+#endif
+
+#ifdef MOZ_WMF_CDM_LPAC_SANDBOX
+ EnsureWidevineL1PathForSandbox(aExtraOpts);
+#endif
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX)
+ EnanbleMFCDMTelemetryEventIfNeeded();
+#endif
+
+ mLaunchPhase = LaunchPhase::Waiting;
+
+ if (!GeckoChildProcessHost::AsyncLaunch(aExtraOpts)) {
+ NS_WARNING("UtilityProcess AsyncLaunch failed, aborting.");
+ mLaunchPhase = LaunchPhase::Complete;
+ mPrefSerializer = nullptr;
+ return false;
+ }
+ LOGD("[%p] UtilityProcessHost::Launch launching async", this);
+ return true;
+}
+
+RefPtr<GenericNonExclusivePromise> UtilityProcessHost::LaunchPromise() {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ if (mLaunchPromiseLaunched) {
+ return mLaunchPromise;
+ }
+
+ WhenProcessHandleReady()->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [this, liveToken = mLiveToken](
+ const ipc::ProcessHandlePromise::ResolveOrRejectValue& aResult) {
+ if (!*liveToken) {
+ // The UtilityProcessHost got deleted. Abort. The promise would have
+ // already been rejected.
+ return;
+ }
+ if (mLaunchCompleted) {
+ return;
+ }
+ mLaunchCompleted = true;
+ if (aResult.IsReject()) {
+ RejectPromise();
+ }
+ // If aResult.IsResolve() then we have succeeded in launching the
+ // Utility process. The promise will be resolved once the channel has
+ // connected (or failed to) later.
+ });
+
+ mLaunchPromiseLaunched = true;
+ return mLaunchPromise;
+}
+
+void UtilityProcessHost::OnChannelConnected(base::ProcessId peer_pid) {
+ MOZ_ASSERT(!NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost::OnChannelConnected", this);
+
+ GeckoChildProcessHost::OnChannelConnected(peer_pid);
+
+ NS_DispatchToMainThread(NS_NewRunnableFunction(
+ "UtilityProcessHost::OnChannelConnected",
+ [this, liveToken = mLiveToken]() {
+ if (*liveToken && mLaunchPhase == LaunchPhase::Waiting) {
+ InitAfterConnect(true);
+ }
+ }));
+}
+
+void UtilityProcessHost::InitAfterConnect(bool aSucceeded) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ MOZ_ASSERT(mLaunchPhase == LaunchPhase::Waiting);
+ MOZ_ASSERT(!mUtilityProcessParent);
+
+ mLaunchPhase = LaunchPhase::Complete;
+
+ if (!aSucceeded) {
+ RejectPromise();
+ return;
+ }
+
+ mUtilityProcessParent = MakeRefPtr<UtilityProcessParent>(this);
+ DebugOnly<bool> rv = TakeInitialEndpoint().Bind(mUtilityProcessParent.get());
+ MOZ_ASSERT(rv);
+
+ // Only clear mPrefSerializer in the success case to avoid a
+ // possible race in the case case of a timeout on Windows launch.
+ // See Bug 1555076 comment 7:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1555076#c7
+ mPrefSerializer = nullptr;
+
+ Maybe<FileDescriptor> brokerFd;
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ UniquePtr<SandboxBroker::Policy> policy;
+ switch (mSandbox) {
+ case SandboxingKind::GENERIC_UTILITY:
+ policy = SandboxBrokerPolicyFactory::GetUtilityProcessPolicy(
+ GetActor()->OtherPid());
+ break;
+
+ default:
+ MOZ_ASSERT(false, "Invalid SandboxingKind");
+ break;
+ }
+ if (policy != nullptr) {
+ brokerFd = Some(FileDescriptor());
+ mSandboxBroker = SandboxBroker::Create(
+ std::move(policy), GetActor()->OtherPid(), brokerFd.ref());
+ // This is unlikely to fail and probably indicates OS resource
+ // exhaustion, but we can at least try to recover.
+ Unused << NS_WARN_IF(mSandboxBroker == nullptr);
+ MOZ_ASSERT(brokerFd.ref().IsValid());
+ }
+#endif // XP_LINUX && MOZ_SANDBOX
+
+ bool isReadyForBackgroundProcessing = false;
+#if defined(XP_WIN)
+ RefPtr<DllServices> dllSvc(DllServices::Get());
+ isReadyForBackgroundProcessing = dllSvc->IsReadyForBackgroundProcessing();
+#endif
+
+ Unused << GetActor()->SendInit(brokerFd, Telemetry::CanRecordReleaseData(),
+ isReadyForBackgroundProcessing);
+
+ Unused << GetActor()->SendInitProfiler(
+ ProfilerParent::CreateForProcess(GetActor()->OtherPid()));
+
+ LOGD("[%p] UtilityProcessHost::InitAfterConnect succeeded", this);
+
+ // Promise will be resolved later, from UtilityProcessParent when the child
+ // will send the InitCompleted message.
+}
+
+void UtilityProcessHost::Shutdown() {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(!mShutdownRequested);
+ LOGD("[%p] UtilityProcessHost::Shutdown", this);
+
+ RejectPromise();
+
+ if (mUtilityProcessParent) {
+ LOGD("[%p] UtilityProcessHost::Shutdown not destroying utility process.",
+ this);
+
+ // OnChannelClosed uses this to check if the shutdown was expected or
+ // unexpected.
+ mShutdownRequested = true;
+
+ // The channel might already be closed if we got here unexpectedly.
+ if (mUtilityProcessParent->CanSend()) {
+ mUtilityProcessParent->Close();
+ }
+
+#ifndef NS_FREE_PERMANENT_DATA
+ // No need to communicate shutdown, the Utility process doesn't need to
+ // communicate anything back.
+ KillHard("NormalShutdown");
+#endif
+
+ // If we're shutting down unexpectedly, we're in the middle of handling an
+ // ActorDestroy for PUtilityProcessParent, which is still on the stack.
+ // We'll return back to OnChannelClosed.
+ //
+ // Otherwise, we'll wait for OnChannelClose to be called whenever
+ // PUtilityProcessParent acknowledges shutdown.
+ return;
+ }
+
+ DestroyProcess();
+}
+
+void UtilityProcessHost::OnChannelClosed() {
+ MOZ_ASSERT(NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost::OnChannelClosed", this);
+
+ RejectPromise();
+
+ if (!mShutdownRequested && mListener) {
+ // This is an unclean shutdown. Notify our listener that we're going away.
+ mListener->OnProcessUnexpectedShutdown(this);
+ }
+
+ DestroyProcess();
+
+ // Release the actor.
+ UtilityProcessParent::Destroy(std::move(mUtilityProcessParent));
+}
+
+void UtilityProcessHost::KillHard(const char* aReason) {
+ MOZ_ASSERT(NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost::KillHard", this);
+
+ ProcessHandle handle = GetChildProcessHandle();
+ if (!base::KillProcess(handle, base::PROCESS_END_KILLED_BY_USER)) {
+ NS_WARNING("failed to kill subprocess!");
+ }
+
+ SetAlreadyDead();
+}
+
+void UtilityProcessHost::DestroyProcess() {
+ MOZ_ASSERT(NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost::DestroyProcess", this);
+
+ RejectPromise();
+
+ // Any pending tasks will be cancelled from now on.
+ *mLiveToken = false;
+
+ NS_DispatchToMainThread(
+ NS_NewRunnableFunction("DestroyProcessRunnable", [this] { Destroy(); }));
+}
+
+void UtilityProcessHost::ResolvePromise() {
+ MOZ_ASSERT(NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost connected - resolving launch promise", this);
+
+ if (!mLaunchPromiseSettled) {
+ mLaunchPromise->Resolve(true, __func__);
+ mLaunchPromiseSettled = true;
+ }
+
+ mLaunchCompleted = true;
+}
+
+void UtilityProcessHost::RejectPromise() {
+ MOZ_ASSERT(NS_IsMainThread());
+ LOGD("[%p] UtilityProcessHost connection failed - rejecting launch promise",
+ this);
+
+ if (!mLaunchPromiseSettled) {
+ mLaunchPromise->Reject(NS_ERROR_FAILURE, __func__);
+ mLaunchPromiseSettled = true;
+ }
+
+ mLaunchCompleted = true;
+}
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+bool UtilityProcessHost::FillMacSandboxInfo(MacSandboxInfo& aInfo) {
+ GeckoChildProcessHost::FillMacSandboxInfo(aInfo);
+ if (!aInfo.shouldLog && PR_GetEnv("MOZ_SANDBOX_UTILITY_LOGGING")) {
+ aInfo.shouldLog = true;
+ }
+ return true;
+}
+
+/* static */
+MacSandboxType UtilityProcessHost::GetMacSandboxType() {
+ return MacSandboxType_Utility;
+}
+#endif
+
+#ifdef MOZ_WMF_CDM_LPAC_SANDBOX
+void UtilityProcessHost::EnsureWidevineL1PathForSandbox(
+ StringVector& aExtraOpts) {
+ if (mSandbox != SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ return;
+ }
+
+ RefPtr<mozilla::gmp::GeckoMediaPluginServiceParent> gmps =
+ mozilla::gmp::GeckoMediaPluginServiceParent::GetSingleton();
+ if (NS_WARN_IF(!gmps)) {
+ WMF_LOG("Failed to get GeckoMediaPluginServiceParent!");
+ return;
+ }
+
+ if (!StaticPrefs::media_eme_widevine_experiment_enabled()) {
+ return;
+ }
+
+ // If Widevine L1 is installed after the MFCDM process starts, we will set it
+ // path later via MFCDMService::UpdateWideivineL1Path().
+ nsString widevineL1Path;
+ nsCOMPtr<nsIFile> pluginFile;
+ if (NS_WARN_IF(NS_FAILED(gmps->FindPluginDirectoryForAPI(
+ nsCString(kWidevineExperimentAPIName),
+ {nsCString(kWidevineExperimentKeySystemName)},
+ getter_AddRefs(pluginFile))))) {
+ WMF_LOG("Widevine L1 is not installed yet");
+ return;
+ }
+
+ if (!pluginFile) {
+ WMF_LOG("No plugin file found!");
+ return;
+ }
+
+ if (NS_WARN_IF(NS_FAILED(pluginFile->GetTarget(widevineL1Path)))) {
+ WMF_LOG("Failed to get L1 path!");
+ return;
+ }
+
+ WMF_LOG("Set Widevine L1 path=%s",
+ NS_ConvertUTF16toUTF8(widevineL1Path).get());
+ geckoargs::sPluginPath.Put(NS_ConvertUTF16toUTF8(widevineL1Path).get(),
+ aExtraOpts);
+ SandboxBroker::EnsureLpacPermsissionsOnDir(widevineL1Path);
+}
+
+# undef WMF_LOG
+
+#endif
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX)
+void UtilityProcessHost::EnanbleMFCDMTelemetryEventIfNeeded() const {
+ if (mSandbox != SandboxingKind::MF_MEDIA_ENGINE_CDM) {
+ return;
+ }
+ static bool sTelemetryEventEnabled = false;
+ if (!sTelemetryEventEnabled) {
+ sTelemetryEventEnabled = true;
+ Telemetry::SetEventRecordingEnabled("mfcdm"_ns, true);
+ }
+}
+#endif
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessHost.h b/ipc/glue/UtilityProcessHost.h
new file mode 100644
index 0000000000..bd4ffabe75
--- /dev/null
+++ b/ipc/glue/UtilityProcessHost.h
@@ -0,0 +1,165 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef _include_ipc_glue_UtilityProcessHost_h_
+#define _include_ipc_glue_UtilityProcessHost_h_
+
+#include "mozilla/UniquePtr.h"
+#include "mozilla/ipc/UtilityProcessParent.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/media/MediaUtils.h"
+#include "mozilla/ipc/ProcessUtils.h"
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxBroker.h"
+#endif
+
+namespace mozilla::ipc {
+
+class UtilityProcessParent;
+
+// UtilityProcessHost is the "parent process" container for a subprocess handle
+// and IPC connection. It owns the parent process IPDL actor, which in this
+// case, is a UtilityChild.
+//
+// UtilityProcessHosts are allocated and managed by UtilityProcessManager.
+class UtilityProcessHost final : public mozilla::ipc::GeckoChildProcessHost {
+ friend class UtilityProcessParent;
+
+ public:
+ class Listener {
+ protected:
+ virtual ~Listener() = default;
+
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityProcessHost::Listener);
+
+ // The UtilityProcessHost has unexpectedly shutdown or had its connection
+ // severed. This is not called if an error occurs after calling
+ // Shutdown().
+ virtual void OnProcessUnexpectedShutdown(UtilityProcessHost* aHost) {}
+ };
+
+ explicit UtilityProcessHost(SandboxingKind aSandbox,
+ RefPtr<Listener> listener);
+
+ // Launch the subprocess asynchronously. On failure, false is returned.
+ // Otherwise, true is returned. If succeeded, a follow-up call should be made
+ // to LaunchPromise() which will return a promise that will be resolved once
+ // the Utility process has launched and a channel has been established.
+ //
+ // @param aExtraOpts (StringVector)
+ // Extra options to pass to the subprocess.
+ bool Launch(StringVector aExtraOpts);
+
+ // Return a promise that will be resolved once the process has completed its
+ // launch. The promise will be immediately resolved if the launch has already
+ // succeeded.
+ RefPtr<GenericNonExclusivePromise> LaunchPromise();
+
+ // Inform the process that it should clean up its resources and shut
+ // down. This initiates an asynchronous shutdown sequence. After this
+ // method returns, it is safe for the caller to forget its pointer to
+ // the UtilityProcessHost.
+ //
+ // After this returns, the attached Listener is no longer used.
+ void Shutdown();
+
+ // Return the actor for the top-level actor of the process. If the process
+ // has not connected yet, this returns null.
+ RefPtr<UtilityProcessParent> GetActor() const {
+ MOZ_ASSERT(NS_IsMainThread());
+ return mUtilityProcessParent;
+ }
+
+ bool IsConnected() const {
+ MOZ_ASSERT(NS_IsMainThread());
+ return bool(mUtilityProcessParent);
+ }
+
+ // Called on the IO thread.
+ void OnChannelConnected(base::ProcessId peer_pid) override;
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ // Return the sandbox type to be used with this process type.
+ static MacSandboxType GetMacSandboxType();
+#endif
+
+ private:
+ ~UtilityProcessHost();
+
+ // Called on the main thread with true after a connection has been established
+ // or false if it failed (including if it failed before the timeout kicked in)
+ void InitAfterConnect(bool aSucceeded);
+
+ // Called on the main thread when the mUtilityProcessParent actor is shutting
+ // down.
+ void OnChannelClosed();
+
+ // Kill the remote process, triggering IPC shutdown.
+ void KillHard(const char* aReason);
+
+ void DestroyProcess();
+
+#if defined(XP_MACOSX) && defined(MOZ_SANDBOX)
+ static bool sLaunchWithMacSandbox;
+
+ // Sandbox the Utility process at launch for all instances
+ bool IsMacSandboxLaunchEnabled() override { return sLaunchWithMacSandbox; }
+
+ // Override so we can turn on Utility process-specific sandbox logging
+ bool FillMacSandboxInfo(MacSandboxInfo& aInfo) override;
+#endif
+
+ DISALLOW_COPY_AND_ASSIGN(UtilityProcessHost);
+
+ RefPtr<Listener> mListener;
+
+ // All members below are only ever accessed on the main thread.
+ enum class LaunchPhase { Unlaunched, Waiting, Complete };
+ LaunchPhase mLaunchPhase = LaunchPhase::Unlaunched;
+
+ RefPtr<UtilityProcessParent> mUtilityProcessParent;
+
+ UniquePtr<ipc::SharedPreferenceSerializer> mPrefSerializer{};
+
+ bool mShutdownRequested = false;
+
+ void RejectPromise();
+ void ResolvePromise();
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX) && !defined(MOZ_ASAN)
+ void EnsureWidevineL1PathForSandbox(StringVector& aExtraOpts);
+#endif
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX)
+ void EnanbleMFCDMTelemetryEventIfNeeded() const;
+#endif
+
+ // Set to true on construction and to false just prior deletion.
+ // The UtilityProcessHost isn't refcounted; so we can capture this by value in
+ // lambdas along with a strong reference to mLiveToken and check if that value
+ // is true before accessing "this".
+ // While a reference to mLiveToken can be taken on any thread; its value can
+ // only be read or written on the main thread.
+ const RefPtr<media::Refcountable<bool>> mLiveToken;
+
+ RefPtr<GenericNonExclusivePromise::Private> mLaunchPromise{};
+ bool mLaunchPromiseSettled = false;
+ bool mLaunchPromiseLaunched = false;
+ // Will be set to true if the Utility process as successfully started.
+ bool mLaunchCompleted = false;
+
+#if defined(XP_LINUX) && defined(MOZ_SANDBOX)
+ UniquePtr<SandboxBroker> mSandboxBroker{};
+#endif
+};
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityProcessHost_h_
diff --git a/ipc/glue/UtilityProcessImpl.cpp b/ipc/glue/UtilityProcessImpl.cpp
new file mode 100644
index 0000000000..b1d8f96cbd
--- /dev/null
+++ b/ipc/glue/UtilityProcessImpl.cpp
@@ -0,0 +1,147 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "UtilityProcessImpl.h"
+
+#include "mozilla/ipc/IOThreadChild.h"
+#include "mozilla/GeckoArgs.h"
+#include "mozilla/ProcInfo.h"
+
+#if defined(XP_WIN)
+# include "nsExceptionHandler.h"
+#endif
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+# include "mozilla/sandboxTarget.h"
+# include "WMF.h"
+# include "WMFDecoderModule.h"
+#endif
+
+#if defined(XP_OPENBSD) && defined(MOZ_SANDBOX)
+# include "mozilla/SandboxSettings.h"
+#endif
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX)
+# include "mozilla/MFCDMParent.h"
+#endif
+
+namespace mozilla::ipc {
+
+UtilityProcessImpl::~UtilityProcessImpl() = default;
+
+#if defined(XP_WIN)
+/* static */
+void UtilityProcessImpl::LoadLibraryOrCrash(LPCWSTR aLib) {
+ // re-try a few times depending on the error we get ; inspired by both our
+ // results on content process allocations as well as msys2:
+ // https://github.com/git-for-windows/msys2-runtime/blob/b4fed42af089ab955286343835a97e287496b3f8/winsup/cygwin/autoload.cc#L323-L339
+
+ const int kMaxRetries = 10;
+ DWORD err;
+
+ for (int i = 0; i < kMaxRetries; i++) {
+ HMODULE module = ::LoadLibraryW(aLib);
+ if (module) {
+ return;
+ }
+
+ err = ::GetLastError();
+
+ if (err != ERROR_NOACCESS && err != ERROR_DLL_INIT_FAILED) {
+ break;
+ }
+
+ PR_Sleep(0);
+ }
+
+ switch (err) {
+ /* case ERROR_ACCESS_DENIED: */
+ /* case ERROR_BAD_EXE_FORMAT: */
+ /* case ERROR_SHARING_VIOLATION: */
+ case ERROR_MOD_NOT_FOUND:
+ case ERROR_COMMITMENT_LIMIT:
+ // We want to make it explicit in telemetry that this was in fact an
+ // OOM condition, even though we could not detect it on our own
+ CrashReporter::AnnotateOOMAllocationSize(1);
+ break;
+
+ default:
+ break;
+ }
+
+ MOZ_CRASH_UNSAFE_PRINTF("Unable to preload module: 0x%lx", err);
+}
+#endif // defined(XP_WIN)
+
+bool UtilityProcessImpl::Init(int aArgc, char* aArgv[]) {
+ Maybe<uint64_t> sandboxingKind = geckoargs::sSandboxingKind.Get(aArgc, aArgv);
+ if (sandboxingKind.isNothing()) {
+ return false;
+ }
+
+ if (*sandboxingKind >= SandboxingKind::COUNT) {
+ return false;
+ }
+
+#if defined(MOZ_SANDBOX) && defined(XP_WIN)
+ // We delay load winmm.dll so that its dependencies don't interfere with COM
+ // initialization when win32k is locked down. We need to load it before we
+ // lower the sandbox in processes where the policy will prevent loading.
+ LoadLibraryOrCrash(L"winmm.dll");
+
+ // Call this once before enabling the sandbox, it will cache its result
+ // in a static variable.
+ GetCpuFrequencyMHz();
+
+ if (*sandboxingKind == SandboxingKind::GENERIC_UTILITY) {
+ // Preload audio generic libraries required for ffmpeg only
+ UtilityAudioDecoderParent::GenericPreloadForSandbox();
+ }
+
+ if (*sandboxingKind == SandboxingKind::UTILITY_AUDIO_DECODING_WMF
+# ifdef MOZ_WMF_MEDIA_ENGINE
+ || *sandboxingKind == SandboxingKind::MF_MEDIA_ENGINE_CDM
+# endif
+ ) {
+ UtilityAudioDecoderParent::WMFPreloadForSandbox();
+ }
+
+ // Go for it
+ mozilla::SandboxTarget::Instance()->StartSandbox();
+#elif defined(__OpenBSD__) && defined(MOZ_SANDBOX)
+ if (*sandboxingKind != SandboxingKind::GENERIC_UTILITY) {
+ StartOpenBSDSandbox(GeckoProcessType_Utility,
+ (SandboxingKind)*sandboxingKind);
+ }
+#endif
+
+#if defined(MOZ_WMF_CDM) && defined(MOZ_SANDBOX)
+ if (*sandboxingKind == MF_MEDIA_ENGINE_CDM) {
+ Maybe<const char*> pluginPath = geckoargs::sPluginPath.Get(aArgc, aArgv);
+ if (pluginPath) {
+ MFCDMParent::SetWidevineL1Path(*pluginPath);
+ } else {
+ NS_WARNING("No Widevine L1 plugin for the utility process!");
+ }
+ }
+#endif
+
+ Maybe<const char*> parentBuildID =
+ geckoargs::sParentBuildID.Get(aArgc, aArgv);
+ if (parentBuildID.isNothing()) {
+ return false;
+ }
+
+ if (!ProcessChild::InitPrefs(aArgc, aArgv)) {
+ return false;
+ }
+
+ return mUtility->Init(TakeInitialEndpoint(), nsCString(*parentBuildID),
+ *sandboxingKind);
+}
+
+void UtilityProcessImpl::CleanUp() { NS_ShutdownXPCOM(nullptr); }
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessImpl.h b/ipc/glue/UtilityProcessImpl.h
new file mode 100644
index 0000000000..9b42cd5f74
--- /dev/null
+++ b/ipc/glue/UtilityProcessImpl.h
@@ -0,0 +1,43 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessImpl_h__
+#define _include_ipc_glue_UtilityProcessImpl_h__
+#include "mozilla/ipc/ProcessChild.h"
+
+#if defined(XP_WIN)
+# include "mozilla/mscom/ProcessRuntime.h"
+#endif
+
+#include "mozilla/ipc/UtilityProcessChild.h"
+
+namespace mozilla::ipc {
+
+// This class owns the subprocess instance of a PUtilityProcess - which in this
+// case, is a UtilityProcessParent. It is instantiated as a singleton in
+// XRE_InitChildProcess.
+class UtilityProcessImpl final : public ipc::ProcessChild {
+ public:
+ using ipc::ProcessChild::ProcessChild;
+ ~UtilityProcessImpl();
+
+ bool Init(int aArgc, char* aArgv[]) override;
+ void CleanUp() override;
+
+#if defined(XP_WIN)
+ static void LoadLibraryOrCrash(LPCWSTR aLib);
+#endif // defined(XP_WIN)
+
+ private:
+ RefPtr<UtilityProcessChild> mUtility = UtilityProcessChild::GetSingleton();
+
+#if defined(XP_WIN)
+ mozilla::mscom::ProcessRuntime mCOMRuntime;
+#endif
+};
+
+} // namespace mozilla::ipc
+
+#endif // _include_ipc_glue_UtilityProcessImpl_h__
diff --git a/ipc/glue/UtilityProcessManager.cpp b/ipc/glue/UtilityProcessManager.cpp
new file mode 100644
index 0000000000..e24fed476b
--- /dev/null
+++ b/ipc/glue/UtilityProcessManager.cpp
@@ -0,0 +1,660 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "UtilityProcessManager.h"
+
+#include "JSOracleParent.h"
+#include "mozilla/ipc/UtilityProcessHost.h"
+#include "mozilla/MemoryReportingProcess.h"
+#include "mozilla/Preferences.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "mozilla/StaticPrefs_media.h"
+#include "mozilla/SyncRunnable.h" // for LaunchUtilityProcess
+#include "mozilla/ipc/UtilityProcessParent.h"
+#include "mozilla/ipc/UtilityAudioDecoderChild.h"
+#include "mozilla/ipc/UtilityAudioDecoderParent.h"
+#include "mozilla/dom/ContentParent.h"
+#include "mozilla/ipc/Endpoint.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+#include "mozilla/ipc/ProcessChild.h"
+#include "nsAppRunner.h"
+#include "nsContentUtils.h"
+
+#ifdef XP_WIN
+# include "mozilla/dom/WindowsUtilsParent.h"
+# include "mozilla/widget/filedialog/WinFileDialogParent.h"
+#endif
+
+#include "mozilla/GeckoArgs.h"
+
+namespace mozilla::ipc {
+
+extern LazyLogModule gUtilityProcessLog;
+#define LOGD(...) MOZ_LOG(gUtilityProcessLog, LogLevel::Debug, (__VA_ARGS__))
+
+static StaticRefPtr<UtilityProcessManager> sSingleton;
+
+static bool sXPCOMShutdown = false;
+
+bool UtilityProcessManager::IsShutdown() const {
+ MOZ_ASSERT(NS_IsMainThread());
+ return sXPCOMShutdown || !sSingleton;
+}
+
+RefPtr<UtilityProcessManager> UtilityProcessManager::GetSingleton() {
+ MOZ_ASSERT(XRE_IsParentProcess());
+ MOZ_ASSERT(NS_IsMainThread());
+
+ if (!sXPCOMShutdown && sSingleton == nullptr) {
+ sSingleton = new UtilityProcessManager();
+ sSingleton->Init();
+ }
+ return sSingleton;
+}
+
+RefPtr<UtilityProcessManager> UtilityProcessManager::GetIfExists() {
+ MOZ_ASSERT(NS_IsMainThread());
+ return sSingleton;
+}
+
+UtilityProcessManager::UtilityProcessManager() {
+ LOGD("[%p] UtilityProcessManager::UtilityProcessManager", this);
+}
+
+void UtilityProcessManager::Init() {
+ // Start listening for pref changes so we can
+ // forward them to the process once it is running.
+ mObserver = new Observer(this);
+ nsContentUtils::RegisterShutdownObserver(mObserver);
+ Preferences::AddStrongObserver(mObserver, "");
+}
+
+UtilityProcessManager::~UtilityProcessManager() {
+ LOGD("[%p] UtilityProcessManager::~UtilityProcessManager", this);
+
+ // The Utility process should ALL have already been shut down.
+ MOZ_ASSERT(NoMoreProcesses());
+}
+
+NS_IMPL_ISUPPORTS(UtilityProcessManager::Observer, nsIObserver);
+
+UtilityProcessManager::Observer::Observer(UtilityProcessManager* aManager)
+ : mManager(aManager) {}
+
+NS_IMETHODIMP
+UtilityProcessManager::Observer::Observe(nsISupports* aSubject,
+ const char* aTopic,
+ const char16_t* aData) {
+ if (!strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID)) {
+ mManager->OnXPCOMShutdown();
+ } else if (!strcmp(aTopic, "nsPref:changed")) {
+ mManager->OnPreferenceChange(aData);
+ }
+ return NS_OK;
+}
+
+void UtilityProcessManager::OnXPCOMShutdown() {
+ LOGD("[%p] UtilityProcessManager::OnXPCOMShutdown", this);
+
+ MOZ_ASSERT(NS_IsMainThread());
+ sXPCOMShutdown = true;
+ nsContentUtils::UnregisterShutdownObserver(mObserver);
+ CleanShutdownAllProcesses();
+}
+
+void UtilityProcessManager::OnPreferenceChange(const char16_t* aData) {
+ MOZ_ASSERT(NS_IsMainThread());
+ if (NoMoreProcesses()) {
+ // Process hasn't been launched yet
+ return;
+ }
+ // We know prefs are ASCII here.
+ NS_LossyConvertUTF16toASCII strData(aData);
+
+ mozilla::dom::Pref pref(strData, /* isLocked */ false,
+ /* isSanitized */ false, Nothing(), Nothing());
+ Preferences::GetPreference(&pref, GeckoProcessType_Utility,
+ /* remoteType */ ""_ns);
+
+ for (auto& p : mProcesses) {
+ if (!p) {
+ continue;
+ }
+
+ if (p->mProcessParent) {
+ Unused << p->mProcessParent->SendPreferenceUpdate(pref);
+ } else if (IsProcessLaunching(p->mSandbox)) {
+ p->mQueuedPrefs.AppendElement(pref);
+ }
+ }
+}
+
+RefPtr<UtilityProcessManager::ProcessFields> UtilityProcessManager::GetProcess(
+ SandboxingKind aSandbox) {
+ if (!mProcesses[aSandbox]) {
+ return nullptr;
+ }
+
+ return mProcesses[aSandbox];
+}
+
+RefPtr<GenericNonExclusivePromise> UtilityProcessManager::LaunchProcess(
+ SandboxingKind aSandbox) {
+ LOGD("[%p] UtilityProcessManager::LaunchProcess SandboxingKind=%" PRIu64,
+ this, aSandbox);
+
+ MOZ_ASSERT(NS_IsMainThread());
+
+ if (IsShutdown()) {
+ NS_WARNING("Reject early LaunchProcess() for Shutdown");
+ return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
+ __func__);
+ }
+
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (p && p->mNumProcessAttempts) {
+ // We failed to start the Utility process earlier, abort now.
+ NS_WARNING("Reject LaunchProcess() for earlier mNumProcessAttempts");
+ return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
+ __func__);
+ }
+
+ if (p && p->mLaunchPromise && p->mProcess) {
+ return p->mLaunchPromise;
+ }
+
+ if (!p) {
+ p = new ProcessFields(aSandbox);
+ mProcesses[aSandbox] = p;
+ }
+
+ std::vector<std::string> extraArgs;
+ ProcessChild::AddPlatformBuildID(extraArgs);
+ geckoargs::sSandboxingKind.Put(aSandbox, extraArgs);
+
+ // The subprocess is launched asynchronously, so we
+ // wait for the promise to be resolved to acquire the IPDL actor.
+ p->mProcess = new UtilityProcessHost(aSandbox, this);
+ if (!p->mProcess->Launch(extraArgs)) {
+ p->mNumProcessAttempts++;
+ DestroyProcess(aSandbox);
+ NS_WARNING("Reject LaunchProcess() for mNumProcessAttempts++");
+ return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_NOT_AVAILABLE,
+ __func__);
+ }
+
+ RefPtr<UtilityProcessManager> self = this;
+ p->mLaunchPromise = p->mProcess->LaunchPromise()->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [self, p, aSandbox](bool) {
+ if (self->IsShutdown()) {
+ NS_WARNING(
+ "Reject LaunchProcess() after LaunchPromise() for Shutdown");
+ return GenericNonExclusivePromise::CreateAndReject(
+ NS_ERROR_NOT_AVAILABLE, __func__);
+ }
+
+ if (self->IsProcessDestroyed(aSandbox)) {
+ NS_WARNING(
+ "Reject LaunchProcess() after LaunchPromise() for destroyed "
+ "process");
+ return GenericNonExclusivePromise::CreateAndReject(
+ NS_ERROR_NOT_AVAILABLE, __func__);
+ }
+
+ p->mProcessParent = p->mProcess->GetActor();
+
+ // Flush any pref updates that happened during
+ // launch and weren't included in the blobs set
+ // up in LaunchUtilityProcess.
+ for (const mozilla::dom::Pref& pref : p->mQueuedPrefs) {
+ Unused << NS_WARN_IF(!p->mProcessParent->SendPreferenceUpdate(pref));
+ }
+ p->mQueuedPrefs.Clear();
+
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::UtilityProcessStatus, "Running"_ns);
+
+ return GenericNonExclusivePromise::CreateAndResolve(true, __func__);
+ },
+ [self, p, aSandbox](nsresult aError) {
+ if (GetSingleton()) {
+ p->mNumProcessAttempts++;
+ self->DestroyProcess(aSandbox);
+ }
+ NS_WARNING("Reject LaunchProcess() for LaunchPromise() rejection");
+ return GenericNonExclusivePromise::CreateAndReject(aError, __func__);
+ });
+
+ return p->mLaunchPromise;
+}
+
+template <typename Actor>
+RefPtr<GenericNonExclusivePromise> UtilityProcessManager::StartUtility(
+ RefPtr<Actor> aActor, SandboxingKind aSandbox) {
+ LOGD(
+ "[%p] UtilityProcessManager::StartUtility actor=%p "
+ "SandboxingKind=%" PRIu64,
+ this, aActor.get(), aSandbox);
+
+ TimeStamp utilityStart = TimeStamp::Now();
+
+ if (!aActor) {
+ MOZ_ASSERT(false, "Actor singleton failure");
+ return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
+ __func__);
+ }
+
+ if (aActor->CanSend()) {
+ // Actor has already been setup, so we:
+ // - know the process has been launched
+ // - the ipc actors are ready
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::StartUtility", IPC,
+ MarkerOptions(MarkerTiming::InstantNow()),
+ nsPrintfCString("SandboxingKind=%" PRIu64 " aActor->CanSend()",
+ aSandbox));
+ return GenericNonExclusivePromise::CreateAndResolve(true, __func__);
+ }
+
+ RefPtr<UtilityProcessManager> self = this;
+ return LaunchProcess(aSandbox)->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [self, aActor, aSandbox, utilityStart]() {
+ RefPtr<UtilityProcessParent> utilityParent =
+ self->GetProcessParent(aSandbox);
+ if (!utilityParent) {
+ NS_WARNING("Missing parent in StartUtility");
+ return GenericNonExclusivePromise::CreateAndReject(NS_ERROR_FAILURE,
+ __func__);
+ }
+
+ // It is possible if multiple processes concurrently request a utility
+ // actor that the previous CanSend() check returned false for both but
+ // that by the time we have started our process for real, one of them
+ // has already been able to establish the IPC connection and thus we
+ // would perform more than one Open() call.
+ //
+ // The tests within browser_utility_multipleAudio.js should be able to
+ // catch that behavior.
+ if (!aActor->CanSend()) {
+ nsresult rv = aActor->BindToUtilityProcess(utilityParent);
+ if (NS_FAILED(rv)) {
+ MOZ_ASSERT(false, "Protocol endpoints failure");
+ return GenericNonExclusivePromise::CreateAndReject(rv, __func__);
+ }
+
+ MOZ_DIAGNOSTIC_ASSERT(aActor->CanSend(), "IPC established for actor");
+ self->RegisterActor(utilityParent, aActor->GetActorName());
+ }
+
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::StartUtility", IPC,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(utilityStart)),
+ nsPrintfCString("SandboxingKind=%" PRIu64 " Resolve", aSandbox));
+ return GenericNonExclusivePromise::CreateAndResolve(true, __func__);
+ },
+ [self, aSandbox, utilityStart](nsresult aError) {
+ NS_WARNING("Reject StartUtility() for LaunchProcess() rejection");
+ if (!self->IsShutdown()) {
+ NS_WARNING("Reject StartUtility() when !IsShutdown()");
+ }
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::StartUtility", IPC,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(utilityStart)),
+ nsPrintfCString("SandboxingKind=%" PRIu64 " Reject", aSandbox));
+ return GenericNonExclusivePromise::CreateAndReject(aError, __func__);
+ });
+}
+
+RefPtr<UtilityProcessManager::StartRemoteDecodingUtilityPromise>
+UtilityProcessManager::StartProcessForRemoteMediaDecoding(
+ base::ProcessId aOtherProcess, dom::ContentParentId aChildId,
+ SandboxingKind aSandbox) {
+ // Not supported kinds.
+ if (aSandbox != SandboxingKind::GENERIC_UTILITY
+#ifdef MOZ_APPLEMEDIA
+ && aSandbox != SandboxingKind::UTILITY_AUDIO_DECODING_APPLE_MEDIA
+#endif
+#ifdef XP_WIN
+ && aSandbox != SandboxingKind::UTILITY_AUDIO_DECODING_WMF
+#endif
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ && aSandbox != SandboxingKind::MF_MEDIA_ENGINE_CDM
+#endif
+ ) {
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(NS_ERROR_FAILURE,
+ __func__);
+ }
+ TimeStamp remoteDecodingStart = TimeStamp::Now();
+
+ RefPtr<UtilityProcessManager> self = this;
+ RefPtr<UtilityAudioDecoderChild> uadc =
+ UtilityAudioDecoderChild::GetSingleton(aSandbox);
+ MOZ_ASSERT(uadc, "Unable to get a singleton for UtilityAudioDecoderChild");
+ return StartUtility(uadc, aSandbox)
+ ->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [self, uadc, aOtherProcess, aChildId, aSandbox,
+ remoteDecodingStart]() {
+ RefPtr<UtilityProcessParent> parent =
+ self->GetProcessParent(aSandbox);
+ if (!parent) {
+ NS_WARNING("UtilityAudioDecoderParent lost in the middle");
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(
+ NS_ERROR_FAILURE, __func__);
+ }
+
+ if (!uadc->CanSend()) {
+ NS_WARNING("UtilityAudioDecoderChild lost in the middle");
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(
+ NS_ERROR_FAILURE, __func__);
+ }
+
+ base::ProcessId process = parent->OtherPid();
+
+ Endpoint<PRemoteDecoderManagerChild> childPipe;
+ Endpoint<PRemoteDecoderManagerParent> parentPipe;
+ nsresult rv = PRemoteDecoderManager::CreateEndpoints(
+ process, aOtherProcess, &parentPipe, &childPipe);
+ if (NS_FAILED(rv)) {
+ MOZ_ASSERT(false, "Could not create content remote decoder");
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(
+ rv, __func__);
+ }
+
+ if (!uadc->SendNewContentRemoteDecoderManager(std::move(parentPipe),
+ aChildId)) {
+ MOZ_ASSERT(false, "SendNewContentRemoteDecoderManager failure");
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(
+ NS_ERROR_FAILURE, __func__);
+ }
+
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ if (aSandbox == SandboxingKind::MF_MEDIA_ENGINE_CDM &&
+ !uadc->CreateVideoBridge()) {
+ MOZ_ASSERT(false, "Failed to create video bridge");
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(
+ NS_ERROR_FAILURE, __func__);
+ }
+#endif
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::StartProcessForRemoteMediaDecoding",
+ MEDIA,
+ MarkerOptions(
+ MarkerTiming::IntervalUntilNowFrom(remoteDecodingStart)),
+ "Resolve"_ns);
+ return StartRemoteDecodingUtilityPromise::CreateAndResolve(
+ std::move(childPipe), __func__);
+ },
+ [self, remoteDecodingStart](nsresult aError) {
+ NS_WARNING(
+ "Reject StartProcessForRemoteMediaDecoding() for "
+ "StartUtility() rejection");
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::StartProcessForRemoteMediaDecoding",
+ MEDIA,
+ MarkerOptions(
+ MarkerTiming::IntervalUntilNowFrom(remoteDecodingStart)),
+ "Reject"_ns);
+ return StartRemoteDecodingUtilityPromise::CreateAndReject(aError,
+ __func__);
+ });
+}
+
+RefPtr<UtilityProcessManager::JSOraclePromise>
+UtilityProcessManager::StartJSOracle(dom::JSOracleParent* aParent) {
+ return StartUtility(RefPtr{aParent}, SandboxingKind::GENERIC_UTILITY);
+}
+
+#ifdef XP_WIN
+
+// Windows Utils
+
+RefPtr<UtilityProcessManager::WindowsUtilsPromise>
+UtilityProcessManager::GetWindowsUtilsPromise() {
+ TimeStamp windowsUtilsStart = TimeStamp::Now();
+ RefPtr<UtilityProcessManager> self = this;
+ if (!mWindowsUtils) {
+ mWindowsUtils = new dom::WindowsUtilsParent();
+ }
+
+ RefPtr<dom::WindowsUtilsParent> wup = mWindowsUtils;
+ MOZ_ASSERT(wup, "Unable to get a singleton for WindowsUtils");
+ return StartUtility(wup, SandboxingKind::WINDOWS_UTILS)
+ ->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [self, wup, windowsUtilsStart]() {
+ if (!wup->CanSend()) {
+ MOZ_ASSERT(false, "WindowsUtilsParent can't send");
+ return WindowsUtilsPromise::CreateAndReject(NS_ERROR_FAILURE,
+ __func__);
+ }
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::GetWindowsUtilsPromise", OTHER,
+ MarkerOptions(
+ MarkerTiming::IntervalUntilNowFrom(windowsUtilsStart)),
+ "Resolve"_ns);
+ return WindowsUtilsPromise::CreateAndResolve(wup, __func__);
+ },
+ [self, windowsUtilsStart](nsresult aError) {
+ NS_WARNING("StartUtility rejected promise for PWindowsUtils");
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::GetWindowsUtilsPromise", OTHER,
+ MarkerOptions(
+ MarkerTiming::IntervalUntilNowFrom(windowsUtilsStart)),
+ "Reject"_ns);
+ return WindowsUtilsPromise::CreateAndReject(aError, __func__);
+ });
+}
+
+void UtilityProcessManager::ReleaseWindowsUtils() { mWindowsUtils = nullptr; }
+
+RefPtr<UtilityProcessManager::WinFileDialogPromise>
+UtilityProcessManager::CreateWinFileDialogActor() {
+ using Promise = WinFileDialogPromise;
+ TimeStamp startTime = TimeStamp::Now();
+ auto wfdp = MakeRefPtr<widget::filedialog::WinFileDialogParent>();
+
+ return StartUtility(wfdp, SandboxingKind::WINDOWS_FILE_DIALOG)
+ ->Then(
+ GetMainThreadSerialEventTarget(), __PRETTY_FUNCTION__,
+ [wfdp, startTime]() mutable {
+ LOGD("CreateWinFileDialogAsync() resolve: wfdp = [%p]", wfdp.get());
+ if (!wfdp->CanSend()) {
+ MOZ_ASSERT(false, "WinFileDialogParent can't send");
+ return Promise::CreateAndReject(NS_ERROR_FAILURE,
+ __PRETTY_FUNCTION__);
+ }
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::CreateWinFileDialogAsync", OTHER,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(startTime)),
+ "Resolve"_ns);
+
+ return Promise::CreateAndResolve(
+ widget::filedialog::ProcessProxy(std::move(wfdp)),
+ __PRETTY_FUNCTION__);
+ },
+ [self = RefPtr(this), startTime](nsresult error) {
+ LOGD("CreateWinFileDialogAsync() reject");
+ if (!self->IsShutdown()) {
+ MOZ_ASSERT_UNREACHABLE("failure when starting file-dialog actor");
+ }
+ PROFILER_MARKER_TEXT(
+ "UtilityProcessManager::CreateWinFileDialogAsync", OTHER,
+ MarkerOptions(MarkerTiming::IntervalUntilNowFrom(startTime)),
+ "Reject"_ns);
+
+ return Promise::CreateAndReject(error, __PRETTY_FUNCTION__);
+ });
+}
+
+#endif // XP_WIN
+
+bool UtilityProcessManager::IsProcessLaunching(SandboxingKind aSandbox) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ MOZ_CRASH("Cannot check process launching with no process");
+ return false;
+ }
+
+ return p->mProcess && !(p->mProcessParent);
+}
+
+bool UtilityProcessManager::IsProcessDestroyed(SandboxingKind aSandbox) {
+ MOZ_ASSERT(NS_IsMainThread());
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ MOZ_CRASH("Cannot check process destroyed with no process");
+ return false;
+ }
+ return !p->mProcess && !p->mProcessParent;
+}
+
+void UtilityProcessManager::OnProcessUnexpectedShutdown(
+ UtilityProcessHost* aHost) {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ for (auto& it : mProcesses) {
+ if (it && it->mProcess && it->mProcess == aHost) {
+ it->mNumUnexpectedCrashes++;
+ DestroyProcess(it->mSandbox);
+ return;
+ }
+ }
+
+ MOZ_CRASH(
+ "Called UtilityProcessManager::OnProcessUnexpectedShutdown with invalid "
+ "aHost");
+}
+
+void UtilityProcessManager::CleanShutdownAllProcesses() {
+ LOGD("[%p] UtilityProcessManager::CleanShutdownAllProcesses", this);
+
+ for (auto& it : mProcesses) {
+ if (it) {
+ DestroyProcess(it->mSandbox);
+ }
+ }
+}
+
+void UtilityProcessManager::CleanShutdown(SandboxingKind aSandbox) {
+ LOGD("[%p] UtilityProcessManager::CleanShutdown SandboxingKind=%" PRIu64,
+ this, aSandbox);
+
+ DestroyProcess(aSandbox);
+}
+
+uint16_t UtilityProcessManager::AliveProcesses() {
+ uint16_t alive = 0;
+ for (auto& p : mProcesses) {
+ if (p != nullptr) {
+ alive++;
+ }
+ }
+ return alive;
+}
+
+bool UtilityProcessManager::NoMoreProcesses() { return AliveProcesses() == 0; }
+
+void UtilityProcessManager::DestroyProcess(SandboxingKind aSandbox) {
+ LOGD("[%p] UtilityProcessManager::DestroyProcess SandboxingKind=%" PRIu64,
+ this, aSandbox);
+
+ MOZ_RELEASE_ASSERT(NS_IsMainThread());
+
+ if (AliveProcesses() <= 1) {
+ if (mObserver) {
+ Preferences::RemoveObserver(mObserver, "");
+ }
+
+ mObserver = nullptr;
+ }
+
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ return;
+ }
+
+ p->mQueuedPrefs.Clear();
+ p->mProcessParent = nullptr;
+
+ if (!p->mProcess) {
+ return;
+ }
+
+ p->mProcess->Shutdown();
+ p->mProcess = nullptr;
+
+ mProcesses[aSandbox] = nullptr;
+
+ CrashReporter::AnnotateCrashReport(
+ CrashReporter::Annotation::UtilityProcessStatus, "Destroyed"_ns);
+
+ if (NoMoreProcesses()) {
+ sSingleton = nullptr;
+ }
+}
+
+Maybe<base::ProcessId> UtilityProcessManager::ProcessPid(
+ SandboxingKind aSandbox) {
+ MOZ_ASSERT(NS_IsMainThread());
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ return Nothing();
+ }
+ if (p->mProcessParent) {
+ return Some(p->mProcessParent->OtherPid());
+ }
+ return Nothing();
+}
+
+class UtilityMemoryReporter : public MemoryReportingProcess {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityMemoryReporter, override)
+
+ explicit UtilityMemoryReporter(UtilityProcessParent* aParent) {
+ mParent = aParent;
+ }
+
+ bool IsAlive() const override { return bool(GetParent()); }
+
+ bool SendRequestMemoryReport(
+ const uint32_t& aGeneration, const bool& aAnonymize,
+ const bool& aMinimizeMemoryUsage,
+ const Maybe<ipc::FileDescriptor>& aDMDFile) override {
+ RefPtr<UtilityProcessParent> parent = GetParent();
+ if (!parent) {
+ return false;
+ }
+
+ return parent->SendRequestMemoryReport(aGeneration, aAnonymize,
+ aMinimizeMemoryUsage, aDMDFile);
+ }
+
+ int32_t Pid() const override {
+ if (RefPtr<UtilityProcessParent> parent = GetParent()) {
+ return (int32_t)parent->OtherPid();
+ }
+ return 0;
+ }
+
+ private:
+ RefPtr<UtilityProcessParent> GetParent() const { return mParent; }
+
+ RefPtr<UtilityProcessParent> mParent = nullptr;
+
+ protected:
+ ~UtilityMemoryReporter() = default;
+};
+
+RefPtr<MemoryReportingProcess> UtilityProcessManager::GetProcessMemoryReporter(
+ UtilityProcessParent* parent) {
+ return new UtilityMemoryReporter(parent);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessManager.h b/ipc/glue/UtilityProcessManager.h
new file mode 100644
index 0000000000..60cea016c9
--- /dev/null
+++ b/ipc/glue/UtilityProcessManager.h
@@ -0,0 +1,246 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessManager_h_
+#define _include_ipc_glue_UtilityProcessManager_h_
+#include "mozilla/MozPromise.h"
+#include "mozilla/dom/ipc/IdType.h"
+#include "mozilla/ipc/UtilityProcessHost.h"
+#include "mozilla/EnumeratedArray.h"
+#include "mozilla/ProcInfo.h"
+#include "nsIObserver.h"
+#include "nsTArray.h"
+
+#include "mozilla/PRemoteDecoderManagerChild.h"
+
+namespace mozilla {
+
+class MemoryReportingProcess;
+
+namespace dom {
+class JSOracleParent;
+class WindowsUtilsParent;
+} // namespace dom
+
+namespace widget::filedialog {
+class ProcessProxy;
+} // namespace widget::filedialog
+
+namespace ipc {
+
+class UtilityProcessParent;
+
+// The UtilityProcessManager is a singleton responsible for creating
+// Utility-bound objects that may live in another process. Currently, it
+// provides access to the Utility process via ContentParent.
+class UtilityProcessManager final : public UtilityProcessHost::Listener {
+ friend class UtilityProcessParent;
+
+ public:
+ template <typename T>
+ using Promise = MozPromise<T, nsresult, true>;
+
+ using StartRemoteDecodingUtilityPromise =
+ Promise<Endpoint<PRemoteDecoderManagerChild>>;
+ using JSOraclePromise = GenericNonExclusivePromise;
+
+#ifdef XP_WIN
+ using WindowsUtilsPromise = Promise<RefPtr<dom::WindowsUtilsParent>>;
+ using WinFileDialogPromise = Promise<widget::filedialog::ProcessProxy>;
+#endif
+
+ static RefPtr<UtilityProcessManager> GetSingleton();
+
+ static RefPtr<UtilityProcessManager> GetIfExists();
+
+ // Launch a new Utility process asynchronously
+ RefPtr<GenericNonExclusivePromise> LaunchProcess(SandboxingKind aSandbox);
+
+ template <typename Actor>
+ RefPtr<GenericNonExclusivePromise> StartUtility(RefPtr<Actor> aActor,
+ SandboxingKind aSandbox);
+
+ RefPtr<StartRemoteDecodingUtilityPromise> StartProcessForRemoteMediaDecoding(
+ base::ProcessId aOtherProcess, dom::ContentParentId aChildId,
+ SandboxingKind aSandbox);
+
+ RefPtr<JSOraclePromise> StartJSOracle(mozilla::dom::JSOracleParent* aParent);
+
+#ifdef XP_WIN
+ // Get the (possibly already resolved) promise for the Windows utility
+ // process actor. Creates the process if it is not running.
+ RefPtr<WindowsUtilsPromise> GetWindowsUtilsPromise();
+ // Releases the WindowsUtils actor so that it can be destroyed.
+ // Subsequent attempts to use WindowsUtils will create a new process.
+ void ReleaseWindowsUtils();
+
+ // Get a new Windows file-dialog utility-process actor. These are never
+ // reused; this will always return a fresh actor.
+ RefPtr<WinFileDialogPromise> CreateWinFileDialogActor();
+#endif
+
+ void OnProcessUnexpectedShutdown(UtilityProcessHost* aHost);
+
+ // Returns the platform pid for this utility sandbox process.
+ Maybe<base::ProcessId> ProcessPid(SandboxingKind aSandbox);
+
+ // Create a MemoryReportingProcess object for this utility process
+ RefPtr<MemoryReportingProcess> GetProcessMemoryReporter(
+ UtilityProcessParent* parent);
+
+ // Returns access to the PUtility protocol if a Utility process for that
+ // sandbox is present.
+ RefPtr<UtilityProcessParent> GetProcessParent(SandboxingKind aSandbox) {
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ return nullptr;
+ }
+ return p->mProcessParent;
+ }
+
+ // Get a list of all valid utility process parent references
+ nsTArray<RefPtr<UtilityProcessParent>> GetAllProcessesProcessParent() {
+ nsTArray<RefPtr<UtilityProcessParent>> rv;
+ for (auto& p : mProcesses) {
+ if (p && p->mProcessParent) {
+ rv.AppendElement(p->mProcessParent);
+ }
+ }
+ return rv;
+ }
+
+ // Returns the Utility Process for that sandbox
+ UtilityProcessHost* Process(SandboxingKind aSandbox) {
+ RefPtr<ProcessFields> p = GetProcess(aSandbox);
+ if (!p) {
+ return nullptr;
+ }
+ return p->mProcess;
+ }
+
+ void RegisterActor(const RefPtr<UtilityProcessParent>& aParent,
+ UtilityActorName aActorName) {
+ for (auto& p : mProcesses) {
+ if (p && p->mProcessParent && p->mProcessParent == aParent) {
+ p->mActors.AppendElement(aActorName);
+ return;
+ }
+ }
+ }
+
+ Span<const UtilityActorName> GetActors(
+ const RefPtr<UtilityProcessParent>& aParent) {
+ for (auto& p : mProcesses) {
+ if (p && p->mProcessParent && p->mProcessParent == aParent) {
+ return p->mActors;
+ }
+ }
+ return {};
+ }
+
+ Span<const UtilityActorName> GetActors(GeckoChildProcessHost* aHost) {
+ for (auto& p : mProcesses) {
+ if (p && p->mProcess == aHost) {
+ return p->mActors;
+ }
+ }
+ return {};
+ }
+
+ Span<const UtilityActorName> GetActors(SandboxingKind aSbKind) {
+ auto proc = GetProcess(aSbKind);
+ if (!proc) {
+ return {};
+ }
+ return proc->mActors;
+ }
+
+ // Shutdown the Utility process for that sandbox.
+ void CleanShutdown(SandboxingKind aSandbox);
+
+ // Shutdown all utility processes
+ void CleanShutdownAllProcesses();
+
+ uint16_t AliveProcesses();
+
+ private:
+ ~UtilityProcessManager();
+
+ bool IsProcessLaunching(SandboxingKind aSandbox);
+ bool IsProcessDestroyed(SandboxingKind aSandbox);
+
+ // Called from our xpcom-shutdown observer.
+ void OnXPCOMShutdown();
+ void OnPreferenceChange(const char16_t* aData);
+
+ UtilityProcessManager();
+
+ void Init();
+
+ void DestroyProcess(SandboxingKind aSandbox);
+
+ bool IsShutdown() const;
+
+ class Observer final : public nsIObserver {
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+ explicit Observer(UtilityProcessManager* aManager);
+
+ protected:
+ ~Observer() = default;
+
+ RefPtr<UtilityProcessManager> mManager;
+ };
+ friend class Observer;
+
+ RefPtr<Observer> mObserver;
+
+ class ProcessFields final {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(ProcessFields);
+
+ explicit ProcessFields(SandboxingKind aSandbox) : mSandbox(aSandbox){};
+
+ // Promise will be resolved when this Utility process has been fully started
+ // and configured. Only accessed on the main thread.
+ RefPtr<GenericNonExclusivePromise> mLaunchPromise;
+
+ uint32_t mNumProcessAttempts = 0;
+ uint32_t mNumUnexpectedCrashes = 0;
+
+ // Fields that are associated with the current Utility process.
+ UtilityProcessHost* mProcess = nullptr;
+ RefPtr<UtilityProcessParent> mProcessParent = nullptr;
+
+ // Collects any pref changes that occur during process launch (after
+ // the initial map is passed in command-line arguments) to be sent
+ // when the process can receive IPC messages.
+ nsTArray<dom::Pref> mQueuedPrefs;
+
+ nsTArray<UtilityActorName> mActors;
+
+ SandboxingKind mSandbox = SandboxingKind::COUNT;
+
+ protected:
+ ~ProcessFields() = default;
+ };
+
+ EnumeratedArray<SandboxingKind, SandboxingKind::COUNT, RefPtr<ProcessFields>>
+ mProcesses;
+
+ RefPtr<ProcessFields> GetProcess(SandboxingKind);
+ bool NoMoreProcesses();
+
+#ifdef XP_WIN
+ RefPtr<dom::WindowsUtilsParent> mWindowsUtils;
+#endif // XP_WIN
+};
+
+} // namespace ipc
+
+} // namespace mozilla
+
+#endif // _include_ipc_glue_UtilityProcessManager_h_
diff --git a/ipc/glue/UtilityProcessParent.cpp b/ipc/glue/UtilityProcessParent.cpp
new file mode 100644
index 0000000000..2860b4704b
--- /dev/null
+++ b/ipc/glue/UtilityProcessParent.cpp
@@ -0,0 +1,203 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "mozilla/ipc/UtilityProcessParent.h"
+#include "mozilla/ipc/UtilityProcessManager.h"
+
+#if defined(XP_WIN)
+# include <dwrite.h>
+# include <process.h>
+# include "mozilla/WinDllServices.h"
+#endif
+
+#include "mozilla/ipc/ProcessChild.h"
+#include "mozilla/FOGIPC.h"
+
+#include "mozilla/Telemetry.h"
+#include "mozilla/TelemetryIPC.h"
+
+#include "nsHashPropertyBag.h"
+#include "mozilla/Services.h"
+#include "nsIObserverService.h"
+
+namespace mozilla::ipc {
+
+UtilityProcessParent::UtilityProcessParent(UtilityProcessHost* aHost)
+ : mHost(aHost) {
+ MOZ_ASSERT(NS_IsMainThread());
+ MOZ_ASSERT(mHost);
+}
+
+UtilityProcessParent::~UtilityProcessParent() = default;
+
+bool UtilityProcessParent::SendRequestMemoryReport(
+ const uint32_t& aGeneration, const bool& aAnonymize,
+ const bool& aMinimizeMemoryUsage, const Maybe<FileDescriptor>& aDMDFile) {
+ mMemoryReportRequest = MakeUnique<MemoryReportRequestHost>(aGeneration);
+
+ PUtilityProcessParent::SendRequestMemoryReport(
+ aGeneration, aAnonymize, aMinimizeMemoryUsage, aDMDFile,
+ [self = RefPtr{this}](const uint32_t& aGeneration2) {
+ if (self->mMemoryReportRequest) {
+ self->mMemoryReportRequest->Finish(aGeneration2);
+ self->mMemoryReportRequest = nullptr;
+ }
+ },
+ [self = RefPtr{this}](mozilla::ipc::ResponseRejectReason) {
+ self->mMemoryReportRequest = nullptr;
+ });
+
+ return true;
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvAddMemoryReport(
+ const MemoryReport& aReport) {
+ if (mMemoryReportRequest) {
+ mMemoryReportRequest->RecvReport(aReport);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvFOGData(ByteBuf&& aBuf) {
+ glean::FOGData(std::move(aBuf));
+ return IPC_OK();
+}
+
+#if defined(XP_WIN)
+mozilla::ipc::IPCResult UtilityProcessParent::RecvGetModulesTrust(
+ ModulePaths&& aModPaths, bool aRunAtNormalPriority,
+ GetModulesTrustResolver&& aResolver) {
+ RefPtr<DllServices> dllSvc(DllServices::Get());
+ dllSvc->GetModulesTrust(std::move(aModPaths), aRunAtNormalPriority)
+ ->Then(
+ GetMainThreadSerialEventTarget(), __func__,
+ [aResolver](ModulesMapResult&& aResult) {
+ aResolver(Some(ModulesMapResult(std::move(aResult))));
+ },
+ [aResolver](nsresult aRv) { aResolver(Nothing()); });
+ return IPC_OK();
+}
+#endif // defined(XP_WIN)
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvAccumulateChildHistograms(
+ nsTArray<HistogramAccumulation>&& aAccumulations) {
+ TelemetryIPC::AccumulateChildHistograms(Telemetry::ProcessID::Utility,
+ aAccumulations);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+UtilityProcessParent::RecvAccumulateChildKeyedHistograms(
+ nsTArray<KeyedHistogramAccumulation>&& aAccumulations) {
+ TelemetryIPC::AccumulateChildKeyedHistograms(Telemetry::ProcessID::Utility,
+ aAccumulations);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvUpdateChildScalars(
+ nsTArray<ScalarAction>&& aScalarActions) {
+ TelemetryIPC::UpdateChildScalars(Telemetry::ProcessID::Utility,
+ aScalarActions);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvUpdateChildKeyedScalars(
+ nsTArray<KeyedScalarAction>&& aScalarActions) {
+ TelemetryIPC::UpdateChildKeyedScalars(Telemetry::ProcessID::Utility,
+ aScalarActions);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvRecordChildEvents(
+ nsTArray<mozilla::Telemetry::ChildEventData>&& aEvents) {
+ TelemetryIPC::RecordChildEvents(Telemetry::ProcessID::Utility, aEvents);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvRecordDiscardedData(
+ const mozilla::Telemetry::DiscardedData& aDiscardedData) {
+ TelemetryIPC::RecordDiscardedData(Telemetry::ProcessID::Utility,
+ aDiscardedData);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult UtilityProcessParent::RecvInitCompleted() {
+ MOZ_ASSERT(mHost);
+ mHost->ResolvePromise();
+ return IPC_OK();
+}
+
+void UtilityProcessParent::ActorDestroy(ActorDestroyReason aWhy) {
+ RefPtr<nsHashPropertyBag> props = new nsHashPropertyBag();
+
+ if (aWhy == AbnormalShutdown) {
+ nsAutoString dumpID;
+
+ if (mCrashReporter) {
+#if defined(MOZ_SANDBOX)
+ RefPtr<mozilla::ipc::UtilityProcessManager> upm =
+ mozilla::ipc::UtilityProcessManager::GetSingleton();
+ if (upm) {
+ Span<const UtilityActorName> actors = upm->GetActors(this);
+ nsAutoCString actorsName;
+ if (!actors.IsEmpty()) {
+ actorsName += GetUtilityActorName(actors.First<1>()[0]);
+ for (const auto& actor : actors.From(1)) {
+ actorsName += ", "_ns + GetUtilityActorName(actor);
+ }
+ }
+ mCrashReporter->AddAnnotation(
+ CrashReporter::Annotation::UtilityActorsName, actorsName);
+ }
+#endif
+ }
+
+ GenerateCrashReport(OtherPid(), &dumpID);
+
+ // It's okay for dumpID to be empty if there was no minidump generated
+ // tests like ipc/glue/test/browser/browser_utility_crashReporter.js are
+ // there to verify this
+ if (!dumpID.IsEmpty()) {
+ props->SetPropertyAsAString(u"dumpID"_ns, dumpID);
+ }
+
+ MaybeTerminateProcess();
+ }
+
+ nsAutoString pid;
+ pid.AppendInt(static_cast<uint64_t>(OtherPid()));
+
+ nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
+ if (obs) {
+ obs->NotifyObservers((nsIPropertyBag2*)props, "ipc:utility-shutdown",
+ pid.get());
+ } else {
+ NS_WARNING("Could not get a nsIObserverService, ipc:utility-shutdown skip");
+ }
+
+ mHost->OnChannelClosed();
+}
+
+// To ensure that IPDL is finished before UtilityParent gets deleted.
+class DeferredDeleteUtilityProcessParent : public Runnable {
+ public:
+ explicit DeferredDeleteUtilityProcessParent(
+ RefPtr<UtilityProcessParent> aParent)
+ : Runnable("ipc::glue::DeferredDeleteUtilityProcessParent"),
+ mParent(std::move(aParent)) {}
+
+ NS_IMETHODIMP Run() override { return NS_OK; }
+
+ private:
+ RefPtr<UtilityProcessParent> mParent;
+};
+
+/* static */
+void UtilityProcessParent::Destroy(RefPtr<UtilityProcessParent> aParent) {
+ NS_DispatchToMainThread(
+ new DeferredDeleteUtilityProcessParent(std::move(aParent)));
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessParent.h b/ipc/glue/UtilityProcessParent.h
new file mode 100644
index 0000000000..6ff907583f
--- /dev/null
+++ b/ipc/glue/UtilityProcessParent.h
@@ -0,0 +1,77 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessParent_h__
+#define _include_ipc_glue_UtilityProcessParent_h__
+#include "mozilla/ipc/PUtilityProcessParent.h"
+#include "mozilla/ipc/CrashReporterHelper.h"
+#include "mozilla/ipc/UtilityProcessHost.h"
+#include "mozilla/dom/MemoryReportRequest.h"
+
+#include "mozilla/RefPtr.h"
+
+namespace mozilla {
+
+namespace ipc {
+
+class UtilityProcessHost;
+
+class UtilityProcessParent final
+ : public PUtilityProcessParent,
+ public ipc::CrashReporterHelper<GeckoProcessType_Utility> {
+ typedef mozilla::dom::MemoryReportRequestHost MemoryReportRequestHost;
+
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(UtilityProcessParent, override);
+ friend class UtilityProcessHost;
+
+ explicit UtilityProcessParent(UtilityProcessHost* aHost);
+
+ mozilla::ipc::IPCResult RecvAddMemoryReport(const MemoryReport& aReport);
+
+ bool SendRequestMemoryReport(const uint32_t& aGeneration,
+ const bool& aAnonymize,
+ const bool& aMinimizeMemoryUsage,
+ const Maybe<ipc::FileDescriptor>& aDMDFile);
+
+ mozilla::ipc::IPCResult RecvFOGData(ByteBuf&& aBuf);
+
+#if defined(XP_WIN)
+ mozilla::ipc::IPCResult RecvGetModulesTrust(
+ ModulePaths&& aModPaths, bool aRunAtNormalPriority,
+ GetModulesTrustResolver&& aResolver);
+#endif // defined(XP_WIN)
+
+ mozilla::ipc::IPCResult RecvAccumulateChildHistograms(
+ nsTArray<HistogramAccumulation>&& aAccumulations);
+ mozilla::ipc::IPCResult RecvAccumulateChildKeyedHistograms(
+ nsTArray<KeyedHistogramAccumulation>&& aAccumulations);
+ mozilla::ipc::IPCResult RecvUpdateChildScalars(
+ nsTArray<ScalarAction>&& aScalarActions);
+ mozilla::ipc::IPCResult RecvUpdateChildKeyedScalars(
+ nsTArray<KeyedScalarAction>&& aScalarActions);
+ mozilla::ipc::IPCResult RecvRecordChildEvents(
+ nsTArray<ChildEventData>&& events);
+ mozilla::ipc::IPCResult RecvRecordDiscardedData(
+ const DiscardedData& aDiscardedData);
+
+ mozilla::ipc::IPCResult RecvInitCompleted();
+
+ void ActorDestroy(ActorDestroyReason aWhy) override;
+
+ private:
+ UtilityProcessHost* mHost;
+ UniquePtr<MemoryReportRequestHost> mMemoryReportRequest{};
+
+ ~UtilityProcessParent();
+
+ static void Destroy(RefPtr<UtilityProcessParent> aParent);
+};
+
+} // namespace ipc
+
+} // namespace mozilla
+
+#endif // _include_ipc_glue_UtilityProcessParent_h__
diff --git a/ipc/glue/UtilityProcessSandboxing.cpp b/ipc/glue/UtilityProcessSandboxing.cpp
new file mode 100644
index 0000000000..0c333fdeca
--- /dev/null
+++ b/ipc/glue/UtilityProcessSandboxing.cpp
@@ -0,0 +1,70 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#include "UtilityProcessSandboxing.h"
+
+#include <vector>
+#include <string>
+
+#include "prenv.h"
+
+namespace mozilla::ipc {
+
+std::vector<std::string> split(const std::string& str, char s) {
+ std::vector<std::string> rv;
+ size_t last = 0;
+ size_t i;
+ size_t c = str.size();
+ for (i = 0; i <= c; ++i) {
+ if (i == c || str[i] == s) {
+ rv.push_back(str.substr(last, i - last));
+ last = i + 1;
+ }
+ }
+ return rv;
+}
+
+bool IsUtilitySandboxEnabled(const char* envVar, SandboxingKind aKind) {
+#ifdef XP_WIN
+ // Sandboxing the Windows file dialog is probably not useful.
+ //
+ // (Additionally, it causes failures in our test environments: when running
+ // tests on windows-11-2009-qr machines, sandboxed child processes can't see
+ // or interact with any other process's windows -- which means they can't
+ // select a window from the parent process as the file dialog's parent. This
+ // occurs regardless of the sandbox preferences, which is why we disable
+ // sandboxing entirely rather than use a maximally permissive preference-set.
+ // This behavior has not been seen in user-facing environments.)
+ if (aKind == SandboxingKind::WINDOWS_FILE_DIALOG) {
+ return false;
+ }
+#endif
+
+ if (envVar == nullptr) {
+ return true;
+ }
+
+ const std::string disableUtility(envVar);
+ if (disableUtility == "1") {
+ return false;
+ }
+
+ std::vector<std::string> components = split(disableUtility, ',');
+ const std::string thisKind = "utility:" + std::to_string(aKind);
+ for (const std::string& thisOne : components) {
+ if (thisOne == thisKind) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool IsUtilitySandboxEnabled(SandboxingKind aKind) {
+ return IsUtilitySandboxEnabled(PR_GetEnv("MOZ_DISABLE_UTILITY_SANDBOX"),
+ aKind);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/glue/UtilityProcessSandboxing.h b/ipc/glue/UtilityProcessSandboxing.h
new file mode 100644
index 0000000000..461bbec7c4
--- /dev/null
+++ b/ipc/glue/UtilityProcessSandboxing.h
@@ -0,0 +1,46 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessSandboxing_h_
+#define _include_ipc_glue_UtilityProcessSandboxing_h_
+
+#include <stdint.h>
+
+namespace mozilla {
+
+namespace ipc {
+
+// When adding a new value, the checks within UtilityProcessImpl::Init() needs
+// to be updated as well.
+enum SandboxingKind : uint64_t {
+
+ GENERIC_UTILITY,
+
+#ifdef MOZ_APPLEMEDIA
+ UTILITY_AUDIO_DECODING_APPLE_MEDIA,
+#endif
+#ifdef XP_WIN
+ UTILITY_AUDIO_DECODING_WMF,
+#endif
+#ifdef MOZ_WMF_MEDIA_ENGINE
+ MF_MEDIA_ENGINE_CDM,
+#endif
+#ifdef XP_WIN
+ WINDOWS_UTILS,
+ WINDOWS_FILE_DIALOG,
+#endif
+
+ COUNT,
+
+};
+
+bool IsUtilitySandboxEnabled(const char* envVar, SandboxingKind aKind);
+bool IsUtilitySandboxEnabled(SandboxingKind aKind);
+
+} // namespace ipc
+
+} // namespace mozilla
+
+#endif // _include_ipc_glue_UtilityProcessSandboxing_h_
diff --git a/ipc/glue/WindowsMessageLoop.cpp b/ipc/glue/WindowsMessageLoop.cpp
new file mode 100644
index 0000000000..1305ecdea1
--- /dev/null
+++ b/ipc/glue/WindowsMessageLoop.cpp
@@ -0,0 +1,1192 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/DebugOnly.h"
+
+#include "WindowsMessageLoop.h"
+#include "Neutering.h"
+#include "MessageChannel.h"
+
+#include "nsServiceManagerUtils.h"
+#include "nsString.h"
+#include "WinUtils.h"
+
+#include "mozilla/ArrayUtils.h"
+#include "mozilla/dom/JSExecutionManager.h"
+#include "mozilla/gfx/Logging.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/mscom/Utils.h"
+#include "mozilla/PaintTracker.h"
+#include "mozilla/StaticPtr.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/WindowsProcessMitigations.h"
+
+using namespace mozilla;
+using namespace mozilla::ipc;
+using namespace mozilla::ipc::windows;
+
+/**
+ * The Windows-only code below exists to solve a general problem with deadlocks
+ * that we experience when sending synchronous IPC messages to processes that
+ * contain native windows (i.e. HWNDs). Windows (the OS) sends synchronous
+ * messages between parent and child HWNDs in multiple circumstances (e.g.
+ * WM_PARENTNOTIFY, WM_NCACTIVATE, etc.), even when those HWNDs are controlled
+ * by different threads or different processes. Thus we can very easily end up
+ * in a deadlock by a call stack like the following:
+ *
+ * Process A:
+ * - CreateWindow(...) creates a "parent" HWND.
+ * - SendCreateChildWidget(HWND) is a sync IPC message that sends the "parent"
+ * HWND over to Process B. Process A blocks until a response is received
+ * from Process B.
+ *
+ * Process B:
+ * - RecvCreateWidget(HWND) gets the "parent" HWND from Process A.
+ * - CreateWindow(..., HWND) creates a "child" HWND with the parent from
+ * process A.
+ * - Windows (the OS) generates a WM_PARENTNOTIFY message that is sent
+ * synchronously to Process A. Process B blocks until a response is
+ * received from Process A. Process A, however, is blocked and cannot
+ * process the message. Both processes are deadlocked.
+ *
+ * The example above has a few different workarounds (e.g. setting the
+ * WS_EX_NOPARENTNOTIFY style on the child window) but the general problem is
+ * persists. Once two HWNDs are parented we must not block their owning
+ * threads when manipulating either HWND.
+ *
+ * Windows requires any application that hosts native HWNDs to always process
+ * messages or risk deadlock. Given our architecture the only way to meet
+ * Windows' requirement and allow for synchronous IPC messages is to pump a
+ * miniature message loop during a sync IPC call. We avoid processing any
+ * queued messages during the loop (with one exception, see below), but
+ * "nonqueued" messages (see
+ * http://msdn.microsoft.com/en-us/library/ms644927(VS.85).aspx under the
+ * section "Nonqueued messages") cannot be avoided. Those messages are trapped
+ * in a special window procedure where we can either ignore the message or
+ * process it in some fashion.
+ *
+ * Queued and "non-queued" messages will be processed during Interrupt calls if
+ * modal UI related api calls block an Interrupt in-call in the child. To
+ * prevent windows from freezing, and to allow concurrent processing of critical
+ * events (such as painting), we spin a native event dispatch loop while
+ * these in-calls are blocked.
+ */
+
+#if defined(ACCESSIBILITY)
+// pulled from accessibility's win utils
+extern const wchar_t* kPropNameTabContent;
+#endif
+
+// widget related message id constants we need to defer, see nsAppShell.
+extern UINT sAppShellGeckoMsgId;
+
+namespace {
+
+const wchar_t kOldWndProcProp[] = L"MozillaIPCOldWndProc";
+
+// This isn't defined before Windows XP.
+enum { WM_XP_THEMECHANGED = 0x031A };
+
+static StaticAutoPtr<AutoTArray<HWND, 20>> gNeuteredWindows;
+
+typedef nsTArray<UniquePtr<DeferredMessage>> DeferredMessageArray;
+DeferredMessageArray* gDeferredMessages = nullptr;
+
+HHOOK gDeferredGetMsgHook = nullptr;
+HHOOK gDeferredCallWndProcHook = nullptr;
+
+DWORD gUIThreadId = 0;
+HWND gCOMWindow = 0;
+// Once initialized, gWinEventHook is never unhooked. We save the handle so
+// that we can check whether or not the hook is initialized.
+HWINEVENTHOOK gWinEventHook = nullptr;
+const wchar_t kCOMWindowClassName[] = L"OleMainThreadWndClass";
+
+// WM_GETOBJECT id pulled from uia headers
+#define MOZOBJID_UIAROOT -25
+
+HWND FindCOMWindow() {
+ MOZ_ASSERT(gUIThreadId);
+
+ HWND last = 0;
+ while (
+ (last = FindWindowExW(HWND_MESSAGE, last, kCOMWindowClassName, NULL))) {
+ if (GetWindowThreadProcessId(last, NULL) == gUIThreadId) {
+ return last;
+ }
+ }
+
+ return (HWND)0;
+}
+
+void CALLBACK WinEventHook(HWINEVENTHOOK aWinEventHook, DWORD aEvent,
+ HWND aHwnd, LONG aIdObject, LONG aIdChild,
+ DWORD aEventThread, DWORD aMsEventTime) {
+ MOZ_ASSERT(aWinEventHook == gWinEventHook);
+ MOZ_ASSERT(gUIThreadId == aEventThread);
+ switch (aEvent) {
+ case EVENT_OBJECT_CREATE: {
+ if (aIdObject != OBJID_WINDOW || aIdChild != CHILDID_SELF) {
+ // Not an event we're interested in
+ return;
+ }
+ wchar_t classBuf[256] = {0};
+ int result = ::GetClassNameW(aHwnd, classBuf, MOZ_ARRAY_LENGTH(classBuf));
+ if (result != (MOZ_ARRAY_LENGTH(kCOMWindowClassName) - 1) ||
+ wcsncmp(kCOMWindowClassName, classBuf, result)) {
+ // Not a class we're interested in
+ return;
+ }
+ MOZ_ASSERT(FindCOMWindow() == aHwnd);
+ gCOMWindow = aHwnd;
+ break;
+ }
+ case EVENT_OBJECT_DESTROY: {
+ if (aHwnd == gCOMWindow && aIdObject == OBJID_WINDOW) {
+ MOZ_ASSERT(aIdChild == CHILDID_SELF);
+ gCOMWindow = 0;
+ }
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+}
+
+LRESULT CALLBACK DeferredMessageHook(int nCode, WPARAM wParam, LPARAM lParam) {
+ // XXX This function is called for *both* the WH_CALLWNDPROC hook and the
+ // WH_GETMESSAGE hook, but they have different parameters. We don't
+ // use any of them except nCode which has the same meaning.
+
+ // Only run deferred messages if all of these conditions are met:
+ // 1. The |nCode| indicates that this hook should do something.
+ // 2. We have deferred messages to run.
+ // 3. We're not being called from the PeekMessage within the WaitFor*Notify
+ // function (indicated with MessageChannel::IsPumpingMessages). We really
+ // only want to run after returning to the main event loop.
+ if (nCode >= 0 && gDeferredMessages && !MessageChannel::IsPumpingMessages()) {
+ NS_ASSERTION(gDeferredGetMsgHook && gDeferredCallWndProcHook,
+ "These hooks must be set if we're being called!");
+ NS_ASSERTION(gDeferredMessages->Length(), "No deferred messages?!");
+
+ // Unset hooks first, in case we reenter below.
+ UnhookWindowsHookEx(gDeferredGetMsgHook);
+ UnhookWindowsHookEx(gDeferredCallWndProcHook);
+ gDeferredGetMsgHook = 0;
+ gDeferredCallWndProcHook = 0;
+
+ // Unset the global and make sure we delete it when we're done here.
+ auto messages = WrapUnique(gDeferredMessages);
+ gDeferredMessages = nullptr;
+
+ // Run all the deferred messages in order.
+ uint32_t count = messages->Length();
+ for (uint32_t index = 0; index < count; index++) {
+ messages->ElementAt(index)->Run();
+ }
+ }
+
+ // Always call the next hook.
+ return CallNextHookEx(nullptr, nCode, wParam, lParam);
+}
+
+void ScheduleDeferredMessageRun() {
+ if (gDeferredMessages && !(gDeferredGetMsgHook && gDeferredCallWndProcHook)) {
+ NS_ASSERTION(gDeferredMessages->Length(), "No deferred messages?!");
+
+ gDeferredGetMsgHook = ::SetWindowsHookEx(WH_GETMESSAGE, DeferredMessageHook,
+ nullptr, gUIThreadId);
+ gDeferredCallWndProcHook = ::SetWindowsHookEx(
+ WH_CALLWNDPROC, DeferredMessageHook, nullptr, gUIThreadId);
+ NS_ASSERTION(gDeferredGetMsgHook && gDeferredCallWndProcHook,
+ "Failed to set hooks!");
+ }
+}
+
+static void DumpNeuteredMessage(HWND hwnd, UINT uMsg) {
+#ifdef DEBUG
+ nsAutoCString log("Received \"nonqueued\" ");
+ // classify messages
+ if (uMsg < WM_USER) {
+ const char* msgText = mozilla::widget::WinUtils::WinEventToEventName(uMsg);
+ if (msgText) {
+ log.AppendPrintf("ui message \"%s\"", msgText);
+ } else {
+ log.AppendPrintf("ui message (0x%X)", uMsg);
+ }
+ } else if (uMsg >= WM_USER && uMsg < WM_APP) {
+ log.AppendPrintf("WM_USER message (0x%X)", uMsg);
+ } else if (uMsg >= WM_APP && uMsg < 0xC000) {
+ log.AppendPrintf("WM_APP message (0x%X)", uMsg);
+ } else if (uMsg >= 0xC000 && uMsg < 0x10000) {
+ log.AppendPrintf("registered windows message (0x%X)", uMsg);
+ } else {
+ log.AppendPrintf("system message (0x%X)", uMsg);
+ }
+
+ log.AppendLiteral(" during a synchronous IPC message for window ");
+ log.AppendPrintf("0x%p", hwnd);
+
+ wchar_t className[256] = {0};
+ if (GetClassNameW(hwnd, className, sizeof(className) - 1) > 0) {
+ log.AppendLiteral(" (\"");
+ log.Append(NS_ConvertUTF16toUTF8((char16_t*)className));
+ log.AppendLiteral("\")");
+ }
+
+ log.AppendLiteral(
+ ", sending it to DefWindowProc instead of the normal "
+ "window procedure.");
+ NS_ERROR(log.get());
+#endif
+}
+
+LRESULT
+ProcessOrDeferMessage(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
+ UniquePtr<DeferredMessage> deferred;
+
+ // Most messages ask for 0 to be returned if the message is processed.
+ LRESULT res = 0;
+
+ switch (uMsg) {
+ // Messages that can be deferred as-is. These must not contain pointers in
+ // their wParam or lParam arguments!
+ case WM_ACTIVATE:
+ case WM_ACTIVATEAPP:
+ case WM_CANCELMODE:
+ case WM_CAPTURECHANGED:
+ case WM_CHILDACTIVATE:
+ case WM_DESTROY:
+ case WM_ENABLE:
+ case WM_IME_NOTIFY:
+ case WM_IME_SETCONTEXT:
+ case WM_KILLFOCUS:
+ case WM_MOUSEWHEEL:
+ case WM_NCDESTROY:
+ case WM_PARENTNOTIFY:
+ case WM_SETFOCUS:
+ case WM_SYSCOMMAND:
+ case WM_DISPLAYCHANGE:
+ case WM_SHOWWINDOW: // Intentional fall-through.
+ case WM_XP_THEMECHANGED: {
+ deferred = MakeUnique<DeferredSendMessage>(hwnd, uMsg, wParam, lParam);
+ break;
+ }
+
+ case WM_DEVICECHANGE:
+ case WM_POWERBROADCAST:
+ case WM_NCACTIVATE: // Intentional fall-through.
+ case WM_SETCURSOR: {
+ // Friggin unconventional return value...
+ res = TRUE;
+ deferred = MakeUnique<DeferredSendMessage>(hwnd, uMsg, wParam, lParam);
+ break;
+ }
+
+ case WM_MOUSEACTIVATE: {
+ res = MA_NOACTIVATE;
+ deferred = MakeUnique<DeferredSendMessage>(hwnd, uMsg, wParam, lParam);
+ break;
+ }
+
+ // These messages need to use the RedrawWindow function to generate the
+ // right kind of message. We can't simply fake them as the MSDN docs say
+ // explicitly that paint messages should not be sent by an application.
+ case WM_ERASEBKGND: {
+ UINT flags = RDW_INVALIDATE | RDW_ERASE | RDW_NOINTERNALPAINT |
+ RDW_NOFRAME | RDW_NOCHILDREN | RDW_ERASENOW;
+ deferred = MakeUnique<DeferredRedrawMessage>(hwnd, flags);
+ break;
+ }
+
+ // This message will generate a WM_PAINT message if there are invalid
+ // areas.
+ case WM_PAINT: {
+ deferred = MakeUnique<DeferredUpdateMessage>(hwnd);
+ break;
+ }
+
+ // This message holds a string in its lParam that we must copy.
+ case WM_SETTINGCHANGE: {
+ deferred =
+ MakeUnique<DeferredSettingChangeMessage>(hwnd, uMsg, wParam, lParam);
+ break;
+ }
+
+ // These messages are faked via a call to SetWindowPos.
+ case WM_WINDOWPOSCHANGED: {
+ deferred = MakeUnique<DeferredWindowPosMessage>(hwnd, lParam);
+ break;
+ }
+ case WM_NCCALCSIZE: {
+ deferred =
+ MakeUnique<DeferredWindowPosMessage>(hwnd, lParam, true, wParam);
+ break;
+ }
+
+ case WM_COPYDATA: {
+ deferred =
+ MakeUnique<DeferredCopyDataMessage>(hwnd, uMsg, wParam, lParam);
+ res = TRUE;
+ break;
+ }
+
+ case WM_STYLECHANGED: {
+ deferred = MakeUnique<DeferredStyleChangeMessage>(hwnd, wParam, lParam);
+ break;
+ }
+
+ case WM_SETICON: {
+ deferred = MakeUnique<DeferredSetIconMessage>(hwnd, uMsg, wParam, lParam);
+ break;
+ }
+
+ // Messages that are safe to pass to DefWindowProc go here.
+ case WM_ENTERIDLE:
+ case WM_GETICON:
+ case WM_NCPAINT: // (never trap nc paint events)
+ case WM_GETMINMAXINFO:
+ case WM_GETTEXT:
+ case WM_NCHITTEST:
+ case WM_STYLECHANGING: // Intentional fall-through.
+ case WM_WINDOWPOSCHANGING:
+ case WM_GETTEXTLENGTH: {
+ return DefWindowProc(hwnd, uMsg, wParam, lParam);
+ }
+
+ // Just return, prevents DefWindowProc from messaging the window
+ // syncronously with other events, which may be deferred. Prevents
+ // random shutdown of aero composition on the window.
+ case WM_SYNCPAINT:
+ return 0;
+
+ // This message causes QuickTime to make re-entrant calls.
+ // Simply discarding it doesn't seem to hurt anything.
+ case WM_APP - 1:
+ return 0;
+
+ // We only support a query for our IAccessible or UIA pointers.
+ // This should be safe, and needs to be sync.
+#if defined(ACCESSIBILITY)
+ case WM_GETOBJECT: {
+ LONG objId = static_cast<LONG>(lParam);
+ if (objId == OBJID_CLIENT || objId == MOZOBJID_UIAROOT) {
+ WNDPROC oldWndProc = (WNDPROC)GetProp(hwnd, kOldWndProcProp);
+ if (oldWndProc) {
+ return CallWindowProcW(oldWndProc, hwnd, uMsg, wParam, lParam);
+ }
+ }
+ return DefWindowProc(hwnd, uMsg, wParam, lParam);
+ }
+#endif // ACCESSIBILITY
+
+ default: {
+ // Unknown messages only are logged in debug builds and sent to
+ // DefWindowProc.
+ if (uMsg && uMsg == sAppShellGeckoMsgId) {
+ // Widget's registered native event callback
+ deferred = MakeUnique<DeferredSendMessage>(hwnd, uMsg, wParam, lParam);
+ }
+ }
+ }
+
+ // No deferred message was created and we land here, this is an
+ // unhandled message.
+ if (!deferred) {
+ DumpNeuteredMessage(hwnd, uMsg);
+ return DefWindowProc(hwnd, uMsg, wParam, lParam);
+ }
+
+ // Create the deferred message array if it doesn't exist already.
+ if (!gDeferredMessages) {
+ gDeferredMessages = new DeferredMessageArray(20);
+ }
+
+ // Save for later. The array takes ownership of |deferred|.
+ gDeferredMessages->AppendElement(std::move(deferred));
+ return res;
+}
+
+} // namespace
+
+LRESULT CALLBACK NeuteredWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,
+ LPARAM lParam) {
+ WNDPROC oldWndProc = (WNDPROC)GetProp(hwnd, kOldWndProcProp);
+ if (!oldWndProc) {
+ // We should really never ever get here.
+ NS_ERROR("No old wndproc!");
+ return DefWindowProc(hwnd, uMsg, wParam, lParam);
+ }
+
+ // See if we care about this message. We may either ignore it, send it to
+ // DefWindowProc, or defer it for later.
+ return ProcessOrDeferMessage(hwnd, uMsg, wParam, lParam);
+}
+
+namespace {
+
+static bool WindowIsDeferredWindow(HWND hWnd) {
+ if (!IsWindow(hWnd)) {
+ NS_WARNING("Window has died!");
+ return false;
+ }
+
+ char16_t buffer[256] = {0};
+ int length = GetClassNameW(hWnd, (wchar_t*)buffer, sizeof(buffer) - 1);
+ if (length <= 0) {
+ NS_WARNING("Failed to get class name!");
+ return false;
+ }
+
+#if defined(ACCESSIBILITY)
+ // Tab content creates a window that responds to accessible WM_GETOBJECT
+ // calls. This window can safely be ignored.
+ if (::GetPropW(hWnd, kPropNameTabContent)) {
+ return false;
+ }
+#endif
+
+ // Common mozilla windows we must defer messages to.
+ nsDependentString className(buffer, length);
+ if (StringBeginsWith(className, u"Mozilla"_ns) ||
+ StringBeginsWith(className, u"Gecko"_ns) ||
+ className.EqualsLiteral("nsToolkitClass") ||
+ className.EqualsLiteral("nsAppShell:EventWindowClass")) {
+ return true;
+ }
+
+ return false;
+}
+
+bool NeuterWindowProcedure(HWND hWnd) {
+ if (!WindowIsDeferredWindow(hWnd)) {
+ // Some other kind of window, skip.
+ return false;
+ }
+
+ NS_ASSERTION(!GetProp(hWnd, kOldWndProcProp), "This should always be null!");
+
+ // It's possible to get nullptr out of SetWindowLongPtr, and the only way to
+ // know if that's a valid old value is to use GetLastError. Clear the error
+ // here so we can tell.
+ SetLastError(ERROR_SUCCESS);
+
+ LONG_PTR currentWndProc =
+ SetWindowLongPtr(hWnd, GWLP_WNDPROC, (LONG_PTR)NeuteredWindowProc);
+ if (!currentWndProc) {
+ if (ERROR_SUCCESS == GetLastError()) {
+ // No error, so we set something and must therefore reset it.
+ SetWindowLongPtr(hWnd, GWLP_WNDPROC, currentWndProc);
+ }
+ return false;
+ }
+
+ NS_ASSERTION(currentWndProc != (LONG_PTR)NeuteredWindowProc,
+ "This shouldn't be possible!");
+
+ if (!SetProp(hWnd, kOldWndProcProp, (HANDLE)currentWndProc)) {
+ // Cleanup
+ NS_WARNING("SetProp failed!");
+ SetWindowLongPtr(hWnd, GWLP_WNDPROC, currentWndProc);
+ RemovePropW(hWnd, kOldWndProcProp);
+ return false;
+ }
+
+ return true;
+}
+
+void RestoreWindowProcedure(HWND hWnd) {
+ NS_ASSERTION(WindowIsDeferredWindow(hWnd),
+ "Not a deferred window, this shouldn't be in our list!");
+ LONG_PTR oldWndProc = (LONG_PTR)GetProp(hWnd, kOldWndProcProp);
+ if (oldWndProc) {
+ NS_ASSERTION(oldWndProc != (LONG_PTR)NeuteredWindowProc,
+ "This shouldn't be possible!");
+
+ DebugOnly<LONG_PTR> currentWndProc =
+ SetWindowLongPtr(hWnd, GWLP_WNDPROC, oldWndProc);
+ NS_ASSERTION(currentWndProc == (LONG_PTR)NeuteredWindowProc,
+ "This should never be switched out from under us!");
+ }
+ RemovePropW(hWnd, kOldWndProcProp);
+}
+
+LRESULT CALLBACK CallWindowProcedureHook(int nCode, WPARAM wParam,
+ LPARAM lParam) {
+ if (nCode >= 0) {
+ NS_ASSERTION(gNeuteredWindows, "This should never be null!");
+
+ HWND hWnd = reinterpret_cast<CWPSTRUCT*>(lParam)->hwnd;
+
+ if (!gNeuteredWindows->Contains(hWnd) &&
+ !SuppressedNeuteringRegion::IsNeuteringSuppressed() &&
+ NeuterWindowProcedure(hWnd)) {
+ // XXX(Bug 1631371) Check if this should use a fallible operation as it
+ // pretended earlier.
+ gNeuteredWindows->AppendElement(hWnd);
+ }
+ }
+ return CallNextHookEx(nullptr, nCode, wParam, lParam);
+}
+
+inline void AssertWindowIsNotNeutered(HWND hWnd) {
+#ifdef DEBUG
+ // Make sure our neutered window hook isn't still in place.
+ LONG_PTR wndproc = GetWindowLongPtr(hWnd, GWLP_WNDPROC);
+ NS_ASSERTION(wndproc != (LONG_PTR)NeuteredWindowProc, "Window is neutered!");
+#endif
+}
+
+void UnhookNeuteredWindows() {
+ if (!gNeuteredWindows) return;
+ uint32_t count = gNeuteredWindows->Length();
+ for (uint32_t index = 0; index < count; index++) {
+ RestoreWindowProcedure(gNeuteredWindows->ElementAt(index));
+ }
+ gNeuteredWindows->Clear();
+}
+
+// This timeout stuff assumes a sane value of mTimeoutMs (less than the overflow
+// value for GetTickCount(), which is something like 50 days). It uses the
+// cheapest (and least accurate) method supported by Windows 2000.
+
+struct TimeoutData {
+ DWORD startTicks;
+ DWORD targetTicks;
+};
+
+void InitTimeoutData(TimeoutData* aData, int32_t aTimeoutMs) {
+ aData->startTicks = GetTickCount();
+ if (!aData->startTicks) {
+ // How unlikely is this!
+ aData->startTicks++;
+ }
+ aData->targetTicks = aData->startTicks + aTimeoutMs;
+}
+
+bool TimeoutHasExpired(const TimeoutData& aData) {
+ if (!aData.startTicks) {
+ return false;
+ }
+
+ DWORD now = GetTickCount();
+
+ if (aData.targetTicks < aData.startTicks) {
+ // Overflow
+ return now < aData.startTicks && now >= aData.targetTicks;
+ }
+ return now >= aData.targetTicks;
+}
+
+} // namespace
+
+namespace mozilla {
+namespace ipc {
+namespace windows {
+
+void InitUIThread() {
+ if (!XRE_UseNativeEventProcessing()) {
+ return;
+ }
+ // If we aren't setup before a call to NotifyWorkerThread, we'll hang
+ // on startup.
+ if (!gUIThreadId) {
+ gUIThreadId = GetCurrentThreadId();
+ }
+
+ MOZ_ASSERT(gUIThreadId);
+ MOZ_ASSERT(gUIThreadId == GetCurrentThreadId(),
+ "Called InitUIThread multiple times on different threads!");
+
+ if (!gWinEventHook && !mscom::IsCurrentThreadMTA()) {
+ gWinEventHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_DESTROY,
+ NULL, &WinEventHook, GetCurrentProcessId(),
+ gUIThreadId, WINEVENT_OUTOFCONTEXT);
+ MOZ_ASSERT(gWinEventHook);
+
+ // We need to execute this after setting the hook in case the OLE window
+ // already existed.
+ gCOMWindow = FindCOMWindow();
+ }
+}
+
+} // namespace windows
+} // namespace ipc
+} // namespace mozilla
+
+// See SpinInternalEventLoop below
+MessageChannel::SyncStackFrame::SyncStackFrame(MessageChannel* channel)
+ : mSpinNestedEvents(false),
+ mListenerNotified(false),
+ mChannel(channel),
+ mPrev(mChannel->mTopFrame),
+ mStaticPrev(sStaticTopFrame) {
+ // Only track stack frames when Windows message deferral behavior
+ // is request for the channel.
+ if (!(mChannel->GetChannelFlags() & REQUIRE_DEFERRED_MESSAGE_PROTECTION)) {
+ return;
+ }
+
+ mChannel->mTopFrame = this;
+ sStaticTopFrame = this;
+
+ if (!mStaticPrev) {
+ NS_ASSERTION(!gNeuteredWindows, "Should only set this once!");
+ gNeuteredWindows = new AutoTArray<HWND, 20>();
+ }
+}
+
+MessageChannel::SyncStackFrame::~SyncStackFrame() {
+ if (!(mChannel->GetChannelFlags() & REQUIRE_DEFERRED_MESSAGE_PROTECTION)) {
+ return;
+ }
+
+ NS_ASSERTION(this == mChannel->mTopFrame,
+ "Mismatched interrupt stack frames");
+ NS_ASSERTION(this == sStaticTopFrame,
+ "Mismatched static Interrupt stack frames");
+
+ mChannel->mTopFrame = mPrev;
+ sStaticTopFrame = mStaticPrev;
+
+ if (!mStaticPrev) {
+ NS_ASSERTION(gNeuteredWindows, "Bad pointer!");
+ gNeuteredWindows = nullptr;
+ }
+}
+
+MessageChannel::SyncStackFrame* MessageChannel::sStaticTopFrame;
+
+// nsAppShell's notification that gecko events are being processed.
+// If we are here and there is an Interrupt Incall active, we are spinning
+// a nested gecko event loop. In which case the remote process needs
+// to know about it.
+void /* static */
+MessageChannel::NotifyGeckoEventDispatch() {
+ // sStaticTopFrame is only valid for Interrupt channels
+ if (!sStaticTopFrame || sStaticTopFrame->mListenerNotified) return;
+
+ sStaticTopFrame->mListenerNotified = true;
+ MessageChannel* channel =
+ static_cast<MessageChannel*>(sStaticTopFrame->mChannel);
+ channel->Listener()->ProcessRemoteNativeEventsInInterruptCall();
+}
+
+// invoked by the module that receives the spin event loop
+// message.
+void MessageChannel::ProcessNativeEventsInInterruptCall() {
+ NS_ASSERTION(GetCurrentThreadId() == gUIThreadId,
+ "Shouldn't be on a non-main thread in here!");
+ if (!mTopFrame) {
+ NS_ERROR("Spin logic error: no Interrupt frame");
+ return;
+ }
+
+ mTopFrame->mSpinNestedEvents = true;
+}
+
+// Spin loop is called in place of WaitFor*Notify when modal ui is being shown
+// in a child. There are some intricacies in using it however. Spin loop is
+// enabled for a particular Interrupt frame by the client calling
+// MessageChannel::ProcessNativeEventsInInterrupt().
+// This call can be nested for multiple Interrupt frames in a single plugin or
+// multiple unrelated plugins.
+void MessageChannel::SpinInternalEventLoop() {
+ if (mozilla::PaintTracker::IsPainting()) {
+ MOZ_CRASH("Don't spin an event loop while painting.");
+ }
+
+ NS_ASSERTION(mTopFrame && mTopFrame->mSpinNestedEvents,
+ "Spinning incorrectly");
+
+ // Nested windows event loop we trigger when the child enters into modal
+ // event loops.
+
+ // Note, when we return, we always reset the notify worker event. So there's
+ // no need to reset it on return here.
+
+ do {
+ MSG msg = {0};
+
+ // Don't get wrapped up in here if the child connection dies.
+ {
+ MonitorAutoLock lock(*mMonitor);
+ if (!Connected()) {
+ return;
+ }
+ }
+
+ // Retrieve window or thread messages
+ if (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) {
+ // The child UI should have been destroyed before the app is closed, in
+ // which case, we should never get this here.
+ if (msg.message == WM_QUIT) {
+ NS_ERROR("WM_QUIT received in SpinInternalEventLoop!");
+ } else {
+ TranslateMessage(&msg);
+ ::DispatchMessageW(&msg);
+ return;
+ }
+ }
+
+ // Note, give dispatching windows events priority over checking if
+ // mEvent is signaled, otherwise heavy ipc traffic can cause jittery
+ // playback of video. We'll exit out on each disaptch above, so ipc
+ // won't get starved.
+
+ // Wait for UI events or a signal from the io thread.
+ DWORD result =
+ MsgWaitForMultipleObjects(1, &mEvent, FALSE, INFINITE, QS_ALLINPUT);
+ if (result == WAIT_OBJECT_0) {
+ // Our NotifyWorkerThread event was signaled
+ return;
+ }
+ } while (true);
+}
+
+static HHOOK gWindowHook;
+
+static inline void StartNeutering() {
+ if (!gUIThreadId) {
+ mozilla::ipc::windows::InitUIThread();
+ }
+ MOZ_ASSERT(gUIThreadId);
+ MOZ_ASSERT(!gWindowHook);
+ NS_ASSERTION(!MessageChannel::IsPumpingMessages(),
+ "Shouldn't be pumping already!");
+ MessageChannel::SetIsPumpingMessages(true);
+ gWindowHook = ::SetWindowsHookEx(WH_CALLWNDPROC, CallWindowProcedureHook,
+ nullptr, gUIThreadId);
+ NS_ASSERTION(gWindowHook, "Failed to set hook!");
+}
+
+static void StopNeutering() {
+ MOZ_ASSERT(MessageChannel::IsPumpingMessages());
+ ::UnhookWindowsHookEx(gWindowHook);
+ gWindowHook = NULL;
+ ::UnhookNeuteredWindows();
+ // Before returning we need to set a hook to run any deferred messages that
+ // we received during the IPC call. The hook will unset itself as soon as
+ // someone else calls GetMessage, PeekMessage, or runs code that generates
+ // a "nonqueued" message.
+ ::ScheduleDeferredMessageRun();
+ MessageChannel::SetIsPumpingMessages(false);
+}
+
+NeuteredWindowRegion::NeuteredWindowRegion(bool aDoNeuter)
+ : mNeuteredByThis(!gWindowHook && aDoNeuter &&
+ XRE_UseNativeEventProcessing()) {
+ if (mNeuteredByThis) {
+ StartNeutering();
+ }
+}
+
+NeuteredWindowRegion::~NeuteredWindowRegion() {
+ if (gWindowHook && mNeuteredByThis) {
+ StopNeutering();
+ }
+}
+
+void NeuteredWindowRegion::PumpOnce() {
+ if (!gWindowHook) {
+ // This should be a no-op if nothing has been neutered.
+ return;
+ }
+
+ MSG msg = {0};
+ // Pump any COM messages so that we don't hang due to STA marshaling.
+ if (gCOMWindow && ::PeekMessageW(&msg, gCOMWindow, 0, 0, PM_REMOVE)) {
+ ::TranslateMessage(&msg);
+ ::DispatchMessageW(&msg);
+ }
+ // Expunge any nonqueued messages on the current thread.
+ ::PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE);
+}
+
+DeneuteredWindowRegion::DeneuteredWindowRegion()
+ : mReneuter(gWindowHook != NULL) {
+ if (mReneuter) {
+ StopNeutering();
+ }
+}
+
+DeneuteredWindowRegion::~DeneuteredWindowRegion() {
+ if (mReneuter) {
+ StartNeutering();
+ }
+}
+
+SuppressedNeuteringRegion::SuppressedNeuteringRegion()
+ : mReenable(::gUIThreadId == ::GetCurrentThreadId() && ::gWindowHook) {
+ if (mReenable) {
+ MOZ_ASSERT(!sSuppressNeutering);
+ sSuppressNeutering = true;
+ }
+}
+
+SuppressedNeuteringRegion::~SuppressedNeuteringRegion() {
+ if (mReenable) {
+ MOZ_ASSERT(sSuppressNeutering);
+ sSuppressNeutering = false;
+ }
+}
+
+bool SuppressedNeuteringRegion::sSuppressNeutering = false;
+
+bool MessageChannel::WaitForSyncNotify() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ if (!gUIThreadId) {
+ mozilla::ipc::windows::InitUIThread();
+ }
+
+ // Use a blocking wait if this channel does not require
+ // Windows message deferral behavior.
+ if (!(mFlags & REQUIRE_DEFERRED_MESSAGE_PROTECTION)) {
+ TimeDuration timeout = (kNoTimeout == mTimeoutMs)
+ ? TimeDuration::Forever()
+ : TimeDuration::FromMilliseconds(mTimeoutMs);
+
+ MOZ_ASSERT(!mIsSyncWaitingOnNonMainThread);
+ mIsSyncWaitingOnNonMainThread = true;
+
+ CVStatus status = mMonitor->Wait(timeout);
+
+ MOZ_ASSERT(mIsSyncWaitingOnNonMainThread);
+ mIsSyncWaitingOnNonMainThread = false;
+
+ // If the timeout didn't expire, we know we received an event. The
+ // converse is not true.
+ return WaitResponse(status == CVStatus::Timeout);
+ }
+
+ NS_ASSERTION(
+ mFlags & REQUIRE_DEFERRED_MESSAGE_PROTECTION,
+ "Shouldn't be here for channels that don't use message deferral!");
+ NS_ASSERTION(mTopFrame, "No top frame!");
+
+ MonitorAutoUnlock unlock(*mMonitor);
+
+ bool timedout = false;
+
+ UINT_PTR timerId = 0;
+ TimeoutData timeoutData = {0};
+
+ if (mTimeoutMs != kNoTimeout) {
+ InitTimeoutData(&timeoutData, mTimeoutMs);
+
+ // We only do this to ensure that we won't get stuck in
+ // MsgWaitForMultipleObjects below.
+ timerId = SetTimer(nullptr, 0, mTimeoutMs, nullptr);
+ NS_ASSERTION(timerId, "SetTimer failed!");
+ }
+
+ NeuteredWindowRegion neuteredRgn(true);
+
+ {
+ while (1) {
+ MSG msg = {0};
+ // Don't get wrapped up in here if the child connection dies.
+ {
+ MonitorAutoLock lock(*mMonitor);
+ if (!Connected()) {
+ break;
+ }
+ }
+
+ // Wait until we have a message in the queue. MSDN docs are a bit unclear
+ // but it seems that windows from two different threads (and it should be
+ // noted that a thread in another process counts as a "different thread")
+ // will implicitly have their message queues attached if they are parented
+ // to one another. This wait call, then, will return for a message
+ // delivered to *either* thread.
+ DWORD result =
+ MsgWaitForMultipleObjects(1, &mEvent, FALSE, INFINITE, QS_ALLINPUT);
+ if (result == WAIT_OBJECT_0) {
+ // Our NotifyWorkerThread event was signaled
+ BOOL success = ResetEvent(mEvent);
+ if (!success) {
+ gfxDevCrash(mozilla::gfx::LogReason::MessageChannelInvalidHandle)
+ << "WindowsMessageChannel::WaitForSyncNotify failed to reset "
+ "event. GetLastError: "
+ << GetLastError();
+ }
+ break;
+ } else if (result != (WAIT_OBJECT_0 + 1)) {
+ NS_ERROR("Wait failed!");
+ break;
+ }
+
+ if (TimeoutHasExpired(timeoutData)) {
+ // A timeout was specified and we've passed it. Break out.
+ timedout = true;
+ break;
+ }
+
+ // The only way to know on which thread the message was delivered is to
+ // use some logic on the return values of GetQueueStatus and PeekMessage.
+ // PeekMessage will return false if there are no "queued" messages, but it
+ // will run all "nonqueued" messages before returning. So if PeekMessage
+ // returns false and there are no "nonqueued" messages that were run then
+ // we know that the message we woke for was intended for a window on
+ // another thread.
+ bool haveSentMessagesPending =
+ (HIWORD(GetQueueStatus(QS_SENDMESSAGE)) & QS_SENDMESSAGE) != 0;
+
+ // Either of the PeekMessage calls below will actually process all
+ // "nonqueued" messages that are pending before returning. If we have
+ // "nonqueued" messages pending then we should have switched out all the
+ // window procedures above. In that case this PeekMessage call won't
+ // actually cause any mozilla code (or plugin code) to run.
+
+ // We have to manually pump all COM messages *after* looking at the queue
+ // queue status but before yielding our thread below.
+ if (gCOMWindow) {
+ if (PeekMessageW(&msg, gCOMWindow, 0, 0, PM_REMOVE)) {
+ TranslateMessage(&msg);
+ ::DispatchMessageW(&msg);
+ }
+ }
+
+ // If the following PeekMessage call fails to return a message for us (and
+ // returns false) and we didn't run any "nonqueued" messages then we must
+ // have woken up for a message designated for a window in another thread.
+ // If we loop immediately then we could enter a tight loop, so we'll give
+ // up our time slice here to let the child process its message.
+ if (!PeekMessageW(&msg, nullptr, 0, 0, PM_NOREMOVE) &&
+ !haveSentMessagesPending) {
+ // Message was for child, we should wait a bit.
+ SwitchToThread();
+ }
+ }
+ }
+
+ if (timerId) {
+ KillTimer(nullptr, timerId);
+ timerId = 0;
+ }
+
+ return WaitResponse(timedout);
+}
+
+void MessageChannel::NotifyWorkerThread() {
+ mMonitor->AssertCurrentThreadOwns();
+
+ if (mIsSyncWaitingOnNonMainThread) {
+ mMonitor->Notify();
+ return;
+ }
+
+ MOZ_RELEASE_ASSERT(mEvent, "No signal event to set, this is really bad!");
+ if (!SetEvent(mEvent)) {
+ NS_WARNING("Failed to set NotifyWorkerThread event!");
+ gfxDevCrash(mozilla::gfx::LogReason::MessageChannelInvalidHandle)
+ << "WindowsMessageChannel failed to SetEvent. GetLastError: "
+ << GetLastError();
+ }
+}
+
+void DeferredSendMessage::Run() {
+ AssertWindowIsNotNeutered(hWnd);
+ if (!IsWindow(hWnd)) {
+ NS_ERROR("Invalid window!");
+ return;
+ }
+
+ WNDPROC wndproc =
+ reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_WNDPROC));
+ if (!wndproc) {
+ NS_ERROR("Invalid window procedure!");
+ return;
+ }
+
+ CallWindowProc(wndproc, hWnd, message, wParam, lParam);
+}
+
+void DeferredRedrawMessage::Run() {
+ AssertWindowIsNotNeutered(hWnd);
+ if (!IsWindow(hWnd)) {
+ NS_ERROR("Invalid window!");
+ return;
+ }
+
+#ifdef DEBUG
+ BOOL ret =
+#endif
+ RedrawWindow(hWnd, nullptr, nullptr, flags);
+ NS_ASSERTION(ret, "RedrawWindow failed!");
+}
+
+DeferredUpdateMessage::DeferredUpdateMessage(HWND aHWnd) {
+ mWnd = aHWnd;
+ if (!GetUpdateRect(mWnd, &mUpdateRect, FALSE)) {
+ memset(&mUpdateRect, 0, sizeof(RECT));
+ return;
+ }
+ ValidateRect(mWnd, &mUpdateRect);
+}
+
+void DeferredUpdateMessage::Run() {
+ AssertWindowIsNotNeutered(mWnd);
+ if (!IsWindow(mWnd)) {
+ NS_ERROR("Invalid window!");
+ return;
+ }
+
+ InvalidateRect(mWnd, &mUpdateRect, FALSE);
+#ifdef DEBUG
+ BOOL ret =
+#endif
+ UpdateWindow(mWnd);
+ NS_ASSERTION(ret, "UpdateWindow failed!");
+}
+
+DeferredSettingChangeMessage::DeferredSettingChangeMessage(HWND aHWnd,
+ UINT aMessage,
+ WPARAM aWParam,
+ LPARAM aLParam)
+ : DeferredSendMessage(aHWnd, aMessage, aWParam, aLParam) {
+ NS_ASSERTION(aMessage == WM_SETTINGCHANGE, "Wrong message type!");
+ if (aLParam) {
+ lParamString = _wcsdup(reinterpret_cast<const wchar_t*>(aLParam));
+ lParam = reinterpret_cast<LPARAM>(lParamString);
+ } else {
+ lParamString = nullptr;
+ lParam = 0;
+ }
+}
+
+DeferredSettingChangeMessage::~DeferredSettingChangeMessage() {
+ free(lParamString);
+}
+
+DeferredWindowPosMessage::DeferredWindowPosMessage(HWND aHWnd, LPARAM aLParam,
+ bool aForCalcSize,
+ WPARAM aWParam) {
+ if (aForCalcSize) {
+ if (aWParam) {
+ NCCALCSIZE_PARAMS* arg = reinterpret_cast<NCCALCSIZE_PARAMS*>(aLParam);
+ memcpy(&windowPos, arg->lppos, sizeof(windowPos));
+
+ NS_ASSERTION(aHWnd == windowPos.hwnd, "Mismatched hwnds!");
+ } else {
+ RECT* arg = reinterpret_cast<RECT*>(aLParam);
+ windowPos.hwnd = aHWnd;
+ windowPos.hwndInsertAfter = nullptr;
+ windowPos.x = arg->left;
+ windowPos.y = arg->top;
+ windowPos.cx = arg->right - arg->left;
+ windowPos.cy = arg->bottom - arg->top;
+
+ NS_ASSERTION(arg->right >= arg->left && arg->bottom >= arg->top,
+ "Negative width or height!");
+ }
+ windowPos.flags = SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOOWNERZORDER |
+ SWP_NOZORDER | SWP_DEFERERASE | SWP_NOSENDCHANGING;
+ } else {
+ // Not for WM_NCCALCSIZE
+ WINDOWPOS* arg = reinterpret_cast<WINDOWPOS*>(aLParam);
+ memcpy(&windowPos, arg, sizeof(windowPos));
+
+ NS_ASSERTION(aHWnd == windowPos.hwnd, "Mismatched hwnds!");
+
+ // Windows sends in some private flags sometimes that we can't simply copy.
+ // Filter here.
+ UINT mask = SWP_ASYNCWINDOWPOS | SWP_DEFERERASE | SWP_DRAWFRAME |
+ SWP_FRAMECHANGED | SWP_HIDEWINDOW | SWP_NOACTIVATE |
+ SWP_NOCOPYBITS | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREDRAW |
+ SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE |
+ SWP_NOZORDER | SWP_SHOWWINDOW;
+ windowPos.flags &= mask;
+ }
+}
+
+void DeferredWindowPosMessage::Run() {
+ AssertWindowIsNotNeutered(windowPos.hwnd);
+ if (!IsWindow(windowPos.hwnd)) {
+ NS_ERROR("Invalid window!");
+ return;
+ }
+
+ if (!IsWindow(windowPos.hwndInsertAfter)) {
+ NS_WARNING("ZOrder change cannot be honored");
+ windowPos.hwndInsertAfter = 0;
+ windowPos.flags |= SWP_NOZORDER;
+ }
+
+#ifdef DEBUG
+ BOOL ret =
+#endif
+ SetWindowPos(windowPos.hwnd, windowPos.hwndInsertAfter, windowPos.x,
+ windowPos.y, windowPos.cx, windowPos.cy, windowPos.flags);
+ NS_ASSERTION(ret, "SetWindowPos failed!");
+}
+
+DeferredCopyDataMessage::DeferredCopyDataMessage(HWND aHWnd, UINT aMessage,
+ WPARAM aWParam, LPARAM aLParam)
+ : DeferredSendMessage(aHWnd, aMessage, aWParam, aLParam) {
+ NS_ASSERTION(IsWindow(reinterpret_cast<HWND>(aWParam)), "Bad window!");
+
+ COPYDATASTRUCT* source = reinterpret_cast<COPYDATASTRUCT*>(aLParam);
+ NS_ASSERTION(source, "Should never be null!");
+
+ copyData.dwData = source->dwData;
+ copyData.cbData = source->cbData;
+
+ if (source->cbData) {
+ copyData.lpData = malloc(source->cbData);
+ if (copyData.lpData) {
+ memcpy(copyData.lpData, source->lpData, source->cbData);
+ } else {
+ NS_ERROR("Out of memory?!");
+ copyData.cbData = 0;
+ }
+ } else {
+ copyData.lpData = nullptr;
+ }
+
+ lParam = reinterpret_cast<LPARAM>(&copyData);
+}
+
+DeferredCopyDataMessage::~DeferredCopyDataMessage() { free(copyData.lpData); }
+
+DeferredStyleChangeMessage::DeferredStyleChangeMessage(HWND aHWnd,
+ WPARAM aWParam,
+ LPARAM aLParam)
+ : hWnd(aHWnd) {
+ index = static_cast<int>(aWParam);
+ style = reinterpret_cast<STYLESTRUCT*>(aLParam)->styleNew;
+}
+
+void DeferredStyleChangeMessage::Run() { SetWindowLongPtr(hWnd, index, style); }
+
+DeferredSetIconMessage::DeferredSetIconMessage(HWND aHWnd, UINT aMessage,
+ WPARAM aWParam, LPARAM aLParam)
+ : DeferredSendMessage(aHWnd, aMessage, aWParam, aLParam) {
+ NS_ASSERTION(aMessage == WM_SETICON, "Wrong message type!");
+}
+
+void DeferredSetIconMessage::Run() {
+ AssertWindowIsNotNeutered(hWnd);
+ if (!IsWindow(hWnd)) {
+ NS_ERROR("Invalid window!");
+ return;
+ }
+
+ WNDPROC wndproc =
+ reinterpret_cast<WNDPROC>(GetWindowLongPtr(hWnd, GWLP_WNDPROC));
+ if (!wndproc) {
+ NS_ERROR("Invalid window procedure!");
+ return;
+ }
+
+ HICON hOld = reinterpret_cast<HICON>(
+ CallWindowProc(wndproc, hWnd, message, wParam, lParam));
+ if (hOld) {
+ DestroyIcon(hOld);
+ }
+}
diff --git a/ipc/glue/WindowsMessageLoop.h b/ipc/glue/WindowsMessageLoop.h
new file mode 100644
index 0000000000..7fa614279b
--- /dev/null
+++ b/ipc/glue/WindowsMessageLoop.h
@@ -0,0 +1,134 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef IPC_GLUE_WINDOWSMESSAGELOOP_H
+#define IPC_GLUE_WINDOWSMESSAGELOOP_H
+
+// This file is only meant to compile on windows
+#include <windows.h>
+
+#include "nsISupportsImpl.h"
+
+namespace mozilla {
+namespace ipc {
+namespace windows {
+
+void InitUIThread();
+
+class DeferredMessage {
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(DeferredMessage)
+
+ MOZ_COUNTED_DTOR_VIRTUAL(DeferredMessage)
+
+ virtual void Run() = 0;
+};
+
+// Uses CallWndProc to deliver a message at a later time. Messages faked with
+// this class must not have pointers in their wParam or lParam members as they
+// may be invalid by the time the message actually runs.
+class DeferredSendMessage : public DeferredMessage {
+ public:
+ DeferredSendMessage(HWND aHWnd, UINT aMessage, WPARAM aWParam, LPARAM aLParam)
+ : hWnd(aHWnd), message(aMessage), wParam(aWParam), lParam(aLParam) {}
+
+ virtual void Run();
+
+ protected:
+ HWND hWnd;
+ UINT message;
+ WPARAM wParam;
+ LPARAM lParam;
+};
+
+// Uses RedrawWindow to fake several painting-related messages. Flags passed
+// to the constructor go directly to RedrawWindow.
+class DeferredRedrawMessage : public DeferredMessage {
+ public:
+ DeferredRedrawMessage(HWND aHWnd, UINT aFlags) : hWnd(aHWnd), flags(aFlags) {}
+
+ virtual void Run();
+
+ private:
+ HWND hWnd;
+ UINT flags;
+};
+
+// Uses UpdateWindow to generate a WM_PAINT message if needed.
+class DeferredUpdateMessage : public DeferredMessage {
+ public:
+ explicit DeferredUpdateMessage(HWND aHWnd);
+
+ virtual void Run();
+
+ private:
+ HWND mWnd;
+ RECT mUpdateRect;
+};
+
+// This class duplicates a string that may exist in the lParam member of the
+// message.
+class DeferredSettingChangeMessage : public DeferredSendMessage {
+ public:
+ DeferredSettingChangeMessage(HWND aHWnd, UINT aMessage, WPARAM aWParam,
+ LPARAM aLParam);
+
+ ~DeferredSettingChangeMessage();
+
+ private:
+ wchar_t* lParamString;
+};
+
+// This class uses SetWindowPos to fake various size-related messages. Flags
+// passed to the constructor go straight through to SetWindowPos.
+class DeferredWindowPosMessage : public DeferredMessage {
+ public:
+ DeferredWindowPosMessage(HWND aHWnd, LPARAM aLParam,
+ bool aForCalcSize = false, WPARAM aWParam = 0);
+
+ virtual void Run();
+
+ private:
+ WINDOWPOS windowPos;
+};
+
+// This class duplicates a data buffer for a WM_COPYDATA message.
+class DeferredCopyDataMessage : public DeferredSendMessage {
+ public:
+ DeferredCopyDataMessage(HWND aHWnd, UINT aMessage, WPARAM aWParam,
+ LPARAM aLParam);
+
+ ~DeferredCopyDataMessage();
+
+ private:
+ COPYDATASTRUCT copyData;
+};
+
+class DeferredStyleChangeMessage : public DeferredMessage {
+ public:
+ DeferredStyleChangeMessage(HWND aHWnd, WPARAM aWParam, LPARAM aLParam);
+
+ virtual void Run();
+
+ private:
+ HWND hWnd;
+ int index;
+ LONG_PTR style;
+};
+
+class DeferredSetIconMessage : public DeferredSendMessage {
+ public:
+ DeferredSetIconMessage(HWND aHWnd, UINT aMessage, WPARAM aWParam,
+ LPARAM aLParam);
+
+ virtual void Run();
+};
+
+} /* namespace windows */
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* IPC_GLUE_WINDOWSMESSAGELOOP_H */
diff --git a/ipc/glue/components.conf b/ipc/glue/components.conf
new file mode 100644
index 0000000000..34048dbbfa
--- /dev/null
+++ b/ipc/glue/components.conf
@@ -0,0 +1,22 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Headers = [
+ 'mozilla/ipc/ForkServer.h',
+]
+
+Classes = [
+ {
+ 'cid': '{cdb4757f-f51b-40c0-8b38-66d12c3bff7b}',
+ 'contract_ids': ['@mozilla.org/fork-server-launcher;1'],
+ 'singleton': True,
+ 'type': 'mozilla::ipc::ForkServerLauncher',
+ 'headers': ['mozilla/ipc/ForkServiceChild.h'],
+ 'constructor': 'mozilla::ipc::ForkServerLauncher::Create',
+ 'processes': ProcessSelector.MAIN_PROCESS_ONLY,
+ 'categories': {'xpcom-startup': 'Fork Server Launcher'},
+ },
+]
diff --git a/ipc/glue/moz.build b/ipc/glue/moz.build
new file mode 100644
index 0000000000..bb23b29a45
--- /dev/null
+++ b/ipc/glue/moz.build
@@ -0,0 +1,313 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+include("/dom/media/webrtc/third_party_build/webrtc.mozbuild")
+
+EXPORTS += [
+ "nsIIPCSerializableInputStream.h",
+]
+
+EXPORTS.mozilla.ipc += [
+ "AsyncBlockers.h",
+ "BackgroundChild.h",
+ "BackgroundParent.h",
+ "BackgroundStarterChild.h",
+ "BackgroundStarterParent.h",
+ "BackgroundUtils.h",
+ "BigBuffer.h",
+ "BrowserProcessSubThread.h",
+ "ByteBuf.h",
+ "ByteBufUtils.h",
+ "CrashReporterClient.h",
+ "CrashReporterHelper.h",
+ "CrashReporterHost.h",
+ "CrossProcessMutex.h",
+ "CrossProcessSemaphore.h",
+ "DataPipe.h",
+ "Endpoint.h",
+ "EnvironmentMap.h",
+ "FileDescriptor.h",
+ "FileDescriptorUtils.h",
+ "GeckoChildProcessHost.h",
+ "IdleSchedulerChild.h",
+ "IdleSchedulerParent.h",
+ "InputStreamUtils.h",
+ "IOThreadChild.h",
+ "IPCCore.h",
+ "IPCForwards.h",
+ "IPCStreamUtils.h",
+ "IPCTypes.h",
+ "IPDLParamTraits.h",
+ "IPDLStructMember.h",
+ "LaunchError.h",
+ "MessageChannel.h",
+ "MessageLink.h",
+ "MessagePump.h",
+ "Neutering.h",
+ "NodeChannel.h",
+ "NodeController.h",
+ "ProcessChild.h",
+ "ProcessUtils.h",
+ "ProtocolMessageUtils.h",
+ "ProtocolUtils.h",
+ "RandomAccessStreamUtils.h",
+ "RawShmem.h",
+ "ScopedPort.h",
+ "SerializedStructuredCloneBuffer.h",
+ "SharedMemory.h",
+ "SharedMemoryBasic.h",
+ "Shmem.h",
+ "ShmemMessageUtils.h",
+ "SideVariant.h",
+ "TaintingIPCUtils.h",
+ "TaskFactory.h",
+ "ToplevelActorHolder.h",
+ "TransportSecurityInfoUtils.h",
+ "URIUtils.h",
+ "UtilityAudioDecoder.h",
+ "UtilityAudioDecoderChild.h",
+ "UtilityAudioDecoderParent.h",
+ "UtilityProcessChild.h",
+ "UtilityProcessHost.h",
+ "UtilityProcessImpl.h",
+ "UtilityProcessManager.h",
+ "UtilityProcessParent.h",
+ "UtilityProcessSandboxing.h",
+ "WindowsMessageLoop.h",
+]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ SOURCES += [
+ "SharedMemory_windows.cpp",
+ "WindowsMessageLoop.cpp",
+ ]
+else:
+ UNIFIED_SOURCES += [
+ "SharedMemory_posix.cpp",
+ ]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ SOURCES += [
+ "CrossProcessMutex_windows.cpp",
+ ]
+elif not CONFIG["OS_ARCH"] in ("NetBSD", "OpenBSD"):
+ UNIFIED_SOURCES += [
+ "CrossProcessMutex_posix.cpp",
+ ]
+else:
+ UNIFIED_SOURCES += [
+ "CrossProcessMutex_unimplemented.cpp",
+ ]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ SOURCES += [
+ "CrossProcessSemaphore_windows.cpp",
+ ]
+elif CONFIG["OS_ARCH"] == "Darwin":
+ SOURCES += [
+ "CrossProcessSemaphore_mach.cpp",
+ ]
+else:
+ UNIFIED_SOURCES += [
+ "CrossProcessSemaphore_posix.cpp",
+ ]
+
+if CONFIG["OS_ARCH"] == "Darwin":
+ EXPORTS.mozilla.ipc += ["SharedMemoryBasic_mach.h"]
+ SOURCES += [
+ "SharedMemoryBasic_mach.mm",
+ ]
+else:
+ EXPORTS.mozilla.ipc += ["SharedMemoryBasic_chromium.h"]
+
+if CONFIG["OS_ARCH"] == "Linux":
+ UNIFIED_SOURCES += [
+ "ProcessUtils_linux.cpp",
+ "SetProcessTitle.cpp",
+ ]
+ EXPORTS.mozilla.ipc += [
+ "SetProcessTitle.h",
+ ]
+elif CONFIG["OS_ARCH"] in ("DragonFly", "FreeBSD", "NetBSD", "OpenBSD"):
+ UNIFIED_SOURCES += [
+ "ProcessUtils_bsd.cpp",
+ "SetProcessTitle.cpp",
+ ]
+ EXPORTS.mozilla.ipc += [
+ "SetProcessTitle.h",
+ ]
+elif CONFIG["OS_ARCH"] == "Darwin":
+ UNIFIED_SOURCES += ["ProcessUtils_mac.mm"]
+else:
+ UNIFIED_SOURCES += [
+ "ProcessUtils_none.cpp",
+ ]
+
+if CONFIG["OS_ARCH"] != "WINNT":
+ EXPORTS.mozilla.ipc += [
+ "FileDescriptorShuffle.h",
+ ]
+ UNIFIED_SOURCES += [
+ "FileDescriptorShuffle.cpp",
+ ]
+
+EXPORTS.ipc += [
+ "EnumSerializer.h",
+ "IPCMessageUtils.h",
+ "IPCMessageUtilsSpecializations.h",
+]
+
+UNIFIED_SOURCES += [
+ "BackgroundImpl.cpp",
+ "BackgroundUtils.cpp",
+ "BigBuffer.cpp",
+ "BrowserProcessSubThread.cpp",
+ "CrashReporterClient.cpp",
+ "CrashReporterHost.cpp",
+ "DataPipe.cpp",
+ "Endpoint.cpp",
+ "FileDescriptor.cpp",
+ "FileDescriptorUtils.cpp",
+ "IdleSchedulerChild.cpp",
+ "IdleSchedulerParent.cpp",
+ "InputStreamUtils.cpp",
+ "IPCMessageUtilsSpecializations.cpp",
+ "IPCStreamUtils.cpp",
+ "LaunchError.cpp",
+ "MessageChannel.cpp",
+ "MessageLink.cpp",
+ "MessagePump.cpp",
+ "NodeChannel.cpp",
+ "NodeController.cpp",
+ "ProcessChild.cpp",
+ "ProcessUtils_common.cpp",
+ "ProtocolUtils.cpp",
+ "RandomAccessStreamUtils.cpp",
+ "RawShmem.cpp",
+ "ScopedPort.cpp",
+ "SerializedStructuredCloneBuffer.cpp",
+ "SharedMemory.cpp",
+ "Shmem.cpp",
+ "StringUtil.cpp",
+ "TransportSecurityInfoUtils.cpp",
+ "URIUtils.cpp",
+ "UtilityAudioDecoder.cpp",
+ "UtilityAudioDecoderChild.cpp",
+ "UtilityAudioDecoderParent.cpp",
+ "UtilityProcessChild.cpp",
+ "UtilityProcessHost.cpp",
+ "UtilityProcessImpl.cpp",
+ "UtilityProcessManager.cpp",
+ "UtilityProcessParent.cpp",
+ "UtilityProcessSandboxing.cpp",
+]
+
+SOURCES += [
+ "BackgroundChildImpl.cpp",
+ "BackgroundParentImpl.cpp",
+]
+
+if CONFIG["OS_ARCH"] == "Darwin":
+ # GeckoChildProcessHost.cpp cannot be built unified due to OSX header
+ # clashes with TextRange.
+ SOURCES += [
+ "GeckoChildProcessHost.cpp",
+ ]
+else:
+ UNIFIED_SOURCES += [
+ "GeckoChildProcessHost.cpp",
+ ]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ UNIFIED_SOURCES += ["MessagePump_windows.cpp"]
+elif CONFIG["OS_ARCH"] == "Darwin":
+ UNIFIED_SOURCES += ["MessagePump_mac.mm"]
+elif CONFIG["OS_TARGET"] == "Android":
+ UNIFIED_SOURCES += ["MessagePump_android.cpp"]
+
+LOCAL_INCLUDES += [
+ "/caps",
+ "/dom/broadcastchannel",
+ "/dom/indexedDB",
+ "/dom/storage",
+ "/netwerk/base",
+ "/third_party/libwebrtc",
+ "/third_party/libwebrtc/third_party/abseil-cpp",
+ "/tools/fuzzing/ipc",
+ "/xpcom/build",
+]
+
+PREPROCESSED_IPDL_SOURCES = [
+ "PUtilityAudioDecoder.ipdl",
+ "PUtilityProcess.ipdl",
+]
+
+IPDL_SOURCES = [
+ "InputStreamParams.ipdlh",
+ "IPCStream.ipdlh",
+ "PBackground.ipdl",
+ "PBackgroundSharedTypes.ipdlh",
+ "PBackgroundStarter.ipdl",
+ "PBackgroundTest.ipdl",
+ "PIdleScheduler.ipdl",
+ "ProtocolTypes.ipdlh",
+ "RandomAccessStreamParams.ipdlh",
+ "URIParams.ipdlh",
+]
+
+if CONFIG["MOZ_ENABLE_FORKSERVER"]:
+ EXPORTS.mozilla.ipc += [
+ "ForkServer.h",
+ "ForkServiceChild.h",
+ "MiniTransceiver.h",
+ ]
+ UNIFIED_SOURCES += [
+ "ForkServer.cpp",
+ "ForkServiceChild.cpp",
+ "MiniTransceiver.cpp",
+ ]
+ XPCOM_MANIFESTS += [
+ "components.conf",
+ ]
+
+LOCAL_INCLUDES += [
+ "/dom/ipc",
+ "/toolkit/crashreporter",
+ "/toolkit/xre",
+ "/xpcom/base",
+ "/xpcom/threads",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
+
+if CONFIG["OS_ARCH"] == "Darwin":
+ OS_LIBS += ["bsm"] # for audit_token_to_pid
+
+for var in (
+ "MOZ_CHILD_PROCESS_NAME",
+ "MOZ_CHILD_PROCESS_BUNDLENAME",
+ "MOZ_EME_PROCESS_NAME_BRANDED",
+ "MOZ_EME_PROCESS_BUNDLENAME",
+):
+ DEFINES[var] = '"%s"' % CONFIG[var]
+
+if CONFIG["MOZ_SANDBOX"] and CONFIG["OS_ARCH"] == "WINNT":
+ LOCAL_INCLUDES += [
+ "/security/sandbox/chromium",
+ "/security/sandbox/chromium-shim",
+ "/security/sandbox/win/src/sandboxbroker",
+ ]
+
+if CONFIG["ENABLE_TESTS"]:
+ DIRS += [
+ "test/gtest",
+ "test/utility_process_xpcom",
+ "test/browser",
+ ]
+
+# Add libFuzzer configuration directives
+include("/tools/fuzzing/libfuzzer-config.mozbuild")
diff --git a/ipc/glue/nsIIPCSerializableInputStream.h b/ipc/glue/nsIIPCSerializableInputStream.h
new file mode 100644
index 0000000000..acc7594f66
--- /dev/null
+++ b/ipc/glue/nsIIPCSerializableInputStream.h
@@ -0,0 +1,104 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_ipc_nsIIPCSerializableInputStream_h
+#define mozilla_ipc_nsIIPCSerializableInputStream_h
+
+#include "mozilla/Attributes.h"
+#include "mozilla/Maybe.h"
+#include "nsISupports.h"
+#include "nsTArrayForwardDeclare.h"
+
+namespace mozilla {
+namespace ipc {
+
+class FileDescriptor;
+class InputStreamParams;
+
+} // namespace ipc
+
+} // namespace mozilla
+
+#define NS_IIPCSERIALIZABLEINPUTSTREAM_IID \
+ { \
+ 0xb0211b14, 0xea6d, 0x40d4, { \
+ 0x87, 0xb5, 0x7b, 0xe3, 0xdf, 0xac, 0x09, 0xd1 \
+ } \
+ }
+
+class NS_NO_VTABLE nsIIPCSerializableInputStream : public nsISupports {
+ public:
+ NS_DECLARE_STATIC_IID_ACCESSOR(NS_IIPCSERIALIZABLEINPUTSTREAM_IID)
+
+ // Determine the serialized complexity of this input stream, initializing
+ // `*aSizeUsed`, `*aPipes` and `*aTransferables` to the number of inline
+ // bytes/pipes/transferable resources which would be used. This will be used
+ // by other `Serialize` implementations to potentially simplify the resulting
+ // stream, reducing the number of pipes or file descriptors required.
+ //
+ // Each outparameter corresponds to a type of resource which will be included
+ // in the serialized message, as follows:
+ //
+ // *aSizeUsed:
+ // Raw bytes to be included inline in the message's payload, usually in the
+ // form of a nsCString for a StringInputStreamParams. This must be less
+ // than or equal to `aMaxSize`. Larger payloads should instead be
+ // serialized using SerializeInputStreamAsPipe.
+ // *aPipes:
+ // New pipes, created using SerializeInputStreamAsPipe, which will be used
+ // to asynchronously transfer part of the pipe over IPC. Callers such as
+ // nsMultiplexInputStream may choose to serialize themselves as a DataPipe
+ // if they contain DataPipes themselves, so existing DataPipe instances
+ // which are cheaply transferred should be counted as transferrables.
+ // *aTransferables:
+ // Existing objects which can be more cheaply transferred over IPC than by
+ // serializing them inline in a payload or transferring them through a new
+ // DataPipe. This includes RemoteLazyInputStreams, FileDescriptors, and
+ // existing DataPipeReceiver instances.
+ //
+ // Callers of this method must have initialized all of `*aSizeUsed`,
+ // `*aPipes`, and `*aTransferables` to 0, so implementations are not required
+ // to initialize all outparameters. The outparameters must not be null.
+ virtual void SerializedComplexity(uint32_t aMaxSize, uint32_t* aSizeUsed,
+ uint32_t* aPipes,
+ uint32_t* aTransferables) = 0;
+
+ virtual void Serialize(mozilla::ipc::InputStreamParams& aParams,
+ uint32_t aMaxSize, uint32_t* aSizeUsed) = 0;
+
+ virtual bool Deserialize(const mozilla::ipc::InputStreamParams& aParams) = 0;
+};
+
+NS_DEFINE_STATIC_IID_ACCESSOR(nsIIPCSerializableInputStream,
+ NS_IIPCSERIALIZABLEINPUTSTREAM_IID)
+
+#define NS_DECL_NSIIPCSERIALIZABLEINPUTSTREAM \
+ virtual void SerializedComplexity(uint32_t aMaxSize, uint32_t* aSizeUsed, \
+ uint32_t* aPipes, \
+ uint32_t* aTransferrables) override; \
+ virtual void Serialize(mozilla::ipc::InputStreamParams&, uint32_t, \
+ uint32_t*) override; \
+ \
+ virtual bool Deserialize(const mozilla::ipc::InputStreamParams&) override;
+
+#define NS_FORWARD_NSIIPCSERIALIZABLEINPUTSTREAM(_to) \
+ virtual void SerializedComplexity(uint32_t aMaxSize, uint32_t* aSizeUsed, \
+ uint32_t* aPipes, \
+ uint32_t* aTransferables) override { \
+ _to SerializedComplexity(aMaxSize, aSizeUsed, aPipes, aTransferables); \
+ }; \
+ \
+ virtual void Serialize(mozilla::ipc::InputStreamParams& aParams, \
+ uint32_t aMaxSize, uint32_t* aSizeUsed) override { \
+ _to Serialize(aParams, aMaxSize, aSizeUsed); \
+ } \
+ \
+ virtual bool Deserialize(const mozilla::ipc::InputStreamParams& aParams) \
+ override { \
+ return _to Deserialize(aParams); \
+ }
+
+#endif // mozilla_ipc_nsIIPCSerializableInputStream_h
diff --git a/ipc/glue/test/browser/browser.toml b/ipc/glue/test/browser/browser.toml
new file mode 100644
index 0000000000..8f94bc130d
--- /dev/null
+++ b/ipc/glue/test/browser/browser.toml
@@ -0,0 +1,94 @@
+[DEFAULT]
+support-files = ["head.js"]
+# Set this since we want to continue monitoring the disabling of pref since we
+# still allow it a little bit.
+environment = "MOZ_DONT_LOCK_UTILITY_PLZ_FILE_A_BUG=1"
+
+["browser_audio_telemetry_content.js"]
+skip-if = ["os == 'win'"] # gfx blocks us because media.rdd-process.enabled=false disables PDMFactory::AllDecodersAreRemote()
+support-files = [
+ "head-telemetry.js",
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac"
+]
+
+["browser_audio_telemetry_rdd.js"]
+support-files = [
+ "head-telemetry.js",
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac"
+]
+
+["browser_audio_telemetry_utility.js"]
+support-files = [
+ "head-telemetry.js",
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac"
+]
+
+["browser_audio_telemetry_utility_EME.js"]
+support-files = [
+ "head-telemetry.js",
+ "../../../../dom/media/test/eme_standalone.js",
+ "../../../../dom/media/test/short-aac-encrypted-audio.mp4"
+]
+
+["browser_utility_audioDecodeCrash.js"]
+support-files = [
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac"
+]
+skip-if = [
+ "!crashreporter",
+ "ccov",
+]
+
+["browser_utility_crashReporter.js"]
+skip-if = [
+ "!crashreporter",
+ "ccov",
+]
+
+["browser_utility_filepicker_crashed.js"]
+run-if = ["os == 'win'"]
+skip-if = [
+ "!crashreporter",
+ "ccov",
+]
+
+["browser_utility_geolocation_crashed.js"]
+run-if = ["os == 'win'"]
+skip-if = [
+ "!crashreporter",
+ "ccov",
+]
+
+["browser_utility_hard_kill.js"]
+
+["browser_utility_hard_kill_delayed.js"] # bug 1754572: we really want hard_kill to be rust before hard_kill_delayed
+
+["browser_utility_memoryReport.js"]
+skip-if = ["tsan"] # bug 1754554
+
+["browser_utility_multipleAudio.js"]
+support-files = [
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac",
+ "head-multiple.js"
+]
+
+["browser_utility_profiler.js"]
+support-files = ["../../../../tools/profiler/tests/shared-head.js"]
+skip-if = ["tsan"] # from tools/profiler/tests/browser/browser.ini, timing out on profiler tests?
+
+["browser_utility_start_clean_shutdown.js"]
diff --git a/ipc/glue/test/browser/browser_audio_fallback.toml b/ipc/glue/test/browser/browser_audio_fallback.toml
new file mode 100644
index 0000000000..0de2a1c9e7
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_fallback.toml
@@ -0,0 +1,17 @@
+[DEFAULT]
+support-files = [
+ "head.js",
+ "head-multiple.js",
+]
+prefs = ["media.allow-audio-non-utility=true"]
+# Set this since we want to continue monitoring the disabling of pref since we
+# still allow it a little bit.
+environment = "MOZ_DONT_LOCK_UTILITY_PLZ_FILE_A_BUG=1"
+
+["browser_utility_multipleAudio_fallback.js"]
+support-files = [
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac",
+]
diff --git a/ipc/glue/test/browser/browser_audio_fallback_content.toml b/ipc/glue/test/browser/browser_audio_fallback_content.toml
new file mode 100644
index 0000000000..3efc6409ac
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_fallback_content.toml
@@ -0,0 +1,17 @@
+[DEFAULT]
+support-files = [
+ "head.js",
+ "head-multiple.js",
+]
+prefs = [
+ "media.allow-audio-non-utility=true",
+ "media.rdd-process.enabled=false",
+]
+
+["browser_utility_multipleAudio_fallback_content.js"]
+support-files = [
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac",
+]
diff --git a/ipc/glue/test/browser/browser_audio_locked.toml b/ipc/glue/test/browser/browser_audio_locked.toml
new file mode 100644
index 0000000000..9f0607bf5f
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_locked.toml
@@ -0,0 +1,3 @@
+[DEFAULT]
+
+["browser_utility_audio_locked.js"]
diff --git a/ipc/glue/test/browser/browser_audio_shutdown.toml b/ipc/glue/test/browser/browser_audio_shutdown.toml
new file mode 100644
index 0000000000..f99fff7830
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_shutdown.toml
@@ -0,0 +1,5 @@
+[DEFAULT]
+support-files = ["head.js"]
+
+["browser_utility_audio_shutdown.js"]
+support-files = ["../../../../dom/media/test/small-shot.ogg"]
diff --git a/ipc/glue/test/browser/browser_audio_telemetry_content.js b/ipc/glue/test/browser/browser_audio_telemetry_content.js
new file mode 100644
index 0000000000..89f5126794
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_telemetry_content.js
@@ -0,0 +1,39 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-telemetry.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-telemetry.js",
+ this
+);
+
+add_setup(async function testNoTelemetry() {
+ await Telemetry.clearScalars();
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.allow-audio-non-utility", true]],
+ });
+});
+
+add_task(async function testAudioDecodingInContent() {
+ await runTest({ expectUtility: false, expectRDD: false });
+});
+
+add_task(async function testContentTelemetry() {
+ const codecs = ["vorbis", "mp3", "aac", "flac"];
+ const extraKey = getExtraKey({
+ rddPref: false,
+ utilityPref: false,
+ allowNonUtility: true,
+ });
+ await verifyTelemetryForProcess("tab", codecs, extraKey);
+
+ const platform = Services.appinfo.OS;
+ for (let exp of utilityPerCodecs[platform]) {
+ await verifyNoTelemetryForProcess(exp.process, exp.codecs, extraKey);
+ }
+
+ await verifyNoTelemetryForProcess("rdd", codecs, extraKey);
+});
diff --git a/ipc/glue/test/browser/browser_audio_telemetry_rdd.js b/ipc/glue/test/browser/browser_audio_telemetry_rdd.js
new file mode 100644
index 0000000000..ec0944303b
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_telemetry_rdd.js
@@ -0,0 +1,36 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-telemetry.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-telemetry.js",
+ this
+);
+
+add_setup(async function testNoTelemetry() {
+ await Telemetry.clearScalars();
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.allow-audio-non-utility", true]],
+ });
+});
+
+add_task(async function testAudioDecodingInRDD() {
+ await runTest({ expectUtility: false, expectRDD: true });
+});
+
+add_task(async function testRDDTelemetry() {
+ const extraKey = getExtraKey({
+ rddPref: true,
+ utilityPref: false,
+ allowNonUtility: true,
+ });
+ const platform = Services.appinfo.OS;
+ for (let exp of utilityPerCodecs[platform]) {
+ await verifyNoTelemetryForProcess(exp.process, exp.codecs, extraKey);
+ }
+ const codecs = ["vorbis", "mp3", "aac", "flac"];
+ await verifyTelemetryForProcess("rdd", codecs, extraKey);
+});
diff --git a/ipc/glue/test/browser/browser_audio_telemetry_utility.js b/ipc/glue/test/browser/browser_audio_telemetry_utility.js
new file mode 100644
index 0000000000..e121c89049
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_telemetry_utility.js
@@ -0,0 +1,32 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-telemetry.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-telemetry.js",
+ this
+);
+
+add_setup(async function testNoTelemetry() {
+ await Telemetry.clearScalars();
+});
+
+add_task(async function testAudioDecodingInUtility() {
+ await runTest({ expectUtility: true, expectRDD: true });
+});
+
+add_task(async function testUtilityTelemetry() {
+ const platform = Services.appinfo.OS;
+ const extraKey = getExtraKey({ rddPref: true, utilityPref: true });
+ for (let exp of utilityPerCodecs[platform]) {
+ await verifyTelemetryForProcess(exp.process, exp.codecs, extraKey);
+ }
+ await verifyNoTelemetryForProcess(
+ "rdd",
+ ["vorbis", "mp3", "aac", "flac"],
+ extraKey
+ );
+});
diff --git a/ipc/glue/test/browser/browser_audio_telemetry_utility_EME.js b/ipc/glue/test/browser/browser_audio_telemetry_utility_EME.js
new file mode 100644
index 0000000000..7d2e9a4e78
--- /dev/null
+++ b/ipc/glue/test/browser/browser_audio_telemetry_utility_EME.js
@@ -0,0 +1,31 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-telemetry.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-telemetry.js",
+ this
+);
+
+SimpleTest.requestCompleteLog();
+
+add_setup(async function testNoTelemetry() {
+ await Telemetry.clearScalars();
+});
+
+add_task(async function testAudioDecodingInUtility() {
+ await runTestWithEME();
+});
+
+add_task(async function testUtilityTelemetry() {
+ const platform = Services.appinfo.OS;
+ const extraKey = getExtraKey({ rddPref: true, utilityPref: true });
+ for (let exp of utilityPerCodecs[platform]) {
+ if (exp.codecs.includes("aac")) {
+ await verifyTelemetryForProcess(exp.process, ["aac"], extraKey);
+ }
+ }
+});
diff --git a/ipc/glue/test/browser/browser_child_hang.js b/ipc/glue/test/browser/browser_child_hang.js
new file mode 100644
index 0000000000..cf890a6c61
--- /dev/null
+++ b/ipc/glue/test/browser/browser_child_hang.js
@@ -0,0 +1,37 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+//
+// Try to open a tab. This provides code coverage for a few things,
+// although currently there's no automated functional test of correctness:
+//
+// * On opt builds, when the tab is closed and the process exits, it
+// will hang for 3s and the parent will kill it after 2s.
+//
+// * On debug[*] builds, the parent process will wait until the
+// process exits normally; but also, on browser shutdown, the
+// preallocated content processes will block parent shutdown in
+// WillDestroyCurrentMessageLoop.
+//
+// [*] Also sanitizer and code coverage builds.
+//
+
+add_task(async function () {
+ await BrowserTestUtils.withNewTab(
+ {
+ gBrowser,
+ url: "https://example.com/",
+ forceNewProcess: true,
+ },
+ async function (browser) {
+ // browser.frameLoader.remoteTab.osPid is the child pid; once we
+ // have a way to get notifications about child process termination
+ // events, that could be useful.
+ ok(true, "Browser isn't broken");
+ }
+ );
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ await new Promise(resolve => setTimeout(resolve, 4000));
+ ok(true, "Still running after child process (hopefully) exited");
+});
diff --git a/ipc/glue/test/browser/browser_child_hang.toml b/ipc/glue/test/browser/browser_child_hang.toml
new file mode 100644
index 0000000000..ddc8b95670
--- /dev/null
+++ b/ipc/glue/test/browser/browser_child_hang.toml
@@ -0,0 +1,7 @@
+# Any copyright is dedicated to the Public Domain.
+# http://creativecommons.org/publicdomain/zero/1.0/
+[DEFAULT]
+tags = "ipc"
+environment = "MOZ_TEST_CHILD_EXIT_HANG=3"
+
+["browser_child_hang.js"]
diff --git a/ipc/glue/test/browser/browser_utility_audioDecodeCrash.js b/ipc/glue/test/browser/browser_utility_audioDecodeCrash.js
new file mode 100644
index 0000000000..1c7551c623
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_audioDecodeCrash.js
@@ -0,0 +1,95 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function getAudioDecoderPid(expectation) {
+ info("Finding a running AudioDecoder");
+
+ const actor = expectation.replace("Utility ", "");
+
+ let audioDecoderProcess = (await ChromeUtils.requestProcInfo()).children.find(
+ p =>
+ p.type === "utility" &&
+ p.utilityActors.find(a => a.actorName === `audioDecoder_${actor}`)
+ );
+ ok(
+ audioDecoderProcess,
+ `Found the AudioDecoder ${actor} process at ${audioDecoderProcess.pid}`
+ );
+ return audioDecoderProcess.pid;
+}
+
+async function crashDecoder(expectation) {
+ const audioPid = await getAudioDecoderPid(expectation);
+ ok(audioPid > 0, `Found an audio decoder ${audioPid}`);
+ const actorIsAudioDecoder = actorNames => {
+ return actorNames
+ .split(",")
+ .some(actorName => actorName.trim().startsWith("audio-decoder-"));
+ };
+ info(`Crashing audio decoder ${audioPid}`);
+ await crashSomeUtility(audioPid, actorIsAudioDecoder);
+}
+
+async function runTest(src, withClose, expectation) {
+ info(`Add media tabs: ${src}`);
+ let tab = await addMediaTab(src);
+
+ info("Play tab");
+ await play(tab, expectation.process, expectation.decoder);
+
+ info("Crash decoder");
+ await crashDecoder(expectation.process);
+
+ if (withClose) {
+ info("Stop tab");
+ await stop(tab);
+
+ info("Remove tab");
+ await BrowserTestUtils.removeTab(tab);
+
+ info("Create tab again");
+ tab = await addMediaTab(src);
+ }
+
+ info("Play tab again");
+ await play(tab, expectation.process, expectation.decoder);
+
+ info("Stop tab");
+ await stop(tab);
+
+ info("Remove tab");
+ await BrowserTestUtils.removeTab(tab);
+}
+
+add_setup(async function setup() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.utility-process.enabled", true]],
+ });
+});
+
+async function testAudioCrash(withClose) {
+ info(`Running tests for audio decoder process crashing: ${withClose}`);
+
+ SimpleTest.expectChildProcessCrash();
+
+ const platform = Services.appinfo.OS;
+
+ for (let { src, expectations } of audioTestData()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ await runTest(src, withClose, expectations[platform]);
+ }
+}
+
+add_task(async function testAudioCrashSimple() {
+ await testAudioCrash(false);
+});
+
+add_task(async function testAudioCrashClose() {
+ await testAudioCrash(true);
+});
diff --git a/ipc/glue/test/browser/browser_utility_audio_locked.js b/ipc/glue/test/browser/browser_utility_audio_locked.js
new file mode 100644
index 0000000000..4be22de425
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_audio_locked.js
@@ -0,0 +1,28 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-multiple.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-multiple.js",
+ this
+);
+
+add_setup(async function setup() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.utility-process.enabled", false]],
+ });
+});
+
+add_task(async function testAudioDecodingInUtility() {
+ // TODO: When getting rid of audio decoding on non utility at all, this
+ // should be removed
+ // We only lock the preference in Nightly builds so far, but on beta we expect
+ // audio decoding error
+ await runTest({
+ expectUtility: isNightlyOnly(),
+ expectError: !isNightlyOnly(),
+ });
+});
diff --git a/ipc/glue/test/browser/browser_utility_audio_shutdown.js b/ipc/glue/test/browser/browser_utility_audio_shutdown.js
new file mode 100644
index 0000000000..a0a4be63f6
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_audio_shutdown.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+// The purpose of that test is to reproduce edge case behaviors that one can
+// have while running whole ipc/glue/test/browser/ suite but that could this
+// way be intermittent and hard to diagnose. By having such a test we make sure
+// it is cleanly reproduced and wont regress somewhat silently.
+
+"use strict";
+
+async function runTest(src, process, decoder) {
+ info(`Add media tabs: ${src}`);
+ let tab = await addMediaTab(src);
+
+ info("Play tab");
+ await play(tab, process, decoder);
+
+ info("Stop tab");
+ await stop(tab);
+
+ info("Remove tab");
+ await BrowserTestUtils.removeTab(tab);
+}
+
+async function findGenericAudioDecoder() {
+ const audioDecoders = (await ChromeUtils.requestProcInfo()).children.filter(
+ p => {
+ return (
+ p.type === "utility" &&
+ p.utilityActors.find(a => a.actorName === "audioDecoder_Generic")
+ );
+ }
+ );
+ ok(audioDecoders.length === 1, "Only one audio decoder present");
+ return audioDecoders[0].pid;
+}
+
+add_setup(async function setup() {
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.utility-process.enabled", true]],
+ });
+});
+
+add_task(async function testKill() {
+ await runTest("small-shot.ogg", "Utility Generic", "ffvpx audio decoder");
+
+ await cleanUtilityProcessShutdown(
+ "audioDecoder_Generic",
+ true /* preferKill */
+ );
+
+ info("Waiting 15s to trigger mShutdownBlockers assertions");
+ await new Promise((resolve, reject) => {
+ /* eslint-disable mozilla/no-arbitrary-setTimeout */
+ setTimeout(resolve, 15 * 1000);
+ });
+
+ ok(true, "Waited 15s to trigger mShutdownBlockers assertions: over");
+});
+
+add_task(async function testShutdown() {
+ await runTest("small-shot.ogg", "Utility Generic", "ffvpx audio decoder");
+
+ const audioDecoderPid = await findGenericAudioDecoder();
+ ok(audioDecoderPid > 0, `Valid PID found: ${audioDecoderPid}`);
+
+ await cleanUtilityProcessShutdown("audioDecoder_Generic");
+
+ info("Waiting 15s to trigger mShutdownBlockers assertions");
+ await new Promise((resolve, reject) => {
+ /* eslint-disable mozilla/no-arbitrary-setTimeout */
+ setTimeout(resolve, 15 * 1000);
+ });
+
+ ok(true, "Waited 15s to trigger mShutdownBlockers assertions: over");
+});
diff --git a/ipc/glue/test/browser/browser_utility_crashReporter.js b/ipc/glue/test/browser/browser_utility_crashReporter.js
new file mode 100644
index 0000000000..73e6c6355a
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_crashReporter.js
@@ -0,0 +1,34 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function startAndCrashUtility(numUnknownActors, actorsCheck) {
+ const actors = Array(numUnknownActors).fill("unknown");
+ const utilityPid = await startUtilityProcess(actors);
+ await crashSomeUtility(utilityPid, actorsCheck);
+}
+
+// When running full suite, previous tests may have left some utility
+// processes running and this might interfere with our testing.
+add_setup(async function ensureNoExistingProcess() {
+ await killUtilityProcesses();
+});
+
+add_task(async function utilityNoActor() {
+ await startAndCrashUtility(0, actorNames => {
+ return actorNames === undefined;
+ });
+});
+
+add_task(async function utilityOneActor() {
+ await startAndCrashUtility(1, actorNames => {
+ return actorNames === kGenericUtilityActor;
+ });
+});
+
+add_task(async function utilityManyActors() {
+ await startAndCrashUtility(42, actorNames => {
+ return actorNames === Array(42).fill("unknown").join(", ");
+ });
+});
diff --git a/ipc/glue/test/browser/browser_utility_filepicker_crashed.js b/ipc/glue/test/browser/browser_utility_filepicker_crashed.js
new file mode 100644
index 0000000000..e8eb83cf30
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_filepicker_crashed.js
@@ -0,0 +1,170 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+SimpleTest.requestCompleteLog();
+
+// Wait until the child process with the given PID has indeed been terminated.
+//
+// Note that `checkUtilityExists`, and other functions deriving from the output
+// of `ChromeUtils.requestProcInfo()`, do not suffice for this purpose! It is an
+// attested failure mode that the file-dialog utility process has been removed
+// from the proc-info list, but is still live with the file-picker dialog still
+// displayed.
+function untilChildProcessDead(pid) {
+ return utilityProcessTest().untilChildProcessDead(pid);
+}
+
+async function fileDialogProcessExists() {
+ return !!(await tryGetUtilityPid("windowsFileDialog"));
+}
+
+// Poll for the creation of a file dialog process.
+function untilFileDialogProcessExists(options = { maxTime: 2000 }) {
+ // milliseconds
+ const maxTime = options.maxTime ?? 2000,
+ pollTime = options.pollTime ?? 100;
+ const count = maxTime / pollTime;
+
+ return TestUtils.waitForCondition(
+ () => tryGetUtilityPid("windowsFileDialog", { quiet: true }),
+ "waiting for file dialog process",
+ pollTime, // interval
+ count // maxTries
+ );
+}
+
+function openFileDialog() {
+ const process = (async () => {
+ await untilFileDialogProcessExists();
+ let pid = await tryGetUtilityPid("windowsFileDialog");
+ ok(pid, `pid should be acquired in openFileDialog::process (got ${pid})`);
+ // HACK: Wait briefly for the file dialog to open.
+ //
+ // If this is not done, we may attempt to crash the process while it's in
+ // the middle of creating and showing the file dialog window. There _should_
+ // be no problem with this, but `::MiniDumpWriteDump()` occasionally fails
+ // with mysterious errors (`ERROR_BAD_LENGTH`) if we crashed the process
+ // while that was happening, yielding no minidump and therefore a failing
+ // test.
+ //
+ // Use of an arbitrary timeout could presumably be avoided by setting a
+ // window hook for the file dialog being shown and `await`ing on that.
+ //
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ await new Promise(res => setTimeout(res, 1000));
+ return pid;
+ })();
+
+ const file = new Promise((resolve, reject) => {
+ info("Opening Windows file dialog");
+ let fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
+ fp.init(window, "Test: browser_utility_filepicker_crashed.js", fp.modeOpen);
+ fp.open(result => {
+ ok(
+ result == fp.returnCancel,
+ "filepicker should resolve to cancellation"
+ );
+ resolve();
+ });
+ });
+
+ return { process, file };
+}
+
+add_setup(async function () {
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ // remote, no fallback
+ ["widget.windows.utility_process_file_picker", 2],
+ ],
+ });
+});
+
+function makeTask(description, Describe, action) {
+ let task = async function () {
+ if (await fileDialogProcessExists()) {
+ // If this test proceeds, it will probably cause whatever other test has a
+ // file dialog open to fail.
+ //
+ // (We shouldn't be running two such tests in parallel on the same Fx
+ // instance, but that's not obvious at this level.)
+ ok(false, "another test has a file dialog open; aborting");
+ return;
+ }
+
+ const { process, file } = openFileDialog();
+ const pid = await process;
+ const untilDead = untilChildProcessDead(pid);
+
+ info(Describe + " the file-dialog utility process");
+ await action();
+
+ // the file-picker's callback should have been promptly cancelled
+ const _before = Date.now();
+ await file;
+ const _after = Date.now();
+ const delta = _after - _before;
+ info(`file callback resolved after ${description} after ${delta}ms`);
+
+ // depending on the test configuration, this may take some time while
+ // cleanup occurs
+ await untilDead;
+ };
+
+ // give this task a legible name
+ Object.defineProperty(task, "name", {
+ value: "testFileDialogProcess-" + Describe.replace(" ", ""),
+ });
+
+ return task;
+}
+
+for (let [description, Describe, action] of [
+ ["crash", "Crash", () => crashSomeUtilityActor("windowsFileDialog")],
+ [
+ "being killed",
+ "Kill",
+ () => cleanUtilityProcessShutdown("windowsFileDialog", true),
+ ],
+ // Unfortunately, a controlled shutdown doesn't actually terminate the utility
+ // process; the file dialog remains open. (This is expected to be resolved with
+ // bug 1837008.)
+ /* [
+ "shutdown",
+ "Shut down",
+ () => cleanUtilityProcessShutdown("windowsFileDialog"),
+ ] */
+]) {
+ add_task(makeTask(description, Describe, action));
+ add_task(testCleanup);
+}
+
+async function testCleanup() {
+ const killFileDialogProcess = async () => {
+ if (await tryGetUtilityPid("windowsFileDialog", { quiet: true })) {
+ await cleanUtilityProcessShutdown("windowsFileDialog", true);
+ return true;
+ }
+ return false;
+ };
+
+ // If a test failure occurred, the file dialog process may or may not already
+ // exist...
+ if (await killFileDialogProcess()) {
+ console.warn("File dialog process found and killed");
+ return;
+ }
+
+ // ... and if not, may or may not be pending creation.
+ info("Active file dialog process not found; waiting...");
+ try {
+ await untilFileDialogProcessExists({ maxTime: 1000 });
+ } catch (e) {
+ info("File dialog process not found during cleanup (as expected)");
+ return;
+ }
+ await killFileDialogProcess();
+ console.warn("Delayed file dialog process found and killed");
+}
diff --git a/ipc/glue/test/browser/browser_utility_geolocation_crashed.js b/ipc/glue/test/browser/browser_utility_geolocation_crashed.js
new file mode 100644
index 0000000000..b0c341b69f
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_geolocation_crashed.js
@@ -0,0 +1,70 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function getGeolocation() {
+ info("Requesting geolocation");
+
+ let resolve;
+ let promise = new Promise((_resolve, _reject) => {
+ resolve = _resolve;
+ });
+
+ navigator.geolocation.getCurrentPosition(
+ () => {
+ ok(true, "geolocation succeeded");
+ resolve(undefined);
+ },
+ () => {
+ ok(false, "geolocation failed");
+ resolve(undefined);
+ }
+ );
+
+ return promise;
+}
+
+add_setup(async function () {
+ // Avoid the permission doorhanger and cache that would trigger instead
+ // of re-requesting location. Setting geo.timeout to 0 causes it to
+ // retry the system geolocation (incl. recreating the utility process)
+ // instead of reusing the MLS geolocation fallback it found the first time.
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["geo.prompt.testing", true],
+ ["geo.prompt.testing.allow", true],
+ ["geo.provider.network.debug.requestCache.enabled", false],
+ ["geo.provider.testing", false],
+ ["geo.timeout", 0],
+ ],
+ });
+});
+
+add_task(async function testGeolocationProcessCrash() {
+ info("Start the Windows utility process");
+ await getGeolocation();
+
+ info("Crash the utility process");
+ await crashSomeUtilityActor("windowsUtils");
+
+ info("Restart the Windows utility process");
+ await getGeolocation();
+
+ info("Confirm the restarted process");
+ await checkUtilityExists("windowsUtils");
+
+ info("Kill the utility process");
+ await cleanUtilityProcessShutdown("windowsUtils", true);
+
+ info("Restart the Windows utility process again");
+ await getGeolocation();
+
+ info("Confirm the restarted process");
+ await checkUtilityExists("windowsUtils");
+});
+
+add_task(async function testCleanup() {
+ info("Clean up to avoid confusing future tests");
+ await cleanUtilityProcessShutdown("windowsUtils", true);
+});
diff --git a/ipc/glue/test/browser/browser_utility_hard_kill.js b/ipc/glue/test/browser/browser_utility_hard_kill.js
new file mode 100644
index 0000000000..516ef64045
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_hard_kill.js
@@ -0,0 +1,13 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async () => {
+ await startUtilityProcess(["unknown"]);
+
+ SimpleTest.expectChildProcessCrash();
+
+ info("Hard kill Utility Process");
+ await cleanUtilityProcessShutdown("unknown", true /* preferKill */);
+});
diff --git a/ipc/glue/test/browser/browser_utility_hard_kill_delayed.js b/ipc/glue/test/browser/browser_utility_hard_kill_delayed.js
new file mode 100644
index 0000000000..ffda4d3988
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_hard_kill_delayed.js
@@ -0,0 +1,57 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async () => {
+ const utilityPid = await startUtilityProcess();
+
+ SimpleTest.expectChildProcessCrash();
+
+ const utilityProcessGone = TestUtils.topicObserved("ipc:utility-shutdown");
+
+ info("Hard kill Utility Process");
+ const ProcessTools = Cc["@mozilla.org/processtools-service;1"].getService(
+ Ci.nsIProcessToolsService
+ );
+
+ // Here we really want to exercise the fact that kill() might not be done
+ // right now but a bit later, and we should wait for the process to be dead
+ // before considering the test is finished.
+ //
+ // Without this, we get into bug 1754572 (where there was no setTimeout nor
+ // the wait) where the kill() operation ends up really killing the child a
+ // bit after the current test has been finished ; unfortunately, this happened
+ // right after the next test, browser_utility_memoryReport.js did start and
+ // even worse, after it thought it had started a new utility process. We were
+ // in fact re-using the one we started here, and when we wanted to query its
+ // pid in the browser_utility_memoryReport.js then the kill() happened, so
+ // no more process and the test intermittently failed.
+ //
+ // The timeout value of 50ms should be long enough to allow the test to finish
+ // and the next one to start and get a reference on the process we launched,
+ // and yet allow us to kill the process in the middle of the next test. Higher
+ // values would allow browser_utility_memoryReport.js to complete without
+ // reproducing the issue (both locally and on try).
+ //
+ // eslint-disable-next-line mozilla/no-arbitrary-setTimeout
+ setTimeout(() => {
+ ProcessTools.kill(utilityPid);
+ }, 50);
+
+ info(`Waiting for utility process ${utilityPid} to go away.`);
+ let [subject, data] = await utilityProcessGone;
+ ok(
+ subject instanceof Ci.nsIPropertyBag2,
+ "Subject needs to be a nsIPropertyBag2 to clean up properly"
+ );
+ is(
+ parseInt(data, 10),
+ utilityPid,
+ `Should match the crashed PID ${utilityPid} with ${data}`
+ );
+
+ // Make sure the process is dead, otherwise there is a risk of race for
+ // writing leak logs
+ utilityProcessTest().noteIntentionalCrash(utilityPid);
+});
diff --git a/ipc/glue/test/browser/browser_utility_memoryReport.js b/ipc/glue/test/browser/browser_utility_memoryReport.js
new file mode 100644
index 0000000000..8cec61b8be
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_memoryReport.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// When running full suite, previous audio decoding tests might have left some
+// running and this might interfere with our testing
+add_setup(async function ensureNoExistingProcess() {
+ await killUtilityProcesses();
+});
+
+add_task(async () => {
+ const utilityPid = await startUtilityProcess();
+
+ const gMgr = Cc["@mozilla.org/memory-reporter-manager;1"].getService(
+ Ci.nsIMemoryReporterManager
+ );
+ ok(utilityPid !== undefined, `Utility process is running as ${utilityPid}`);
+
+ var utilityReports = [];
+
+ const performCollection = new Promise((resolve, reject) => {
+ // Record the reports from the live memory reporters then process them.
+ let handleReport = function (
+ aProcess,
+ aUnsafePath,
+ aKind,
+ aUnits,
+ aAmount,
+ aDescription
+ ) {
+ const expectedProcess = `Utility (pid ${utilityPid}, sandboxingKind ${kGenericUtilitySandbox})`;
+ if (aProcess !== expectedProcess) {
+ return;
+ }
+
+ let report = {
+ process: aProcess,
+ path: aUnsafePath,
+ kind: aKind,
+ units: aUnits,
+ amount: aAmount,
+ description: aDescription,
+ };
+
+ utilityReports.push(report);
+ };
+
+ info("Memory report: Perform the call");
+ gMgr.getReports(handleReport, null, resolve, null, false);
+ });
+
+ await performCollection;
+
+ info(
+ `Collected ${utilityReports.length} reports from utility process ${utilityPid}`
+ );
+ ok(!!utilityReports.length, "Collected some reports");
+ ok(
+ utilityReports.filter(r => r.path === "vsize" && r.amount > 0).length === 1,
+ "Collected vsize report"
+ );
+ ok(
+ utilityReports.filter(r => r.path === "resident" && r.amount > 0).length ===
+ 1,
+ "Collected resident report"
+ );
+ ok(
+ !!utilityReports.filter(
+ r => r.path.search(/^explicit\/.*/) >= 0 && r.amount > 0
+ ).length,
+ "Collected some explicit/ report"
+ );
+
+ await cleanUtilityProcessShutdown();
+});
diff --git a/ipc/glue/test/browser/browser_utility_multipleAudio.js b/ipc/glue/test/browser/browser_utility_multipleAudio.js
new file mode 100644
index 0000000000..107cd2e234
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_multipleAudio.js
@@ -0,0 +1,45 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-multiple.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-multiple.js",
+ this
+);
+
+add_setup(async function checkAudioDecodingNonUtility() {
+ const isAudioDecodingNonUtilityAllowed = await SpecialPowers.getBoolPref(
+ "media.allow-audio-non-utility"
+ );
+ ok(
+ !isAudioDecodingNonUtilityAllowed,
+ "Audio decoding should not be allowed on non utility processes by default"
+ );
+});
+
+add_task(async function testAudioDecodingInUtility() {
+ await runTest({ expectUtility: true });
+});
+
+add_task(async function testFailureAudioDecodingInRDD() {
+ await runTest({ expectUtility: false, expectError: true });
+});
+
+add_task(async function testFailureAudioDecodingInContent() {
+ const platform = Services.appinfo.OS;
+ if (platform === "WINNT") {
+ ok(
+ true,
+ "Manually skipping on Windows because of gfx killing us, cf browser.ini"
+ );
+ return;
+ }
+
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.rdd-process.enabled", false]],
+ });
+ await runTest({ expectUtility: false, expectRDD: false, expectError: true });
+});
diff --git a/ipc/glue/test/browser/browser_utility_multipleAudio_fallback.js b/ipc/glue/test/browser/browser_utility_multipleAudio_fallback.js
new file mode 100644
index 0000000000..cbebd08287
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_multipleAudio_fallback.js
@@ -0,0 +1,22 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-multiple.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-multiple.js",
+ this
+);
+
+add_setup(async function checkAudioDecodingNonUtility() {
+ const isAudioDecodingNonUtilityAllowed = await SpecialPowers.getBoolPref(
+ "media.allow-audio-non-utility"
+ );
+ ok(isAudioDecodingNonUtilityAllowed, "Audio decoding has been allowed");
+});
+
+add_task(async function testFallbackAudioDecodingInRDD() {
+ await runTest({ expectUtility: false, expectError: false });
+});
diff --git a/ipc/glue/test/browser/browser_utility_multipleAudio_fallback_content.js b/ipc/glue/test/browser/browser_utility_multipleAudio_fallback_content.js
new file mode 100644
index 0000000000..f07a29985f
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_multipleAudio_fallback_content.js
@@ -0,0 +1,22 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head-multiple.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/head-multiple.js",
+ this
+);
+
+add_setup(async function checkAudioDecodingNonUtility() {
+ const isAudioDecodingNonUtilityAllowed = await SpecialPowers.getBoolPref(
+ "media.allow-audio-non-utility"
+ );
+ ok(isAudioDecodingNonUtilityAllowed, "Audio decoding has been allowed");
+});
+
+add_task(async function testFallbackAudioDecodingInContent() {
+ await runTest({ expectContent: true });
+});
diff --git a/ipc/glue/test/browser/browser_utility_profiler.js b/ipc/glue/test/browser/browser_utility_profiler.js
new file mode 100644
index 0000000000..084cd67747
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_profiler.js
@@ -0,0 +1,76 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from /tools/profiler/tests/shared-head.js */
+
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/tools/profiler/tests/browser/shared-head.js",
+ this
+);
+
+// When running full suite, previous tests may have left some utility
+// processes running and this might interfere with our testing.
+add_setup(async function ensureNoExistingProcess() {
+ await killUtilityProcesses();
+});
+
+add_task(async () => {
+ const utilityPid = await startUtilityProcess();
+
+ info("Start the profiler");
+ await startProfiler();
+
+ let profile;
+ await TestUtils.waitForCondition(async () => {
+ profile = await Services.profiler.getProfileDataAsync();
+ return (
+ // Search for process name to not be disturbed by other types of utility
+ // e.g. Utility AudioDecoder
+ profile.processes.filter(
+ ps => ps.threads[0].processName === "Utility Process"
+ ).length === 1
+ );
+ }, "Give time for the profiler to start and collect some samples");
+
+ info(`Check that the utility process ${utilityPid} is present.`);
+ let utilityProcessIndex = profile.processes.findIndex(
+ p => p.threads[0].pid == utilityPid
+ );
+ Assert.notEqual(utilityProcessIndex, -1, "Could find index of utility");
+
+ Assert.equal(
+ profile.processes[utilityProcessIndex].threads[0].processType,
+ "utility",
+ "Profile has processType utility"
+ );
+
+ Assert.equal(
+ profile.processes[utilityProcessIndex].threads[0].name,
+ "GeckoMain",
+ "Profile has correct main thread name"
+ );
+
+ Assert.equal(
+ profile.processes[utilityProcessIndex].threads[0].processName,
+ "Utility Process",
+ "Profile has correct process name"
+ );
+
+ Assert.greater(
+ profile.processes[utilityProcessIndex].threads.length,
+ 0,
+ "The utility process should have threads"
+ );
+
+ Assert.equal(
+ profile.threads.length,
+ 1,
+ "The parent process should have only one thread"
+ );
+
+ Services.profiler.StopProfiler();
+
+ await cleanUtilityProcessShutdown();
+});
diff --git a/ipc/glue/test/browser/browser_utility_start_clean_shutdown.js b/ipc/glue/test/browser/browser_utility_start_clean_shutdown.js
new file mode 100644
index 0000000000..62a9e4065b
--- /dev/null
+++ b/ipc/glue/test/browser/browser_utility_start_clean_shutdown.js
@@ -0,0 +1,9 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+add_task(async () => {
+ await startUtilityProcess();
+ await cleanUtilityProcessShutdown();
+});
diff --git a/ipc/glue/test/browser/head-multiple.js b/ipc/glue/test/browser/head-multiple.js
new file mode 100644
index 0000000000..0ab098448e
--- /dev/null
+++ b/ipc/glue/test/browser/head-multiple.js
@@ -0,0 +1,78 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head.js */
+
+async function runTest({
+ expectUtility = false,
+ expectRDD = false,
+ expectContent = false,
+ expectError = false,
+}) {
+ info(`Running tests with decoding from somewhere`);
+ info(` expectUtility: ${expectUtility}`);
+ info(` expectRDD: ${expectRDD}`);
+ info(` expectContent: ${expectContent}`);
+
+ // Utility should now be the default, so dont toggle the pref unless we test
+ // RDD
+ if (!expectUtility) {
+ await SpecialPowers.pushPrefEnv({
+ set: [["media.utility-process.enabled", expectUtility]],
+ });
+ }
+
+ const platform = Services.appinfo.OS;
+
+ for (let { src, expectations } of audioTestData()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ const expectation = expectations[platform];
+
+ info(`Add media tabs: ${src}`);
+ let tabs = [await addMediaTab(src), await addMediaTab(src)];
+ let playback = [];
+
+ info("Play tabs");
+ for (let tab of tabs) {
+ playback.push(
+ play(
+ tab,
+ expectUtility && !expectContent && !expectError
+ ? expectation.process
+ : "RDD",
+ expectation.decoder,
+ expectContent,
+ false, // expectJava
+ expectError
+ )
+ );
+ }
+
+ info("Wait all playback");
+ await Promise.all(playback);
+
+ let allstop = [];
+ info("Stop tabs");
+ for (let tab of tabs) {
+ allstop.push(stop(tab));
+ }
+
+ info("Wait all stop");
+ await Promise.all(allstop);
+
+ let remove = [];
+ info("Remove tabs");
+ for (let tab of tabs) {
+ remove.push(BrowserTestUtils.removeTab(tab));
+ }
+
+ info("Wait all tabs to be removed");
+ await Promise.all(remove);
+ }
+}
diff --git a/ipc/glue/test/browser/head-telemetry.js b/ipc/glue/test/browser/head-telemetry.js
new file mode 100644
index 0000000000..46841347fa
--- /dev/null
+++ b/ipc/glue/test/browser/head-telemetry.js
@@ -0,0 +1,269 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* import-globals-from head.js */
+
+const Telemetry = Services.telemetry;
+
+const { TelemetryController } = ChromeUtils.importESModule(
+ "resource://gre/modules/TelemetryController.sys.mjs"
+);
+
+/* eslint-disable mozilla/no-redeclare-with-import-autofix */
+const { ContentTaskUtils } = ChromeUtils.importESModule(
+ "resource://testing-common/ContentTaskUtils.sys.mjs"
+);
+
+const MEDIA_AUDIO_PROCESS = "media.audio_process_per_codec_name";
+
+const utilityPerCodecs = {
+ Linux: [
+ {
+ process: "utility+audioDecoder_Generic",
+ codecs: ["vorbis", "mp3", "aac", "flac"],
+ },
+ ],
+ WINNT: [
+ {
+ process: "utility+audioDecoder_Generic",
+ codecs: ["vorbis", "mp3", "flac"],
+ },
+ {
+ process: "utility+audioDecoder_WMF",
+ codecs: ["aac"],
+ },
+ ],
+ Darwin: [
+ {
+ process: "utility+audioDecoder_Generic",
+ codecs: ["vorbis", "mp3", "flac"],
+ },
+ {
+ process: "utility+audioDecoder_AppleMedia",
+ codecs: ["aac"],
+ },
+ ],
+};
+
+const kInterval = 300; /* ms */
+const kRetries = 5;
+
+/**
+ * This function waits until utility scalars are reported into the
+ * scalar snapshot.
+ */
+async function waitForKeyedScalars(process) {
+ await ContentTaskUtils.waitForCondition(
+ () => {
+ const scalars = Telemetry.getSnapshotForKeyedScalars("main", false);
+ return Object.keys(scalars).includes("content");
+ },
+ `Waiting for ${process} scalars to have been set`,
+ kInterval,
+ kRetries
+ );
+}
+
+async function waitForValue(process, codecNames, extra = "") {
+ await ContentTaskUtils.waitForCondition(
+ () => {
+ const telemetry = Telemetry.getSnapshotForKeyedScalars(
+ "main",
+ false
+ ).content;
+ if (telemetry && MEDIA_AUDIO_PROCESS in telemetry) {
+ const keyProcMimeTypes = Object.keys(telemetry[MEDIA_AUDIO_PROCESS]);
+ const found = codecNames.every(item =>
+ keyProcMimeTypes.includes(`${process},${item}${extra}`)
+ );
+ return found;
+ }
+ return false;
+ },
+ `Waiting for ${MEDIA_AUDIO_PROCESS} [${process}, ${codecNames}, ${extra}]`,
+ kInterval,
+ kRetries
+ );
+}
+
+async function runTest({
+ expectUtility = false,
+ expectRDD = false,
+ expectError = false,
+}) {
+ info(
+ `Running tests with decoding from Utility or RDD: expectUtility=${expectUtility} expectRDD=${expectRDD} expectError=${expectError}`
+ );
+
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["media.utility-process.enabled", expectUtility],
+ ["media.rdd-process.enabled", expectRDD],
+ ["toolkit.telemetry.ipcBatchTimeout", 0],
+ ],
+ });
+
+ const platform = Services.appinfo.OS;
+
+ for (let { src, expectations } of audioTestData()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ const expectation = expectations[platform];
+
+ info(`Add media tab: ${src}`);
+ let tab = await addMediaTab(src);
+
+ info("Play tab");
+ await play(
+ tab,
+ expectUtility ? expectation.process : "RDD",
+ expectation.decoder,
+ !expectUtility && !expectRDD,
+ false,
+ expectError
+ );
+
+ info("Stop tab");
+ await stop(tab);
+
+ info("Remove tab");
+ await BrowserTestUtils.removeTab(tab);
+ }
+}
+
+async function runTestWithEME() {
+ info(`Running tests with decoding from Utility for EME`);
+
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["media.utility-process.enabled", true],
+ ["toolkit.telemetry.ipcBatchTimeout", 0],
+ ],
+ });
+
+ const platform = Services.appinfo.OS;
+
+ for (let { src, expectations } of audioTestDataEME()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ const expectation = expectations[platform];
+
+ info(`Add EME media tab`);
+ let tab = await addMediaTabWithEME(src.sourceBuffer, src.audioFile);
+
+ info("Play tab");
+ await play(
+ tab,
+ expectation.process,
+ expectation.decoder,
+ false, // expectContent
+ false, // expectJava
+ false, // expectError
+ true // withEME
+ );
+
+ info("Stop tab");
+ await stop(tab);
+
+ info("Remove tab");
+ await BrowserTestUtils.removeTab(tab);
+ }
+}
+
+function getTelemetry() {
+ const telemetry = Telemetry.getSnapshotForKeyedScalars("main", false).content;
+ return telemetry;
+}
+
+async function verifyTelemetryForProcess(process, codecNames, extraKey = "") {
+ // Once scalars are set by the utility process, they don't immediately get
+ // sent to the parent process. Wait for the Telemetry IPC Timer to trigger
+ // and batch send the data back to the parent process.
+ await waitForKeyedScalars(process);
+ await waitForValue(process, codecNames, extraKey);
+
+ const telemetry = getTelemetry();
+
+ // The amount here depends on how many times RemoteAudioDecoderParent::RemoteAudioDecoderParent
+ // gets called, which might be more than actual audio files being playback, e.g., we would get one for metadata loading, then one for playback etc.
+ // But we dont care really we just want to ensure 0 on RDD, Content and others
+ // in the wild.[${codecName}]
+ codecNames.forEach(codecName => {
+ Assert.equal(
+ telemetry[MEDIA_AUDIO_PROCESS][`${process},${codecName}${extraKey}`],
+ 1,
+ `${MEDIA_AUDIO_PROCESS} must have the correct value (${process}, ${codecName}).`
+ );
+ });
+}
+
+async function verifyNoTelemetryForProcess(process, codecNames, extraKey = "") {
+ try {
+ await waitForKeyedScalars(process);
+ await waitForValue(process, codecNames, extraKey);
+ } catch (ex) {
+ if (ex.indexOf("timed out after") > 0) {
+ Assert.ok(
+ true,
+ `Expected timeout ${process}[${MEDIA_AUDIO_PROCESS}] for ${codecNames}`
+ );
+ } else {
+ Assert.ok(
+ false,
+ `Unexpected exception on ${process}[${MEDIA_AUDIO_PROCESS}] for ${codecNames}: ${ex}`
+ );
+ }
+ }
+
+ const telemetry = getTelemetry();
+
+ // There could be races with telemetry for power usage coming up
+ codecNames.forEach(codecName => {
+ if (telemetry) {
+ if (telemetry && MEDIA_AUDIO_PROCESS in telemetry) {
+ Assert.ok(
+ !(
+ `${process},${codecName}${extraKey}` in
+ telemetry[MEDIA_AUDIO_PROCESS]
+ ),
+ `Some telemetry but no ${process}[${MEDIA_AUDIO_PROCESS}][${codecName}]`
+ );
+ } else {
+ Assert.ok(
+ !(MEDIA_AUDIO_PROCESS in telemetry),
+ `No telemetry for ${process}[${MEDIA_AUDIO_PROCESS}][${codecName}]`
+ );
+ }
+ } else {
+ Assert.equal(
+ undefined,
+ telemetry,
+ `No telemetry for ${process}[${MEDIA_AUDIO_PROCESS}][${codecName}]`
+ );
+ }
+ });
+}
+
+function getExtraKey({ utilityPref, rddPref, allowNonUtility }) {
+ let extraKey = "";
+ if (!rddPref) {
+ extraKey += ",rdd-disabled";
+ }
+ if (!utilityPref) {
+ extraKey += ",utility-disabled";
+ }
+ // TODO: This needs to be removed when getting rid of ability to decode on
+ // non utility at all
+ if (allowNonUtility) {
+ extraKey += ",allow-non-utility";
+ }
+ return extraKey;
+}
diff --git a/ipc/glue/test/browser/head.js b/ipc/glue/test/browser/head.js
new file mode 100644
index 0000000000..8acff88273
--- /dev/null
+++ b/ipc/glue/test/browser/head.js
@@ -0,0 +1,562 @@
+/* Any copyright is dedicated to the Public Domain.
+ * http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const utilityProcessTest = () => {
+ return Cc["@mozilla.org/utility-process-test;1"].createInstance(
+ Ci.nsIUtilityProcessTest
+ );
+};
+
+const kGenericUtilitySandbox = 0;
+const kGenericUtilityActor = "unknown";
+
+// Start a generic utility process with the given array of utility actor names
+// registered.
+async function startUtilityProcess(actors = []) {
+ info("Start a UtilityProcess");
+ return utilityProcessTest().startProcess(actors);
+}
+
+// Returns an array of process infos for utility processes of the given type
+// or all utility processes if actor is not defined.
+async function getUtilityProcesses(actor = undefined, options = {}) {
+ let procInfos = (await ChromeUtils.requestProcInfo()).children.filter(p => {
+ return (
+ p.type === "utility" &&
+ (actor == undefined ||
+ p.utilityActors.find(a => a.actorName.startsWith(actor)))
+ );
+ });
+
+ if (!options?.quiet) {
+ info(`Utility process infos = ${JSON.stringify(procInfos)}`);
+ }
+ return procInfos;
+}
+
+async function tryGetUtilityPid(actor, options = {}) {
+ let process = await getUtilityProcesses(actor, options);
+ if (!options?.quiet) {
+ ok(process.length <= 1, `at most one ${actor} process exists`);
+ }
+ return process[0]?.pid;
+}
+
+async function checkUtilityExists(actor) {
+ info(`Looking for a running ${actor} utility process`);
+ const utilityPid = await tryGetUtilityPid(actor);
+ ok(utilityPid > 0, `Found ${actor} utility process ${utilityPid}`);
+ return utilityPid;
+}
+
+// "Cleanly stop" a utility process. This will never leave a crash dump file.
+// preferKill will "kill" the process (e.g. SIGABRT) instead of using the
+// UtilityProcessManager.
+// To "crash" -- i.e. shutdown and generate a crash dump -- use
+// crashSomeUtility().
+async function cleanUtilityProcessShutdown(actor, preferKill = false) {
+ info(`${preferKill ? "Kill" : "Clean shutdown"} Utility Process ${actor}`);
+
+ const utilityPid = await tryGetUtilityPid(actor);
+ ok(utilityPid !== undefined, `Must have PID for ${actor} utility process`);
+
+ const utilityProcessGone = TestUtils.topicObserved(
+ "ipc:utility-shutdown",
+ (subject, data) => parseInt(data, 10) === utilityPid
+ );
+
+ if (preferKill) {
+ SimpleTest.expectChildProcessCrash();
+ info(`Kill Utility Process ${utilityPid}`);
+ const ProcessTools = Cc["@mozilla.org/processtools-service;1"].getService(
+ Ci.nsIProcessToolsService
+ );
+ ProcessTools.kill(utilityPid);
+ } else {
+ info(`Stopping Utility Process ${utilityPid}`);
+ await utilityProcessTest().stopProcess(actor);
+ }
+
+ let [subject, data] = await utilityProcessGone;
+ ok(
+ subject instanceof Ci.nsIPropertyBag2,
+ "Subject needs to be a nsIPropertyBag2 to clean up properly"
+ );
+ is(
+ parseInt(data, 10),
+ utilityPid,
+ `Should match the crashed PID ${utilityPid} with ${data}`
+ );
+
+ // Make sure the process is dead, otherwise there is a risk of race for
+ // writing leak logs
+ utilityProcessTest().noteIntentionalCrash(utilityPid);
+
+ ok(!subject.hasKey("dumpID"), "There should be no dumpID");
+}
+
+async function killUtilityProcesses() {
+ let utilityProcesses = await getUtilityProcesses();
+ for (const utilityProcess of utilityProcesses) {
+ for (const actor of utilityProcess.utilityActors) {
+ info(`Stopping ${actor.actorName} utility process`);
+ await cleanUtilityProcessShutdown(actor.actorName, /* preferKill */ true);
+ }
+ }
+}
+
+function audioTestData() {
+ return [
+ {
+ src: "small-shot.ogg",
+ expectations: {
+ Android: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ Linux: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ WINNT: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ Darwin: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ },
+ },
+ {
+ src: "small-shot.mp3",
+ expectations: {
+ Android: { process: "Utility Generic", decoder: "ffvpx audio decoder" },
+ Linux: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ WINNT: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ Darwin: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ },
+ },
+ {
+ src: "small-shot.m4a",
+ expectations: {
+ // Add Android after Bug 1771196
+ Linux: {
+ process: "Utility Generic",
+ decoder: "ffmpeg audio decoder",
+ },
+ WINNT: {
+ process: "Utility WMF",
+ decoder: "wmf audio decoder",
+ },
+ Darwin: {
+ process: "Utility AppleMedia",
+ decoder: "apple coremedia decoder",
+ },
+ },
+ },
+ {
+ src: "small-shot.flac",
+ expectations: {
+ Android: { process: "Utility Generic", decoder: "ffvpx audio decoder" },
+ Linux: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ WINNT: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ Darwin: {
+ process: "Utility Generic",
+ decoder: "ffvpx audio decoder",
+ },
+ },
+ },
+ ];
+}
+
+function audioTestDataEME() {
+ return [
+ {
+ src: {
+ audioFile:
+ "https://example.com/browser/ipc/glue/test/browser/short-aac-encrypted-audio.mp4",
+ sourceBuffer: "audio/mp4",
+ },
+ expectations: {
+ Linux: {
+ process: "Utility Generic",
+ decoder: "ffmpeg audio decoder",
+ },
+ WINNT: {
+ process: "Utility WMF",
+ decoder: "wmf audio decoder",
+ },
+ Darwin: {
+ process: "Utility AppleMedia",
+ decoder: "apple coremedia decoder",
+ },
+ },
+ },
+ ];
+}
+
+async function addMediaTab(src) {
+ const tab = BrowserTestUtils.addTab(gBrowser, "about:blank", {
+ forceNewProcess: true,
+ });
+ const browser = gBrowser.getBrowserForTab(tab);
+ await BrowserTestUtils.browserLoaded(browser);
+ await SpecialPowers.spawn(browser, [src], createAudioElement);
+ return tab;
+}
+
+async function addMediaTabWithEME(sourceBuffer, audioFile) {
+ const tab = BrowserTestUtils.addTab(
+ gBrowser,
+ "https://example.com/browser/",
+ {
+ forceNewProcess: true,
+ }
+ );
+ const browser = gBrowser.getBrowserForTab(tab);
+ await BrowserTestUtils.browserLoaded(browser);
+ await SpecialPowers.spawn(
+ browser,
+ [sourceBuffer, audioFile],
+ createAudioElementEME
+ );
+ return tab;
+}
+
+async function play(
+ tab,
+ expectUtility,
+ expectDecoder,
+ expectContent = false,
+ expectJava = false,
+ expectError = false,
+ withEME = false
+) {
+ let browser = tab.linkedBrowser;
+ return SpecialPowers.spawn(
+ browser,
+ [
+ expectUtility,
+ expectDecoder,
+ expectContent,
+ expectJava,
+ expectError,
+ withEME,
+ ],
+ checkAudioDecoder
+ );
+}
+
+async function stop(tab) {
+ let browser = tab.linkedBrowser;
+ await SpecialPowers.spawn(browser, [], async function () {
+ let audio = content.document.querySelector("audio");
+ audio.pause();
+ });
+}
+
+async function createAudioElement(src) {
+ const doc = typeof content !== "undefined" ? content.document : document;
+ const ROOT = "https://example.com/browser/ipc/glue/test/browser";
+ let audio = doc.createElement("audio");
+ audio.setAttribute("controls", "true");
+ audio.setAttribute("loop", true);
+ audio.src = `${ROOT}/${src}`;
+ doc.body.appendChild(audio);
+}
+
+async function createAudioElementEME(sourceBuffer, audioFile) {
+ // Helper to clone data into content so the EME helper can use the data.
+ function cloneIntoContent(data) {
+ return Cu.cloneInto(data, content.wrappedJSObject);
+ }
+
+ // Load the EME helper into content.
+ Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/ipc/glue/test/browser/eme_standalone.js",
+ content
+ );
+
+ let audio = content.document.createElement("audio");
+ audio.setAttribute("controls", "true");
+ audio.setAttribute("loop", true);
+ audio.setAttribute("_sourceBufferType", sourceBuffer);
+ audio.setAttribute("_audioUrl", audioFile);
+ content.document.body.appendChild(audio);
+
+ let emeHelper = new content.wrappedJSObject.EmeHelper();
+ emeHelper.SetKeySystem(
+ content.wrappedJSObject.EmeHelper.GetClearkeyKeySystemString()
+ );
+ emeHelper.SetInitDataTypes(cloneIntoContent(["keyids", "cenc"]));
+ emeHelper.SetAudioCapabilities(
+ cloneIntoContent([{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }])
+ );
+ emeHelper.AddKeyIdAndKey(
+ "2cdb0ed6119853e7850671c3e9906c3c",
+ "808B9ADAC384DE1E4F56140F4AD76194"
+ );
+ emeHelper.onerror = error => {
+ is(false, `Got unexpected error from EME helper: ${error}`);
+ };
+ await emeHelper.ConfigureEme(audio);
+ // Done setting up EME.
+}
+
+async function checkAudioDecoder(
+ expectedProcess,
+ expectedDecoder,
+ expectContent = false,
+ expectJava = false,
+ expectError = false,
+ withEME = false
+) {
+ const doc = typeof content !== "undefined" ? content.document : document;
+ let audio = doc.querySelector("audio");
+ const checkPromise = new Promise((resolve, reject) => {
+ const timeUpdateHandler = async ev => {
+ const debugInfo = await SpecialPowers.wrap(audio).mozRequestDebugInfo();
+ const audioDecoderName = debugInfo.decoder.reader.audioDecoderName;
+
+ const isExpectedDecoder =
+ audioDecoderName.indexOf(`${expectedDecoder}`) == 0;
+ ok(
+ isExpectedDecoder,
+ `playback ${audio.src} was from decoder '${audioDecoderName}', expected '${expectedDecoder}'`
+ );
+
+ const isExpectedProcess =
+ audioDecoderName.indexOf(`(${expectedProcess} remote)`) > 0;
+ const isJavaRemote = audioDecoderName.indexOf("(remote)") > 0;
+ const isOk =
+ (isExpectedProcess && !isJavaRemote && !expectContent && !expectJava) || // Running in Utility
+ (expectJava && !isExpectedProcess && isJavaRemote) || // Running in Java remote
+ (expectContent && !isExpectedProcess && !isJavaRemote); // Running in Content
+
+ ok(
+ isOk,
+ `playback ${audio.src} was from process '${audioDecoderName}', expected '${expectedProcess}'`
+ );
+
+ if (isOk) {
+ resolve();
+ } else {
+ reject();
+ }
+ };
+
+ const startPlaybackHandler = async ev => {
+ ok(
+ await audio.play().then(
+ _ => true,
+ _ => false
+ ),
+ "audio started playing"
+ );
+
+ audio.addEventListener("timeupdate", timeUpdateHandler, { once: true });
+ };
+
+ audio.addEventListener("error", async err => {
+ info(
+ `Received HTML media error: ${audio.error.code}: ${audio.error.message}`
+ );
+ if (expectError) {
+ const w = typeof content !== "undefined" ? content.window : window;
+ ok(
+ audio.error.code === w.MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED ||
+ w.MediaError.MEDIA_ERR_DECODE,
+ "Media supported but decoding failed"
+ );
+ resolve();
+ } else {
+ info(`Unexpected error`);
+ reject();
+ }
+ });
+
+ audio.addEventListener("canplaythrough", startPlaybackHandler, {
+ once: true,
+ });
+ });
+
+ if (!withEME) {
+ // We need to make sure the decoder is ready before play()ing otherwise we
+ // could get into bad situations
+ audio.load();
+ } else {
+ // For EME we need to create and load content ourselves. We do this here
+ // because if we do it in createAudioElementEME() above then we end up
+ // with events fired before we get a chance to listen to them here
+ async function once(target, name) {
+ return new Promise(r => target.addEventListener(name, r, { once: true }));
+ }
+
+ // Setup MSE.
+ const ms = new content.wrappedJSObject.MediaSource();
+ audio.src = content.wrappedJSObject.URL.createObjectURL(ms);
+ await once(ms, "sourceopen");
+ const sb = ms.addSourceBuffer(audio.getAttribute("_sourceBufferType"));
+ let fetchResponse = await content.fetch(audio.getAttribute("_audioUrl"));
+ let dataBuffer = await fetchResponse.arrayBuffer();
+ sb.appendBuffer(dataBuffer);
+ await once(sb, "updateend");
+ ms.endOfStream();
+ await once(ms, "sourceended");
+ }
+
+ return checkPromise;
+}
+
+async function runMochitestUtilityAudio(
+ src,
+ {
+ expectUtility,
+ expectDecoder,
+ expectContent = false,
+ expectJava = false,
+ expectError = false,
+ } = {}
+) {
+ info(`Add media: ${src}`);
+ await createAudioElement(src);
+ let audio = document.querySelector("audio");
+ ok(audio, "Found an audio element created");
+
+ info(`Play media: ${src}`);
+ await checkAudioDecoder(
+ expectUtility,
+ expectDecoder,
+ expectContent,
+ expectJava,
+ expectError
+ );
+
+ info(`Pause media: ${src}`);
+ await audio.pause();
+
+ info(`Remove media: ${src}`);
+ document.body.removeChild(audio);
+}
+
+async function crashSomeUtility(utilityPid, actorsCheck) {
+ SimpleTest.expectChildProcessCrash();
+
+ const crashMan = Services.crashmanager;
+ const utilityProcessGone = TestUtils.topicObserved(
+ "ipc:utility-shutdown",
+ (subject, data) => {
+ info(`ipc:utility-shutdown: data=${data} subject=${subject}`);
+ return parseInt(data, 10) === utilityPid;
+ }
+ );
+
+ info("prune any previous crashes");
+ const future = new Date(Date.now() + 1000 * 60 * 60 * 24);
+ await crashMan.pruneOldCrashes(future);
+
+ info("crash Utility Process");
+ const ProcessTools = Cc["@mozilla.org/processtools-service;1"].getService(
+ Ci.nsIProcessToolsService
+ );
+
+ info(`Crash Utility Process ${utilityPid}`);
+ ProcessTools.crash(utilityPid);
+
+ info(`Waiting for utility process ${utilityPid} to go away.`);
+ let [subject, data] = await utilityProcessGone;
+ ok(
+ parseInt(data, 10) === utilityPid,
+ `Should match the crashed PID ${utilityPid} with ${data}`
+ );
+ ok(
+ subject instanceof Ci.nsIPropertyBag2,
+ "Subject needs to be a nsIPropertyBag2 to clean up properly"
+ );
+
+ // Make sure the process is dead, otherwise there is a risk of race for
+ // writing leak logs
+ utilityProcessTest().noteIntentionalCrash(utilityPid);
+
+ const dumpID = subject.getPropertyAsAString("dumpID");
+ ok(dumpID, "There should be a dumpID");
+
+ await crashMan.ensureCrashIsPresent(dumpID);
+ await crashMan.getCrashes().then(crashes => {
+ is(crashes.length, 1, "There should be only one record");
+ const crash = crashes[0];
+ ok(
+ crash.isOfType(
+ crashMan.processTypes[Ci.nsIXULRuntime.PROCESS_TYPE_UTILITY],
+ crashMan.CRASH_TYPE_CRASH
+ ),
+ "Record should be a utility process crash"
+ );
+ ok(crash.id === dumpID, "Record should have an ID");
+ ok(
+ actorsCheck(crash.metadata.UtilityActorsName),
+ `Record should have the correct actors name for: ${crash.metadata.UtilityActorsName}`
+ );
+ });
+
+ let minidumpDirectory = Services.dirsvc.get("ProfD", Ci.nsIFile);
+ minidumpDirectory.append("minidumps");
+
+ let dumpfile = minidumpDirectory.clone();
+ dumpfile.append(dumpID + ".dmp");
+ if (dumpfile.exists()) {
+ info(`Removal of ${dumpfile.path}`);
+ dumpfile.remove(false);
+ }
+
+ let extrafile = minidumpDirectory.clone();
+ extrafile.append(dumpID + ".extra");
+ info(`Removal of ${extrafile.path}`);
+ if (extrafile.exists()) {
+ extrafile.remove(false);
+ }
+}
+
+// Crash a utility process and generate a crash dump. To close a utility
+// process (forcefully or not) without a generating a crash, use
+// cleanUtilityProcessShutdown.
+async function crashSomeUtilityActor(
+ actor,
+ actorsCheck = () => {
+ return true;
+ }
+) {
+ // Get PID for utility type
+ const procInfos = await getUtilityProcesses(actor);
+ ok(
+ procInfos.length == 1,
+ `exactly one ${actor} utility process should be found`
+ );
+ const utilityPid = procInfos[0].pid;
+ return crashSomeUtility(utilityPid, actorsCheck);
+}
+
+function isNightlyOnly() {
+ const { AppConstants } = ChromeUtils.importESModule(
+ "resource://gre/modules/AppConstants.sys.mjs"
+ );
+ return AppConstants.NIGHTLY_BUILD;
+}
diff --git a/ipc/glue/test/browser/mochitest_audio_off.toml b/ipc/glue/test/browser/mochitest_audio_off.toml
new file mode 100644
index 0000000000..d174ea3939
--- /dev/null
+++ b/ipc/glue/test/browser/mochitest_audio_off.toml
@@ -0,0 +1,12 @@
+[DEFAULT]
+run-if = ["os == 'android' && !isolated_process"] # Bug 1771452
+support-files = [
+ "head.js",
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac",
+]
+prefs = ["media.utility-process.enabled=false"]
+
+["test_utility_audio_off.html"]
diff --git a/ipc/glue/test/browser/mochitest_audio_on.toml b/ipc/glue/test/browser/mochitest_audio_on.toml
new file mode 100644
index 0000000000..908f4005f1
--- /dev/null
+++ b/ipc/glue/test/browser/mochitest_audio_on.toml
@@ -0,0 +1,12 @@
+[DEFAULT]
+run-if = ["os == 'android' && !isolated_process"] # Bug 1771452
+support-files = [
+ "head.js",
+ "../../../../dom/media/test/small-shot.ogg",
+ "../../../../dom/media/test/small-shot.mp3",
+ "../../../../dom/media/test/small-shot.m4a",
+ "../../../../dom/media/test/small-shot.flac",
+]
+prefs = ["media.utility-process.enabled=true"]
+
+["test_utility_audio_on.html"]
diff --git a/ipc/glue/test/browser/moz.build b/ipc/glue/test/browser/moz.build
new file mode 100644
index 0000000000..671bdea5de
--- /dev/null
+++ b/ipc/glue/test/browser/moz.build
@@ -0,0 +1,15 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+BROWSER_CHROME_MANIFESTS += [
+ "browser.toml",
+ "browser_audio_fallback.toml",
+ "browser_audio_fallback_content.toml",
+ "browser_audio_locked.toml",
+ "browser_audio_shutdown.toml",
+ "browser_child_hang.toml",
+]
+MOCHITEST_MANIFESTS += ["mochitest_audio_off.toml", "mochitest_audio_on.toml"]
diff --git a/ipc/glue/test/browser/test_utility_audio_off.html b/ipc/glue/test/browser/test_utility_audio_off.html
new file mode 100644
index 0000000000..619cfaf11d
--- /dev/null
+++ b/ipc/glue/test/browser/test_utility_audio_off.html
@@ -0,0 +1,44 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Audio decoder not in Utility process</title>
+ <script src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<pre id="test">
+<script type="text/javascript">
+SimpleTest.waitForExplicitFinish();
+
+(async function() {
+ const platform = SpecialPowers.Services.appinfo.OS;
+ for (let {src, expectations} of audioTestData()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ try {
+ await runMochitestUtilityAudio(src, { expectUtility: "", expectDecoder: expectations[platform].decoder, expectContent: true, expectJava: false, expectError: true });
+ } catch (ex) {
+ ok(false, "Failure");
+ }
+ }
+
+ for (let src of [
+ "small-shot.m4a",
+ ]) {
+ try {
+ await runMochitestUtilityAudio(src, { expectUtility: "", expectDecoder: "android decoder", expectContent: false, expectJava: true, expectError: false });
+ } catch (ex) {
+ ok(false, `Failure ${ex}`);
+ }
+ }
+
+ SimpleTest.finish();
+})();
+</script>
+</pre>
+</body>
+</html>
diff --git a/ipc/glue/test/browser/test_utility_audio_on.html b/ipc/glue/test/browser/test_utility_audio_on.html
new file mode 100644
index 0000000000..f473527520
--- /dev/null
+++ b/ipc/glue/test/browser/test_utility_audio_on.html
@@ -0,0 +1,45 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+ <title>Audio decoder in Utility process</title>
+ <script src="/tests/SimpleTest/SimpleTest.js"></script>
+ <script src="head.js"></script>
+ <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
+</head>
+<body>
+<pre id="test">
+<script type="text/javascript">
+SimpleTest.waitForExplicitFinish();
+
+(async function() {
+ const platform = SpecialPowers.Services.appinfo.OS;
+ for (let {src, expectations} of audioTestData()) {
+ if (!(platform in expectations)) {
+ info(`Skipping ${src} for ${platform}`);
+ continue;
+ }
+
+ try {
+ await runMochitestUtilityAudio(src, { expectUtility: expectations[platform].process, expectDecoder: expectations[platform].decoder, expectContent: false, expectJava: false });
+ } catch (ex) {
+ ok(false, "Failure");
+ }
+ }
+
+ // Remove all after Bug 1771196
+ for (let src of [
+ "small-shot.m4a",
+ ]) {
+ try {
+ await runMochitestUtilityAudio(src, { expectUtility: "", expectDecoder: "android decoder", expectContent: false, expectJava: true });
+ } catch (ex) {
+ ok(false, `Failure ${ex}`);
+ }
+ }
+
+ SimpleTest.finish();
+})();
+</script>
+</pre>
+</body>
+</html>
diff --git a/ipc/glue/test/gtest/TestAsyncBlockers.cpp b/ipc/glue/test/gtest/TestAsyncBlockers.cpp
new file mode 100644
index 0000000000..6f8d298621
--- /dev/null
+++ b/ipc/glue/test/gtest/TestAsyncBlockers.cpp
@@ -0,0 +1,166 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/SpinEventLoopUntil.h"
+#include "mozilla/ipc/AsyncBlockers.h"
+#include "mozilla/gtest/MozHelpers.h"
+
+#include "nsCOMPtr.h"
+#include "nsITimer.h"
+#include "nsINamed.h"
+
+using namespace mozilla;
+using namespace mozilla::ipc;
+
+#define PROCESS_EVENTS_UNTIL(_done) \
+ SpinEventLoopUntil("TestAsyncBlockers"_ns, [&]() { return _done; });
+
+class TestAsyncBlockers : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ SAVE_GDB_SLEEP(mOldSleepDuration);
+ return;
+ }
+
+ void TearDown() final { RESTORE_GDB_SLEEP(mOldSleepDuration); }
+
+ private:
+#if defined(HAS_GDB_SLEEP_DURATION)
+ unsigned int mOldSleepDuration = 0;
+#endif // defined(HAS_GDB_SLEEP_DURATION)
+};
+
+class Blocker {};
+
+TEST_F(TestAsyncBlockers, Register) {
+ AsyncBlockers blockers;
+ Blocker* blocker = new Blocker();
+ blockers.Register(blocker);
+ EXPECT_TRUE(true);
+}
+
+TEST_F(TestAsyncBlockers, Register_Deregister) {
+ AsyncBlockers blockers;
+ Blocker* blocker = new Blocker();
+ blockers.Register(blocker);
+ blockers.Deregister(blocker);
+ EXPECT_TRUE(true);
+}
+
+TEST_F(TestAsyncBlockers, Register_WaitUntilClear) {
+ AsyncBlockers blockers;
+ bool done = false;
+
+ Blocker* blocker = new Blocker();
+ blockers.Register(blocker);
+
+ blockers.WaitUntilClear(5 * 1000)->Then(GetCurrentSerialEventTarget(),
+ __func__, [&]() {
+ EXPECT_TRUE(true);
+ done = true;
+ });
+
+ NS_ProcessPendingEvents(nullptr);
+
+ blockers.Deregister(blocker);
+
+ PROCESS_EVENTS_UNTIL(done);
+}
+
+class AsyncBlockerTimerCallback : public nsITimerCallback, public nsINamed {
+ protected:
+ virtual ~AsyncBlockerTimerCallback();
+
+ public:
+ explicit AsyncBlockerTimerCallback() {}
+
+ NS_DECL_THREADSAFE_ISUPPORTS
+ NS_DECL_NSITIMERCALLBACK
+ NS_DECL_NSINAMED
+};
+
+NS_IMPL_ISUPPORTS(AsyncBlockerTimerCallback, nsITimerCallback, nsINamed)
+
+AsyncBlockerTimerCallback::~AsyncBlockerTimerCallback() = default;
+
+NS_IMETHODIMP
+AsyncBlockerTimerCallback::Notify(nsITimer* timer) {
+ // If we resolve through this, it means
+ // blockers.WaitUntilClear() started to wait for
+ // the completion of the timeout which is not
+ // good.
+ EXPECT_TRUE(false);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+AsyncBlockerTimerCallback::GetName(nsACString& aName) {
+ aName.AssignLiteral("AsyncBlockerTimerCallback");
+ return NS_OK;
+}
+
+TEST_F(TestAsyncBlockers, NoRegister_WaitUntilClear) {
+ AsyncBlockers blockers;
+ bool done = false;
+
+ nsCOMPtr<nsITimer> timer = NS_NewTimer();
+ ASSERT_TRUE(timer);
+
+ RefPtr<AsyncBlockerTimerCallback> timerCb = new AsyncBlockerTimerCallback();
+ timer->InitWithCallback(timerCb, 1 * 1000, nsITimer::TYPE_ONE_SHOT);
+
+ blockers.WaitUntilClear(10 * 1000)->Then(GetCurrentSerialEventTarget(),
+ __func__, [&]() {
+ // If we resolve through this
+ // before the nsITimer it means we
+ // have been resolved before the 5s
+ // timeout
+ EXPECT_TRUE(true);
+ timer->Cancel();
+ done = true;
+ });
+
+ PROCESS_EVENTS_UNTIL(done);
+}
+
+TEST_F(TestAsyncBlockers, Register_WaitUntilClear_0s) {
+ AsyncBlockers blockers;
+ bool done = false;
+
+ Blocker* blocker = new Blocker();
+ blockers.Register(blocker);
+
+ blockers.WaitUntilClear(0)->Then(GetCurrentSerialEventTarget(), __func__,
+ [&]() {
+ EXPECT_TRUE(true);
+ done = true;
+ });
+
+ NS_ProcessPendingEvents(nullptr);
+
+ blockers.Deregister(blocker);
+
+ PROCESS_EVENTS_UNTIL(done);
+}
+
+#if defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED) && !defined(ANDROID) && \
+ !(defined(XP_DARWIN) && !defined(MOZ_DEBUG))
+static void DeregisterEmpty_Test() {
+ mozilla::gtest::DisableCrashReporter();
+
+ AsyncBlockers blockers;
+ Blocker* blocker = new Blocker();
+ blockers.Deregister(blocker);
+}
+
+TEST_F(TestAsyncBlockers, DeregisterEmpty) {
+ ASSERT_DEATH_IF_SUPPORTED(DeregisterEmpty_Test(), "");
+}
+#endif // defined(MOZ_DIAGNOSTIC_ASSERT_ENABLED) && !defined(ANDROID) &&
+ // !(defined(XP_DARWIN) && !defined(MOZ_DEBUG))
+
+#undef PROCESS_EVENTS_UNTIL
diff --git a/ipc/glue/test/gtest/TestUtilityProcess.cpp b/ipc/glue/test/gtest/TestUtilityProcess.cpp
new file mode 100644
index 0000000000..c5d19c992f
--- /dev/null
+++ b/ipc/glue/test/gtest/TestUtilityProcess.cpp
@@ -0,0 +1,155 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+#include "mozilla/SpinEventLoopUntil.h"
+
+#include "mozilla/ipc/UtilityProcessManager.h"
+
+#if defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+# include "nsIAppShellService.h"
+# include "nsServiceManagerUtils.h"
+#endif // defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+
+#if defined(XP_WIN)
+# include "mozilla/gtest/MozHelpers.h"
+# include "mozilla/ipc/UtilityProcessImpl.h"
+#endif // defined(XP_WIN)
+
+#ifdef MOZ_WIDGET_ANDROID
+# define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/widget/appshell/android;1"
+#endif // MOZ_WIDGET_ANDROID
+
+#ifdef XP_MACOSX
+# define NS_APPSHELLSERVICE_CONTRACTID "@mozilla.org/widget/appshell/mac;1"
+#endif // XP_MACOSX
+
+using namespace mozilla;
+using namespace mozilla::ipc;
+
+#define WAIT_FOR_EVENTS \
+ SpinEventLoopUntil("UtilityProcess::emptyUtil"_ns, [&]() { return done; });
+
+bool setupDone = false;
+
+class UtilityProcess : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ if (setupDone) {
+ return;
+ }
+
+#if defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+ appShell = do_GetService(NS_APPSHELLSERVICE_CONTRACTID);
+#endif // defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+
+#if defined(XP_WIN) && defined(MOZ_SANDBOX)
+ mozilla::SandboxBroker::GeckoDependentInitialize();
+#endif // defined(XP_WIN) && defined(MOZ_SANDBOX)
+
+ setupDone = true;
+ }
+
+#if defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+ nsCOMPtr<nsIAppShellService> appShell;
+#endif // defined(MOZ_WIDGET_ANDROID) || defined(XP_MACOSX)
+};
+
+TEST_F(UtilityProcess, ProcessManager) {
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ ASSERT_NE(utilityProc, nullptr);
+}
+
+TEST_F(UtilityProcess, NoProcess) {
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ EXPECT_NE(utilityProc, nullptr);
+
+ Maybe<int32_t> noPid =
+ utilityProc->ProcessPid(SandboxingKind::GENERIC_UTILITY);
+ ASSERT_TRUE(noPid.isNothing());
+}
+
+TEST_F(UtilityProcess, LaunchProcess) {
+ bool done = false;
+
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ EXPECT_NE(utilityProc, nullptr);
+
+ int32_t thisPid = base::GetCurrentProcId();
+ EXPECT_GE(thisPid, 1);
+
+ utilityProc->LaunchProcess(SandboxingKind::GENERIC_UTILITY)
+ ->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [&]() mutable {
+ EXPECT_TRUE(true);
+
+ Maybe<int32_t> utilityPid =
+ utilityProc->ProcessPid(SandboxingKind::GENERIC_UTILITY);
+ EXPECT_TRUE(utilityPid.isSome());
+ EXPECT_GE(*utilityPid, 1);
+ EXPECT_NE(*utilityPid, thisPid);
+
+ printf_stderr("UtilityProcess running as %d\n", *utilityPid);
+
+ done = true;
+ },
+ [&](nsresult aError) mutable {
+ EXPECT_TRUE(false);
+ done = true;
+ });
+
+ WAIT_FOR_EVENTS;
+}
+
+TEST_F(UtilityProcess, DestroyProcess) {
+ bool done = false;
+
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+
+ utilityProc->LaunchProcess(SandboxingKind::GENERIC_UTILITY)
+ ->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [&]() {
+ Maybe<int32_t> utilityPid =
+ utilityProc->ProcessPid(SandboxingKind::GENERIC_UTILITY);
+ EXPECT_TRUE(utilityPid.isSome());
+ EXPECT_GE(*utilityPid, 1);
+
+ utilityProc->CleanShutdown(SandboxingKind::GENERIC_UTILITY);
+
+ utilityPid =
+ utilityProc->ProcessPid(SandboxingKind::GENERIC_UTILITY);
+ EXPECT_TRUE(utilityPid.isNothing());
+
+ EXPECT_TRUE(true);
+ done = true;
+ },
+ [&](nsresult aError) {
+ EXPECT_TRUE(false);
+ done = true;
+ });
+
+ WAIT_FOR_EVENTS;
+}
+
+#if defined(XP_WIN)
+static void LoadLibraryCrash_Test() {
+ mozilla::gtest::DisableCrashReporter();
+ // Just a uuidgen name to have something random
+ UtilityProcessImpl::LoadLibraryOrCrash(
+ L"2b49036e-6ba3-400c-a297-38fa1f6c5255.dll");
+}
+
+TEST_F(UtilityProcess, LoadLibraryCrash) {
+ ASSERT_DEATH_IF_SUPPORTED(LoadLibraryCrash_Test(), "");
+}
+#endif // defined(XP_WIN)
+
+#undef WAIT_FOR_EVENTS
diff --git a/ipc/glue/test/gtest/TestUtilityProcessSandboxing.cpp b/ipc/glue/test/gtest/TestUtilityProcessSandboxing.cpp
new file mode 100644
index 0000000000..fff17d63ef
--- /dev/null
+++ b/ipc/glue/test/gtest/TestUtilityProcessSandboxing.cpp
@@ -0,0 +1,66 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/gtest/MozHelpers.h"
+#include "mozilla/ipc/UtilityProcessSandboxing.h"
+
+using namespace mozilla;
+using namespace mozilla::ipc;
+
+TEST(UtilityProcessSandboxing, ParseNoEnvVar)
+{ EXPECT_TRUE(IsUtilitySandboxEnabled("", SandboxingKind::COUNT)); }
+
+TEST(UtilityProcessSandboxing, ParseEnvVar_DisableAll)
+{ EXPECT_FALSE(IsUtilitySandboxEnabled("1", SandboxingKind::COUNT)); }
+
+TEST(UtilityProcessSandboxing, ParseEnvVar_DontDisableAll)
+{ EXPECT_TRUE(IsUtilitySandboxEnabled("0", SandboxingKind::COUNT)); }
+
+TEST(UtilityProcessSandboxing, ParseEnvVar_DisableGenericOnly)
+{
+ EXPECT_FALSE(
+ IsUtilitySandboxEnabled("utility:0", SandboxingKind::GENERIC_UTILITY));
+ EXPECT_TRUE(IsUtilitySandboxEnabled("utility:0", SandboxingKind::COUNT));
+}
+
+#if defined(XP_DARWIN)
+TEST(UtilityProcessSandboxing, ParseEnvVar_DisableAppleAudioOnly)
+{
+ EXPECT_FALSE(IsUtilitySandboxEnabled(
+ "utility:1", SandboxingKind::UTILITY_AUDIO_DECODING_APPLE_MEDIA));
+ EXPECT_TRUE(
+ IsUtilitySandboxEnabled("utility:1", SandboxingKind::GENERIC_UTILITY));
+}
+#endif // defined(XP_DARWIN)
+
+#if defined(XP_WIN)
+TEST(UtilityProcessSandboxing, ParseEnvVar_DisableWMFOnly)
+{
+ EXPECT_FALSE(IsUtilitySandboxEnabled(
+ "utility:1", SandboxingKind::UTILITY_AUDIO_DECODING_WMF));
+ EXPECT_TRUE(
+ IsUtilitySandboxEnabled("utility:1", SandboxingKind::GENERIC_UTILITY));
+}
+#endif // defined(XP_WIN)
+
+TEST(UtilityProcessSandboxing, ParseEnvVar_DisableGenericOnly_Multiples)
+{
+ EXPECT_FALSE(IsUtilitySandboxEnabled("utility:1,utility:0,utility:2",
+ SandboxingKind::GENERIC_UTILITY));
+#if defined(XP_DARWIN)
+ EXPECT_FALSE(IsUtilitySandboxEnabled(
+ "utility:1,utility:0,utility:2",
+ SandboxingKind::UTILITY_AUDIO_DECODING_APPLE_MEDIA));
+#endif // XP_DARWIN
+#if defined(XP_WIN)
+ EXPECT_FALSE(
+ IsUtilitySandboxEnabled("utility:1,utility:0,utility:2",
+ SandboxingKind::UTILITY_AUDIO_DECODING_WMF));
+#endif // XP_WIN
+ EXPECT_TRUE(IsUtilitySandboxEnabled("utility:8,utility:0,utility:6",
+ SandboxingKind::COUNT));
+}
diff --git a/ipc/glue/test/gtest/moz.build b/ipc/glue/test/gtest/moz.build
new file mode 100644
index 0000000000..b0af6d80cd
--- /dev/null
+++ b/ipc/glue/test/gtest/moz.build
@@ -0,0 +1,22 @@
+# -*- Mode: python; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, you can obtain one at http://mozilla.org/MPL/2.0/.
+
+Library("ipcgluetest")
+
+UNIFIED_SOURCES = [
+ "TestAsyncBlockers.cpp",
+ "TestUtilityProcess.cpp",
+ "TestUtilityProcessSandboxing.cpp",
+]
+
+LOCAL_INCLUDES += [
+ "/widget",
+ "/widget/android",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul-gtest"
diff --git a/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp
new file mode 100644
index 0000000000..6c084a3153
--- /dev/null
+++ b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.cpp
@@ -0,0 +1,280 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#if defined(ENABLE_TESTS)
+# include "mozilla/ipc/UtilityProcessManager.h"
+# include "mozilla/ipc/UtilityProcessTest.h"
+# include "mozilla/dom/Promise.h"
+# include "mozilla/ProcInfo.h"
+# include "mozilla/IntentionalCrash.h"
+
+# ifdef XP_WIN
+# include <handleapi.h>
+# include <processthreadsapi.h>
+# include <tlhelp32.h>
+
+# include "mozilla/WinHandleWatcher.h"
+# include "nsISupports.h"
+# include "nsWindowsHelpers.h"
+# endif
+
+namespace mozilla::ipc {
+
+static UtilityActorName UtilityActorNameFromString(
+ const nsACString& aStringName) {
+ using namespace mozilla::dom;
+
+ // We use WebIDLUtilityActorNames because UtilityActorNames is not designed
+ // for iteration.
+ for (size_t i = 0; i < WebIDLUtilityActorNameValues::Count; ++i) {
+ auto idlName = static_cast<UtilityActorName>(i);
+ const nsDependentCSubstring idlNameString(
+ WebIDLUtilityActorNameValues::GetString(idlName));
+ if (idlNameString.Equals(aStringName)) {
+ return idlName;
+ }
+ }
+ MOZ_CRASH("Unknown utility actor name");
+}
+
+// Find the utility process with the given actor or any utility process if
+// the actor is UtilityActorName::EndGuard_.
+static SandboxingKind FindUtilityProcessWithActor(UtilityActorName aActorName) {
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ MOZ_ASSERT(utilityProc, "No UtilityprocessManager?");
+
+ for (size_t i = 0; i < SandboxingKind::COUNT; ++i) {
+ auto sbKind = static_cast<SandboxingKind>(i);
+ if (!utilityProc->Process(sbKind)) {
+ continue;
+ }
+ if (aActorName == UtilityActorName::EndGuard_) {
+ return sbKind;
+ }
+ for (auto actor : utilityProc->GetActors(sbKind)) {
+ if (actor == aActorName) {
+ return sbKind;
+ }
+ }
+ }
+
+ return SandboxingKind::COUNT;
+}
+
+# ifdef XP_WIN
+namespace {
+// Promise implementation for `UntilChildProcessDead`.
+//
+// Resolves the provided JS promise when the provided Windows HANDLE becomes
+// signaled.
+class WinHandlePromiseImpl final {
+ public:
+ NS_INLINE_DECL_REFCOUNTING(WinHandlePromiseImpl)
+
+ using HandlePtr = mozilla::UniqueFileHandle;
+
+ // Takes ownership of aHandle.
+ static void Create(mozilla::UniqueFileHandle handle,
+ RefPtr<mozilla::dom::Promise> promise) {
+ MOZ_ASSERT(handle);
+ MOZ_ASSERT(promise);
+
+ RefPtr obj{new WinHandlePromiseImpl(std::move(handle), std::move(promise))};
+
+ // WARNING: This creates an owning-reference cycle: (self -> HandleWatcher
+ // -> Runnable -> self). `obj` will therefore only be destroyed when and
+ // if the HANDLE is signaled.
+ obj->watcher.Watch(obj->handle.get(), GetCurrentSerialEventTarget(),
+ NewRunnableMethod("WinHandlePromiseImpl::Resolve", obj,
+ &WinHandlePromiseImpl::Resolve));
+ }
+
+ private:
+ WinHandlePromiseImpl(mozilla::UniqueFileHandle handle,
+ RefPtr<mozilla::dom::Promise> promise)
+ : handle(std::move(handle)), promise(std::move(promise)) {}
+
+ ~WinHandlePromiseImpl() { watcher.Stop(); }
+
+ void Resolve() { promise->MaybeResolveWithUndefined(); }
+
+ mozilla::UniqueFileHandle handle;
+ HandleWatcher watcher;
+ RefPtr<mozilla::dom::Promise> promise;
+};
+
+} // namespace
+# endif
+
+NS_IMETHODIMP
+UtilityProcessTest::StartProcess(const nsTArray<nsCString>& aActorsToRegister,
+ JSContext* aCx,
+ mozilla::dom::Promise** aOutPromise) {
+ NS_ENSURE_ARG(aOutPromise);
+ *aOutPromise = nullptr;
+ nsIGlobalObject* global = xpc::CurrentNativeGlobal(aCx);
+ if (NS_WARN_IF(!global)) {
+ return NS_ERROR_FAILURE;
+ }
+
+ ErrorResult erv;
+ RefPtr<dom::Promise> promise = dom::Promise::Create(global, erv);
+ if (NS_WARN_IF(erv.Failed())) {
+ return erv.StealNSResult();
+ }
+
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ MOZ_ASSERT(utilityProc, "No UtilityprocessManager?");
+
+ auto actors = aActorsToRegister.Clone();
+
+ utilityProc->LaunchProcess(SandboxingKind::GENERIC_UTILITY)
+ ->Then(
+ GetCurrentSerialEventTarget(), __func__,
+ [promise, utilityProc, actors = std::move(actors)] {
+ RefPtr<UtilityProcessParent> utilityParent =
+ utilityProc->GetProcessParent(SandboxingKind::GENERIC_UTILITY);
+ Maybe<int32_t> utilityPid =
+ utilityProc->ProcessPid(SandboxingKind::GENERIC_UTILITY);
+ for (size_t i = 0; i < actors.Length(); ++i) {
+ auto uan = UtilityActorNameFromString(actors[i]);
+ utilityProc->RegisterActor(utilityParent, uan);
+ }
+ if (utilityPid.isSome()) {
+ promise->MaybeResolve(*utilityPid);
+ } else {
+ promise->MaybeReject(NS_ERROR_NOT_AVAILABLE);
+ }
+ },
+ [promise](nsresult aError) {
+ MOZ_ASSERT_UNREACHABLE(
+ "UtilityProcessTest; failure to get Utility process");
+ promise->MaybeReject(aError);
+ });
+
+ promise.forget(aOutPromise);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+UtilityProcessTest::NoteIntentionalCrash(uint32_t aPid) {
+ mozilla::NoteIntentionalCrash("utility", aPid);
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+UtilityProcessTest::UntilChildProcessDead(
+ uint32_t pid, JSContext* cx, ::mozilla::dom::Promise** aOutPromise) {
+ NS_ENSURE_ARG(aOutPromise);
+ *aOutPromise = nullptr;
+
+# ifdef XP_WIN
+ if (pid == 0) {
+ return NS_ERROR_INVALID_ARG;
+ }
+
+ nsIGlobalObject* global = xpc::CurrentNativeGlobal(cx);
+ if (NS_WARN_IF(!global)) {
+ return NS_ERROR_FAILURE;
+ }
+
+ ErrorResult erv;
+ RefPtr<dom::Promise> promise = dom::Promise::Create(global, erv);
+ if (NS_WARN_IF(erv.Failed())) {
+ return erv.StealNSResult();
+ }
+
+ // Get a fresh handle to the child process with the specified PID.
+ mozilla::UniqueFileHandle handle;
+ {
+ bool failed = false;
+ GeckoChildProcessHost::GetAll([&](GeckoChildProcessHost* aProc) {
+ if (handle || failed) {
+ return;
+ }
+ if (aProc->GetChildProcessId() != pid) {
+ return;
+ }
+
+ HANDLE handle_ = nullptr;
+ if (!::DuplicateHandle(
+ ::GetCurrentProcess(), aProc->GetChildProcessHandle(),
+ ::GetCurrentProcess(), &handle_, SYNCHRONIZE, FALSE, 0)) {
+ failed = true;
+ } else {
+ handle.reset(handle_);
+ }
+ });
+
+ if (failed || !handle) {
+ return NS_ERROR_FAILURE;
+ }
+ }
+
+ // Create and attach the resolver for the promise, giving the handle over to
+ // it.
+ WinHandlePromiseImpl::Create(std::move(handle), promise);
+
+ promise.forget(aOutPromise);
+
+ return NS_OK;
+# else // !defined(XP_WIN)
+ return NS_ERROR_NOT_IMPLEMENTED;
+# endif
+}
+
+NS_IMETHODIMP
+UtilityProcessTest::StopProcess(const char* aActorName) {
+ using namespace mozilla::dom;
+
+ SandboxingKind sbKind;
+ if (aActorName) {
+ const nsDependentCString actorStringName(aActorName);
+ UtilityActorName actorName = UtilityActorNameFromString(actorStringName);
+ sbKind = FindUtilityProcessWithActor(actorName);
+ } else {
+ sbKind = FindUtilityProcessWithActor(UtilityActorName::EndGuard_);
+ }
+
+ if (sbKind == SandboxingKind::COUNT) {
+ MOZ_ASSERT_UNREACHABLE(
+ "Attempted to stop process for actor when no "
+ "such process exists");
+ return NS_ERROR_FAILURE;
+ }
+
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ MOZ_ASSERT(utilityProc, "No UtilityprocessManager?");
+
+ utilityProc->CleanShutdown(sbKind);
+ Maybe<int32_t> utilityPid = utilityProc->ProcessPid(sbKind);
+ MOZ_RELEASE_ASSERT(utilityPid.isNothing(),
+ "Should not have a utility process PID anymore");
+
+ return NS_OK;
+}
+
+NS_IMETHODIMP
+UtilityProcessTest::TestTelemetryProbes() {
+ RefPtr<UtilityProcessManager> utilityProc =
+ UtilityProcessManager::GetSingleton();
+ MOZ_ASSERT(utilityProc, "No UtilityprocessManager?");
+
+ for (RefPtr<UtilityProcessParent>& parent :
+ utilityProc->GetAllProcessesProcessParent()) {
+ Unused << parent->SendTestTelemetryProbes();
+ }
+
+ return NS_OK;
+}
+
+NS_IMPL_ISUPPORTS(UtilityProcessTest, nsIUtilityProcessTest)
+
+} // namespace mozilla::ipc
+#endif // defined(ENABLE_TESTS)
diff --git a/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.h b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.h
new file mode 100644
index 0000000000..6c80fce71b
--- /dev/null
+++ b/ipc/glue/test/utility_process_xpcom/UtilityProcessTest.h
@@ -0,0 +1,29 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+#ifndef _include_ipc_glue_UtilityProcessTest_h_
+#define _include_ipc_glue_UtilityProcessTest_h_
+
+#if defined(ENABLE_TESTS)
+# include "nsServiceManagerUtils.h"
+# include "nsIUtilityProcessTest.h"
+
+namespace mozilla::ipc {
+
+class UtilityProcessTest final : public nsIUtilityProcessTest {
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+ NS_DECL_NSIUTILITYPROCESSTEST
+
+ UtilityProcessTest() = default;
+
+ private:
+ ~UtilityProcessTest() = default;
+};
+
+} // namespace mozilla::ipc
+#endif // defined(ENABLE_TESTS)
+
+#endif // _include_ipc_glue_UtilityProcessTest_h_
diff --git a/ipc/glue/test/utility_process_xpcom/components.conf b/ipc/glue/test/utility_process_xpcom/components.conf
new file mode 100644
index 0000000000..25208ba7fc
--- /dev/null
+++ b/ipc/glue/test/utility_process_xpcom/components.conf
@@ -0,0 +1,15 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Classes = [
+ {
+ 'cid': '{0a4478f4-c5ae-4fb1-8686-d5b09fb99afb}',
+ 'contract_ids': ['@mozilla.org/utility-process-test;1'],
+ 'type': 'mozilla::ipc::UtilityProcessTest',
+ 'headers': ['mozilla/ipc/UtilityProcessTest.h'],
+ 'processes': ProcessSelector.MAIN_PROCESS_ONLY,
+ },
+]
diff --git a/ipc/glue/test/utility_process_xpcom/moz.build b/ipc/glue/test/utility_process_xpcom/moz.build
new file mode 100644
index 0000000000..f04b436cbe
--- /dev/null
+++ b/ipc/glue/test/utility_process_xpcom/moz.build
@@ -0,0 +1,21 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+EXPORTS.mozilla.ipc += ["UtilityProcessTest.h"]
+
+UNIFIED_SOURCES += ["UtilityProcessTest.cpp"]
+
+XPCOM_MANIFESTS += ["components.conf"]
+
+XPIDL_MODULE = "utility_process_xpcom_test"
+
+XPIDL_SOURCES += [
+ "nsIUtilityProcessTest.idl",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
diff --git a/ipc/glue/test/utility_process_xpcom/nsIUtilityProcessTest.idl b/ipc/glue/test/utility_process_xpcom/nsIUtilityProcessTest.idl
new file mode 100644
index 0000000000..142be6f0e1
--- /dev/null
+++ b/ipc/glue/test/utility_process_xpcom/nsIUtilityProcessTest.idl
@@ -0,0 +1,56 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "nsISupports.idl"
+
+[scriptable, uuid(0a4478f4-c5ae-4fb1-8686-d5b09fb99afb)]
+interface nsIUtilityProcessTest : nsISupports
+{
+ /**
+ * ** Test-only Method **
+ *
+ * Start a generic utility process from JS code.
+ *
+ * actorsToAdd: An array of actor names, taken from WebIDLUtilityActorName.
+ * Unlike normal utility processes, test processes launched this way do not
+ * have any associated actor names unless specified here. Empty by default.
+ */
+ [implicit_jscontext]
+ Promise startProcess([optional] in Array<ACString> actorsToAdd);
+
+ /**
+ * ** Test-only Method **
+ *
+ * Report when a child process is actually dead (as opposed to merely having
+ * been removed from our internal list of child processes). Must be called
+ * while the process is still live.
+ *
+ * Only implemented on Windows.
+ */
+ [implicit_jscontext]
+ Promise untilChildProcessDead(in uint32_t pid);
+
+ /**
+ * ** Test-only Method **
+ *
+ * Note that we are going to manually crash a process
+ */
+ void noteIntentionalCrash(in unsigned long pid);
+
+ /**
+ * ** Test-only Method **
+ *
+ * Allowing to stop Utility Process from JS code.
+ * Default behavior is to stop any utility process.
+ */
+ void stopProcess([optional] in string utilityActorName);
+
+ /**
+ * ** Test-only Method **
+ *
+ * Sending Telemetry probes
+ */
+ void testTelemetryProbes();
+};
diff --git a/ipc/gtest/TestBigBuffer.cpp b/ipc/gtest/TestBigBuffer.cpp
new file mode 100644
index 0000000000..88c353d53d
--- /dev/null
+++ b/ipc/gtest/TestBigBuffer.cpp
@@ -0,0 +1,86 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "gtest/gtest.h"
+
+#include "mozilla/RandomNum.h"
+#include "mozilla/ipc/BigBuffer.h"
+
+namespace mozilla::ipc {
+
+static bool SerializeAndDeserialize(BigBuffer&& aIn, BigBuffer* aOut) {
+ IPC::Message msg(MSG_ROUTING_NONE, 0);
+ {
+ IPC::MessageWriter writer(msg);
+ IPC::WriteParam(&writer, std::move(aIn));
+ }
+ EXPECT_EQ(aIn.Size(), 0u);
+
+ IPC::MessageReader reader(msg);
+ return IPC::ReadParam(&reader, aOut);
+}
+
+TEST(BigBuffer, Empty)
+{
+ BigBuffer in(0);
+ EXPECT_EQ(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), 0u);
+
+ BigBuffer out;
+ ASSERT_TRUE(SerializeAndDeserialize(std::move(in), &out));
+
+ EXPECT_EQ(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), 0u);
+ EXPECT_EQ(out.GetSharedMemory(), nullptr);
+ EXPECT_EQ(out.Size(), 0u);
+}
+
+TEST(BigBuffer, SmallSize)
+{
+ uint8_t data[]{1, 2, 3};
+ BigBuffer in{Span(data)};
+ EXPECT_EQ(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), 3u);
+
+ BigBuffer out;
+ ASSERT_TRUE(SerializeAndDeserialize(std::move(in), &out));
+
+ EXPECT_EQ(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), 0u);
+ EXPECT_EQ(out.GetSharedMemory(), nullptr);
+ EXPECT_EQ(out.Size(), 3u);
+
+ EXPECT_TRUE(out.AsSpan() == Span(data));
+}
+
+TEST(BigBuffer, BigSize)
+{
+ size_t size = BigBuffer::kShmemThreshold * 2;
+ // Generate a large block of random data which will be serialized in a shmem.
+ nsTArray<uint8_t> data(size);
+ for (size_t i = 0; i < size; ++i) {
+ data.AppendElement(mozilla::RandomUint64OrDie());
+ }
+ BigBuffer in{Span(data)};
+ EXPECT_NE(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), size);
+ EXPECT_EQ(in.GetSharedMemory()->memory(), in.Data());
+
+ BigBuffer out;
+ ASSERT_TRUE(SerializeAndDeserialize(std::move(in), &out));
+
+ EXPECT_EQ(in.GetSharedMemory(), nullptr);
+ EXPECT_EQ(in.Size(), 0u);
+ EXPECT_NE(out.GetSharedMemory(), nullptr);
+ EXPECT_EQ(out.Size(), size);
+ EXPECT_EQ(out.GetSharedMemory()->memory(), out.Data());
+
+ EXPECT_TRUE(out.AsSpan() == Span(data));
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/gtest/TestDataPipe.cpp b/ipc/gtest/TestDataPipe.cpp
new file mode 100644
index 0000000000..340da7c218
--- /dev/null
+++ b/ipc/gtest/TestDataPipe.cpp
@@ -0,0 +1,374 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_message.h"
+#include "gtest/gtest.h"
+
+#include "mozilla/gtest/MozAssertions.h"
+#include "mozilla/ipc/DataPipe.h"
+#include "nsIAsyncInputStream.h"
+#include "nsIAsyncOutputStream.h"
+#include "nsNetUtil.h"
+#include "nsStreamUtils.h"
+
+namespace mozilla::ipc {
+
+namespace {
+
+struct InputStreamCallback : public nsIInputStreamCallback {
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ explicit InputStreamCallback(
+ std::function<nsresult(nsIAsyncInputStream*)> aFunc = nullptr)
+ : mFunc(std::move(aFunc)) {}
+
+ NS_IMETHOD OnInputStreamReady(nsIAsyncInputStream* aStream) override {
+ MOZ_ALWAYS_FALSE(mCalled.exchange(true));
+ return mFunc ? mFunc(aStream) : NS_OK;
+ }
+
+ bool Called() const { return mCalled; }
+
+ private:
+ virtual ~InputStreamCallback() = default;
+
+ std::atomic<bool> mCalled = false;
+ std::function<nsresult(nsIAsyncInputStream*)> mFunc;
+};
+
+NS_IMPL_ISUPPORTS(InputStreamCallback, nsIInputStreamCallback)
+
+struct OutputStreamCallback : public nsIOutputStreamCallback {
+ public:
+ NS_DECL_THREADSAFE_ISUPPORTS
+
+ explicit OutputStreamCallback(
+ std::function<nsresult(nsIAsyncOutputStream*)> aFunc = nullptr)
+ : mFunc(std::move(aFunc)) {}
+
+ NS_IMETHOD OnOutputStreamReady(nsIAsyncOutputStream* aStream) override {
+ MOZ_ALWAYS_FALSE(mCalled.exchange(true));
+ return mFunc ? mFunc(aStream) : NS_OK;
+ }
+
+ bool Called() const { return mCalled; }
+
+ private:
+ virtual ~OutputStreamCallback() = default;
+
+ std::atomic<bool> mCalled = false;
+ std::function<nsresult(nsIAsyncOutputStream*)> mFunc;
+};
+
+NS_IMPL_ISUPPORTS(OutputStreamCallback, nsIOutputStreamCallback)
+
+// Populate an array with the given number of bytes. Data is lorem ipsum
+// random text, but deterministic across multiple calls.
+void CreateData(uint32_t aNumBytes, nsCString& aDataOut) {
+ static const char data[] =
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec egestas "
+ "purus eu condimentum iaculis. In accumsan leo eget odio porttitor, non "
+ "rhoncus nulla vestibulum. Etiam lacinia consectetur nisl nec "
+ "sollicitudin. Sed fringilla accumsan diam, pulvinar varius massa. Duis "
+ "mollis dignissim felis, eget tempus nisi tristique ut. Fusce euismod, "
+ "lectus non lacinia tempor, tellus diam suscipit quam, eget hendrerit "
+ "lacus nunc fringilla ante. Sed ultrices massa vitae risus molestie, ut "
+ "finibus quam laoreet nullam.";
+ static const uint32_t dataLength = sizeof(data) - 1;
+
+ aDataOut.SetCapacity(aNumBytes);
+
+ while (aNumBytes > 0) {
+ uint32_t amount = std::min(dataLength, aNumBytes);
+ aDataOut.Append(data, amount);
+ aNumBytes -= amount;
+ }
+}
+
+// Synchronously consume the given input stream and validate the resulting data
+// against the given string of expected values.
+void ConsumeAndValidateStream(nsIInputStream* aStream,
+ const nsACString& aExpectedData) {
+ nsAutoCString outputData;
+ nsresult rv = NS_ConsumeStream(aStream, UINT32_MAX, outputData);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(aExpectedData.Length(), outputData.Length());
+ ASSERT_TRUE(aExpectedData.Equals(outputData));
+}
+
+} // namespace
+
+TEST(DataPipe, SegmentedReadWrite)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ nsresult rv =
+ NewDataPipe(1024, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData1;
+ CreateData(512, inputData1);
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData1.BeginReading(), inputData1.Length(),
+ &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, 512u);
+
+ uint64_t available = 0;
+ rv = reader->Available(&available);
+ EXPECT_EQ(available, 512u);
+ ConsumeAndValidateStream(reader, inputData1);
+
+ nsCString inputData2;
+ CreateData(1024, inputData2);
+
+ rv = writer->Write(inputData2.BeginReading(), inputData2.Length(),
+ &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, 1024u);
+
+ rv = reader->Available(&available);
+ EXPECT_EQ(available, 1024u);
+ ConsumeAndValidateStream(reader, inputData2);
+}
+
+TEST(DataPipe, SegmentedPartialRead)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ nsresult rv =
+ NewDataPipe(1024, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData1;
+ CreateData(512, inputData1);
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData1.BeginReading(), inputData1.Length(),
+ &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, 512u);
+
+ uint64_t available = 0;
+ rv = reader->Available(&available);
+ EXPECT_EQ(available, 512u);
+ ConsumeAndValidateStream(reader, inputData1);
+
+ nsCString inputData2;
+ CreateData(1024, inputData2);
+
+ rv = writer->Write(inputData2.BeginReading(), inputData2.Length(),
+ &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, 1024u);
+
+ rv = reader->Available(&available);
+ EXPECT_EQ(available, 1024u);
+
+ nsAutoCString outputData;
+ rv = NS_ReadInputStreamToString(reader, outputData, 768);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(768u, outputData.Length());
+ ASSERT_TRUE(Substring(inputData2, 0, 768).Equals(outputData));
+
+ rv = reader->Available(&available);
+ EXPECT_EQ(available, 256u);
+
+ nsAutoCString outputData2;
+ rv = NS_ReadInputStreamToString(reader, outputData2, 256);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(256u, outputData2.Length());
+ ASSERT_TRUE(Substring(inputData2, 768).Equals(outputData2));
+}
+
+TEST(DataPipe, Write_AsyncWait)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ const uint32_t segmentSize = 1024;
+
+ nsresult rv =
+ NewDataPipe(segmentSize, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData;
+ CreateData(segmentSize, inputData);
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, segmentSize);
+
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_EQ(NS_BASE_STREAM_WOULD_BLOCK, rv);
+
+ RefPtr<OutputStreamCallback> cb = new OutputStreamCallback();
+
+ rv = writer->AsyncWait(cb, 0, 0, GetCurrentSerialEventTarget());
+ ASSERT_NS_SUCCEEDED(rv);
+
+ NS_ProcessPendingEvents(nullptr);
+
+ ASSERT_FALSE(cb->Called());
+
+ ConsumeAndValidateStream(reader, inputData);
+
+ ASSERT_FALSE(cb->Called());
+
+ NS_ProcessPendingEvents(nullptr);
+
+ ASSERT_TRUE(cb->Called());
+}
+
+TEST(DataPipe, Read_AsyncWait)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ const uint32_t segmentSize = 1024;
+
+ nsresult rv =
+ NewDataPipe(segmentSize, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData;
+ CreateData(segmentSize, inputData);
+
+ RefPtr<InputStreamCallback> cb = new InputStreamCallback();
+
+ rv = reader->AsyncWait(cb, 0, 0, GetCurrentSerialEventTarget());
+ ASSERT_NS_SUCCEEDED(rv);
+
+ NS_ProcessPendingEvents(nullptr);
+
+ ASSERT_FALSE(cb->Called());
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ ASSERT_FALSE(cb->Called());
+
+ NS_ProcessPendingEvents(nullptr);
+
+ ASSERT_TRUE(cb->Called());
+
+ ConsumeAndValidateStream(reader, inputData);
+}
+
+TEST(DataPipe, Write_AsyncWait_Cancel)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ const uint32_t segmentSize = 1024;
+
+ nsresult rv =
+ NewDataPipe(segmentSize, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData;
+ CreateData(segmentSize, inputData);
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ EXPECT_EQ(numWritten, segmentSize);
+
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_EQ(NS_BASE_STREAM_WOULD_BLOCK, rv);
+
+ RefPtr<OutputStreamCallback> cb = new OutputStreamCallback();
+
+ // Register a callback and immediately cancel it.
+ rv = writer->AsyncWait(cb, 0, 0, GetCurrentSerialEventTarget());
+ ASSERT_NS_SUCCEEDED(rv);
+ rv = writer->AsyncWait(nullptr, 0, 0, nullptr);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ // Even after consuming the stream and processing pending events, the callback
+ // shouldn't be called as it was cancelled.
+ ConsumeAndValidateStream(reader, inputData);
+ NS_ProcessPendingEvents(nullptr);
+ ASSERT_FALSE(cb->Called());
+}
+
+TEST(DataPipe, Read_AsyncWait_Cancel)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+
+ const uint32_t segmentSize = 1024;
+
+ nsresult rv =
+ NewDataPipe(segmentSize, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ nsCString inputData;
+ CreateData(segmentSize, inputData);
+
+ RefPtr<InputStreamCallback> cb = new InputStreamCallback();
+
+ // Register a callback and immediately cancel it.
+ rv = reader->AsyncWait(cb, 0, 0, GetCurrentSerialEventTarget());
+ ASSERT_NS_SUCCEEDED(rv);
+
+ rv = reader->AsyncWait(nullptr, 0, 0, nullptr);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ // Write data into the pipe to make the callback become ready.
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ // Even after processing pending events, the callback shouldn't be called as
+ // it was cancelled.
+ NS_ProcessPendingEvents(nullptr);
+ ASSERT_FALSE(cb->Called());
+
+ ConsumeAndValidateStream(reader, inputData);
+}
+
+TEST(DataPipe, SerializeReader)
+{
+ RefPtr<DataPipeReceiver> reader;
+ RefPtr<DataPipeSender> writer;
+ nsresult rv =
+ NewDataPipe(1024, getter_AddRefs(writer), getter_AddRefs(reader));
+ ASSERT_NS_SUCCEEDED(rv);
+
+ IPC::Message msg(MSG_ROUTING_NONE, 0);
+ IPC::MessageWriter msgWriter(msg);
+ IPC::WriteParam(&msgWriter, reader);
+
+ uint64_t available = 0;
+ rv = reader->Available(&available);
+ ASSERT_NS_FAILED(rv);
+
+ nsCString inputData;
+ CreateData(512, inputData);
+
+ uint32_t numWritten = 0;
+ rv = writer->Write(inputData.BeginReading(), inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ RefPtr<DataPipeReceiver> reader2;
+ IPC::MessageReader msgReader(msg);
+ ASSERT_TRUE(IPC::ReadParam(&msgReader, &reader2));
+ ASSERT_TRUE(reader2);
+
+ rv = reader2->Available(&available);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(available, 512u);
+ ConsumeAndValidateStream(reader2, inputData);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/gtest/TestLogging.cpp b/ipc/gtest/TestLogging.cpp
new file mode 100644
index 0000000000..52a8a8ead6
--- /dev/null
+++ b/ipc/gtest/TestLogging.cpp
@@ -0,0 +1,65 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/ipc/ProtocolUtils.h"
+
+namespace mozilla::ipc {
+
+#if defined(DEBUG) || defined(FUZZING)
+TEST(IPCLogging, EmptyFilter)
+{
+ const char* emptyFilter = "";
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ParentSide, emptyFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ChildSide, emptyFilter));
+}
+
+TEST(IPCLogging, SingleProtocolFilter)
+{
+ const char* contentParentFilter = "PContentParent";
+ EXPECT_TRUE(LoggingEnabledFor("PContent", ParentSide, contentParentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ChildSide, contentParentFilter));
+}
+
+TEST(IPCLogging, CommaDelimitedProtocolsFilter)
+{
+ const char* gmpContentFilter = "PGMPContentChild,PGMPContentParent";
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ChildSide, gmpContentFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ParentSide, gmpContentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ParentSide, gmpContentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ChildSide, gmpContentFilter));
+}
+
+TEST(IPCLogging, SpaceDelimitedProtocolsFilter)
+{
+ const char* gmpContentFilter = "PGMPContentChild PGMPContentParent";
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ChildSide, gmpContentFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ParentSide, gmpContentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ParentSide, gmpContentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ChildSide, gmpContentFilter));
+}
+
+TEST(IPCLogging, CatchAllFilter)
+{
+ const char* catchAllFilter = "1";
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ChildSide, catchAllFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ParentSide, catchAllFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PContent", ParentSide, catchAllFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PContent", ChildSide, catchAllFilter));
+}
+
+TEST(IPCLogging, BothSidesFilter)
+{
+ const char* gmpContentFilter = "PGMPContent,PContentParent";
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ChildSide, gmpContentFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PGMPContent", ParentSide, gmpContentFilter));
+ EXPECT_TRUE(LoggingEnabledFor("PContent", ParentSide, gmpContentFilter));
+ EXPECT_FALSE(LoggingEnabledFor("PContent", ChildSide, gmpContentFilter));
+}
+#endif // defined(DEBUG) || defined(FUZZING)
+
+} // namespace mozilla::ipc
diff --git a/ipc/gtest/TestRandomAccessStreamUtils.cpp b/ipc/gtest/TestRandomAccessStreamUtils.cpp
new file mode 100644
index 0000000000..899c528a30
--- /dev/null
+++ b/ipc/gtest/TestRandomAccessStreamUtils.cpp
@@ -0,0 +1,216 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_message.h"
+#include "gtest/gtest.h"
+#include "mozilla/NotNull.h"
+#include "mozilla/Result.h"
+#include "mozilla/ResultVariant.h"
+#include "mozilla/ipc/RandomAccessStreamParams.h"
+#include "mozilla/ipc/RandomAccessStreamUtils.h"
+#include "mozilla/gtest/MozAssertions.h"
+#include "nsAppDirectoryServiceDefs.h"
+#include "nsCOMPtr.h"
+#include "nsDirectoryServiceUtils.h"
+#include "nsIFile.h"
+#include "nsIFileStreams.h"
+#include "nsIRandomAccessStream.h"
+#include "nsNetUtil.h"
+#include "nsStreamUtils.h"
+
+namespace mozilla::ipc {
+
+namespace {
+
+Result<nsCOMPtr<nsIRandomAccessStream>, nsresult> CreateFileStream() {
+ nsCOMPtr<nsIFile> dir;
+ nsresult rv =
+ NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(dir));
+ if (NS_FAILED(rv)) {
+ return Err(rv);
+ }
+
+ nsCOMPtr<nsIFile> file;
+ rv = dir->Clone(getter_AddRefs(file));
+ if (NS_FAILED(rv)) {
+ return Err(rv);
+ }
+
+ rv = file->Append(u"testfile"_ns);
+ if (NS_FAILED(rv)) {
+ return Err(rv);
+ }
+
+ rv = file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0666);
+ if (NS_FAILED(rv)) {
+ return Err(rv);
+ }
+
+ nsCOMPtr<nsIRandomAccessStream> stream;
+ rv = NS_NewLocalFileRandomAccessStream(getter_AddRefs(stream), file);
+ if (NS_FAILED(rv)) {
+ return Err(rv);
+ }
+
+ return stream;
+}
+
+// Populate an array with the given number of bytes. Data is lorem ipsum
+// random text, but deterministic across multiple calls.
+void CreateData(uint32_t aNumBytes, nsCString& aDataOut) {
+ static const char data[] =
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec egestas "
+ "purus eu condimentum iaculis. In accumsan leo eget odio porttitor, non "
+ "rhoncus nulla vestibulum. Etiam lacinia consectetur nisl nec "
+ "sollicitudin. Sed fringilla accumsan diam, pulvinar varius massa. Duis "
+ "mollis dignissim felis, eget tempus nisi tristique ut. Fusce euismod, "
+ "lectus non lacinia tempor, tellus diam suscipit quam, eget hendrerit "
+ "lacus nunc fringilla ante. Sed ultrices massa vitae risus molestie, ut "
+ "finibus quam laoreet nullam.";
+ static const uint32_t dataLength = sizeof(data) - 1;
+
+ aDataOut.SetCapacity(aNumBytes);
+
+ while (aNumBytes > 0) {
+ uint32_t amount = std::min(dataLength, aNumBytes);
+ aDataOut.Append(data, amount);
+ aNumBytes -= amount;
+ }
+}
+
+// Synchronously consume the given input stream and validate the resulting data
+// against the given string of expected values.
+void ConsumeAndValidateStream(nsIInputStream* aStream,
+ const nsACString& aExpectedData) {
+ uint64_t available = 0;
+ nsresult rv = aStream->Available(&available);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(available, aExpectedData.Length());
+
+ nsAutoCString outputData;
+ rv = NS_ConsumeStream(aStream, UINT32_MAX, outputData);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ ASSERT_EQ(aExpectedData.Length(), outputData.Length());
+ ASSERT_TRUE(aExpectedData.Equals(outputData));
+}
+
+} // namespace
+
+TEST(RandomAccessStreamUtils, NullRandomAccessStream_MaybeSerialize)
+{
+ nsCOMPtr<nsIRandomAccessStream> stream;
+
+ Maybe<RandomAccessStreamParams> streamParams =
+ SerializeRandomAccessStream(stream, nullptr);
+
+ ASSERT_TRUE(streamParams.isNothing());
+
+ auto res = DeserializeRandomAccessStream(streamParams);
+ ASSERT_TRUE(res.isOk());
+
+ nsCOMPtr<nsIRandomAccessStream> stream2 = res.unwrap();
+ ASSERT_EQ(stream2, nullptr);
+}
+
+TEST(RandomAccessStreamUtils, FileRandomAccessStream_Serialize)
+{
+ const uint32_t dataSize = 256;
+
+ auto res = CreateFileStream();
+ ASSERT_TRUE(res.isOk());
+
+ auto stream = res.unwrap();
+ ASSERT_TRUE(stream);
+
+ nsCOMPtr<nsIFileRandomAccessStream> fileStream = do_QueryInterface(stream);
+ ASSERT_TRUE(fileStream);
+
+ nsCString inputData;
+ CreateData(dataSize, inputData);
+
+ uint32_t numWritten = 0;
+ nsresult rv = stream->OutputStream()->Write(inputData.BeginReading(),
+ inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(numWritten, dataSize);
+
+ RandomAccessStreamParams streamParams = SerializeRandomAccessStream(
+ WrapMovingNotNullUnchecked(std::move(stream)), nullptr);
+
+ ASSERT_EQ(streamParams.type(),
+ RandomAccessStreamParams::TFileRandomAccessStreamParams);
+
+ auto res2 = DeserializeRandomAccessStream(streamParams);
+ ASSERT_TRUE(res2.isOk());
+
+ NotNull<nsCOMPtr<nsIRandomAccessStream>> stream2 = res2.unwrap();
+
+ nsCOMPtr<nsIFileRandomAccessStream> fileStream2 =
+ do_QueryInterface(stream2.get());
+ ASSERT_TRUE(fileStream2);
+
+ int64_t offset;
+ rv = stream2->Tell(&offset);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(offset, dataSize);
+
+ rv = stream2->Seek(nsISeekableStream::NS_SEEK_SET, 0);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ ConsumeAndValidateStream(stream2->InputStream(), inputData);
+}
+
+TEST(RandomAccessStreamUtils, FileRandomAccessStream_MaybeSerialize)
+{
+ const uint32_t dataSize = 512;
+
+ auto res = CreateFileStream();
+ ASSERT_TRUE(res.isOk());
+
+ auto stream = res.unwrap();
+ ASSERT_TRUE(stream);
+
+ nsCOMPtr<nsIFileRandomAccessStream> fileStream = do_QueryInterface(stream);
+ ASSERT_TRUE(fileStream);
+
+ nsCString inputData;
+ CreateData(dataSize, inputData);
+
+ uint32_t numWritten = 0;
+ nsresult rv = stream->OutputStream()->Write(inputData.BeginReading(),
+ inputData.Length(), &numWritten);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(numWritten, dataSize);
+
+ Maybe<RandomAccessStreamParams> streamParams =
+ SerializeRandomAccessStream(stream, nullptr);
+
+ ASSERT_TRUE(streamParams);
+ ASSERT_EQ(streamParams->type(),
+ RandomAccessStreamParams::TFileRandomAccessStreamParams);
+
+ auto res2 = DeserializeRandomAccessStream(streamParams);
+ ASSERT_TRUE(res2.isOk());
+
+ nsCOMPtr<nsIRandomAccessStream> stream2 = res2.unwrap();
+ ASSERT_TRUE(stream2);
+
+ nsCOMPtr<nsIFileRandomAccessStream> fileStream2 = do_QueryInterface(stream2);
+ ASSERT_TRUE(fileStream2);
+
+ int64_t offset;
+ rv = stream2->Tell(&offset);
+ ASSERT_NS_SUCCEEDED(rv);
+ ASSERT_EQ(offset, dataSize);
+
+ rv = stream2->Seek(nsISeekableStream::NS_SEEK_SET, 0);
+ ASSERT_NS_SUCCEEDED(rv);
+
+ ConsumeAndValidateStream(stream2->InputStream(), inputData);
+}
+
+} // namespace mozilla::ipc
diff --git a/ipc/gtest/TestSharedMemory.cpp b/ipc/gtest/TestSharedMemory.cpp
new file mode 100644
index 0000000000..5d27bd81d0
--- /dev/null
+++ b/ipc/gtest/TestSharedMemory.cpp
@@ -0,0 +1,338 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "base/shared_memory.h"
+
+#include "mozilla/RefPtr.h"
+#include "mozilla/ipc/SharedMemory.h"
+#include "mozilla/ipc/SharedMemoryBasic.h"
+
+#ifdef XP_LINUX
+# include <errno.h>
+# include <linux/magic.h>
+# include <stdio.h>
+# include <string.h>
+# include <sys/statfs.h>
+# include <sys/utsname.h>
+#endif
+
+#ifdef XP_WIN
+# include <windows.h>
+#endif
+
+namespace mozilla {
+
+// Try to map a frozen shm for writing. Threat model: the process is
+// compromised and then receives a frozen handle.
+TEST(IPCSharedMemory, FreezeAndMapRW)
+{
+ base::SharedMemory shm;
+
+ // Create and initialize
+ ASSERT_TRUE(shm.CreateFreezeable(1));
+ ASSERT_TRUE(shm.Map(1));
+ auto mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_TRUE(mem);
+ *mem = 'A';
+
+ // Freeze
+ ASSERT_TRUE(shm.Freeze());
+ ASSERT_FALSE(shm.memory());
+
+ // Re-create as writeable
+ auto handle = shm.TakeHandle();
+ ASSERT_TRUE(shm.IsHandleValid(handle));
+ ASSERT_FALSE(shm.IsValid());
+ ASSERT_TRUE(shm.SetHandle(std::move(handle), /* read-only */ false));
+ ASSERT_TRUE(shm.IsValid());
+
+ // This should fail
+ EXPECT_FALSE(shm.Map(1));
+}
+
+// Try to restore write permissions to a frozen mapping. Threat
+// model: the process has mapped frozen shm normally and then is
+// compromised, or as for FreezeAndMapRW (see also the
+// proof-of-concept at https://crbug.com/project-zero/1671 ).
+TEST(IPCSharedMemory, FreezeAndReprotect)
+{
+ base::SharedMemory shm;
+
+ // Create and initialize
+ ASSERT_TRUE(shm.CreateFreezeable(1));
+ ASSERT_TRUE(shm.Map(1));
+ auto mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_TRUE(mem);
+ *mem = 'A';
+
+ // Freeze
+ ASSERT_TRUE(shm.Freeze());
+ ASSERT_FALSE(shm.memory());
+
+ // Re-map
+ ASSERT_TRUE(shm.Map(1));
+ mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_EQ(*mem, 'A');
+
+ // Try to alter protection; should fail
+ EXPECT_FALSE(ipc::SharedMemory::SystemProtectFallible(
+ mem, 1, ipc::SharedMemory::RightsReadWrite));
+}
+
+#ifndef XP_WIN
+// This essentially tests whether FreezeAndReprotect would have failed
+// without the freeze. It doesn't work on Windows: VirtualProtect
+// can't exceed the permissions set in MapViewOfFile regardless of the
+// security status of the original handle.
+TEST(IPCSharedMemory, Reprotect)
+{
+ base::SharedMemory shm;
+
+ // Create and initialize
+ ASSERT_TRUE(shm.CreateFreezeable(1));
+ ASSERT_TRUE(shm.Map(1));
+ auto mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_TRUE(mem);
+ *mem = 'A';
+
+ // Re-create as read-only
+ auto handle = shm.TakeHandle();
+ ASSERT_TRUE(shm.IsHandleValid(handle));
+ ASSERT_FALSE(shm.IsValid());
+ ASSERT_TRUE(shm.SetHandle(std::move(handle), /* read-only */ true));
+ ASSERT_TRUE(shm.IsValid());
+
+ // Re-map
+ ASSERT_TRUE(shm.Map(1));
+ mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_EQ(*mem, 'A');
+
+ // Try to alter protection; should succeed, because not frozen
+ EXPECT_TRUE(ipc::SharedMemory::SystemProtectFallible(
+ mem, 1, ipc::SharedMemory::RightsReadWrite));
+}
+#endif
+
+#ifdef XP_WIN
+// Try to regain write permissions on a read-only handle using
+// DuplicateHandle; this will succeed if the object has no DACL.
+// See also https://crbug.com/338538
+TEST(IPCSharedMemory, WinUnfreeze)
+{
+ base::SharedMemory shm;
+
+ // Create and initialize
+ ASSERT_TRUE(shm.CreateFreezeable(1));
+ ASSERT_TRUE(shm.Map(1));
+ auto mem = reinterpret_cast<char*>(shm.memory());
+ ASSERT_TRUE(mem);
+ *mem = 'A';
+
+ // Freeze
+ ASSERT_TRUE(shm.Freeze());
+ ASSERT_FALSE(shm.memory());
+
+ // Extract handle.
+ auto handle = shm.TakeHandle();
+ ASSERT_TRUE(shm.IsHandleValid(handle));
+ ASSERT_FALSE(shm.IsValid());
+
+ // Unfreeze.
+ HANDLE newHandle = INVALID_HANDLE_VALUE;
+ bool unfroze = ::DuplicateHandle(
+ GetCurrentProcess(), handle.release(), GetCurrentProcess(), &newHandle,
+ FILE_MAP_ALL_ACCESS, false, DUPLICATE_CLOSE_SOURCE);
+ ASSERT_FALSE(unfroze);
+}
+#endif
+
+// Test that a read-only copy sees changes made to the writeable
+// mapping in the case that the page wasn't accessed before the copy.
+TEST(IPCSharedMemory, ROCopyAndWrite)
+{
+ base::SharedMemory shmRW, shmRO;
+
+ // Create and initialize
+ ASSERT_TRUE(shmRW.CreateFreezeable(1));
+ ASSERT_TRUE(shmRW.Map(1));
+ auto memRW = reinterpret_cast<char*>(shmRW.memory());
+ ASSERT_TRUE(memRW);
+
+ // Create read-only copy
+ ASSERT_TRUE(shmRW.ReadOnlyCopy(&shmRO));
+ EXPECT_FALSE(shmRW.IsValid());
+ ASSERT_EQ(shmRW.memory(), memRW);
+ ASSERT_EQ(shmRO.max_size(), size_t(1));
+
+ // Map read-only
+ ASSERT_TRUE(shmRO.IsValid());
+ ASSERT_TRUE(shmRO.Map(1));
+ auto memRO = reinterpret_cast<const char*>(shmRO.memory());
+ ASSERT_TRUE(memRO);
+ ASSERT_NE(memRW, memRO);
+
+ // Check
+ *memRW = 'A';
+ EXPECT_EQ(*memRO, 'A');
+}
+
+// Test that a read-only copy sees changes made to the writeable
+// mapping in the case that the page was accessed before the copy
+// (and, before that, sees the state as of when the copy was made).
+TEST(IPCSharedMemory, ROCopyAndRewrite)
+{
+ base::SharedMemory shmRW, shmRO;
+
+ // Create and initialize
+ ASSERT_TRUE(shmRW.CreateFreezeable(1));
+ ASSERT_TRUE(shmRW.Map(1));
+ auto memRW = reinterpret_cast<char*>(shmRW.memory());
+ ASSERT_TRUE(memRW);
+ *memRW = 'A';
+
+ // Create read-only copy
+ ASSERT_TRUE(shmRW.ReadOnlyCopy(&shmRO));
+ EXPECT_FALSE(shmRW.IsValid());
+ ASSERT_EQ(shmRW.memory(), memRW);
+ ASSERT_EQ(shmRO.max_size(), size_t(1));
+
+ // Map read-only
+ ASSERT_TRUE(shmRO.IsValid());
+ ASSERT_TRUE(shmRO.Map(1));
+ auto memRO = reinterpret_cast<const char*>(shmRO.memory());
+ ASSERT_TRUE(memRO);
+ ASSERT_NE(memRW, memRO);
+
+ // Check
+ ASSERT_EQ(*memRW, 'A');
+ EXPECT_EQ(*memRO, 'A');
+ *memRW = 'X';
+ EXPECT_EQ(*memRO, 'X');
+}
+
+// See FreezeAndMapRW.
+TEST(IPCSharedMemory, ROCopyAndMapRW)
+{
+ base::SharedMemory shmRW, shmRO;
+
+ // Create and initialize
+ ASSERT_TRUE(shmRW.CreateFreezeable(1));
+ ASSERT_TRUE(shmRW.Map(1));
+ auto memRW = reinterpret_cast<char*>(shmRW.memory());
+ ASSERT_TRUE(memRW);
+ *memRW = 'A';
+
+ // Create read-only copy
+ ASSERT_TRUE(shmRW.ReadOnlyCopy(&shmRO));
+ ASSERT_TRUE(shmRO.IsValid());
+
+ // Re-create as writeable
+ auto handle = shmRO.TakeHandle();
+ ASSERT_TRUE(shmRO.IsHandleValid(handle));
+ ASSERT_FALSE(shmRO.IsValid());
+ ASSERT_TRUE(shmRO.SetHandle(std::move(handle), /* read-only */ false));
+ ASSERT_TRUE(shmRO.IsValid());
+
+ // This should fail
+ EXPECT_FALSE(shmRO.Map(1));
+}
+
+// See FreezeAndReprotect
+TEST(IPCSharedMemory, ROCopyAndReprotect)
+{
+ base::SharedMemory shmRW, shmRO;
+
+ // Create and initialize
+ ASSERT_TRUE(shmRW.CreateFreezeable(1));
+ ASSERT_TRUE(shmRW.Map(1));
+ auto memRW = reinterpret_cast<char*>(shmRW.memory());
+ ASSERT_TRUE(memRW);
+ *memRW = 'A';
+
+ // Create read-only copy
+ ASSERT_TRUE(shmRW.ReadOnlyCopy(&shmRO));
+ ASSERT_TRUE(shmRO.IsValid());
+
+ // Re-map
+ ASSERT_TRUE(shmRO.Map(1));
+ auto memRO = reinterpret_cast<char*>(shmRO.memory());
+ ASSERT_EQ(*memRO, 'A');
+
+ // Try to alter protection; should fail
+ EXPECT_FALSE(ipc::SharedMemory::SystemProtectFallible(
+ memRO, 1, ipc::SharedMemory::RightsReadWrite));
+}
+
+TEST(IPCSharedMemory, IsZero)
+{
+ base::SharedMemory shm;
+
+ static constexpr size_t kSize = 65536;
+ ASSERT_TRUE(shm.Create(kSize));
+ ASSERT_TRUE(shm.Map(kSize));
+
+ auto* mem = reinterpret_cast<char*>(shm.memory());
+ for (size_t i = 0; i < kSize; ++i) {
+ ASSERT_EQ(mem[i], 0) << "offset " << i;
+ }
+}
+
+#ifndef FUZZING
+TEST(IPCSharedMemory, BasicIsZero)
+{
+ auto shm = MakeRefPtr<ipc::SharedMemoryBasic>();
+
+ static constexpr size_t kSize = 65536;
+ ASSERT_TRUE(shm->Create(kSize));
+ ASSERT_TRUE(shm->Map(kSize));
+
+ auto* mem = reinterpret_cast<char*>(shm->memory());
+ for (size_t i = 0; i < kSize; ++i) {
+ ASSERT_EQ(mem[i], 0) << "offset " << i;
+ }
+}
+#endif
+
+#if defined(XP_LINUX) && !defined(ANDROID)
+// Test that memfd_create is used where expected.
+//
+// More precisely: if memfd_create support is expected, verify that
+// shared memory isn't subject to a filesystem size limit.
+TEST(IPCSharedMemory, IsMemfd)
+{
+ static constexpr int kMajor = 3;
+ static constexpr int kMinor = 17;
+
+ struct utsname uts;
+ ASSERT_EQ(uname(&uts), 0) << strerror(errno);
+ ASSERT_STREQ(uts.sysname, "Linux");
+ int major, minor;
+ ASSERT_EQ(sscanf(uts.release, "%d.%d", &major, &minor), 2);
+ bool expectMemfd = major > kMajor || (major == kMajor && minor >= kMinor);
+
+ base::SharedMemory shm;
+ ASSERT_TRUE(shm.Create(1));
+ UniqueFileHandle fd = shm.TakeHandle();
+ ASSERT_TRUE(fd);
+
+ struct statfs fs;
+ ASSERT_EQ(fstatfs(fd.get(), &fs), 0) << strerror(errno);
+ EXPECT_EQ(fs.f_type, TMPFS_MAGIC);
+ static constexpr decltype(fs.f_blocks) kNoLimit = 0;
+ if (expectMemfd) {
+ EXPECT_EQ(fs.f_blocks, kNoLimit);
+ } else {
+ // On older kernels, we expect the memfd / no-limit test to fail.
+ // (In theory it could succeed if backported memfd support exists;
+ // if that ever happens, this check can be removed.)
+ EXPECT_NE(fs.f_blocks, kNoLimit);
+ }
+}
+#endif
+
+} // namespace mozilla
diff --git a/ipc/gtest/TestUnsafeSharedMemoryHandle.cpp b/ipc/gtest/TestUnsafeSharedMemoryHandle.cpp
new file mode 100644
index 0000000000..6934ae0d4c
--- /dev/null
+++ b/ipc/gtest/TestUnsafeSharedMemoryHandle.cpp
@@ -0,0 +1,58 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "chrome/common/ipc_message.h"
+#include "chrome/common/ipc_message_utils.h"
+#include "gtest/gtest.h"
+
+#include "mozilla/RandomNum.h"
+#include "mozilla/ipc/RawShmem.h"
+
+namespace mozilla::ipc {
+
+static bool SerializeAndDeserialize(UnsafeSharedMemoryHandle&& aIn,
+ UnsafeSharedMemoryHandle* aOut) {
+ IPC::Message msg(MSG_ROUTING_NONE, 0);
+ {
+ IPC::MessageWriter writer(msg);
+ IPC::WriteParam(&writer, std::move(aIn));
+ }
+
+ IPC::MessageReader reader(msg);
+ return IPC::ReadParam(&reader, aOut);
+}
+
+void TestUnsafeSharedMemoryHandle(size_t aSize) {
+ auto maybeHandle = UnsafeSharedMemoryHandle::CreateAndMap(aSize);
+ ASSERT_TRUE(maybeHandle);
+ auto [handle, mapping] = maybeHandle.extract();
+
+ EXPECT_EQ(mapping.Size(), aSize);
+
+ auto inBytes = mapping.Bytes();
+ for (size_t i = 0; i < aSize; ++i) {
+ inBytes[i] = static_cast<uint8_t>(i % 255);
+ }
+
+ UnsafeSharedMemoryHandle out;
+ ASSERT_TRUE(SerializeAndDeserialize(std::move(handle), &out));
+
+ auto mapping2 = WritableSharedMemoryMapping::Open(std::move(out)).value();
+
+ EXPECT_EQ(mapping2.Size(), aSize);
+ auto outBytes = mapping2.Bytes();
+ for (size_t i = 0; i < aSize; ++i) {
+ EXPECT_EQ(outBytes[i], static_cast<uint8_t>(i % 255));
+ }
+}
+
+TEST(UnsafeSharedMemoryHandle, Empty)
+{ TestUnsafeSharedMemoryHandle(0); }
+
+TEST(UnsafeSharedMemoryHandle, SmallSize)
+{ TestUnsafeSharedMemoryHandle(2048); }
+
+} // namespace mozilla::ipc
diff --git a/ipc/gtest/moz.build b/ipc/gtest/moz.build
new file mode 100644
index 0000000000..e56b0754ec
--- /dev/null
+++ b/ipc/gtest/moz.build
@@ -0,0 +1,20 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Library("ipctest")
+
+SOURCES += [
+ "TestBigBuffer.cpp",
+ "TestDataPipe.cpp",
+ "TestLogging.cpp",
+ "TestRandomAccessStreamUtils.cpp",
+ "TestSharedMemory.cpp",
+ "TestUnsafeSharedMemoryHandle.cpp",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul-gtest"
diff --git a/ipc/ipdl/Makefile.in b/ipc/ipdl/Makefile.in
new file mode 100644
index 0000000000..7a4d2acfba
--- /dev/null
+++ b/ipc/ipdl/Makefile.in
@@ -0,0 +1,33 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+ifdef COMPILE_ENVIRONMENT
+
+# This file is generated by the moz.build backend.
+include ipdlsrcs.mk
+
+include $(topsrcdir)/config/rules.mk
+
+ipdl_py_deps := \
+ $(wildcard $(srcdir)/*.py) \
+ $(wildcard $(srcdir)/ipdl/*.py) \
+ $(wildcard $(srcdir)/ipdl/cxx/*.py) \
+ $(wildcard $(topsrcdir)/other-licenses/ply/ply/*.py) \
+ $(NULL)
+
+# NB: the IPDL compiler manages .ipdl-->.h/.cpp dependencies itself,
+# which is why we don't have explicit .h/.cpp targets here
+ipdl.track: $(ALL_IPDLSRCS) $(srcdir)/sync-messages.ini $(srcdir)/message-metadata.ini $(ipdl_py_deps)
+ $(PYTHON3) $(srcdir)/ipdl.py \
+ --sync-msg-list=$(srcdir)/sync-messages.ini \
+ --msg-metadata=$(srcdir)/message-metadata.ini \
+ --outheaders-dir=_ipdlheaders \
+ --outcpp-dir=. \
+ $(IPDLDIRS:%=-I%) \
+ $(ALL_IPDLSRCS)
+ touch $@
+
+export:: ipdl.track
+endif
+
diff --git a/ipc/ipdl/ipdl.py b/ipc/ipdl/ipdl.py
new file mode 100644
index 0000000000..230e0a213f
--- /dev/null
+++ b/ipc/ipdl/ipdl.py
@@ -0,0 +1,336 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+import optparse
+import os
+import sys
+from configparser import RawConfigParser
+from io import StringIO
+
+import ipdl
+
+
+def log(minv, fmt, *args):
+ if _verbosity >= minv:
+ print(fmt % args)
+
+
+# process command line
+
+
+op = optparse.OptionParser(usage="ipdl.py [options] IPDLfiles...")
+op.add_option(
+ "-I",
+ "--include",
+ dest="includedirs",
+ default=[],
+ action="append",
+ help="Additional directory to search for included protocol specifications",
+)
+op.add_option(
+ "-s",
+ "--sync-msg-list",
+ dest="syncMsgList",
+ default="sync-messages.ini",
+ help="Config file listing allowed sync messages",
+)
+op.add_option(
+ "-m",
+ "--msg-metadata",
+ dest="msgMetadata",
+ default="message-metadata.ini",
+ help="Predicted message sizes for reducing serialization malloc overhead.",
+)
+op.add_option(
+ "-v",
+ "--verbose",
+ dest="verbosity",
+ default=1,
+ action="count",
+ help="Verbose logging (specify -vv or -vvv for very verbose logging)",
+)
+op.add_option(
+ "-q",
+ "--quiet",
+ dest="verbosity",
+ action="store_const",
+ const=0,
+ help="Suppress logging output",
+)
+op.add_option(
+ "-d",
+ "--outheaders-dir",
+ dest="headersdir",
+ default=".",
+ help="""Directory into which C++ headers will be generated.
+A protocol Foo in the namespace bar will cause the headers
+ dir/bar/Foo.h, dir/bar/FooParent.h, and dir/bar/FooParent.h
+to be generated""",
+)
+op.add_option(
+ "-o",
+ "--outcpp-dir",
+ dest="cppdir",
+ default=".",
+ help="""Directory into which C++ sources will be generated
+A protocol Foo in the namespace bar will cause the sources
+ cppdir/FooParent.cpp, cppdir/FooChild.cpp
+to be generated""",
+)
+
+options, files = op.parse_args()
+_verbosity = options.verbosity
+syncMsgList = options.syncMsgList
+msgMetadata = options.msgMetadata
+headersdir = options.headersdir
+cppdir = options.cppdir
+includedirs = [os.path.abspath(incdir) for incdir in options.includedirs]
+
+if not len(files):
+ op.error("No IPDL files specified")
+
+ipcmessagestartpath = os.path.join(headersdir, "IPCMessageStart.h")
+ipc_msgtype_name_path = os.path.join(cppdir, "IPCMessageTypeName.cpp")
+
+log(2, 'Generated C++ headers will be generated relative to "%s"', headersdir)
+log(2, 'Generated C++ sources will be generated in "%s"', cppdir)
+
+allmessages = {}
+allmessageprognames = []
+allprotocols = []
+
+
+def normalizedFilename(f):
+ if f == "-":
+ return "<stdin>"
+ return f
+
+
+log(2, "Reading sync message list")
+parser = RawConfigParser()
+parser.read_file(open(options.syncMsgList))
+syncMsgList = parser.sections()
+
+for section in syncMsgList:
+ if not parser.get(section, "description"):
+ print("Error: Sync message %s lacks a description" % section, file=sys.stderr)
+ sys.exit(1)
+
+# Read message metadata. Right now we only have 'segment_capacity'
+# for the standard segment size used for serialization.
+log(2, "Reading message metadata...")
+msgMetadataConfig = RawConfigParser()
+msgMetadataConfig.read_file(open(options.msgMetadata))
+
+segmentCapacityDict = {}
+for msgName in msgMetadataConfig.sections():
+ if msgMetadataConfig.has_option(msgName, "segment_capacity"):
+ capacity = msgMetadataConfig.get(msgName, "segment_capacity")
+ segmentCapacityDict[msgName] = capacity
+
+# First pass: parse and type-check all protocols
+for f in files:
+ log(2, os.path.basename(f))
+ filename = normalizedFilename(f)
+ if f == "-":
+ fd = sys.stdin
+ else:
+ fd = open(f)
+
+ specstring = fd.read()
+ fd.close()
+
+ ast = ipdl.parse(specstring, filename, includedirs=includedirs)
+ if ast is None:
+ print("Specification could not be parsed.", file=sys.stderr)
+ sys.exit(1)
+
+ log(2, "checking types")
+ if not ipdl.typecheck(ast):
+ print("Specification is not well typed.", file=sys.stderr)
+ sys.exit(1)
+
+ if not ipdl.checkSyncMessage(ast, syncMsgList):
+ print(
+ "Error: New sync IPC messages must be reviewed by an IPC peer and recorded in %s"
+ % options.syncMsgList,
+ file=sys.stderr,
+ ) # NOQA: E501
+ sys.exit(1)
+
+if not ipdl.checkFixedSyncMessages(parser):
+ # Errors have alraedy been printed to stderr, just exit
+ sys.exit(1)
+
+# Second pass: generate code
+for f in files:
+ # Read from parser cache
+ filename = normalizedFilename(f)
+ ast = ipdl.parse(None, filename, includedirs=includedirs)
+ ipdl.gencxx(filename, ast, headersdir, cppdir, segmentCapacityDict)
+
+ if ast.protocol:
+ allmessages[ast.protocol.name] = ipdl.genmsgenum(ast)
+ allprotocols.append(ast.protocol.name)
+ # e.g. PContent::RequestMemoryReport (not prefixed or suffixed.)
+ for md in ast.protocol.messageDecls:
+ allmessageprognames.append("%s::%s" % (md.namespace, md.decl.progname))
+
+allprotocols.sort()
+
+# Check if we have undefined message names in segmentCapacityDict.
+# This is a fool-proof of the 'message-metadata.ini' file.
+undefinedMessages = set(segmentCapacityDict.keys()) - set(allmessageprognames)
+if len(undefinedMessages) > 0:
+ print("Error: Undefined message names in message-metadata.ini:", file=sys.stderr)
+ print(undefinedMessages, file=sys.stderr)
+ sys.exit(1)
+
+ipcmsgstart = StringIO()
+
+print(
+ """
+// CODE GENERATED by ipdl.py. Do not edit.
+
+#ifndef IPCMessageStart_h
+#define IPCMessageStart_h
+
+enum IPCMessageStart {
+""",
+ file=ipcmsgstart,
+)
+
+for name in allprotocols:
+ print(" %sMsgStart," % name, file=ipcmsgstart)
+
+print(
+ """
+ LastMsgIndex
+};
+
+static_assert(LastMsgIndex <= 65536, "need to update IPC_MESSAGE_MACRO");
+
+#endif // ifndef IPCMessageStart_h
+""",
+ file=ipcmsgstart,
+)
+
+ipc_msgtype_name = StringIO()
+print(
+ """
+// CODE GENERATED by ipdl.py. Do not edit.
+#include <cstdint>
+
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "IPCMessageStart.h"
+
+using std::uint32_t;
+
+namespace {
+
+enum IPCMessages {
+""",
+ file=ipc_msgtype_name,
+)
+
+for protocol in sorted(allmessages.keys()):
+ for msg, num in allmessages[protocol].idnums:
+ if num:
+ print(" %s = %s," % (msg, num), file=ipc_msgtype_name)
+ elif not msg.endswith("End"):
+ print(" %s__%s," % (protocol, msg), file=ipc_msgtype_name)
+
+print(
+ """
+};
+
+} // anonymous namespace
+
+namespace IPC {
+
+const char* StringFromIPCMessageType(uint32_t aMessageType)
+{
+ switch (aMessageType) {
+""",
+ file=ipc_msgtype_name,
+)
+
+for protocol in sorted(allmessages.keys()):
+ for msg, num in allmessages[protocol].idnums:
+ if num or msg.endswith("End"):
+ continue
+ print(
+ """
+ case %s__%s:
+ return "%s::%s";"""
+ % (protocol, msg, protocol, msg),
+ file=ipc_msgtype_name,
+ )
+
+print(
+ """
+ case DATA_PIPE_CLOSED_MESSAGE_TYPE:
+ return "DATA_PIPE_CLOSED_MESSAGE";
+ case DATA_PIPE_BYTES_CONSUMED_MESSAGE_TYPE:
+ return "DATA_PIPE_BYTES_CONSUMED_MESSAGE";
+ case ACCEPT_INVITE_MESSAGE_TYPE:
+ return "ACCEPT_INVITE_MESSAGE";
+ case REQUEST_INTRODUCTION_MESSAGE_TYPE:
+ return "REQUEST_INTRODUCTION_MESSAGE";
+ case INTRODUCE_MESSAGE_TYPE:
+ return "INTRODUCE_MESSAGE";
+ case BROADCAST_MESSAGE_TYPE:
+ return "BROADCAST_MESSAGE";
+ case EVENT_MESSAGE_TYPE:
+ return "EVENT_MESSAGE";
+ case IMPENDING_SHUTDOWN_MESSAGE_TYPE:
+ return "IMPENDING_SHUTDOWN";
+ case BUILD_IDS_MATCH_MESSAGE_TYPE:
+ return "BUILD_IDS_MATCH_MESSAGE";
+ case BUILD_ID_MESSAGE_TYPE:
+ return "BUILD_ID_MESSAGE";
+ case CHANNEL_OPENED_MESSAGE_TYPE:
+ return "CHANNEL_OPENED_MESSAGE";
+ case SHMEM_DESTROYED_MESSAGE_TYPE:
+ return "SHMEM_DESTROYED_MESSAGE";
+ case SHMEM_CREATED_MESSAGE_TYPE:
+ return "SHMEM_CREATED_MESSAGE";
+ case GOODBYE_MESSAGE_TYPE:
+ return "GOODBYE_MESSAGE";
+ case CANCEL_MESSAGE_TYPE:
+ return "CANCEL_MESSAGE";
+ default:
+ return "<unknown IPC msg name>";
+ }
+}
+
+} // namespace IPC
+
+namespace mozilla {
+namespace ipc {
+
+const char* ProtocolIdToName(IPCMessageStart aId) {
+ switch (aId) {
+""",
+ file=ipc_msgtype_name,
+)
+
+for name in allprotocols:
+ print(" case %sMsgStart:" % name, file=ipc_msgtype_name)
+ print(' return "%s";' % name, file=ipc_msgtype_name)
+
+print(
+ """
+ default:
+ return "<unknown protocol id>";
+ }
+}
+
+} // namespace ipc
+} // namespace mozilla
+""",
+ file=ipc_msgtype_name,
+)
+
+ipdl.writeifmodified(ipcmsgstart.getvalue(), ipcmessagestartpath)
+ipdl.writeifmodified(ipc_msgtype_name.getvalue(), ipc_msgtype_name_path)
diff --git a/ipc/ipdl/ipdl/__init__.py b/ipc/ipdl/ipdl/__init__.py
new file mode 100644
index 0000000000..50ceb4f953
--- /dev/null
+++ b/ipc/ipdl/ipdl/__init__.py
@@ -0,0 +1,98 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+__all__ = [
+ "gencxx",
+ "genipdl",
+ "parse",
+ "typecheck",
+ "writeifmodified",
+ "checkSyncMessage",
+ "checkFixedSyncMessages",
+]
+
+import os
+import sys
+from io import StringIO
+
+from ipdl.cgen import IPDLCodeGen
+from ipdl.lower import LowerToCxx, msgenums
+from ipdl.parser import Parser, ParseError
+from ipdl.type import TypeCheck
+from ipdl.checker import checkSyncMessage, checkFixedSyncMessages
+
+from ipdl.cxx.cgen import CxxCodeGen
+
+
+def parse(specstring, filename="/stdin", includedirs=[], errout=sys.stderr):
+ """Return an IPDL AST if parsing was successful. Print errors to |errout|
+ if it is not."""
+ # The file type and name are later enforced by the type checker.
+ # This is just a hint to the parser.
+ prefix, ext = os.path.splitext(filename)
+ name = os.path.basename(prefix)
+ if ext == ".ipdlh":
+ type = "header"
+ else:
+ type = "protocol"
+
+ try:
+ return Parser(type, name).parse(
+ specstring, os.path.abspath(filename), includedirs
+ )
+ except ParseError as p:
+ print(p, file=errout)
+ return None
+
+
+def typecheck(ast, errout=sys.stderr):
+ """Return True iff |ast| is well typed. Print errors to |errout| if
+ it is not."""
+ return TypeCheck().check(ast, errout)
+
+
+def gencxx(ipdlfilename, ast, outheadersdir, outcppdir, segmentcapacitydict):
+ headers, cpps = LowerToCxx().lower(ast, segmentcapacitydict)
+
+ def resolveHeader(hdr):
+ return [
+ hdr,
+ os.path.join(
+ outheadersdir, *([ns.name for ns in ast.namespaces] + [hdr.name])
+ ),
+ ]
+
+ def resolveCpp(cpp):
+ return [cpp, os.path.join(outcppdir, cpp.name)]
+
+ for ast, filename in [resolveHeader(hdr) for hdr in headers] + [
+ resolveCpp(cpp) for cpp in cpps
+ ]:
+ tempfile = StringIO()
+ CxxCodeGen(tempfile).cgen(ast)
+ writeifmodified(tempfile.getvalue(), filename)
+
+
+def genipdl(ast, outdir):
+ return IPDLCodeGen().cgen(ast)
+
+
+def genmsgenum(ast):
+ return msgenums(ast.protocol, pretty=True)
+
+
+def writeifmodified(contents, file):
+ contents = contents.encode("utf-8")
+ dir = os.path.dirname(file)
+ os.path.exists(dir) or os.makedirs(dir)
+
+ oldcontents = None
+ if os.path.exists(file):
+ fd = open(file, "rb")
+ oldcontents = fd.read()
+ fd.close()
+ if oldcontents != contents:
+ fd = open(file, "wb")
+ fd.write(contents)
+ fd.close()
diff --git a/ipc/ipdl/ipdl/ast.py b/ipc/ipdl/ipdl/ast.py
new file mode 100644
index 0000000000..ff083cf628
--- /dev/null
+++ b/ipc/ipdl/ipdl/ast.py
@@ -0,0 +1,477 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+from .util import hash_str
+
+
+NOT_NESTED = 1
+INSIDE_SYNC_NESTED = 2
+INSIDE_CPOW_NESTED = 3
+
+NESTED_ATTR_MAP = {
+ "not": NOT_NESTED,
+ "inside_sync": INSIDE_SYNC_NESTED,
+ "inside_cpow": INSIDE_CPOW_NESTED,
+}
+
+# Each element of this list is the IPDL source representation of a priority.
+priorityList = ["normal", "input", "vsync", "mediumhigh", "control"]
+
+priorityAttrMap = {src: idx for idx, src in enumerate(priorityList)}
+
+NORMAL_PRIORITY = priorityAttrMap["normal"]
+
+
+class Visitor:
+ def defaultVisit(self, node):
+ raise Exception(
+ "INTERNAL ERROR: no visitor for node type `%s'" % (node.__class__.__name__)
+ )
+
+ def visitTranslationUnit(self, tu):
+ for cxxInc in tu.cxxIncludes:
+ cxxInc.accept(self)
+ for inc in tu.includes:
+ inc.accept(self)
+ for su in tu.structsAndUnions:
+ su.accept(self)
+ for using in tu.builtinUsing:
+ using.accept(self)
+ for using in tu.using:
+ using.accept(self)
+ if tu.protocol:
+ tu.protocol.accept(self)
+
+ def visitCxxInclude(self, inc):
+ pass
+
+ def visitInclude(self, inc):
+ # Note: we don't visit the child AST here, because that needs delicate
+ # and pass-specific handling
+ pass
+
+ def visitStructDecl(self, struct):
+ for f in struct.fields:
+ f.accept(self)
+ for a in struct.attributes.values():
+ a.accept(self)
+
+ def visitStructField(self, field):
+ field.typespec.accept(self)
+
+ def visitUnionDecl(self, union):
+ for t in union.components:
+ t.accept(self)
+ for a in union.attributes.values():
+ a.accept(self)
+
+ def visitUsingStmt(self, using):
+ for a in using.attributes.values():
+ a.accept(self)
+
+ def visitProtocol(self, p):
+ for namespace in p.namespaces:
+ namespace.accept(self)
+ for mgr in p.managers:
+ mgr.accept(self)
+ for managed in p.managesStmts:
+ managed.accept(self)
+ for msgDecl in p.messageDecls:
+ msgDecl.accept(self)
+ for a in p.attributes.values():
+ a.accept(self)
+
+ def visitNamespace(self, ns):
+ pass
+
+ def visitManager(self, mgr):
+ pass
+
+ def visitManagesStmt(self, mgs):
+ pass
+
+ def visitMessageDecl(self, md):
+ for inParam in md.inParams:
+ inParam.accept(self)
+ for outParam in md.outParams:
+ outParam.accept(self)
+ for a in md.attributes.values():
+ a.accept(self)
+
+ def visitParam(self, decl):
+ for a in decl.attributes.values():
+ a.accept(self)
+
+ def visitTypeSpec(self, ts):
+ pass
+
+ def visitAttribute(self, a):
+ if isinstance(a.value, Node):
+ a.value.accept(self)
+
+ def visitStringLiteral(self, sl):
+ pass
+
+ def visitDecl(self, d):
+ for a in d.attributes.values():
+ a.accept(self)
+
+
+class Loc:
+ def __init__(self, filename="<??>", lineno=0):
+ assert filename
+ self.filename = filename
+ self.lineno = lineno
+
+ def __repr__(self):
+ return "%r:%r" % (self.filename, self.lineno)
+
+ def __str__(self):
+ return "%s:%s" % (self.filename, self.lineno)
+
+
+Loc.NONE = Loc(filename="<??>", lineno=0)
+
+
+class _struct:
+ pass
+
+
+class Node:
+ def __init__(self, loc=Loc.NONE):
+ self.loc = loc
+
+ def accept(self, visitor):
+ visit = getattr(visitor, "visit" + self.__class__.__name__, None)
+ if visit is None:
+ return getattr(visitor, "defaultVisit")(self)
+ return visit(self)
+
+ def addAttrs(self, attrsName):
+ if not hasattr(self, attrsName):
+ setattr(self, attrsName, _struct())
+
+
+class NamespacedNode(Node):
+ def __init__(self, loc=Loc.NONE, name=None):
+ Node.__init__(self, loc)
+ self.name = name
+ self.namespaces = []
+
+ def addOuterNamespace(self, namespace):
+ self.namespaces.insert(0, namespace)
+
+ def qname(self):
+ return QualifiedId(self.loc, self.name, [ns.name for ns in self.namespaces])
+
+
+class TranslationUnit(NamespacedNode):
+ def __init__(self, type, name):
+ NamespacedNode.__init__(self, name=name)
+ self.filetype = type
+ self.filename = None
+ self.cxxIncludes = []
+ self.includes = []
+ self.builtinUsing = []
+ self.using = []
+ self.structsAndUnions = []
+ self.protocol = None
+
+ def addCxxInclude(self, cxxInclude):
+ self.cxxIncludes.append(cxxInclude)
+
+ def addInclude(self, inc):
+ self.includes.append(inc)
+
+ def addStructDecl(self, struct):
+ self.structsAndUnions.append(struct)
+
+ def addUnionDecl(self, union):
+ self.structsAndUnions.append(union)
+
+ def addUsingStmt(self, using):
+ self.using.append(using)
+
+ def setProtocol(self, protocol):
+ self.protocol = protocol
+
+
+class CxxInclude(Node):
+ def __init__(self, loc, cxxFile):
+ Node.__init__(self, loc)
+ self.file = cxxFile
+
+
+class Include(Node):
+ def __init__(self, loc, type, name):
+ Node.__init__(self, loc)
+ suffix = "ipdl"
+ if type == "header":
+ suffix += "h"
+ self.file = "%s.%s" % (name, suffix)
+
+
+class UsingStmt(Node):
+ def __init__(
+ self,
+ loc,
+ cxxTypeSpec,
+ cxxHeader=None,
+ kind=None,
+ attributes={},
+ ):
+ Node.__init__(self, loc)
+ assert isinstance(cxxTypeSpec, QualifiedId)
+ assert cxxHeader is None or isinstance(cxxHeader, str)
+ assert kind is None or kind == "class" or kind == "struct"
+ self.type = cxxTypeSpec
+ self.header = cxxHeader
+ self.kind = kind
+ self.attributes = attributes
+
+ def canBeForwardDeclared(self):
+ return self.isClass() or self.isStruct()
+
+ def isClass(self):
+ return self.kind == "class"
+
+ def isStruct(self):
+ return self.kind == "struct"
+
+ def isRefcounted(self):
+ return "RefCounted" in self.attributes
+
+ def isSendMoveOnly(self):
+ moveonly = self.attributes.get("MoveOnly")
+ return moveonly and moveonly.value in (None, "send")
+
+ def isDataMoveOnly(self):
+ moveonly = self.attributes.get("MoveOnly")
+ return moveonly and moveonly.value in (None, "data")
+
+
+# "singletons"
+
+
+class PrettyPrinted:
+ @classmethod
+ def __hash__(cls):
+ return hash_str(cls.pretty)
+
+ @classmethod
+ def __str__(cls):
+ return cls.pretty
+
+
+class ASYNC(PrettyPrinted):
+ pretty = "async"
+
+
+class INTR(PrettyPrinted):
+ pretty = "intr"
+
+
+class SYNC(PrettyPrinted):
+ pretty = "sync"
+
+
+class INOUT(PrettyPrinted):
+ pretty = "inout"
+
+
+class IN(PrettyPrinted):
+ pretty = "in"
+
+
+class OUT(PrettyPrinted):
+ pretty = "out"
+
+
+class Namespace(Node):
+ def __init__(self, loc, namespace):
+ Node.__init__(self, loc)
+ self.name = namespace
+
+
+class Protocol(NamespacedNode):
+ def __init__(self, loc):
+ NamespacedNode.__init__(self, loc)
+ self.attributes = {}
+ self.sendSemantics = ASYNC
+ self.managers = []
+ self.managesStmts = []
+ self.messageDecls = []
+
+ def nestedUpTo(self):
+ if "NestedUpTo" not in self.attributes:
+ return NOT_NESTED
+
+ return NESTED_ATTR_MAP.get(self.attributes["NestedUpTo"].value, NOT_NESTED)
+
+ def implAttribute(self, side):
+ assert side in ("parent", "child")
+ attr = self.attributes.get(side.capitalize() + "Impl")
+ if attr is not None:
+ return attr.value
+ return None
+
+ def procAttribute(self, side):
+ assert side in ("parent", "child")
+ attr = self.attributes.get(side.capitalize() + "Proc")
+ if attr is not None:
+ return attr.value
+ elif side == "parent" and len(self.managers) == 0:
+ return "Parent" # Default for toplevel actors
+ return None
+
+
+class StructField(Node):
+ def __init__(self, loc, type, name):
+ Node.__init__(self, loc)
+ self.typespec = type
+ self.name = name
+
+
+class StructDecl(NamespacedNode):
+ def __init__(self, loc, name, fields, attributes):
+ NamespacedNode.__init__(self, loc, name)
+ self.fields = fields
+ self.attributes = attributes
+ # A list of indices into `fields` for determining the order in
+ # which fields are laid out in memory. We don't just reorder
+ # `fields` itself so as to keep the ordering reasonably stable
+ # for e.g. C++ constructors when new fields are added.
+ self.packed_field_ordering = []
+
+
+class UnionDecl(NamespacedNode):
+ def __init__(self, loc, name, components, attributes):
+ NamespacedNode.__init__(self, loc, name)
+ self.components = components
+ self.attributes = attributes
+
+
+class Manager(Node):
+ def __init__(self, loc, managerName):
+ Node.__init__(self, loc)
+ self.name = managerName
+
+
+class ManagesStmt(Node):
+ def __init__(self, loc, managedName):
+ Node.__init__(self, loc)
+ self.name = managedName
+
+
+class MessageDecl(Node):
+ def __init__(self, loc):
+ Node.__init__(self, loc)
+ self.name = None
+ self.attributes = {}
+ self.sendSemantics = ASYNC
+ self.direction = None
+ self.inParams = []
+ self.outParams = []
+
+ def addInParams(self, inParamsList):
+ self.inParams += inParamsList
+
+ def addOutParams(self, outParamsList):
+ self.outParams += outParamsList
+
+ def nested(self):
+ if "Nested" not in self.attributes:
+ return NOT_NESTED
+
+ return NESTED_ATTR_MAP.get(self.attributes["Nested"].value, NOT_NESTED)
+
+ def priority(self):
+ if "Priority" in self.attributes:
+ sourcePriority = self.attributes["Priority"].value
+ else:
+ sourcePriority = "normal"
+ return priorityAttrMap.get(sourcePriority, NORMAL_PRIORITY)
+
+ def replyPriority(self):
+ if "ReplyPriority" in self.attributes:
+ sourcePriority = self.attributes["ReplyPriority"].value
+ if sourcePriority in priorityAttrMap:
+ return priorityAttrMap[sourcePriority]
+ return self.priority()
+
+
+class Param(Node):
+ def __init__(self, loc, typespec, name, attributes={}):
+ Node.__init__(self, loc)
+ self.name = name
+ self.typespec = typespec
+ self.attributes = attributes
+
+
+class TypeSpec(Node):
+ def __init__(self, loc, spec):
+ Node.__init__(self, loc)
+ assert isinstance(spec, str)
+ self.spec = spec # str
+ self.array = False # bool
+ self.maybe = False # bool
+ self.nullable = False # bool
+ self.uniqueptr = False # bool
+
+ def basename(self):
+ return self.spec
+
+ def __str__(self):
+ return self.spec
+
+
+class Attribute(Node):
+ def __init__(self, loc, name, value):
+ Node.__init__(self, loc)
+ self.name = name
+ self.value = value
+
+
+class StringLiteral(Node):
+ def __init__(self, loc, value):
+ Node.__init__(self, loc)
+ self.value = value
+
+ def __str__(self):
+ return '"%s"' % self.value
+
+
+class QualifiedId: # FIXME inherit from node?
+ def __init__(self, loc, baseid, quals=[]):
+ assert isinstance(baseid, str)
+ for qual in quals:
+ assert isinstance(qual, str)
+
+ self.loc = loc
+ self.baseid = baseid
+ self.quals = quals
+
+ def qualify(self, id):
+ self.quals.append(self.baseid)
+ self.baseid = id
+
+ def __str__(self):
+ # NOTE: include a leading "::" in order to force all QualifiedIds to be
+ # fully qualified types in C++
+ return "::" + "::".join(self.quals + [self.baseid])
+
+
+# added by type checking passes
+
+
+class Decl(Node):
+ def __init__(self, loc):
+ Node.__init__(self, loc)
+ self.progname = None # what the programmer typed, if relevant
+ self.shortname = None # shortest way to refer to this decl
+ self.fullname = None # full way to refer to this decl
+ self.loc = loc
+ self.type = None
+ self.scope = None
+ self.attributes = {}
diff --git a/ipc/ipdl/ipdl/builtin.py b/ipc/ipdl/ipdl/builtin.py
new file mode 100644
index 0000000000..b1bab64af8
--- /dev/null
+++ b/ipc/ipdl/ipdl/builtin.py
@@ -0,0 +1,76 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# WARNING: the syntax of the builtin types is not checked, so please
+# don't add something syntactically invalid. It will not be fun to
+# track down the bug.
+
+# C types
+# These types don't live in any namespace, so can't be imported with `using`
+# statements like normal C++ types.
+CTypes = (
+ "bool",
+ "char",
+ "short",
+ "int",
+ "long",
+ "float",
+ "double",
+)
+
+# C++ types
+# These types must be fully qualified, and will be `typedef`-ed into IPDL
+# structs to make them readily available when used.
+Types = (
+ # stdint types
+ "int8_t",
+ "uint8_t",
+ "int16_t",
+ "uint16_t",
+ "int32_t",
+ "uint32_t",
+ "int64_t",
+ "uint64_t",
+ "intptr_t",
+ "uintptr_t",
+ # You may be tempted to add size_t. Do not! See bug 1525199.
+ # Mozilla types: "less" standard things we know how serialize/deserialize
+ "nsresult",
+ "nsString",
+ "nsCString",
+ "mozilla::ipc::Shmem",
+ "mozilla::ipc::ByteBuf",
+ "mozilla::UniquePtr",
+ "mozilla::ipc::FileDescriptor",
+)
+
+
+# XXX(Bug 1677487) Can we restrict including ByteBuf.h, FileDescriptor.h,
+# MozPromise.h and Shmem.h to those protocols that really use them?
+HeaderIncludes = (
+ "mozilla/Attributes.h",
+ "IPCMessageStart.h",
+ "mozilla/RefPtr.h",
+ "nsString.h",
+ "nsTArray.h",
+ "nsTHashtable.h",
+ "mozilla/MozPromise.h",
+ "mozilla/OperatorNewExtensions.h",
+ "mozilla/UniquePtr.h",
+ "mozilla/ipc/ByteBuf.h",
+ "mozilla/ipc/FileDescriptor.h",
+ "mozilla/ipc/IPCForwards.h",
+ "mozilla/ipc/Shmem.h",
+)
+
+CppIncludes = (
+ "ipc/IPCMessageUtils.h",
+ "ipc/IPCMessageUtilsSpecializations.h",
+ "nsIFile.h",
+ "mozilla/ipc/Endpoint.h",
+ "mozilla/ipc/ProtocolMessageUtils.h",
+ "mozilla/ipc/ProtocolUtils.h",
+ "mozilla/ipc/ShmemMessageUtils.h",
+ "mozilla/ipc/TaintingIPCUtils.h",
+)
diff --git a/ipc/ipdl/ipdl/cgen.py b/ipc/ipdl/ipdl/cgen.py
new file mode 100644
index 0000000000..8ed8da4d81
--- /dev/null
+++ b/ipc/ipdl/ipdl/cgen.py
@@ -0,0 +1,108 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+
+from ipdl.ast import Visitor
+
+
+class CodePrinter:
+ def __init__(self, outf=sys.stdout, indentCols=4):
+ self.outf = outf
+ self.col = 0
+ self.indentCols = indentCols
+
+ def write(self, str):
+ self.outf.write(str)
+
+ def printdent(self, str=""):
+ self.write((" " * self.col) + str)
+
+ def println(self, str=""):
+ self.write(str + "\n")
+
+ def printdentln(self, str):
+ self.write((" " * self.col) + str + "\n")
+
+ def indent(self):
+ self.col += self.indentCols
+
+ def dedent(self):
+ self.col -= self.indentCols
+
+
+# -----------------------------------------------------------------------------
+class IPDLCodeGen(CodePrinter, Visitor):
+ """Spits back out equivalent IPDL to the code that generated this.
+ Also known as pretty-printing."""
+
+ def __init__(self, outf=sys.stdout, indentCols=4, printed=set()):
+ CodePrinter.__init__(self, outf, indentCols)
+ self.printed = printed
+
+ def visitTranslationUnit(self, tu):
+ self.printed.add(tu.filename)
+ self.println("//\n// Automatically generated by ipdlc\n//")
+ CodeGen.visitTranslationUnit(self, tu) # NOQA: F821
+
+ def visitCxxInclude(self, inc):
+ self.println('include "' + inc.file + '";')
+
+ def visitProtocolInclude(self, inc):
+ self.println('include protocol "' + inc.file + '";')
+ if inc.tu.filename not in self.printed:
+ self.println("/* Included file:")
+ IPDLCodeGen(
+ outf=self.outf, indentCols=self.indentCols, printed=self.printed
+ ).visitTranslationUnit(inc.tu)
+
+ self.println("*/")
+
+ def visitProtocol(self, p):
+ self.println()
+ for namespace in p.namespaces:
+ namespace.accept(self)
+
+ self.println("%s protocol %s\n{" % (p.sendSemantics[0], p.name))
+ self.indent()
+
+ for mgs in p.managesStmts:
+ mgs.accept(self)
+ if len(p.managesStmts):
+ self.println()
+
+ for msgDecl in p.messageDecls:
+ msgDecl.accept(self)
+ self.println()
+
+ self.dedent()
+ self.println("}")
+ self.write("}\n" * len(p.namespaces))
+
+ def visitManagerStmt(self, mgr):
+ self.printdentln("manager " + mgr.name + ";")
+
+ def visitManagesStmt(self, mgs):
+ self.printdentln("manages " + mgs.name + ";")
+
+ def visitMessageDecl(self, msg):
+ self.printdent("%s %s %s(" % (msg.sendSemantics[0], msg.direction[0], msg.name))
+ for i, inp in enumerate(msg.inParams):
+ inp.accept(self)
+ if i != (len(msg.inParams) - 1):
+ self.write(", ")
+ self.write(")")
+ if 0 == len(msg.outParams):
+ self.println(";")
+ return
+
+ self.println()
+ self.indent()
+ self.printdent("returns (")
+ for i, outp in enumerate(msg.outParams):
+ outp.accept(self)
+ if i != (len(msg.outParams) - 1):
+ self.write(", ")
+ self.println(");")
+ self.dedent()
diff --git a/ipc/ipdl/ipdl/checker.py b/ipc/ipdl/ipdl/checker.py
new file mode 100644
index 0000000000..c93dc3e0e8
--- /dev/null
+++ b/ipc/ipdl/ipdl/checker.py
@@ -0,0 +1,79 @@
+# vim: set ts=4 sw=4 tw=99 et:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+from ipdl.ast import Visitor, ASYNC
+
+
+class SyncMessageChecker(Visitor):
+ syncMsgList = []
+ seenProtocols = []
+ seenSyncMessages = []
+
+ def __init__(self, syncMsgList):
+ SyncMessageChecker.syncMsgList = syncMsgList
+ self.errors = []
+
+ def prettyMsgName(self, msg):
+ return "%s::%s" % (self.currentProtocol, msg)
+
+ def errorUnknownSyncMessage(self, loc, msg):
+ self.errors.append("%s: error: Unknown sync IPC message %s" % (str(loc), msg))
+
+ def errorAsyncMessageCanRemove(self, loc, msg):
+ self.errors.append(
+ "%s: error: IPC message %s is async, can be delisted" % (str(loc), msg)
+ )
+
+ def visitProtocol(self, p):
+ self.errors = []
+ self.currentProtocol = p.name
+ SyncMessageChecker.seenProtocols.append(p.name)
+ Visitor.visitProtocol(self, p)
+
+ def visitMessageDecl(self, md):
+ pn = self.prettyMsgName(md.name)
+ if md.sendSemantics is not ASYNC:
+ if pn not in SyncMessageChecker.syncMsgList:
+ self.errorUnknownSyncMessage(md.loc, pn)
+ SyncMessageChecker.seenSyncMessages.append(pn)
+ elif pn in SyncMessageChecker.syncMsgList:
+ self.errorAsyncMessageCanRemove(md.loc, pn)
+
+ @staticmethod
+ def getFixedSyncMessages():
+ return set(SyncMessageChecker.syncMsgList) - set(
+ SyncMessageChecker.seenSyncMessages
+ )
+
+
+def checkSyncMessage(tu, syncMsgList, errout=sys.stderr):
+ checker = SyncMessageChecker(syncMsgList)
+ tu.accept(checker)
+ if len(checker.errors):
+ for error in checker.errors:
+ print(error, file=errout)
+ return False
+ return True
+
+
+def checkFixedSyncMessages(config, errout=sys.stderr):
+ fixed = SyncMessageChecker.getFixedSyncMessages()
+ error_free = True
+ for item in fixed:
+ protocol = item.split("::")[0]
+ # Ignore things like sync messages in test protocols we didn't compile.
+ # Also, ignore platform-specific IPC messages.
+ if (
+ protocol in SyncMessageChecker.seenProtocols
+ and "platform" not in config.options(item)
+ ):
+ print(
+ "Error: Sync IPC message %s not found, it appears to be fixed.\n"
+ "Please remove it from sync-messages.ini." % item,
+ file=errout,
+ )
+ error_free = False
+ return error_free
diff --git a/ipc/ipdl/ipdl/cxx/__init__.py b/ipc/ipdl/ipdl/cxx/__init__.py
new file mode 100644
index 0000000000..6fbe8159b2
--- /dev/null
+++ b/ipc/ipdl/ipdl/cxx/__init__.py
@@ -0,0 +1,3 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
diff --git a/ipc/ipdl/ipdl/cxx/ast.py b/ipc/ipdl/ipdl/cxx/ast.py
new file mode 100644
index 0000000000..a4aba98571
--- /dev/null
+++ b/ipc/ipdl/ipdl/cxx/ast.py
@@ -0,0 +1,1033 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import copy
+import functools
+
+from ipdl.util import hash_str
+
+
+class Visitor:
+ def defaultVisit(self, node):
+ raise Exception(
+ "INTERNAL ERROR: no visitor for node type `%s'" % (node.__class__.__name__)
+ )
+
+ def visitWhitespace(self, ws):
+ pass
+
+ def visitVerbatimNode(self, verb):
+ pass
+
+ def visitGroupNode(self, group):
+ for node in group.nodes:
+ node.accept(self)
+
+ def visitFile(self, f):
+ for thing in f.stuff:
+ thing.accept(self)
+
+ def visitCppDirective(self, ppd):
+ pass
+
+ def visitBlock(self, block):
+ for stmt in block.stmts:
+ stmt.accept(self)
+
+ def visitNamespace(self, ns):
+ self.visitBlock(ns)
+
+ def visitType(self, type):
+ pass
+
+ def visitTypeArray(self, ta):
+ ta.basetype.accept(self)
+ ta.nmemb.accept(self)
+
+ def visitTypeEnum(self, enum):
+ pass
+
+ def visitTypeFunction(self, fn):
+ pass
+
+ def visitTypeUnion(self, union):
+ for t, name in union.components:
+ t.accept(self)
+
+ def visitTypedef(self, tdef):
+ tdef.fromtype.accept(self)
+
+ def visitUsing(self, us):
+ us.type.accept(self)
+
+ def visitForwardDecl(self, fd):
+ pass
+
+ def visitDecl(self, decl):
+ decl.type.accept(self)
+
+ def visitParam(self, param):
+ self.visitDecl(param)
+ if param.default is not None:
+ param.default.accept(self)
+
+ def visitClass(self, cls):
+ for inherit in cls.inherits:
+ inherit.accept(self)
+ self.visitBlock(cls)
+
+ def visitInherit(self, inh):
+ pass
+
+ def visitFriendClassDecl(self, fcd):
+ pass
+
+ def visitMethodDecl(self, meth):
+ for param in meth.params:
+ param.accept(self)
+ if meth.ret is not None:
+ meth.ret.accept(self)
+ if meth.typeop is not None:
+ meth.typeop.accept(self)
+ if meth.T is not None:
+ meth.T.accept(self)
+
+ def visitMethodDefn(self, meth):
+ meth.decl.accept(self)
+ self.visitBlock(meth)
+
+ def visitFunctionDecl(self, fun):
+ self.visitMethodDecl(fun)
+
+ def visitFunctionDefn(self, fd):
+ self.visitMethodDefn(fd)
+
+ def visitConstructorDecl(self, ctor):
+ self.visitMethodDecl(ctor)
+
+ def visitConstructorDefn(self, cd):
+ cd.decl.accept(self)
+ for init in cd.memberinits:
+ init.accept(self)
+ self.visitBlock(cd)
+
+ def visitDestructorDecl(self, dtor):
+ self.visitMethodDecl(dtor)
+
+ def visitDestructorDefn(self, dd):
+ dd.decl.accept(self)
+ self.visitBlock(dd)
+
+ def visitExprLiteral(self, l):
+ pass
+
+ def visitExprVar(self, v):
+ pass
+
+ def visitExprPrefixUnop(self, e):
+ e.expr.accept(self)
+
+ def visitExprBinary(self, e):
+ e.left.accept(self)
+ e.right.accept(self)
+
+ def visitExprConditional(self, c):
+ c.cond.accept(self)
+ c.ife.accept(self)
+ c.elsee.accept(self)
+
+ def visitExprAddrOf(self, eao):
+ self.visitExprPrefixUnop(eao)
+
+ def visitExprDeref(self, ed):
+ self.visitExprPrefixUnop(ed)
+
+ def visitExprNot(self, en):
+ self.visitExprPrefixUnop(en)
+
+ def visitExprCast(self, ec):
+ ec.expr.accept(self)
+
+ def visitExprSelect(self, es):
+ es.obj.accept(self)
+
+ def visitExprAssn(self, ea):
+ ea.lhs.accept(self)
+ ea.rhs.accept(self)
+
+ def visitExprCall(self, ec):
+ ec.func.accept(self)
+ for arg in ec.args:
+ arg.accept(self)
+
+ def visitExprMove(self, ec):
+ self.visitExprCall(ec)
+
+ def visitExprNothing(self, ec):
+ self.visitExprCall(ec)
+
+ def visitExprSome(self, ec):
+ self.visitExprCall(ec)
+
+ def visitExprNew(self, en):
+ en.ctype.accept(self)
+ if en.newargs is not None:
+ for arg in en.newargs:
+ arg.accept(self)
+ if en.args is not None:
+ for arg in en.args:
+ arg.accept(self)
+
+ def visitExprDelete(self, ed):
+ ed.obj.accept(self)
+
+ def visitExprMemberInit(self, minit):
+ self.visitExprCall(minit)
+
+ def visitExprLambda(self, l):
+ self.visitBlock(l)
+
+ def visitStmtBlock(self, sb):
+ self.visitBlock(sb)
+
+ def visitStmtDecl(self, sd):
+ sd.decl.accept(self)
+ if sd.init is not None:
+ sd.init.accept(self)
+
+ def visitLabel(self, label):
+ pass
+
+ def visitCaseLabel(self, case):
+ pass
+
+ def visitDefaultLabel(self, dl):
+ pass
+
+ def visitStmtIf(self, si):
+ si.cond.accept(self)
+ si.ifb.accept(self)
+ if si.elseb is not None:
+ si.elseb.accept(self)
+
+ def visitStmtFor(self, sf):
+ if sf.init is not None:
+ sf.init.accept(self)
+ if sf.cond is not None:
+ sf.cond.accept(self)
+ if sf.update is not None:
+ sf.update.accept(self)
+
+ def visitStmtSwitch(self, ss):
+ ss.expr.accept(self)
+ self.visitBlock(ss)
+
+ def visitStmtBreak(self, sb):
+ pass
+
+ def visitStmtExpr(self, se):
+ se.expr.accept(self)
+
+ def visitStmtReturn(self, sr):
+ if sr.expr is not None:
+ sr.expr.accept(self)
+
+
+# ------------------------------
+
+
+class Node:
+ def __init__(self):
+ pass
+
+ def accept(self, visitor):
+ visit = getattr(visitor, "visit" + self.__class__.__name__, None)
+ if visit is None:
+ return getattr(visitor, "defaultVisit")(self)
+ return visit(self)
+
+
+class Whitespace(Node):
+ # yes, this is silly. but we need to stick comments in the
+ # generated code without resorting to more serious hacks
+ def __init__(self, ws, indent=False):
+ Node.__init__(self)
+ self.ws = ws
+ self.indent = indent
+
+
+Whitespace.NL = Whitespace("\n")
+
+
+class VerbatimNode(Node):
+ # A block of text to be written verbatim to the output file.
+ #
+ # NOTE: This node is usually created by `code`. See `code.py` for details.
+ # FIXME: Merge Whitespace and VerbatimNode? They're identical.
+ def __init__(self, text, indent=0):
+ Node.__init__(self)
+ self.text = text
+ self.indent = indent
+
+
+class GroupNode(Node):
+ # A group of nodes to be treated as a single node. These nodes have an
+ # optional indentation level which should be applied when generating them.
+ #
+ # NOTE: This node is usually created by `code`. See `code.py` for details.
+ def __init__(self, nodes, offset=0):
+ Node.__init__(self)
+ self.nodes = nodes
+ self.offset = offset
+
+
+class File(Node):
+ def __init__(self, filename):
+ Node.__init__(self)
+ self.name = filename
+ # array of stuff in the file --- stmts and preprocessor thingies
+ self.stuff = []
+
+ def addthing(self, thing):
+ assert thing is not None
+ assert not isinstance(thing, list)
+ self.stuff.append(thing)
+
+ def addthings(self, things):
+ for t in things:
+ self.addthing(t)
+
+ # "look like" a Block so code doesn't have to care whether they're
+ # in global scope or not
+ def addstmt(self, stmt):
+ assert stmt is not None
+ assert not isinstance(stmt, list)
+ self.stuff.append(stmt)
+
+ def addstmts(self, stmts):
+ for s in stmts:
+ self.addstmt(s)
+
+ def addcode(self, tmpl, **context):
+ from ipdl.cxx.code import StmtCode
+
+ self.addstmt(StmtCode(tmpl, **context))
+
+
+class CppDirective(Node):
+ """represents |#[directive] [rest]|, where |rest| is any string"""
+
+ def __init__(self, directive, rest=None):
+ Node.__init__(self)
+ self.directive = directive
+ self.rest = rest
+
+
+class Block(Node):
+ def __init__(self):
+ Node.__init__(self)
+ self.stmts = []
+
+ def addstmt(self, stmt):
+ assert stmt is not None
+ assert not isinstance(stmt, tuple)
+ self.stmts.append(stmt)
+
+ def addstmts(self, stmts):
+ for s in stmts:
+ self.addstmt(s)
+
+ def addcode(self, tmpl, **context):
+ from ipdl.cxx.code import StmtCode
+
+ self.addstmt(StmtCode(tmpl, **context))
+
+
+# ------------------------------
+# type and decl thingies
+
+
+class Namespace(Block):
+ def __init__(self, name):
+ assert isinstance(name, str)
+
+ Block.__init__(self)
+ self.name = name
+
+
+class Type(Node):
+ def __init__(
+ self,
+ name,
+ const=False,
+ ptr=False,
+ ptrptr=False,
+ ptrconstptr=False,
+ ref=False,
+ rvalref=False,
+ rightconst=False,
+ hasimplicitcopyctor=True,
+ T=None,
+ inner=None,
+ ):
+ """
+ Represents the type |name<T>::inner| with the ptr and const
+ modifiers as specified.
+
+ To avoid getting fancy with recursive types, we limit the kinds
+ of pointer types that can be be constructed.
+
+ ptr => T*
+ ptrptr => T**
+ ptrconstptr => T* const*
+ ref => T&
+ rvalref => T&&
+
+ Any type, naked or pointer, can be const (const T) or ref (T&)."""
+ # XXX(nika): This type is complex enough at this point, perhaps we
+ # should get "fancy with recursive types" to simplify it.
+ assert isinstance(name, str)
+ assert isinstance(const, bool)
+ assert isinstance(ptr, bool)
+ assert isinstance(ptrptr, bool)
+ assert isinstance(ptrconstptr, bool)
+ assert isinstance(ref, bool)
+ assert isinstance(rvalref, bool)
+ assert isinstance(rightconst, bool)
+ assert not isinstance(T, str)
+
+ Node.__init__(self)
+ self.name = name
+ self.const = const
+ self.ptr = ptr
+ self.ptrptr = ptrptr
+ self.ptrconstptr = ptrconstptr
+ self.ref = ref
+ self.rvalref = rvalref
+ self.rightconst = rightconst
+ self.hasimplicitcopyctor = hasimplicitcopyctor
+ self.T = T
+ self.inner = inner
+ # XXX could get serious here with recursive types, but shouldn't
+ # need that for this codegen
+
+ def __deepcopy__(self, memo):
+ return Type(
+ self.name,
+ const=self.const,
+ ptr=self.ptr,
+ ptrptr=self.ptrptr,
+ ptrconstptr=self.ptrconstptr,
+ ref=self.ref,
+ rvalref=self.rvalref,
+ rightconst=self.rightconst,
+ T=copy.deepcopy(self.T, memo),
+ inner=copy.deepcopy(self.inner, memo),
+ )
+
+
+Type.BOOL = Type("bool")
+Type.INT = Type("int")
+Type.INT32 = Type("int32_t")
+Type.INTPTR = Type("intptr_t")
+Type.NSRESULT = Type("nsresult")
+Type.UINT32 = Type("uint32_t")
+Type.UINT32PTR = Type("uint32_t", ptr=True)
+Type.SIZE = Type("size_t")
+Type.VOID = Type("void")
+Type.VOIDPTR = Type("void", ptr=True)
+Type.AUTO = Type("auto")
+Type.AUTORVAL = Type("auto", rvalref=True)
+
+
+class TypeArray(Node):
+ def __init__(self, basetype, nmemb):
+ """the type |basetype DECLNAME[nmemb]|. |nmemb| is an Expr"""
+ self.basetype = basetype
+ self.nmemb = nmemb
+
+
+class TypeEnum(Node):
+ def __init__(self, name=None):
+ """name can be None"""
+ Node.__init__(self)
+ self.name = name
+ self.idnums = [] # pairs of ('Foo', [num]) or ('Foo', None)
+
+ def addId(self, id, num=None):
+ self.idnums.append((id, num))
+
+
+class TypeUnion(Node):
+ def __init__(self, name=None):
+ Node.__init__(self)
+ self.name = name
+ self.components = [] # [ Decl ]
+
+ def addComponent(self, type, name):
+ self.components.append(Decl(type, name))
+
+
+class TypeFunction(Node):
+ def __init__(self, params=[], ret=Type("void")):
+ """Anonymous function type std::function<>"""
+ self.params = params
+ self.ret = ret
+
+
+@functools.total_ordering
+class Typedef(Node):
+ def __init__(self, fromtype, totypename, templateargs=[]):
+ assert isinstance(totypename, str)
+
+ Node.__init__(self)
+ self.fromtype = fromtype
+ self.totypename = totypename
+ self.templateargs = templateargs
+
+ def __lt__(self, other):
+ return self.totypename < other.totypename
+
+ def __eq__(self, other):
+ return self.__class__ == other.__class__ and self.totypename == other.totypename
+
+ def __hash__(self):
+ return hash_str(self.totypename)
+
+
+class Using(Node):
+ def __init__(self, type):
+ Node.__init__(self)
+ self.type = type
+
+
+class ForwardDecl(Node):
+ def __init__(self, pqname, cls=False, struct=False):
+ # Exactly one of cls and struct must be set
+ assert cls ^ struct
+
+ self.pqname = pqname
+ self.cls = cls
+ self.struct = struct
+
+
+class Decl(Node):
+ """represents |Foo bar|, e.g. in a function signature"""
+
+ def __init__(self, type, name):
+ assert type is not None
+ assert not isinstance(type, str)
+ assert isinstance(name, str)
+
+ Node.__init__(self)
+ self.type = type
+ self.name = name
+
+ def __deepcopy__(self, memo):
+ return Decl(copy.deepcopy(self.type, memo), self.name)
+
+
+class Param(Decl):
+ def __init__(self, type, name, default=None):
+ Decl.__init__(self, type, name)
+ self.default = default
+
+ def __deepcopy__(self, memo):
+ return Param(
+ copy.deepcopy(self.type, memo), self.name, copy.deepcopy(self.default, memo)
+ )
+
+
+# ------------------------------
+# class stuff
+
+
+class Class(Block):
+ def __init__(
+ self,
+ name,
+ inherits=[],
+ interface=False,
+ abstract=False,
+ final=False,
+ specializes=None,
+ struct=False,
+ ):
+ assert not (interface and abstract)
+ assert not (abstract and final)
+ assert not (interface and final)
+ assert not (inherits and specializes)
+
+ Block.__init__(self)
+ self.name = name
+ self.inherits = inherits # [ Type ]
+ self.interface = interface # bool
+ self.abstract = abstract # bool
+ self.final = final # bool
+ self.specializes = specializes # Type or None
+ self.struct = struct # bool
+
+
+class Inherit(Node):
+ def __init__(self, type, viz="public"):
+ assert isinstance(viz, str)
+ Node.__init__(self)
+ self.type = type
+ self.viz = viz
+
+
+class FriendClassDecl(Node):
+ def __init__(self, friend):
+ Node.__init__(self)
+ self.friend = friend
+
+
+# Python2 polyfill for Python3's Enum() functional API.
+
+
+def make_enum(name, members_str):
+ members_list = members_str.split()
+ members_dict = {}
+ for member_value, member in enumerate(members_list, start=1):
+ members_dict[member] = member_value
+ return type(name, (), members_dict)
+
+
+MethodSpec = make_enum("MethodSpec", "NONE VIRTUAL PURE OVERRIDE STATIC FINAL")
+
+
+class MethodDecl(Node):
+ def __init__(
+ self,
+ name,
+ params=[],
+ ret=Type("void"),
+ methodspec=MethodSpec.NONE,
+ const=False,
+ warn_unused=False,
+ force_inline=False,
+ typeop=None,
+ T=None,
+ cls=None,
+ ):
+ assert not (name and typeop)
+ assert name is None or isinstance(name, str)
+ assert not isinstance(ret, list)
+ for decl in params:
+ assert not isinstance(decl, str)
+ assert not isinstance(T, int)
+ assert isinstance(const, bool)
+ assert isinstance(warn_unused, bool)
+ assert isinstance(force_inline, bool)
+
+ if typeop is not None:
+ assert methodspec == MethodSpec.NONE
+ ret = None
+
+ Node.__init__(self)
+ self.name = name
+ self.params = params # [ Param ]
+ self.ret = ret # Type or None
+ self.methodspec = methodspec # enum
+ self.const = const # bool
+ self.warn_unused = warn_unused # bool
+ self.force_inline = force_inline or bool(T) # bool
+ self.typeop = typeop # Type or None
+ self.T = T # Type or None
+ self.cls = cls # Class or None
+ self.only_for_definition = False
+
+ def __deepcopy__(self, memo):
+ return MethodDecl(
+ self.name,
+ params=copy.deepcopy(self.params, memo),
+ ret=copy.deepcopy(self.ret, memo),
+ methodspec=self.methodspec,
+ const=self.const,
+ warn_unused=self.warn_unused,
+ force_inline=self.force_inline,
+ typeop=copy.deepcopy(self.typeop, memo),
+ T=copy.deepcopy(self.T, memo),
+ )
+
+
+class MethodDefn(Block):
+ def __init__(self, decl):
+ Block.__init__(self)
+ self.decl = decl
+
+
+class FunctionDecl(MethodDecl):
+ def __init__(
+ self,
+ name,
+ params=[],
+ ret=Type("void"),
+ methodspec=MethodSpec.NONE,
+ warn_unused=False,
+ force_inline=False,
+ T=None,
+ ):
+ assert methodspec == MethodSpec.NONE or methodspec == MethodSpec.STATIC
+ MethodDecl.__init__(
+ self,
+ name,
+ params=params,
+ ret=ret,
+ methodspec=methodspec,
+ warn_unused=warn_unused,
+ force_inline=force_inline,
+ T=T,
+ )
+
+
+class FunctionDefn(MethodDefn):
+ def __init__(self, decl):
+ MethodDefn.__init__(self, decl)
+
+
+class ConstructorDecl(MethodDecl):
+ def __init__(self, name, params=[], explicit=False, force_inline=False):
+ MethodDecl.__init__(
+ self, name, params=params, ret=None, force_inline=force_inline
+ )
+ self.explicit = explicit
+
+ def __deepcopy__(self, memo):
+ return ConstructorDecl(
+ self.name, copy.deepcopy(self.params, memo), self.explicit
+ )
+
+
+class ConstructorDefn(MethodDefn):
+ def __init__(self, decl, memberinits=[]):
+ MethodDefn.__init__(self, decl)
+ self.memberinits = memberinits
+
+
+class DestructorDecl(MethodDecl):
+ def __init__(self, name, methodspec=MethodSpec.NONE, force_inline=False):
+ # C++ allows pure or override destructors, but ipdl cgen does not.
+ assert methodspec == MethodSpec.NONE or methodspec == MethodSpec.VIRTUAL
+ MethodDecl.__init__(
+ self,
+ name,
+ params=[],
+ ret=None,
+ methodspec=methodspec,
+ force_inline=force_inline,
+ )
+
+ def __deepcopy__(self, memo):
+ return DestructorDecl(
+ self.name, methodspec=self.methodspec, force_inline=self.force_inline
+ )
+
+
+class DestructorDefn(MethodDefn):
+ def __init__(self, decl):
+ MethodDefn.__init__(self, decl)
+
+
+# ------------------------------
+# expressions
+
+
+class ExprVar(Node):
+ def __init__(self, name):
+ assert isinstance(name, str)
+
+ Node.__init__(self)
+ self.name = name
+
+
+ExprVar.THIS = ExprVar("this")
+
+
+class ExprLiteral(Node):
+ def __init__(self, value, type):
+ """|type| is a Python format specifier; 'd' for example"""
+ Node.__init__(self)
+ self.value = value
+ self.type = type
+
+ @staticmethod
+ def Int(i):
+ return ExprLiteral(i, "d")
+
+ @staticmethod
+ def String(s):
+ return ExprLiteral('"' + s + '"', "s")
+
+ def __str__(self):
+ return ("%" + self.type) % (self.value)
+
+
+ExprLiteral.ZERO = ExprLiteral.Int(0)
+ExprLiteral.ONE = ExprLiteral.Int(1)
+ExprLiteral.NULL = ExprVar("nullptr")
+ExprLiteral.TRUE = ExprVar("true")
+ExprLiteral.FALSE = ExprVar("false")
+
+
+class ExprPrefixUnop(Node):
+ def __init__(self, expr, op):
+ assert not isinstance(expr, tuple)
+ self.expr = expr
+ self.op = op
+
+
+class ExprNot(ExprPrefixUnop):
+ def __init__(self, expr):
+ ExprPrefixUnop.__init__(self, expr, "!")
+
+
+class ExprAddrOf(ExprPrefixUnop):
+ def __init__(self, expr):
+ ExprPrefixUnop.__init__(self, expr, "&")
+
+
+class ExprDeref(ExprPrefixUnop):
+ def __init__(self, expr):
+ ExprPrefixUnop.__init__(self, expr, "*")
+
+
+class ExprCast(Node):
+ def __init__(self, expr, type, static=False, const=False):
+ # Exactly one of these should be set
+ assert static ^ const
+
+ Node.__init__(self)
+ self.expr = expr
+ self.type = type
+ self.static = static
+ self.const = const
+
+
+class ExprBinary(Node):
+ def __init__(self, left, op, right):
+ Node.__init__(self)
+ self.left = left
+ self.op = op
+ self.right = right
+
+
+class ExprConditional(Node):
+ def __init__(self, cond, ife, elsee):
+ Node.__init__(self)
+ self.cond = cond
+ self.ife = ife
+ self.elsee = elsee
+
+
+class ExprSelect(Node):
+ def __init__(self, obj, op, field):
+ assert obj and op and field
+ assert not isinstance(obj, str)
+ assert isinstance(op, str)
+
+ Node.__init__(self)
+ self.obj = obj
+ self.op = op
+ if isinstance(field, str):
+ self.field = ExprVar(field)
+ else:
+ self.field = field
+
+
+class ExprAssn(Node):
+ def __init__(self, lhs, rhs, op="="):
+ Node.__init__(self)
+ self.lhs = lhs
+ self.op = op
+ self.rhs = rhs
+
+
+class ExprCall(Node):
+ def __init__(self, func, args=[]):
+ assert hasattr(func, "accept")
+ assert isinstance(args, list)
+ for arg in args:
+ assert arg and not isinstance(arg, str)
+
+ Node.__init__(self)
+ self.func = func
+ self.args = args
+
+
+class ExprMove(ExprCall):
+ def __init__(self, arg):
+ ExprCall.__init__(self, ExprVar("std::move"), args=[arg])
+
+
+class ExprNew(Node):
+ # XXX taking some poetic license ...
+ def __init__(self, ctype, args=[], newargs=None):
+ assert not (ctype.const or ctype.ref or ctype.rvalref)
+
+ Node.__init__(self)
+ self.ctype = ctype
+ self.args = args
+ self.newargs = newargs
+
+
+class ExprDelete(Node):
+ def __init__(self, obj):
+ Node.__init__(self)
+ self.obj = obj
+
+
+class ExprMemberInit(ExprCall):
+ def __init__(self, member, args=[]):
+ ExprCall.__init__(self, member, args)
+
+
+class ExprLambda(Block):
+ def __init__(self, captures=[], params=[], ret=None):
+ Block.__init__(self)
+ assert isinstance(captures, list)
+ assert isinstance(params, list)
+ self.captures = captures
+ self.params = params
+ self.ret = ret
+
+
+# ------------------------------
+# statements etc.
+
+
+class StmtBlock(Block):
+ def __init__(self, stmts=[]):
+ Block.__init__(self)
+ self.addstmts(stmts)
+
+
+class StmtDecl(Node):
+ def __init__(self, decl, init=None, initargs=None):
+ assert not (init and initargs)
+ assert not isinstance(init, str) # easy to confuse with Decl
+ assert not isinstance(init, list)
+ assert not isinstance(decl, tuple)
+
+ Node.__init__(self)
+ self.decl = decl
+ self.init = init
+ self.initargs = initargs
+
+
+class Label(Node):
+ def __init__(self, name):
+ Node.__init__(self)
+ self.name = name
+
+
+Label.PUBLIC = Label("public")
+Label.PROTECTED = Label("protected")
+Label.PRIVATE = Label("private")
+
+
+class CaseLabel(Node):
+ def __init__(self, name):
+ Node.__init__(self)
+ self.name = name
+
+
+class DefaultLabel(Node):
+ def __init__(self):
+ Node.__init__(self)
+
+
+class StmtIf(Node):
+ def __init__(self, cond):
+ Node.__init__(self)
+ self.cond = cond
+ self.ifb = Block()
+ self.elseb = None
+
+ def addifstmt(self, stmt):
+ self.ifb.addstmt(stmt)
+
+ def addifstmts(self, stmts):
+ self.ifb.addstmts(stmts)
+
+ def addelsestmt(self, stmt):
+ if self.elseb is None:
+ self.elseb = Block()
+ self.elseb.addstmt(stmt)
+
+ def addelsestmts(self, stmts):
+ if self.elseb is None:
+ self.elseb = Block()
+ self.elseb.addstmts(stmts)
+
+
+class StmtFor(Block):
+ def __init__(self, init=None, cond=None, update=None):
+ Block.__init__(self)
+ self.init = init
+ self.cond = cond
+ self.update = update
+
+
+class StmtRangedFor(Block):
+ def __init__(self, var, iteree):
+ assert isinstance(var, ExprVar)
+ assert iteree
+
+ Block.__init__(self)
+ self.var = var
+ self.iteree = iteree
+
+
+class StmtSwitch(Block):
+ def __init__(self, expr):
+ Block.__init__(self)
+ self.expr = expr
+ self.nr_cases = 0
+
+ def addcase(self, case, block):
+ """NOTE: |case| is not checked for uniqueness"""
+ assert not isinstance(case, str)
+ assert (
+ isinstance(block, StmtBreak)
+ or isinstance(block, StmtReturn)
+ or isinstance(block, StmtSwitch)
+ or isinstance(block, GroupNode)
+ or isinstance(block, VerbatimNode)
+ or (
+ hasattr(block, "stmts")
+ and (
+ isinstance(block.stmts[-1], StmtBreak)
+ or isinstance(block.stmts[-1], StmtReturn)
+ or isinstance(block.stmts[-1], GroupNode)
+ or isinstance(block.stmts[-1], VerbatimNode)
+ )
+ )
+ )
+ self.addstmt(case)
+ self.addstmt(block)
+ self.nr_cases += 1
+
+
+class StmtBreak(Node):
+ def __init__(self):
+ Node.__init__(self)
+
+
+class StmtExpr(Node):
+ def __init__(self, expr):
+ assert expr is not None
+
+ Node.__init__(self)
+ self.expr = expr
+
+
+class StmtReturn(Node):
+ def __init__(self, expr=None):
+ Node.__init__(self)
+ self.expr = expr
+
+
+StmtReturn.TRUE = StmtReturn(ExprLiteral.TRUE)
+StmtReturn.FALSE = StmtReturn(ExprLiteral.FALSE)
diff --git a/ipc/ipdl/ipdl/cxx/cgen.py b/ipc/ipdl/ipdl/cxx/cgen.py
new file mode 100644
index 0000000000..43fba4bf99
--- /dev/null
+++ b/ipc/ipdl/ipdl/cxx/cgen.py
@@ -0,0 +1,559 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+
+from ipdl.cgen import CodePrinter
+from ipdl.cxx.ast import MethodSpec, TypeArray, Visitor, DestructorDecl
+
+
+class CxxCodeGen(CodePrinter, Visitor):
+ def __init__(self, outf=sys.stdout, indentCols=4):
+ CodePrinter.__init__(self, outf, indentCols)
+
+ def cgen(self, cxxfile):
+ cxxfile.accept(self)
+
+ def visitWhitespace(self, ws):
+ if ws.indent:
+ self.printdent("")
+ self.write(ws.ws)
+
+ def visitVerbatimNode(self, verb):
+ if verb.indent:
+ self.printdent("")
+ self.write(verb.text)
+
+ def visitGroupNode(self, group):
+ offsetCols = self.indentCols * group.offset
+ self.col += offsetCols
+ for node in group.nodes:
+ node.accept(self)
+ self.col -= offsetCols
+
+ def visitCppDirective(self, cd):
+ if cd.rest:
+ self.println("#%s %s" % (cd.directive, cd.rest))
+ else:
+ self.println("#%s" % (cd.directive))
+
+ def visitNamespace(self, ns):
+ self.println("namespace " + ns.name + " {")
+ self.visitBlock(ns)
+ self.println("} // namespace " + ns.name)
+
+ def visitType(self, t):
+ if t.const:
+ self.write("const ")
+
+ self.write(t.name)
+
+ if t.T is not None:
+ self.write("<")
+ if type(t.T) is list:
+ t.T[0].accept(self)
+ for tt in t.T[1:]:
+ self.write(", ")
+ tt.accept(self)
+ else:
+ t.T.accept(self)
+ self.write(">")
+
+ if t.inner is not None:
+ self.write("::")
+ t.inner.accept(self)
+
+ ts = ""
+ if t.ptr:
+ ts += "*"
+ elif t.ptrptr:
+ ts += "**"
+ elif t.ptrconstptr:
+ ts += "* const*"
+
+ if t.ref:
+ ts += "&"
+ elif t.rvalref:
+ ts += "&&"
+ elif t.rightconst:
+ ts += " const"
+
+ self.write(ts)
+
+ def visitTypeEnum(self, te):
+ self.write("enum")
+ if te.name:
+ self.write(" " + te.name)
+ self.println(" {")
+
+ self.indent()
+ nids = len(te.idnums)
+ for i, (id, num) in enumerate(te.idnums):
+ self.printdent(id)
+ if num:
+ self.write(" = " + str(num))
+ if i != (nids - 1):
+ self.write(",")
+ self.println()
+ self.dedent()
+ self.printdent("}")
+
+ def visitTypeUnion(self, u):
+ self.write("union")
+ if u.name:
+ self.write(" " + u.name)
+ self.println(" {")
+
+ self.indent()
+ for decl in u.components:
+ self.printdent()
+ decl.accept(self)
+ self.println(";")
+ self.dedent()
+
+ self.printdent("}")
+
+ def visitTypeFunction(self, fn):
+ self.write("std::function<")
+ fn.ret.accept(self)
+ self.write("(")
+ self.writeDeclList(fn.params)
+ self.write(")>")
+
+ def visitTypedef(self, td):
+ if td.templateargs:
+ formals = ", ".join(["class " + T for T in td.templateargs])
+ args = ", ".join(td.templateargs)
+ self.printdent("template<" + formals + "> using " + td.totypename + " = ")
+ td.fromtype.accept(self)
+ self.println("<" + args + ">;")
+ else:
+ self.printdent("typedef ")
+ td.fromtype.accept(self)
+ self.println(" " + td.totypename + ";")
+
+ def visitUsing(self, us):
+ self.printdent("using ")
+ us.type.accept(self)
+ self.println(";")
+
+ def visitForwardDecl(self, fd):
+ if fd.cls:
+ self.printdent("class ")
+ elif fd.struct:
+ self.printdent("struct ")
+ self.write(str(fd.pqname))
+ self.println(";")
+
+ def visitDecl(self, d):
+ # C-syntax arrays make code generation much more annoying
+ if isinstance(d.type, TypeArray):
+ d.type.basetype.accept(self)
+ else:
+ d.type.accept(self)
+
+ if d.name:
+ self.write(" " + d.name)
+
+ if isinstance(d.type, TypeArray):
+ self.write("[")
+ d.type.nmemb.accept(self)
+ self.write("]")
+
+ def visitParam(self, p):
+ self.visitDecl(p)
+ if p.default is not None:
+ self.write(" = ")
+ p.default.accept(self)
+
+ def visitClass(self, c):
+ if c.specializes is not None:
+ self.printdentln("template<>")
+
+ if c.struct:
+ self.printdent("struct")
+ else:
+ self.printdent("class")
+ self.write(" " + c.name)
+ if c.final:
+ self.write(" final")
+
+ if c.specializes is not None:
+ self.write(" <")
+ c.specializes.accept(self)
+ self.write(">")
+
+ ninh = len(c.inherits)
+ if 0 < ninh:
+ self.println(" :")
+ self.indent()
+ for i, inherit in enumerate(c.inherits):
+ self.printdent()
+ inherit.accept(self)
+ if i != (ninh - 1):
+ self.println(",")
+ self.dedent()
+ self.println()
+
+ self.printdentln("{")
+ self.indent()
+
+ self.visitBlock(c)
+
+ self.dedent()
+ self.printdentln("};")
+
+ def visitInherit(self, inh):
+ self.write(inh.viz + " ")
+ inh.type.accept(self)
+
+ def visitFriendClassDecl(self, fcd):
+ self.printdentln("friend class " + fcd.friend + ";")
+
+ def visitMethodDecl(self, md):
+ if md.T:
+ self.write("template<")
+ self.write("typename ")
+ md.T.accept(self)
+ self.println(">")
+ self.printdent()
+
+ if md.warn_unused:
+ self.write("[[nodiscard]] ")
+
+ if md.methodspec == MethodSpec.STATIC:
+ self.write("static ")
+ elif md.methodspec == MethodSpec.VIRTUAL or md.methodspec == MethodSpec.PURE:
+ self.write("virtual ")
+
+ if md.ret:
+ if md.only_for_definition:
+ self.write("auto ")
+ else:
+ md.ret.accept(self)
+ self.println()
+ self.printdent()
+
+ if md.cls is not None:
+ assert md.only_for_definition
+
+ self.write(md.cls.name)
+ if md.cls.specializes is not None:
+ self.write("<")
+ md.cls.specializes.accept(self)
+ self.write(">")
+ self.write("::")
+
+ if md.typeop is not None:
+ self.write("operator ")
+ md.typeop.accept(self)
+ else:
+ if isinstance(md, DestructorDecl):
+ self.write("~")
+ self.write(md.name)
+
+ self.write("(")
+ self.writeDeclList(md.params)
+ self.write(")")
+
+ if md.const:
+ self.write(" const")
+ if md.ret and md.only_for_definition:
+ self.write(" -> ")
+ md.ret.accept(self)
+
+ if md.methodspec == MethodSpec.OVERRIDE:
+ self.write(" override")
+ elif md.methodspec == MethodSpec.FINAL:
+ self.write(" final")
+ elif md.methodspec == MethodSpec.PURE:
+ self.write(" = 0")
+
+ def visitMethodDefn(self, md):
+ # Method specifiers are for decls, not defns.
+ assert md.decl.methodspec == MethodSpec.NONE
+
+ self.printdent()
+ md.decl.accept(self)
+ self.println()
+
+ self.printdentln("{")
+ self.indent()
+ self.visitBlock(md)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitConstructorDecl(self, cd):
+ if cd.explicit:
+ self.write("explicit ")
+ else:
+ self.write("MOZ_IMPLICIT ")
+ self.visitMethodDecl(cd)
+
+ def visitConstructorDefn(self, cd):
+ self.printdent()
+ cd.decl.accept(self)
+ if len(cd.memberinits):
+ self.println(" :")
+ self.indent()
+ ninits = len(cd.memberinits)
+ for i, init in enumerate(cd.memberinits):
+ self.printdent()
+ init.accept(self)
+ if i != (ninits - 1):
+ self.println(",")
+ self.dedent()
+ self.println()
+
+ self.printdentln("{")
+ self.indent()
+
+ self.visitBlock(cd)
+
+ self.dedent()
+ self.printdentln("}")
+
+ def visitDestructorDecl(self, dd):
+ self.visitMethodDecl(dd)
+
+ def visitDestructorDefn(self, dd):
+ self.printdent()
+ dd.decl.accept(self)
+ self.println()
+
+ self.printdentln("{")
+ self.indent()
+
+ self.visitBlock(dd)
+
+ self.dedent()
+ self.printdentln("}")
+
+ def visitExprLiteral(self, el):
+ self.write(str(el))
+
+ def visitExprVar(self, ev):
+ self.write(ev.name)
+
+ def visitExprPrefixUnop(self, e):
+ self.write("(")
+ self.write(e.op)
+ self.write("(")
+ e.expr.accept(self)
+ self.write(")")
+ self.write(")")
+
+ def visitExprCast(self, c):
+ if c.static:
+ pfx, sfx = "static_cast<", ">"
+ else:
+ assert c.const
+ pfx, sfx = "const_cast<", ">"
+ self.write(pfx)
+ c.type.accept(self)
+ self.write(sfx + "(")
+ c.expr.accept(self)
+ self.write(")")
+
+ def visitExprBinary(self, e):
+ self.write("(")
+ e.left.accept(self)
+ self.write(") " + e.op + " (")
+ e.right.accept(self)
+ self.write(")")
+
+ def visitExprConditional(self, c):
+ self.write("(")
+ c.cond.accept(self)
+ self.write(" ? ")
+ c.ife.accept(self)
+ self.write(" : ")
+ c.elsee.accept(self)
+ self.write(")")
+
+ def visitExprSelect(self, es):
+ self.write("(")
+ es.obj.accept(self)
+ self.write(")")
+ self.write(es.op)
+ es.field.accept(self)
+
+ def visitExprAssn(self, ea):
+ ea.lhs.accept(self)
+ self.write(" " + ea.op + " ")
+ ea.rhs.accept(self)
+
+ def visitExprCall(self, ec):
+ ec.func.accept(self)
+ self.write("(")
+ self.writeExprList(ec.args)
+ self.write(")")
+
+ def visitExprNew(self, en):
+ self.write("new ")
+ if en.newargs is not None:
+ self.write("(")
+ self.writeExprList(en.newargs)
+ self.write(") ")
+ en.ctype.accept(self)
+ if en.args is not None:
+ self.write("(")
+ self.writeExprList(en.args)
+ self.write(")")
+
+ def visitExprDelete(self, ed):
+ self.write("delete ")
+ ed.obj.accept(self)
+
+ def visitExprLambda(self, l):
+ self.write("[")
+ ncaptures = len(l.captures)
+ for i, c in enumerate(l.captures):
+ c.accept(self)
+ if i != (ncaptures - 1):
+ self.write(", ")
+ self.write("](")
+ self.writeDeclList(l.params)
+ self.write(")")
+ if l.ret:
+ self.write(" -> ")
+ l.ret.accept(self)
+ self.println(" {")
+ self.indent()
+ self.visitBlock(l)
+ self.dedent()
+ self.printdent("}")
+
+ def visitStmtBlock(self, b):
+ self.printdentln("{")
+ self.indent()
+ self.visitBlock(b)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitLabel(self, label):
+ self.dedent() # better not be at global scope ...
+ self.printdentln(label.name + ":")
+ self.indent()
+
+ def visitCaseLabel(self, cl):
+ self.dedent()
+ self.printdentln("case " + cl.name + ":")
+ self.indent()
+
+ def visitDefaultLabel(self, dl):
+ self.dedent()
+ self.printdentln("default:")
+ self.indent()
+
+ def visitStmtIf(self, si):
+ self.printdent("if (")
+ si.cond.accept(self)
+ self.println(") {")
+ self.indent()
+ si.ifb.accept(self)
+ self.dedent()
+ self.printdentln("}")
+
+ if si.elseb is not None:
+ self.printdentln("else {")
+ self.indent()
+ si.elseb.accept(self)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitStmtFor(self, sf):
+ self.printdent("for (")
+ if sf.init is not None:
+ sf.init.accept(self)
+ self.write("; ")
+ if sf.cond is not None:
+ sf.cond.accept(self)
+ self.write("; ")
+ if sf.update is not None:
+ sf.update.accept(self)
+ self.println(") {")
+
+ self.indent()
+ self.visitBlock(sf)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitStmtRangedFor(self, rf):
+ self.printdent("for (auto& ")
+ rf.var.accept(self)
+ self.write(" : ")
+ rf.iteree.accept(self)
+ self.println(") {")
+
+ self.indent()
+ self.visitBlock(rf)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitStmtSwitch(self, sw):
+ self.printdent("switch (")
+ sw.expr.accept(self)
+ self.println(") {")
+ self.indent()
+ self.visitBlock(sw)
+ self.dedent()
+ self.printdentln("}")
+
+ def visitStmtBreak(self, sb):
+ self.printdentln("break;")
+
+ def visitStmtDecl(self, sd):
+ self.printdent()
+ sd.decl.accept(self)
+ if sd.initargs is not None:
+ self.write("{")
+ self.writeDeclList(sd.initargs)
+ self.write("}")
+ if sd.init is not None:
+ self.write(" = ")
+ sd.init.accept(self)
+ self.println(";")
+
+ def visitStmtExpr(self, se):
+ self.printdent()
+ se.expr.accept(self)
+ self.println(";")
+
+ def visitStmtReturn(self, sr):
+ self.printdent("return")
+ if sr.expr:
+ self.write(" ")
+ sr.expr.accept(self)
+ self.println(";")
+
+ def writeDeclList(self, decls):
+ # FIXME/cjones: try to do nice formatting of these guys
+
+ ndecls = len(decls)
+ if 0 == ndecls:
+ return
+ elif 1 == ndecls:
+ decls[0].accept(self)
+ return
+
+ self.indent()
+ self.indent()
+ for i, decl in enumerate(decls):
+ self.println()
+ self.printdent()
+ decl.accept(self)
+ if i != (ndecls - 1):
+ self.write(",")
+ self.dedent()
+ self.dedent()
+
+ def writeExprList(self, exprs):
+ # FIXME/cjones: try to do nice formatting and share code with
+ # writeDeclList()
+ nexprs = len(exprs)
+ for i, expr in enumerate(exprs):
+ expr.accept(self)
+ if i != (nexprs - 1):
+ self.write(", ")
diff --git a/ipc/ipdl/ipdl/cxx/code.py b/ipc/ipdl/ipdl/cxx/code.py
new file mode 100644
index 0000000000..0b5019b623
--- /dev/null
+++ b/ipc/ipdl/ipdl/cxx/code.py
@@ -0,0 +1,187 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# This module contains functionality for adding formatted, opaque "code" blocks
+# into the IPDL ast. These code objects follow IPDL C++ ast patterns, and
+# perform lowering in much the same way.
+
+# In general it is recommended to use these for blocks of code which would
+# otherwise be specified by building a hardcoded IPDL-C++ AST, as users of this
+# API are often easier to read than users of the AST APIs in these cases.
+
+import re
+import math
+import textwrap
+
+from ipdl.cxx.ast import Node, Whitespace, GroupNode, VerbatimNode
+
+
+# -----------------------------------------------------------------------------
+# Public API.
+
+
+def StmtCode(tmpl, **kwargs):
+ """Perform template substitution to build opaque C++ AST nodes. See the
+ module documentation for more information on the templating syntax.
+
+ StmtCode nodes should be used where Stmt* nodes are used. They are placed
+ on their own line and indented."""
+ return _code(tmpl, False, kwargs)
+
+
+def ExprCode(tmpl, **kwargs):
+ """Perform template substitution to build opaque C++ AST nodes. See the
+ module documentation for more information on the templating syntax.
+
+ ExprCode nodes should be used where Expr* nodes are used. They are placed
+ inline, and no trailing newline is added."""
+ return _code(tmpl, True, kwargs)
+
+
+def StmtVerbatim(text):
+ """Build an opaque C++ AST node which emits input text verbatim.
+
+ StmtVerbatim nodes should be used where Stmt* nodes are used. They are placed
+ on their own line and indented."""
+ return _verbatim(text, False)
+
+
+def ExprVerbatim(text):
+ """Build an opaque C++ AST node which emits input text verbatim.
+
+ ExprVerbatim nodes should be used where Expr* nodes are used. They are
+ placed inline, and no trailing newline is added."""
+ return _verbatim(text, True)
+
+
+# -----------------------------------------------------------------------------
+# Implementation
+
+
+def _code(tmpl, inline, context):
+ # Remove common indentation, and strip the preceding newline from
+ # '''-quoting, because we usually don't want it.
+ if tmpl.startswith("\n"):
+ tmpl = tmpl[1:]
+ tmpl = textwrap.dedent(tmpl)
+
+ # Process each line in turn, building up a list of nodes.
+ nodes = []
+ for idx, line in enumerate(tmpl.splitlines()):
+ # Place newline tokens between lines in the input.
+ if idx > 0:
+ nodes.append(Whitespace.NL)
+
+ # Don't indent the first line if `inline` is set.
+ skip_indent = inline and idx == 0
+ nodes.append(_line(line.rstrip(), skip_indent, idx + 1, context))
+
+ # If we're inline, don't add the final trailing newline.
+ if not inline:
+ nodes.append(Whitespace.NL)
+ return GroupNode(nodes)
+
+
+def _verbatim(text, inline):
+ # For simplicitly, _verbatim is implemented using the same logic as _code,
+ # but with '$' characters escaped. This ensures we only need to worry about
+ # a single, albeit complex, codepath.
+ return _code(text.replace("$", "$$"), inline, {})
+
+
+# Pattern used to identify substitutions.
+_substPat = re.compile(
+ r"""
+ \$(?:
+ (?P<escaped>\$) | # '$$' is an escaped '$'
+ (?P<list>[*,])?{(?P<expr>[^}]+)} | # ${expr}, $*{expr}, or $,{expr}
+ (?P<invalid>) # For error reporting
+ )
+ """,
+ re.IGNORECASE | re.VERBOSE,
+)
+
+
+def _line(raw, skip_indent, lineno, context):
+ assert "\n" not in raw
+
+ # Determine the level of indentation used for this line
+ line = raw.lstrip()
+ offset = int(math.ceil((len(raw) - len(line)) / 4))
+
+ # If line starts with a directive, don't indent it.
+ if line.startswith("#"):
+ skip_indent = True
+
+ column = 0
+ children = []
+ for match in _substPat.finditer(line):
+ if match.group("invalid") is not None:
+ raise ValueError("Invalid substitution on line %d" % lineno)
+
+ # Any text from before the current entry should be written, and column
+ # advanced.
+ if match.start() > column:
+ before = line[column : match.start()]
+ children.append(VerbatimNode(before))
+ column = match.end()
+
+ # If we have an escaped group, emit a '$' node.
+ if match.group("escaped") is not None:
+ children.append(VerbatimNode("$"))
+ continue
+
+ # At this point we should have an expression.
+ list_chr = match.group("list")
+ expr = match.group("expr")
+ assert expr is not None
+
+ # Evaluate our expression in the context to get the values.
+ try:
+ values = eval(expr, context, {})
+ except Exception as e:
+ msg = "%s in substitution on line %d" % (repr(e), lineno)
+ raise ValueError(msg) from e
+
+ # If we aren't dealing with lists, wrap the result into a
+ # single-element list.
+ if list_chr is None:
+ values = [values]
+
+ # Check if this substitution is inline, or the entire line.
+ inline = match.span() != (0, len(line))
+
+ for idx, value in enumerate(values):
+ # If we're using ',' as list mode, put a comma between each node.
+ if idx > 0 and list_chr == ",":
+ children.append(VerbatimNode(", "))
+
+ # If our value isn't a node, turn it into one. Verbatim should be
+ # inline unless indent isn't being skipped, and the match isn't
+ # inline.
+ if not isinstance(value, Node):
+ value = _verbatim(str(value), skip_indent or inline)
+ children.append(value)
+
+ # If we were the entire line, indentation is handled by the added child
+ # nodes. Do this after the above loop such that created verbatims have
+ # the correct inline-ness.
+ if not inline:
+ skip_indent = True
+
+ # Add any remaining text in the line.
+ if len(line) > column:
+ children.append(VerbatimNode(line[column:]))
+
+ # If we have no children, just emit the empty string. This will become a
+ # blank line.
+ if len(children) == 0:
+ return VerbatimNode("")
+
+ # Add the initial indent if we aren't skipping it.
+ if not skip_indent:
+ children.insert(0, VerbatimNode("", indent=True))
+
+ # Wrap ourselves into a group node with the correct indent offset
+ return GroupNode(children, offset=offset)
diff --git a/ipc/ipdl/ipdl/lower.py b/ipc/ipdl/ipdl/lower.py
new file mode 100644
index 0000000000..aac8ebaf36
--- /dev/null
+++ b/ipc/ipdl/ipdl/lower.py
@@ -0,0 +1,5738 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import re
+from copy import deepcopy
+from collections import OrderedDict
+import itertools
+
+import ipdl.ast
+import ipdl.builtin
+from ipdl.cxx.ast import *
+from ipdl.cxx.code import *
+from ipdl.type import ActorType, UnionType, TypeVisitor, builtinHeaderIncludes
+from ipdl.util import hash_str
+
+
+# -----------------------------------------------------------------------------
+# "Public" interface to lowering
+##
+
+
+class LowerToCxx:
+ def lower(self, tu, segmentcapacitydict):
+ """returns |[ header: File ], [ cpp : File ]| representing the
+ lowered form of |tu|"""
+ # annotate the AST with IPDL/C++ IR-type stuff used later
+ tu.accept(_DecorateWithCxxStuff())
+
+ # Any modifications to the filename scheme here need corresponding
+ # modifications in the ipdl.py driver script.
+ name = tu.name
+ pheader, pcpp = File(name + ".h"), File(name + ".cpp")
+
+ _GenerateProtocolCode().lower(tu, pheader, pcpp, segmentcapacitydict)
+ headers = [pheader]
+ cpps = [pcpp]
+
+ if tu.protocol:
+ pname = tu.protocol.name
+
+ parentheader, parentcpp = (
+ File(pname + "Parent.h"),
+ File(pname + "Parent.cpp"),
+ )
+ _GenerateProtocolParentCode().lower(
+ tu, pname + "Parent", parentheader, parentcpp
+ )
+
+ childheader, childcpp = File(pname + "Child.h"), File(pname + "Child.cpp")
+ _GenerateProtocolChildCode().lower(
+ tu, pname + "Child", childheader, childcpp
+ )
+
+ headers += [parentheader, childheader]
+ cpps += [parentcpp, childcpp]
+
+ return headers, cpps
+
+
+# -----------------------------------------------------------------------------
+# Helper code
+##
+
+
+def hashfunc(value):
+ h = hash_str(value) % 2**32
+ if h < 0:
+ h += 2**32
+ return h
+
+
+_NULL_ACTOR_ID = ExprLiteral.ZERO
+_FREED_ACTOR_ID = ExprLiteral.ONE
+
+_DISCLAIMER = Whitespace(
+ """//
+// Automatically generated by ipdlc.
+// Edit at your own risk
+//
+
+"""
+)
+
+
+class _struct:
+ pass
+
+
+def _namespacedHeaderName(name, namespaces):
+ pfx = "/".join([ns.name for ns in namespaces])
+ if pfx:
+ return pfx + "/" + name
+ else:
+ return name
+
+
+def _ipdlhHeaderName(tu):
+ assert tu.filetype == "header"
+ return _namespacedHeaderName(tu.name, tu.namespaces)
+
+
+def _protocolHeaderName(p, side=""):
+ if side:
+ side = side.title()
+ base = p.name + side
+ return _namespacedHeaderName(base, p.namespaces)
+
+
+def _includeGuardMacroName(headerfile):
+ return re.sub(r"[./]", "_", headerfile.name)
+
+
+def _includeGuardStart(headerfile):
+ guard = _includeGuardMacroName(headerfile)
+ return [CppDirective("ifndef", guard), CppDirective("define", guard)]
+
+
+def _includeGuardEnd(headerfile):
+ guard = _includeGuardMacroName(headerfile)
+ return [CppDirective("endif", "// ifndef " + guard)]
+
+
+def _messageStartName(ptype):
+ return ptype.name() + "MsgStart"
+
+
+def _protocolId(ptype):
+ return ExprVar(_messageStartName(ptype))
+
+
+def _protocolIdType():
+ return Type.INT32
+
+
+def _actorName(pname, side):
+ """|pname| is the protocol name. |side| is 'Parent' or 'Child'."""
+ tag = side
+ if not tag[0].isupper():
+ tag = side.title()
+ return pname + tag
+
+
+def _actorIdType():
+ return Type.INT32
+
+
+def _actorTypeTagType():
+ return Type.INT32
+
+
+def _actorId(actor=None):
+ if actor is not None:
+ return ExprCall(ExprSelect(actor, "->", "Id"))
+ return ExprCall(ExprVar("Id"))
+
+
+def _actorHId(actorhandle):
+ return ExprSelect(actorhandle, ".", "mId")
+
+
+def _backstagePass():
+ return ExprCall(ExprVar("mozilla::ipc::PrivateIPDLInterface"))
+
+
+def _deleteId():
+ return ExprVar("Msg___delete____ID")
+
+
+def _deleteReplyId():
+ return ExprVar("Reply___delete____ID")
+
+
+def _lookupListener(idexpr):
+ return ExprCall(ExprVar("Lookup"), args=[idexpr])
+
+
+def _makeForwardDeclForQClass(clsname, quals, cls=True, struct=False):
+ fd = ForwardDecl(clsname, cls=cls, struct=struct)
+ if 0 == len(quals):
+ return fd
+
+ outerns = Namespace(quals[0])
+ innerns = outerns
+ for ns in quals[1:]:
+ tmpns = Namespace(ns)
+ innerns.addstmt(tmpns)
+ innerns = tmpns
+
+ innerns.addstmt(fd)
+ return outerns
+
+
+def _makeForwardDeclForActor(ptype, side):
+ return _makeForwardDeclForQClass(
+ _actorName(ptype.qname.baseid, side), ptype.qname.quals
+ )
+
+
+def _makeForwardDecl(type):
+ return _makeForwardDeclForQClass(type.name(), type.qname.quals)
+
+
+def _putInNamespaces(cxxthing, namespaces):
+ """|namespaces| is in order [ outer, ..., inner ]"""
+ if 0 == len(namespaces):
+ return cxxthing
+
+ outerns = Namespace(namespaces[0].name)
+ innerns = outerns
+ for ns in namespaces[1:]:
+ newns = Namespace(ns.name)
+ innerns.addstmt(newns)
+ innerns = newns
+ innerns.addstmt(cxxthing)
+ return outerns
+
+
+def _sendPrefix(msgtype):
+ """Prefix of the name of the C++ method that sends |msgtype|."""
+ if msgtype.isInterrupt():
+ return "Call"
+ return "Send"
+
+
+def _recvPrefix(msgtype):
+ """Prefix of the name of the C++ method that handles |msgtype|."""
+ if msgtype.isInterrupt():
+ return "Answer"
+ return "Recv"
+
+
+def _flatTypeName(ipdltype):
+ """Return a 'flattened' IPDL type name that can be used as an
+ identifier.
+ E.g., |Foo[]| --> |ArrayOfFoo|."""
+ # NB: this logic depends heavily on what IPDL types are allowed to
+ # be constructed; e.g., Foo[][] is disallowed. needs to be kept in
+ # sync with grammar.
+ if ipdltype.isIPDL() and ipdltype.isArray():
+ return "ArrayOf" + _flatTypeName(ipdltype.basetype)
+ if ipdltype.isIPDL() and ipdltype.isMaybe():
+ return "Maybe" + _flatTypeName(ipdltype.basetype)
+ # NotNull types just assume the underlying variant name to avoid unnecessary
+ # noise, as a NotNull<T> and T should never exist in the same union.
+ if ipdltype.isIPDL() and ipdltype.isNotNull():
+ return _flatTypeName(ipdltype.basetype)
+ return ipdltype.name()
+
+
+def _hasVisibleActor(ipdltype):
+ """Return true iff a C++ decl of |ipdltype| would have an Actor* type.
+ For example: |Actor[]| would turn into |Array<ActorParent*>|, so this
+ function would return true for |Actor[]|."""
+ return ipdltype.isIPDL() and (
+ ipdltype.isActor()
+ or (ipdltype.hasBaseType() and _hasVisibleActor(ipdltype.basetype))
+ )
+
+
+def _abortIfFalse(cond, msg):
+ return StmtExpr(
+ ExprCall(ExprVar("MOZ_RELEASE_ASSERT"), [cond, ExprLiteral.String(msg)])
+ )
+
+
+def _refptr(T):
+ return Type("RefPtr", T=T)
+
+
+def _alreadyaddrefed(T):
+ return Type("already_AddRefed", T=T)
+
+
+def _tuple(types, const=False, ref=False):
+ return Type("std::tuple", T=types, const=const, ref=ref)
+
+
+def _promise(resolvetype, rejecttype, tail, resolver=False):
+ inner = Type("Private") if resolver else None
+ return Type("MozPromise", T=[resolvetype, rejecttype, tail], inner=inner)
+
+
+def _makePromise(returns, side, resolver=False):
+ if len(returns) > 1:
+ resolvetype = _tuple([d.bareType(side) for d in returns])
+ else:
+ resolvetype = returns[0].bareType(side)
+
+ # MozPromise is purposefully made to be exclusive only. Really, we mean it.
+ return _promise(
+ resolvetype, _ResponseRejectReason.Type(), ExprLiteral.TRUE, resolver=resolver
+ )
+
+
+def _resolveType(returns, side):
+ if len(returns) > 1:
+ return _tuple([d.inType(side, "send") for d in returns])
+ return returns[0].inType(side, "send")
+
+
+def _makeResolver(returns, side):
+ return TypeFunction([Decl(_resolveType(returns, side), "")])
+
+
+def _cxxArrayType(basetype, const=False, ref=False):
+ return Type("nsTArray", T=basetype, const=const, ref=ref, hasimplicitcopyctor=False)
+
+
+def _cxxSpanType(basetype, const=False, ref=False):
+ basetype = deepcopy(basetype)
+ basetype.rightconst = True
+ return Type(
+ "mozilla::Span", T=basetype, const=const, ref=ref, hasimplicitcopyctor=True
+ )
+
+
+def _cxxMaybeType(basetype, const=False, ref=False):
+ return Type(
+ "mozilla::Maybe",
+ T=basetype,
+ const=const,
+ ref=ref,
+ hasimplicitcopyctor=basetype.hasimplicitcopyctor,
+ )
+
+
+def _cxxReadResultType(basetype, const=False, ref=False):
+ return Type(
+ "IPC::ReadResult",
+ T=basetype,
+ const=const,
+ ref=ref,
+ hasimplicitcopyctor=basetype.hasimplicitcopyctor,
+ )
+
+
+def _cxxNotNullType(basetype, const=False, ref=False):
+ return Type(
+ "mozilla::NotNull",
+ T=basetype,
+ const=const,
+ ref=ref,
+ hasimplicitcopyctor=basetype.hasimplicitcopyctor,
+ )
+
+
+def _cxxManagedContainerType(basetype, const=False, ref=False):
+ return Type(
+ "ManagedContainer", T=basetype, const=const, ref=ref, hasimplicitcopyctor=False
+ )
+
+
+def _cxxLifecycleProxyType(ptr=False):
+ return Type("mozilla::ipc::ActorLifecycleProxy", ptr=ptr)
+
+
+def _cxxSide(side):
+ if side == "child":
+ return ExprVar("mozilla::ipc::ChildSide")
+ if side == "parent":
+ return ExprVar("mozilla::ipc::ParentSide")
+ assert 0
+
+
+def _otherSide(side):
+ if side == "child":
+ return "parent"
+ if side == "parent":
+ return "child"
+ assert 0
+
+
+# XXX we need to remove these and install proper error handling
+
+
+def _printErrorMessage(msg):
+ if isinstance(msg, str):
+ msg = ExprLiteral.String(msg)
+ return StmtExpr(ExprCall(ExprVar("NS_ERROR"), args=[msg]))
+
+
+def _protocolErrorBreakpoint(msg):
+ if isinstance(msg, str):
+ msg = ExprLiteral.String(msg)
+ return StmtExpr(
+ ExprCall(ExprVar("mozilla::ipc::ProtocolErrorBreakpoint"), args=[msg])
+ )
+
+
+def _printWarningMessage(msg):
+ if isinstance(msg, str):
+ msg = ExprLiteral.String(msg)
+ return StmtExpr(ExprCall(ExprVar("NS_WARNING"), args=[msg]))
+
+
+def _fatalError(msg):
+ return StmtExpr(ExprCall(ExprVar("FatalError"), args=[ExprLiteral.String(msg)]))
+
+
+def _logicError(msg):
+ return StmtExpr(
+ ExprCall(ExprVar("mozilla::ipc::LogicError"), args=[ExprLiteral.String(msg)])
+ )
+
+
+def _sentinelReadError(classname):
+ return StmtExpr(
+ ExprCall(
+ ExprVar("mozilla::ipc::SentinelReadError"),
+ args=[ExprLiteral.String(classname)],
+ )
+ )
+
+
+# Results that IPDL-generated code returns back to *Channel code.
+# Users never see these
+
+
+class _Result:
+ @staticmethod
+ def Type():
+ return Type("Result")
+
+ Processed = ExprVar("MsgProcessed")
+ NotKnown = ExprVar("MsgNotKnown")
+ NotAllowed = ExprVar("MsgNotAllowed")
+ PayloadError = ExprVar("MsgPayloadError")
+ ProcessingError = ExprVar("MsgProcessingError")
+ RouteError = ExprVar("MsgRouteError")
+ ValuError = ExprVar("MsgValueError") # [sic]
+
+
+# these |errfn*| are functions that generate code to be executed on an
+# error, such as "bad actor ID". each is given a Python string
+# containing a description of the error
+
+# used in user-facing Send*() methods
+
+
+def errfnSend(msg, errcode=ExprLiteral.FALSE):
+ return [_fatalError(msg), StmtReturn(errcode)]
+
+
+def errfnSendCtor(msg):
+ return errfnSend(msg, errcode=ExprLiteral.NULL)
+
+
+# TODO should this error handling be strengthened for dtors?
+
+
+def errfnSendDtor(msg):
+ return [_printErrorMessage(msg), StmtReturn.FALSE]
+
+
+# used in |OnMessage*()| handlers that hand in-messages off to Recv*()
+# interface methods
+
+
+def errfnRecv(msg, errcode=_Result.ValuError):
+ return [_fatalError(msg), StmtReturn(errcode)]
+
+
+def errfnSentinel(rvalue=ExprLiteral.FALSE):
+ def inner(msg):
+ return [_sentinelReadError(msg), StmtReturn(rvalue)]
+
+ return inner
+
+
+def _destroyMethod():
+ return ExprVar("ActorDestroy")
+
+
+def errfnUnreachable(msg):
+ return [_logicError(msg)]
+
+
+def readResultError():
+ return ExprCode("{}")
+
+
+class _DestroyReason:
+ @staticmethod
+ def Type():
+ return Type("ActorDestroyReason")
+
+ Deletion = ExprVar("Deletion")
+ AncestorDeletion = ExprVar("AncestorDeletion")
+ NormalShutdown = ExprVar("NormalShutdown")
+ AbnormalShutdown = ExprVar("AbnormalShutdown")
+ FailedConstructor = ExprVar("FailedConstructor")
+ ManagedEndpointDropped = ExprVar("ManagedEndpointDropped")
+
+
+class _ResponseRejectReason:
+ @staticmethod
+ def Type():
+ return Type("ResponseRejectReason")
+
+ SendError = ExprVar("ResponseRejectReason::SendError")
+ ChannelClosed = ExprVar("ResponseRejectReason::ChannelClosed")
+ HandlerRejected = ExprVar("ResponseRejectReason::HandlerRejected")
+ ActorDestroyed = ExprVar("ResponseRejectReason::ActorDestroyed")
+
+
+# -----------------------------------------------------------------------------
+# Intermediate representation (IR) nodes used during lowering
+
+
+class _ConvertToCxxType(TypeVisitor):
+ def __init__(self, side, fq):
+ self.side = side
+ self.fq = fq
+
+ def typename(self, thing):
+ if self.fq:
+ return thing.fullname()
+ return thing.name()
+
+ def visitImportedCxxType(self, t):
+ cxxtype = Type(self.typename(t))
+ if t.isRefcounted():
+ cxxtype = _refptr(cxxtype)
+ return cxxtype
+
+ def visitBuiltinCType(self, b):
+ return Type(self.typename(b))
+
+ def visitActorType(self, a):
+ if self.side is None:
+ return Type(
+ "::mozilla::ipc::SideVariant",
+ T=[
+ _cxxBareType(a, "parent", self.fq),
+ _cxxBareType(a, "child", self.fq),
+ ],
+ )
+ return Type(_actorName(self.typename(a.protocol), self.side), ptr=True)
+
+ def visitStructType(self, s):
+ return Type(self.typename(s))
+
+ def visitUnionType(self, u):
+ return Type(self.typename(u))
+
+ def visitArrayType(self, a):
+ basecxxtype = a.basetype.accept(self)
+ return _cxxArrayType(basecxxtype)
+
+ def visitMaybeType(self, m):
+ basecxxtype = m.basetype.accept(self)
+ return _cxxMaybeType(basecxxtype)
+
+ def visitShmemType(self, s):
+ return Type(self.typename(s))
+
+ def visitByteBufType(self, s):
+ return Type(self.typename(s))
+
+ def visitFDType(self, s):
+ return Type(self.typename(s))
+
+ def visitEndpointType(self, s):
+ return Type(self.typename(s))
+
+ def visitManagedEndpointType(self, s):
+ return Type(self.typename(s))
+
+ def visitUniquePtrType(self, s):
+ return Type(self.typename(s))
+
+ def visitNotNullType(self, n):
+ basecxxtype = n.basetype.accept(self)
+ return _cxxNotNullType(basecxxtype)
+
+ def visitProtocolType(self, p):
+ assert 0
+
+ def visitMessageType(self, m):
+ assert 0
+
+ def visitVoidType(self, v):
+ assert 0
+
+
+def _cxxBareType(ipdltype, side, fq=False):
+ return ipdltype.accept(_ConvertToCxxType(side, fq))
+
+
+def _cxxRefType(ipdltype, side):
+ t = _cxxBareType(ipdltype, side)
+ t.ref = True
+ return t
+
+
+def _cxxConstRefType(ipdltype, side):
+ t = _cxxBareType(ipdltype, side)
+ if ipdltype.isIPDL() and ipdltype.isActor():
+ return t
+ if ipdltype.isIPDL() and ipdltype.isShmem():
+ t.ref = True
+ return t
+ if ipdltype.isIPDL() and ipdltype.isNotNull():
+ # If the inner type chooses to use a raw pointer, wrap that instead.
+ inner = _cxxConstRefType(ipdltype.basetype, side)
+ if inner.ptr:
+ t = _cxxNotNullType(inner)
+ return t
+ if ipdltype.isIPDL() and ipdltype.hasBaseType():
+ # Keep same constness as inner type.
+ inner = _cxxConstRefType(ipdltype.basetype, side)
+ t.const = inner.const or not inner.ref
+ t.ref = True
+ return t
+ if ipdltype.isCxx() and (ipdltype.isSendMoveOnly() or ipdltype.isDataMoveOnly()):
+ t.const = True
+ t.ref = True
+ return t
+ if ipdltype.isCxx() and ipdltype.isRefcounted():
+ # Use T* instead of const RefPtr<T>&
+ t = t.T
+ t.ptr = True
+ return t
+ t.const = True
+ t.ref = True
+ return t
+
+
+def _cxxTypeNeedsMoveForSend(ipdltype, context="root", visited=None):
+ """Returns `True` if serializing ipdltype requires a mutable reference, e.g.
+ because the underlying resource represented by the value is being
+ transferred to another process. This is occasionally distinct from whether
+ the C++ type exposes a copy constructor, such as for types which are not
+ cheaply copiable, but are not mutated when serialized."""
+
+ if visited is None:
+ visited = set()
+
+ visited.add(ipdltype)
+
+ if ipdltype.isCxx():
+ return ipdltype.isSendMoveOnly()
+
+ if ipdltype.isIPDL():
+ if ipdltype.hasBaseType():
+ return _cxxTypeNeedsMoveForSend(ipdltype.basetype, "wrapper", visited)
+ if ipdltype.isStruct() or ipdltype.isUnion():
+ return any(
+ _cxxTypeNeedsMoveForSend(t, "compound", visited)
+ for t in ipdltype.itercomponents()
+ if t not in visited
+ )
+
+ # For historical reasons, shmem is `const_cast` to a mutable reference
+ # when being stored in a struct or union (see
+ # `_StructField.constRefExpr` and `_UnionMember.getConstValue`), meaning
+ # that they do not cause the containing struct to require move for
+ # sending.
+ if ipdltype.isShmem():
+ return context != "compound"
+
+ return (
+ ipdltype.isByteBuf()
+ or ipdltype.isEndpoint()
+ or ipdltype.isManagedEndpoint()
+ )
+
+ return False
+
+
+def _cxxTypeNeedsMoveForData(ipdltype, context="root", visited=None):
+ """Returns `True` if the bare C++ type corresponding to ipdltype does not
+ satisfy std::is_copy_constructible_v<T>. All C++ types supported by IPDL
+ must support std::is_move_constructible_v<T>, so non-movable types must be
+ passed behind a `UniquePtr`."""
+
+ if visited is None:
+ visited = set()
+
+ visited.add(ipdltype)
+
+ if ipdltype.isCxx():
+ return ipdltype.isDataMoveOnly()
+
+ if ipdltype.isIPDL():
+ if ipdltype.isUniquePtr():
+ return True
+
+ # When nested within a maybe or array, arrays are no longer copyable.
+ if context == "wrapper" and ipdltype.isArray():
+ return True
+ if ipdltype.hasBaseType():
+ return _cxxTypeNeedsMoveForData(ipdltype.basetype, "wrapper", visited)
+ if ipdltype.isStruct() or ipdltype.isUnion():
+ return any(
+ _cxxTypeNeedsMoveForData(t, "compound", visited)
+ for t in ipdltype.itercomponents()
+ if t not in visited
+ )
+ return (
+ ipdltype.isByteBuf()
+ or ipdltype.isEndpoint()
+ or ipdltype.isManagedEndpoint()
+ )
+
+ return False
+
+
+def _cxxTypeCanMove(ipdltype):
+ return not (ipdltype.isIPDL() and ipdltype.isActor())
+
+
+def _cxxForceMoveRefType(ipdltype, side):
+ assert _cxxTypeCanMove(ipdltype)
+ t = _cxxBareType(ipdltype, side)
+ t.rvalref = True
+ return t
+
+
+def _cxxPtrToType(ipdltype, side):
+ t = _cxxBareType(ipdltype, side)
+ if ipdltype.isIPDL() and ipdltype.isActor() and side is not None:
+ t.ptr = False
+ t.ptrptr = True
+ return t
+ t.ptr = True
+ return t
+
+
+def _cxxConstPtrToType(ipdltype, side):
+ t = _cxxBareType(ipdltype, side)
+ if ipdltype.isIPDL() and ipdltype.isActor() and side is not None:
+ t.ptr = False
+ t.ptrconstptr = True
+ return t
+ t.const = True
+ t.ptr = True
+ return t
+
+
+def _cxxInType(ipdltype, side, direction):
+ t = _cxxBareType(ipdltype, side)
+ if ipdltype.isIPDL() and ipdltype.isActor():
+ return t
+ if ipdltype.isIPDL() and ipdltype.isNotNull():
+ # If the inner type chooses to use a raw pointer, wrap that instead.
+ inner = _cxxInType(ipdltype.basetype, side, direction)
+ if inner.ptr:
+ t = _cxxNotNullType(inner)
+ return t
+ if _cxxTypeNeedsMoveForSend(ipdltype):
+ t.rvalref = True
+ return t
+ if ipdltype.isCxx():
+ if ipdltype.isRefcounted():
+ # Use T* instead of const RefPtr<T>&
+ t = t.T
+ t.ptr = True
+ return t
+ if ipdltype.name() == "nsCString":
+ t = Type("nsACString")
+ if ipdltype.name() == "nsString":
+ t = Type("nsAString")
+ # Use Span<T const> rather than nsTArray<T> for array types which aren't
+ # `_cxxTypeNeedsMoveForSend`. This is only done for the "send" side, and not
+ # for recv signatures.
+ if direction == "send" and ipdltype.isIPDL() and ipdltype.isArray():
+ inner = _cxxBareType(ipdltype.basetype, side)
+ return _cxxSpanType(inner)
+
+ t.const = True
+ t.ref = True
+ return t
+
+
+def _allocMethod(ptype, side):
+ return "Alloc" + ptype.name() + side.title()
+
+
+def _deallocMethod(ptype, side):
+ return "Dealloc" + ptype.name() + side.title()
+
+
+##
+# A _HybridDecl straddles IPDL and C++ decls. It knows which C++
+# types correspond to which IPDL types, and it also knows how
+# serialize and deserialize "special" IPDL C++ types.
+##
+
+
+class _HybridDecl:
+ """A hybrid decl stores both an IPDL type and all the C++ type
+ info needed by later passes, along with a basic name for the decl."""
+
+ def __init__(self, ipdltype, name, attributes={}):
+ self.ipdltype = ipdltype
+ self.name = name
+ self.attributes = attributes
+
+ def var(self):
+ return ExprVar(self.name)
+
+ def bareType(self, side, fq=False):
+ """Return this decl's unqualified C++ type."""
+ return _cxxBareType(self.ipdltype, side, fq=fq)
+
+ def refType(self, side):
+ """Return this decl's C++ type as a 'reference' type, which is not
+ necessarily a C++ reference."""
+ return _cxxRefType(self.ipdltype, side)
+
+ def constRefType(self, side):
+ """Return this decl's C++ type as a const, 'reference' type."""
+ return _cxxConstRefType(self.ipdltype, side)
+
+ def ptrToType(self, side):
+ return _cxxPtrToType(self.ipdltype, side)
+
+ def constPtrToType(self, side):
+ return _cxxConstPtrToType(self.ipdltype, side)
+
+ def inType(self, side, direction):
+ """Return this decl's C++ Type with sending inparam semantics."""
+ return _cxxInType(self.ipdltype, side, direction)
+
+ def outType(self, side):
+ """Return this decl's C++ Type with outparam semantics."""
+ t = self.bareType(side)
+ if self.ipdltype.isIPDL() and self.ipdltype.isActor():
+ t.ptr = False
+ t.ptrptr = True
+ return t
+ t.ptr = True
+ return t
+
+ def forceMoveType(self, side):
+ """Return this decl's C++ Type with forced move semantics."""
+ assert _cxxTypeCanMove(self.ipdltype)
+ return _cxxForceMoveRefType(self.ipdltype, side)
+
+
+# --------------------------------------------------
+
+
+class HasFQName:
+ def fqClassName(self):
+ return self.decl.type.fullname()
+
+
+class _CompoundTypeComponent(_HybridDecl):
+ # @override the following methods to make the side argument optional.
+ def bareType(self, side=None, fq=False):
+ return _HybridDecl.bareType(self, side, fq=fq)
+
+ def refType(self, side=None):
+ return _HybridDecl.refType(self, side)
+
+ def constRefType(self, side=None):
+ return _HybridDecl.constRefType(self, side)
+
+ def ptrToType(self, side=None):
+ return _HybridDecl.ptrToType(self, side)
+
+ def constPtrToType(self, side=None):
+ return _HybridDecl.constPtrToType(self, side)
+
+ def forceMoveType(self, side=None):
+ return _HybridDecl.forceMoveType(self, side)
+
+
+class StructDecl(ipdl.ast.StructDecl, HasFQName):
+ def fields_ipdl_order(self):
+ for f in self.fields:
+ yield f
+
+ def fields_member_order(self):
+ assert len(self.packed_field_order) == len(self.fields)
+
+ for i in self.packed_field_order:
+ yield self.fields[i]
+
+ @staticmethod
+ def upgrade(structDecl):
+ assert isinstance(structDecl, ipdl.ast.StructDecl)
+ structDecl.__class__ = StructDecl
+
+
+class _StructField(_CompoundTypeComponent):
+ def __init__(self, ipdltype, name, sd):
+ self.basename = name
+
+ _CompoundTypeComponent.__init__(self, ipdltype, name)
+
+ def getMethod(self, thisexpr=None, sel="."):
+ meth = self.var()
+ if thisexpr is not None:
+ return ExprSelect(thisexpr, sel, meth.name)
+ return meth
+
+ def refExpr(self, thisexpr=None):
+ ref = self.memberVar()
+ if thisexpr is not None:
+ ref = ExprSelect(thisexpr, ".", ref.name)
+ return ref
+
+ def constRefExpr(self, thisexpr=None):
+ # sigh, gross hack
+ refexpr = self.refExpr(thisexpr)
+ if "Shmem" == self.ipdltype.name():
+ refexpr = ExprCast(refexpr, Type("Shmem", ref=True), const=True)
+ return refexpr
+
+ def argVar(self):
+ return ExprVar("_" + self.name)
+
+ def memberVar(self):
+ return ExprVar(self.name + "_")
+
+
+class UnionDecl(ipdl.ast.UnionDecl, HasFQName):
+ def callType(self, var=None):
+ func = ExprVar("type")
+ if var is not None:
+ func = ExprSelect(var, ".", func.name)
+ return ExprCall(func)
+
+ @staticmethod
+ def upgrade(unionDecl):
+ assert isinstance(unionDecl, ipdl.ast.UnionDecl)
+ unionDecl.__class__ = UnionDecl
+
+
+class _UnionMember(_CompoundTypeComponent):
+ """Not in the AFL sense, but rather a member (e.g. |int;|) of an
+ IPDL union type."""
+
+ def __init__(self, ipdltype, ud):
+ flatname = _flatTypeName(ipdltype)
+
+ _CompoundTypeComponent.__init__(self, ipdltype, "V" + flatname)
+ self.flattypename = flatname
+
+ # To create a finite object with a mutually recursive type, a union must
+ # be present somewhere in the recursive loop. Because of that we only
+ # need to care about introducing indirections inside unions.
+ self.recursive = ud.decl.type.mutuallyRecursiveWith(ipdltype)
+
+ def enum(self):
+ return "T" + self.flattypename
+
+ def enumvar(self):
+ return ExprVar(self.enum())
+
+ def internalType(self):
+ if self.recursive:
+ return self.ptrToType()
+ else:
+ return self.bareType()
+
+ def unionType(self):
+ """Type used for storage in generated C union decl."""
+ if self.recursive:
+ return self.ptrToType()
+ else:
+ return Type("mozilla::AlignedStorage2", T=self.internalType())
+
+ def unionValue(self):
+ # NB: knows that Union's storage C union is named |mValue|
+ return ExprSelect(ExprVar("mValue"), ".", self.name)
+
+ def typedef(self):
+ return self.flattypename + "__tdef"
+
+ def callGetConstPtr(self):
+ """Return an expression of type self.constptrToSelfType()"""
+ return ExprCall(ExprVar(self.getConstPtrName()))
+
+ def callGetPtr(self):
+ """Return an expression of type self.ptrToSelfType()"""
+ return ExprCall(ExprVar(self.getPtrName()))
+
+ def callCtor(self, expr=None):
+ assert not isinstance(expr, list)
+
+ if expr is None:
+ args = None
+ elif (
+ self.ipdltype.isIPDL()
+ and self.ipdltype.isArray()
+ and not isinstance(expr, ExprMove)
+ ):
+ args = [ExprCall(ExprSelect(expr, ".", "Clone"), args=[])]
+ else:
+ args = [expr]
+
+ if self.recursive:
+ return ExprAssn(self.callGetPtr(), ExprNew(self.bareType(), args=args))
+ else:
+ return ExprNew(
+ self.bareType(),
+ args=args,
+ newargs=[ExprVar("mozilla::KnownNotNull"), self.callGetPtr()],
+ )
+
+ def callDtor(self):
+ if self.recursive:
+ return ExprDelete(self.callGetPtr())
+ else:
+ return ExprCall(ExprSelect(self.callGetPtr(), "->", "~" + self.typedef()))
+
+ def getTypeName(self):
+ return "get_" + self.flattypename
+
+ def getConstTypeName(self):
+ return "get_" + self.flattypename
+
+ def getOtherTypeName(self):
+ return "get_" + self.otherflattypename
+
+ def getPtrName(self):
+ return "ptr_" + self.flattypename
+
+ def getConstPtrName(self):
+ return "constptr_" + self.flattypename
+
+ def ptrToSelfExpr(self):
+ """|*ptrToSelfExpr()| has type |self.bareType()|"""
+ v = self.unionValue()
+ if self.recursive:
+ return v
+ else:
+ return ExprCall(ExprSelect(v, ".", "addr"))
+
+ def constptrToSelfExpr(self):
+ """|*constptrToSelfExpr()| has type |self.constType()|"""
+ v = self.unionValue()
+ if self.recursive:
+ return v
+ return ExprCall(ExprSelect(v, ".", "addr"))
+
+ def ptrToInternalType(self):
+ t = self.ptrToType()
+ if self.recursive:
+ t.ref = True
+ return t
+
+ def defaultValue(self, fq=False):
+ # Use the default constructor for any class that does not have an
+ # implicit copy constructor.
+ if not self.bareType().hasimplicitcopyctor:
+ return None
+
+ if self.ipdltype.isIPDL() and self.ipdltype.isActor():
+ return ExprLiteral.NULL
+ # XXX sneaky here, maybe need ExprCtor()?
+ return ExprCall(self.bareType(fq=fq))
+
+ def getConstValue(self):
+ v = ExprDeref(self.callGetConstPtr())
+ # sigh
+ if "Shmem" == self.ipdltype.name():
+ v = ExprCast(v, Type("Shmem", ref=True), const=True)
+ return v
+
+
+# --------------------------------------------------
+
+
+class MessageDecl(ipdl.ast.MessageDecl):
+ def baseName(self):
+ return self.name
+
+ def recvMethod(self):
+ name = _recvPrefix(self.decl.type) + self.baseName()
+ if self.decl.type.isCtor():
+ name += "Constructor"
+ return name
+
+ def sendMethod(self):
+ name = _sendPrefix(self.decl.type) + self.baseName()
+ if self.decl.type.isCtor():
+ name += "Constructor"
+ return name
+
+ def hasReply(self):
+ return (
+ self.decl.type.hasReply()
+ or self.decl.type.isCtor()
+ or self.decl.type.isDtor()
+ )
+
+ def hasAsyncReturns(self):
+ return self.decl.type.isAsync() and self.returns
+
+ def msgCtorFunc(self):
+ return "Msg_%s" % (self.decl.progname)
+
+ def prettyMsgName(self, pfx=""):
+ return pfx + self.msgCtorFunc()
+
+ def pqMsgCtorFunc(self):
+ return "%s::%s" % (self.namespace, self.msgCtorFunc())
+
+ def msgId(self):
+ return self.msgCtorFunc() + "__ID"
+
+ def pqMsgId(self):
+ return "%s::%s" % (self.namespace, self.msgId())
+
+ def replyCtorFunc(self):
+ return "Reply_%s" % (self.decl.progname)
+
+ def pqReplyCtorFunc(self):
+ return "%s::%s" % (self.namespace, self.replyCtorFunc())
+
+ def replyId(self):
+ return self.replyCtorFunc() + "__ID"
+
+ def pqReplyId(self):
+ return "%s::%s" % (self.namespace, self.replyId())
+
+ def prettyReplyName(self, pfx=""):
+ return pfx + self.replyCtorFunc()
+
+ def promiseName(self):
+ name = self.baseName()
+ if self.decl.type.isCtor():
+ name += "Constructor"
+ name += "Promise"
+ return name
+
+ def resolverName(self):
+ return self.baseName() + "Resolver"
+
+ def actorDecl(self):
+ return self.params[0]
+
+ def makeCxxParams(
+ self, paramsems="in", returnsems="out", side=None, implicit=True, direction=None
+ ):
+ """Return a list of C++ decls per the spec'd configuration.
+ |params| and |returns| is the C++ semantics of those: 'in', 'out', or None."""
+
+ def makeDecl(d, sems):
+ if (
+ self.decl.type.tainted
+ and "NoTaint" not in d.attributes
+ and direction == "recv"
+ ):
+ # Tainted types are passed by-value, allowing the receiver to move them if desired.
+ assert sems != "out"
+ return Decl(Type("Tainted", T=d.bareType(side)), d.name)
+
+ if sems == "in":
+ t = d.inType(side, direction)
+ # If this is the `recv` side, and we're not using "move"
+ # semantics, that means we're an alloc method, and cannot accept
+ # values by rvalue reference. Downgrade to an lvalue reference.
+ if direction == "recv" and t.rvalref:
+ t.rvalref = False
+ t.ref = True
+ return Decl(t, d.name)
+ elif sems == "move":
+ assert direction == "recv"
+ # For legacy reasons, use an rvalue reference when generating
+ # parameters for recv methods which accept arrays.
+ if d.ipdltype.isIPDL() and d.ipdltype.isArray():
+ t = d.bareType(side)
+ t.rvalref = True
+ return Decl(t, d.name)
+ return Decl(d.inType(side, direction), d.name)
+ elif sems == "out":
+ return Decl(d.outType(side), d.name)
+ else:
+ assert 0
+
+ def makeResolverDecl(returns):
+ return Decl(Type(self.resolverName(), rvalref=True), "aResolve")
+
+ def makeCallbackResolveDecl(returns):
+ if len(returns) > 1:
+ resolvetype = _tuple([d.bareType(side) for d in returns])
+ else:
+ resolvetype = returns[0].bareType(side)
+
+ return Decl(
+ Type("mozilla::ipc::ResolveCallback", T=resolvetype, rvalref=True),
+ "aResolve",
+ )
+
+ def makeCallbackRejectDecl(returns):
+ return Decl(Type("mozilla::ipc::RejectCallback", rvalref=True), "aReject")
+
+ cxxparams = []
+ if paramsems is not None:
+ cxxparams.extend([makeDecl(d, paramsems) for d in self.params])
+
+ if returnsems == "promise" and self.returns:
+ pass
+ elif returnsems == "callback" and self.returns:
+ cxxparams.extend(
+ [
+ makeCallbackResolveDecl(self.returns),
+ makeCallbackRejectDecl(self.returns),
+ ]
+ )
+ elif returnsems == "resolver" and self.returns:
+ cxxparams.extend([makeResolverDecl(self.returns)])
+ elif returnsems is not None:
+ cxxparams.extend([makeDecl(r, returnsems) for r in self.returns])
+
+ if not implicit and self.decl.type.hasImplicitActorParam():
+ cxxparams = cxxparams[1:]
+
+ return cxxparams
+
+ def makeCxxArgs(
+ self, paramsems="in", retsems="out", retcallsems="out", implicit=True
+ ):
+ assert not retcallsems or retsems # retcallsems => returnsems
+ cxxargs = []
+
+ if paramsems == "move":
+ # We don't std::move() RefPtr<T> types because current Recv*()
+ # implementors take these parameters as T*, and
+ # std::move(RefPtr<T>) doesn't coerce to T*.
+ # We also don't move NotNull, as it has no move constructor.
+ cxxargs.extend(
+ [
+ p.var()
+ if p.ipdltype.isRefcounted()
+ or (p.ipdltype.isIPDL() and p.ipdltype.isNotNull())
+ else ExprMove(p.var())
+ for p in self.params
+ ]
+ )
+ elif paramsems == "in":
+ cxxargs.extend([p.var() for p in self.params])
+ else:
+ assert False
+
+ for ret in self.returns:
+ if retsems == "in":
+ if retcallsems == "in":
+ cxxargs.append(ret.var())
+ elif retcallsems == "out":
+ cxxargs.append(ExprAddrOf(ret.var()))
+ else:
+ assert 0
+ elif retsems == "out":
+ if retcallsems == "in":
+ cxxargs.append(ExprDeref(ret.var()))
+ elif retcallsems == "out":
+ cxxargs.append(ret.var())
+ else:
+ assert 0
+ elif retsems == "resolver":
+ pass
+ if retsems == "resolver":
+ cxxargs.append(ExprMove(ExprVar("resolver")))
+
+ if not implicit:
+ assert self.decl.type.hasImplicitActorParam()
+ cxxargs = cxxargs[1:]
+
+ return cxxargs
+
+ @staticmethod
+ def upgrade(messageDecl):
+ assert isinstance(messageDecl, ipdl.ast.MessageDecl)
+ if messageDecl.decl.type.hasImplicitActorParam():
+ messageDecl.params.insert(
+ 0,
+ _HybridDecl(
+ ipdl.type.ActorType(messageDecl.decl.type.constructedType()),
+ "actor",
+ ),
+ )
+ messageDecl.__class__ = MessageDecl
+
+
+# --------------------------------------------------
+def _usesShmem(p):
+ for md in p.messageDecls:
+ for param in md.inParams:
+ if ipdl.type.hasshmem(param.type):
+ return True
+ for ret in md.outParams:
+ if ipdl.type.hasshmem(ret.type):
+ return True
+ return False
+
+
+def _subtreeUsesShmem(p):
+ if _usesShmem(p):
+ return True
+
+ ptype = p.decl.type
+ for mgd in ptype.manages:
+ if ptype is not mgd:
+ if _subtreeUsesShmem(mgd._ast):
+ return True
+ return False
+
+
+class Protocol(ipdl.ast.Protocol):
+ def _ipdlmgrtype(self):
+ assert 1 == len(self.decl.type.managers)
+ for mgr in self.decl.type.managers:
+ return mgr
+
+ def managerActorType(self, side, ptr=False):
+ return Type(_actorName(self._ipdlmgrtype().name(), side), ptr=ptr)
+
+ def unregisterMethod(self, actorThis=None):
+ if actorThis is not None:
+ return ExprSelect(actorThis, "->", "Unregister")
+ return ExprVar("Unregister")
+
+ def removeManageeMethod(self):
+ return ExprVar("RemoveManagee")
+
+ def deallocManageeMethod(self):
+ return ExprVar("DeallocManagee")
+
+ def getChannelMethod(self):
+ return ExprVar("GetIPCChannel")
+
+ def callGetChannel(self, actorThis=None):
+ fn = self.getChannelMethod()
+ if actorThis is not None:
+ fn = ExprSelect(actorThis, "->", fn.name)
+ return ExprCall(fn)
+
+ def processingErrorVar(self):
+ assert self.decl.type.isToplevel()
+ return ExprVar("ProcessingError")
+
+ def shouldContinueFromTimeoutVar(self):
+ assert self.decl.type.isToplevel()
+ return ExprVar("ShouldContinueFromReplyTimeout")
+
+ def routingId(self, actorThis=None):
+ if self.decl.type.isToplevel():
+ return ExprVar("MSG_ROUTING_CONTROL")
+ if actorThis is not None:
+ return ExprCall(ExprSelect(actorThis, "->", "Id"))
+ return ExprCall(ExprVar("Id"))
+
+ def managerVar(self, thisexpr=None):
+ assert thisexpr is not None or not self.decl.type.isToplevel()
+ mvar = ExprCall(ExprVar("Manager"), args=[])
+ if thisexpr is not None:
+ mvar = ExprCall(ExprSelect(thisexpr, "->", "Manager"), args=[])
+ return mvar
+
+ def managedCxxType(self, actortype, side):
+ assert self.decl.type.isManagerOf(actortype)
+ return Type(_actorName(actortype.name(), side), ptr=True)
+
+ def managedMethod(self, actortype, side):
+ assert self.decl.type.isManagerOf(actortype)
+ return ExprVar("Managed" + _actorName(actortype.name(), side))
+
+ def managedVar(self, actortype, side):
+ assert self.decl.type.isManagerOf(actortype)
+ return ExprVar("mManaged" + _actorName(actortype.name(), side))
+
+ def managedVarType(self, actortype, side, const=False, ref=False):
+ assert self.decl.type.isManagerOf(actortype)
+ return _cxxManagedContainerType(
+ Type(_actorName(actortype.name(), side)), const=const, ref=ref
+ )
+
+ def subtreeUsesShmem(self):
+ return _subtreeUsesShmem(self)
+
+ @staticmethod
+ def upgrade(protocol):
+ assert isinstance(protocol, ipdl.ast.Protocol)
+ protocol.__class__ = Protocol
+
+
+class TranslationUnit(ipdl.ast.TranslationUnit):
+ @staticmethod
+ def upgrade(tu):
+ assert isinstance(tu, ipdl.ast.TranslationUnit)
+ tu.__class__ = TranslationUnit
+
+
+# -----------------------------------------------------------------------------
+
+pod_types = {
+ "::int8_t": 1,
+ "::uint8_t": 1,
+ "::int16_t": 2,
+ "::uint16_t": 2,
+ "::int32_t": 4,
+ "::uint32_t": 4,
+ "::int64_t": 8,
+ "::uint64_t": 8,
+ "float": 4,
+ "double": 8,
+}
+max_pod_size = max(pod_types.values())
+# We claim that all types we don't recognize are automatically "bigger"
+# than pod types for ease of sorting.
+pod_size_sentinel = max_pod_size * 2
+
+
+def pod_size(ipdltype):
+ if not ipdltype.isCxx():
+ return pod_size_sentinel
+
+ return pod_types.get(ipdltype.fullname(), pod_size_sentinel)
+
+
+class _DecorateWithCxxStuff(ipdl.ast.Visitor):
+ """Phase 1 of lowering: decorate the IPDL AST with information
+ relevant to C++ code generation.
+
+ This pass results in an AST that is a poor man's "IR"; in reality, a
+ "hybrid" AST mainly consisting of IPDL nodes with new C++ info along
+ with some new IPDL/C++ nodes that are tuned for C++ codegen."""
+
+ def __init__(self):
+ self.visitedTus = set()
+ self.protocolName = None
+
+ def visitTranslationUnit(self, tu):
+ if tu not in self.visitedTus:
+ self.visitedTus.add(tu)
+ ipdl.ast.Visitor.visitTranslationUnit(self, tu)
+ if not isinstance(tu, TranslationUnit):
+ TranslationUnit.upgrade(tu)
+
+ def visitInclude(self, inc):
+ if inc.tu.filetype == "header":
+ inc.tu.accept(self)
+
+ def visitProtocol(self, pro):
+ self.protocolName = pro.name
+ Protocol.upgrade(pro)
+ return ipdl.ast.Visitor.visitProtocol(self, pro)
+
+ def visitStructDecl(self, sd):
+ if not isinstance(sd, StructDecl):
+ newfields = [_StructField(f.decl.type, f.name, sd) for f in sd.fields]
+
+ # Compute a permutation of the fields for in-memory storage such
+ # that the memory layout of the structure will be well-packed.
+ permutation = list(range(len(newfields)))
+
+ # Note that the results of `pod_size` ensure that non-POD fields
+ # sort before POD ones.
+ def size(idx):
+ return pod_size(newfields[idx].ipdltype)
+
+ permutation.sort(key=size, reverse=True)
+
+ sd.fields = newfields
+ sd.packed_field_order = permutation
+ StructDecl.upgrade(sd)
+
+ def visitUnionDecl(self, ud):
+ ud.components = [_UnionMember(ctype, ud) for ctype in ud.decl.type.components]
+ UnionDecl.upgrade(ud)
+
+ def visitDecl(self, decl):
+ return _HybridDecl(decl.type, decl.progname, decl.attributes)
+
+ def visitMessageDecl(self, md):
+ md.namespace = self.protocolName
+ md.params = [param.accept(self) for param in md.inParams]
+ md.returns = [ret.accept(self) for ret in md.outParams]
+ MessageDecl.upgrade(md)
+
+
+# -----------------------------------------------------------------------------
+
+
+def msgenums(protocol, pretty=False):
+ msgenum = TypeEnum("MessageType")
+ msgstart = _messageStartName(protocol.decl.type) + " << 16"
+ msgenum.addId(protocol.name + "Start", msgstart)
+
+ for md in protocol.messageDecls:
+ msgenum.addId(md.prettyMsgName() if pretty else md.msgId())
+ if md.hasReply():
+ msgenum.addId(md.prettyReplyName() if pretty else md.replyId())
+
+ msgenum.addId(protocol.name + "End")
+ return msgenum
+
+
+class _GenerateProtocolCode(ipdl.ast.Visitor):
+ """Creates code common to both the parent and child actors."""
+
+ def __init__(self):
+ self.protocol = None # protocol we're generating a class for
+ self.hdrfile = None # what will become Protocol.h
+ self.cppfile = None # what will become Protocol.cpp
+ self.cppIncludeHeaders = []
+ self.structUnionDefns = []
+ self.funcDefns = []
+
+ def lower(self, tu, cxxHeaderFile, cxxFile, segmentcapacitydict):
+ self.protocol = tu.protocol
+ self.hdrfile = cxxHeaderFile
+ self.cppfile = cxxFile
+ self.segmentcapacitydict = segmentcapacitydict
+ tu.accept(self)
+
+ def visitTranslationUnit(self, tu):
+ hf = self.hdrfile
+
+ hf.addthing(_DISCLAIMER)
+ hf.addthings(_includeGuardStart(hf))
+ hf.addthing(Whitespace.NL)
+
+ for inc in builtinHeaderIncludes:
+ self.visitBuiltinCxxInclude(inc)
+
+ # Compute the set of includes we need for declared structure/union
+ # classes for this protocol.
+ typesToIncludes = {}
+ for using in tu.using:
+ typestr = str(using.type)
+ if typestr not in typesToIncludes:
+ typesToIncludes[typestr] = using.header
+ else:
+ assert typesToIncludes[typestr] == using.header
+
+ aggregateTypeIncludes = set()
+ for su in tu.structsAndUnions:
+ typedeps = _ComputeTypeDeps(su.decl.type, typesToIncludes)
+ if isinstance(su, ipdl.ast.StructDecl):
+ aggregateTypeIncludes.add("mozilla/ipc/IPDLStructMember.h")
+ for f in su.fields:
+ f.ipdltype.accept(typedeps)
+ elif isinstance(su, ipdl.ast.UnionDecl):
+ for c in su.components:
+ c.ipdltype.accept(typedeps)
+
+ aggregateTypeIncludes.update(typedeps.includeHeaders)
+
+ if len(aggregateTypeIncludes) != 0:
+ hf.addthing(Whitespace.NL)
+ hf.addthings([Whitespace("// Headers for typedefs"), Whitespace.NL])
+
+ for headername in sorted(iter(aggregateTypeIncludes)):
+ hf.addthing(CppDirective("include", '"' + headername + '"'))
+
+ # Manually run Visitor.visitTranslationUnit. For dependency resolution
+ # we need to handle structs and unions separately.
+ for cxxInc in tu.cxxIncludes:
+ cxxInc.accept(self)
+ for inc in tu.includes:
+ inc.accept(self)
+ self.generateStructsAndUnions(tu)
+ for using in tu.builtinUsing:
+ using.accept(self)
+ for using in tu.using:
+ using.accept(self)
+ if tu.protocol:
+ tu.protocol.accept(self)
+
+ if tu.filetype == "header":
+ self.cppIncludeHeaders.append(_ipdlhHeaderName(tu) + ".h")
+
+ hf.addthing(Whitespace.NL)
+ hf.addthings(_includeGuardEnd(hf))
+
+ cf = self.cppfile
+ cf.addthings(
+ (
+ [_DISCLAIMER, Whitespace.NL]
+ + [
+ CppDirective("include", '"' + h + '"')
+ for h in self.cppIncludeHeaders
+ ]
+ + [Whitespace.NL]
+ + [
+ CppDirective("include", '"%s"' % filename)
+ for filename in ipdl.builtin.CppIncludes
+ ]
+ + [Whitespace.NL]
+ )
+ )
+
+ if self.protocol:
+ # construct the namespace into which we'll stick all our defns
+ ns = Namespace(self.protocol.name)
+ cf.addthing(_putInNamespaces(ns, self.protocol.namespaces))
+ ns.addstmts(([Whitespace.NL] + self.funcDefns + [Whitespace.NL]))
+
+ cf.addthings(self.structUnionDefns)
+
+ def visitBuiltinCxxInclude(self, inc):
+ self.hdrfile.addthing(CppDirective("include", '"' + inc.file + '"'))
+
+ def visitCxxInclude(self, inc):
+ self.cppIncludeHeaders.append(inc.file)
+
+ def visitInclude(self, inc):
+ if inc.tu.filetype == "header":
+ self.hdrfile.addthing(
+ CppDirective("include", '"' + _ipdlhHeaderName(inc.tu) + '.h"')
+ )
+ # Inherit cpp includes defined by imported header files, as they may
+ # be required to serialize an imported `using` type.
+ for cxxinc in inc.tu.cxxIncludes:
+ cxxinc.accept(self)
+ else:
+ self.cppIncludeHeaders += [
+ _protocolHeaderName(inc.tu.protocol, "parent") + ".h",
+ _protocolHeaderName(inc.tu.protocol, "child") + ".h",
+ ]
+
+ def generateStructsAndUnions(self, tu):
+ """Generate the definitions for all structs and unions. This will
+ re-order the declarations if needed in the C++ code such that
+ dependencies have already been defined."""
+ decls = OrderedDict()
+ for su in tu.structsAndUnions:
+ if isinstance(su, StructDecl):
+ which = "struct"
+ forwarddecls, fulldecltypes, cls = _generateCxxStruct(su)
+ traitsdecl, traitsdefns = _ParamTraits.structPickling(su.decl.type)
+ else:
+ assert isinstance(su, UnionDecl)
+ which = "union"
+ forwarddecls, fulldecltypes, cls = _generateCxxUnion(su)
+ traitsdecl, traitsdefns = _ParamTraits.unionPickling(su.decl.type)
+
+ clsdecl, methoddefns = _splitClassDeclDefn(cls)
+
+ # Store the declarations in the decls map so we can emit in
+ # dependency order.
+ decls[su.decl.type] = (
+ fulldecltypes,
+ [Whitespace.NL]
+ + forwarddecls
+ + [
+ Whitespace(
+ """
+//-----------------------------------------------------------------------------
+// Declaration of the IPDL type |%s %s|
+//
+"""
+ % (which, su.name)
+ ),
+ _putInNamespaces(clsdecl, su.namespaces),
+ ]
+ + [Whitespace.NL, traitsdecl],
+ )
+
+ self.structUnionDefns.extend(
+ [
+ Whitespace(
+ """
+//-----------------------------------------------------------------------------
+// Method definitions for the IPDL type |%s %s|
+//
+"""
+ % (which, su.name)
+ ),
+ _putInNamespaces(methoddefns, su.namespaces),
+ Whitespace.NL,
+ traitsdefns,
+ ]
+ )
+
+ # Generate the declarations structs in dependency order.
+ def gen_struct(deps, defn):
+ for dep in deps:
+ if dep in decls:
+ d, t = decls[dep]
+ del decls[dep]
+ gen_struct(d, t)
+ self.hdrfile.addthings(defn)
+
+ while len(decls) > 0:
+ _, (d, t) = decls.popitem(False)
+ gen_struct(d, t)
+
+ def visitProtocol(self, p):
+ self.cppIncludeHeaders.append(_protocolHeaderName(self.protocol, "") + ".h")
+ self.cppIncludeHeaders.append(
+ _protocolHeaderName(self.protocol, "Parent") + ".h"
+ )
+ self.cppIncludeHeaders.append(
+ _protocolHeaderName(self.protocol, "Child") + ".h"
+ )
+
+ # Forward declare our own actors.
+ self.hdrfile.addthings(
+ [
+ Whitespace.NL,
+ _makeForwardDeclForActor(p.decl.type, "Parent"),
+ _makeForwardDeclForActor(p.decl.type, "Child"),
+ ]
+ )
+
+ self.hdrfile.addthing(
+ Whitespace(
+ """
+//-----------------------------------------------------------------------------
+// Code common to %sChild and %sParent
+//
+"""
+ % (p.name, p.name)
+ )
+ )
+
+ # construct the namespace into which we'll stick all our decls
+ ns = Namespace(self.protocol.name)
+ self.hdrfile.addthing(_putInNamespaces(ns, p.namespaces))
+ ns.addstmt(Whitespace.NL)
+
+ for func in self.genEndpointFuncs():
+ edecl, edefn = _splitFuncDeclDefn(func)
+ ns.addstmts([edecl, Whitespace.NL])
+ self.funcDefns.append(edefn)
+
+ # spit out message type enum and classes
+ msgenum = msgenums(self.protocol)
+ ns.addstmts([StmtDecl(Decl(msgenum, "")), Whitespace.NL])
+
+ for md in p.messageDecls:
+ decls = []
+
+ # Look up the segment capacity used for serializing this
+ # message. If the capacity is not specified, use '0' for
+ # the default capacity (defined in ipc_message.cc)
+ name = "%s::%s" % (md.namespace, md.decl.progname)
+ segmentcapacity = self.segmentcapacitydict.get(name, 0)
+
+ mfDecl, mfDefn = _splitFuncDeclDefn(
+ _generateMessageConstructor(md, segmentcapacity, p, forReply=False)
+ )
+ decls.append(mfDecl)
+ self.funcDefns.append(mfDefn)
+
+ if md.hasReply():
+ rfDecl, rfDefn = _splitFuncDeclDefn(
+ _generateMessageConstructor(md, 0, p, forReply=True)
+ )
+ decls.append(rfDecl)
+ self.funcDefns.append(rfDefn)
+
+ decls.append(Whitespace.NL)
+ ns.addstmts(decls)
+
+ ns.addstmts([Whitespace.NL, Whitespace.NL])
+
+ # Generate code for PFoo::CreateEndpoints.
+ def genEndpointFuncs(self):
+ p = self.protocol.decl.type
+ tparent = _cxxBareType(ActorType(p), "Parent", fq=True)
+ tchild = _cxxBareType(ActorType(p), "Child", fq=True)
+
+ def mkOverload(includepids):
+ params = []
+ if includepids:
+ params = [
+ Decl(Type("base::ProcessId"), "aParentDestPid"),
+ Decl(Type("base::ProcessId"), "aChildDestPid"),
+ ]
+ params += [
+ Decl(
+ Type("mozilla::ipc::Endpoint<" + tparent.name + ">", ptr=True),
+ "aParent",
+ ),
+ Decl(
+ Type("mozilla::ipc::Endpoint<" + tchild.name + ">", ptr=True),
+ "aChild",
+ ),
+ ]
+ openfunc = MethodDefn(
+ MethodDecl("CreateEndpoints", params=params, ret=Type.NSRESULT)
+ )
+ openfunc.addcode(
+ """
+ return mozilla::ipc::CreateEndpoints(
+ mozilla::ipc::PrivateIPDLInterface(),
+ $,{args});
+ """,
+ args=[ExprVar(d.name) for d in params],
+ )
+ return openfunc
+
+ funcs = [mkOverload(True)]
+ if not p.hasOtherPid():
+ funcs.append(mkOverload(False))
+ return funcs
+
+
+# --------------------------------------------------
+
+cppPriorityList = list(
+ map(lambda src: src.upper() + "_PRIORITY", ipdl.ast.priorityList)
+)
+
+
+def _generateMessageConstructor(md, segmentSize, protocol, forReply=False):
+ if forReply:
+ clsname = md.replyCtorFunc()
+ msgid = md.replyId()
+ replyEnum = "REPLY"
+ prioEnum = cppPriorityList[md.decl.type.replyPrio]
+ else:
+ clsname = md.msgCtorFunc()
+ msgid = md.msgId()
+ replyEnum = "NOT_REPLY"
+ prioEnum = cppPriorityList[md.decl.type.prio]
+
+ nested = md.decl.type.nested
+ compress = md.decl.type.compress
+ lazySend = md.decl.type.lazySend
+
+ routingId = ExprVar("routingId")
+
+ func = FunctionDefn(
+ FunctionDecl(
+ clsname,
+ params=[Decl(Type("int32_t"), routingId.name)],
+ ret=Type("mozilla::UniquePtr<IPC::Message>"),
+ )
+ )
+
+ if not compress:
+ compression = "COMPRESSION_NONE"
+ elif compress.value == "all":
+ compression = "COMPRESSION_ALL"
+ else:
+ assert compress.value is None
+ compression = "COMPRESSION_ENABLED"
+
+ if lazySend:
+ lazySendEnum = "LAZY_SEND"
+ else:
+ lazySendEnum = "EAGER_SEND"
+
+ if nested == ipdl.ast.NOT_NESTED:
+ nestedEnum = "NOT_NESTED"
+ elif nested == ipdl.ast.INSIDE_SYNC_NESTED:
+ nestedEnum = "NESTED_INSIDE_SYNC"
+ else:
+ assert nested == ipdl.ast.INSIDE_CPOW_NESTED
+ nestedEnum = "NESTED_INSIDE_CPOW"
+
+ if md.decl.type.isSync():
+ syncEnum = "SYNC"
+ else:
+ syncEnum = "ASYNC"
+
+ # FIXME(bug ???) - remove support for interrupt messages from the IPDL compiler.
+ if md.decl.type.isInterrupt():
+ func.addcode(
+ """
+ static_assert(
+ false,
+ "runtime support for intr messages has been removed from IPDL");
+ """
+ )
+
+ if md.decl.type.isCtor():
+ ctorEnum = "CONSTRUCTOR"
+ else:
+ ctorEnum = "NOT_CONSTRUCTOR"
+
+ def messageEnum(valname):
+ return ExprVar("IPC::Message::" + valname)
+
+ flags = ExprCall(
+ ExprVar("IPC::Message::HeaderFlags"),
+ args=[
+ messageEnum(nestedEnum),
+ messageEnum(prioEnum),
+ messageEnum(compression),
+ messageEnum(lazySendEnum),
+ messageEnum(ctorEnum),
+ messageEnum(syncEnum),
+ messageEnum(replyEnum),
+ ],
+ )
+
+ segmentSize = int(segmentSize)
+ if not segmentSize:
+ segmentSize = 0
+ func.addstmt(
+ StmtReturn(
+ ExprCall(
+ ExprVar("IPC::Message::IPDLMessage"),
+ args=[
+ routingId,
+ ExprVar(msgid),
+ ExprLiteral.Int(int(segmentSize)),
+ flags,
+ ],
+ )
+ )
+ )
+
+ return func
+
+
+# --------------------------------------------------
+
+
+class _ParamTraits:
+ var = ExprVar("aVar")
+ writervar = ExprVar("aWriter")
+ readervar = ExprVar("aReader")
+
+ @classmethod
+ def ifsideis(cls, rdrwtr, side, then, els=None):
+ ifstmt = StmtIf(
+ ExprBinary(
+ _cxxSide(side),
+ "==",
+ ExprCode("${rdrwtr}->GetActor()->GetSide()", rdrwtr=rdrwtr),
+ )
+ )
+ ifstmt.addifstmt(then)
+ if els is not None:
+ ifstmt.addelsestmt(els)
+ return ifstmt
+
+ @classmethod
+ def fatalError(cls, rdrwtr, reason):
+ return StmtCode(
+ "${rdrwtr}->FatalError(${reason});",
+ rdrwtr=rdrwtr,
+ reason=ExprLiteral.String(reason),
+ )
+
+ @classmethod
+ def writeSentinel(cls, writervar, sentinelKey):
+ return [
+ Whitespace("// Sentinel = " + repr(sentinelKey) + "\n", indent=True),
+ StmtExpr(
+ ExprCall(
+ ExprSelect(writervar, "->", "WriteSentinel"),
+ args=[ExprLiteral.Int(hashfunc(sentinelKey))],
+ )
+ ),
+ ]
+
+ @classmethod
+ def readSentinel(cls, readervar, sentinelKey, sentinelFail):
+ # Read the sentinel
+ read = ExprCall(
+ ExprSelect(readervar, "->", "ReadSentinel"),
+ args=[ExprLiteral.Int(hashfunc(sentinelKey))],
+ )
+ ifsentinel = StmtIf(ExprNot(read))
+ ifsentinel.addifstmts(sentinelFail)
+
+ return [
+ Whitespace("// Sentinel = " + repr(sentinelKey) + "\n", indent=True),
+ ifsentinel,
+ ]
+
+ @classmethod
+ def write(cls, var, writervar, ipdltype=None):
+ if ipdltype and _cxxTypeNeedsMoveForSend(ipdltype):
+ var = ExprMove(var)
+ return ExprCall(ExprVar("IPC::WriteParam"), args=[writervar, var])
+
+ @classmethod
+ def checkedWrite(cls, ipdltype, var, writervar, sentinelKey):
+ assert sentinelKey
+ block = Block()
+
+ block.addstmts(
+ [
+ StmtExpr(cls.write(var, writervar, ipdltype)),
+ ]
+ )
+ block.addstmts(cls.writeSentinel(writervar, sentinelKey))
+ return block
+
+ @classmethod
+ def bulkSentinelKey(cls, fields):
+ return " | ".join(f.basename for f in fields)
+
+ @classmethod
+ def checkedBulkWrite(cls, var, size, fields):
+ block = Block()
+ first = fields[0]
+
+ block.addstmts(
+ [
+ StmtExpr(
+ ExprCall(
+ ExprSelect(cls.writervar, "->", "WriteBytes"),
+ args=[
+ ExprAddrOf(
+ ExprCall(first.getMethod(thisexpr=var, sel="."))
+ ),
+ ExprLiteral.Int(size * len(fields)),
+ ],
+ )
+ )
+ ]
+ )
+ block.addstmts(cls.writeSentinel(cls.writervar, cls.bulkSentinelKey(fields)))
+
+ return block
+
+ @classmethod
+ def checkedBulkRead(cls, var, size, fields):
+ block = Block()
+ first = fields[0]
+
+ readbytes = ExprCall(
+ ExprSelect(cls.readervar, "->", "ReadBytesInto"),
+ args=[
+ ExprAddrOf(ExprCall(first.getMethod(thisexpr=var, sel="->"))),
+ ExprLiteral.Int(size * len(fields)),
+ ],
+ )
+ ifbad = StmtIf(ExprNot(readbytes))
+ errmsg = "Error bulk reading fields from %s" % first.ipdltype.name()
+ ifbad.addifstmts(
+ [cls.fatalError(cls.readervar, errmsg), StmtReturn(readResultError())]
+ )
+ block.addstmt(ifbad)
+ block.addstmts(
+ cls.readSentinel(
+ cls.readervar,
+ cls.bulkSentinelKey(fields),
+ errfnSentinel(readResultError())(errmsg),
+ )
+ )
+
+ return block
+
+ @classmethod
+ def checkedRead(
+ cls,
+ ipdltype,
+ cxxtype,
+ var,
+ readervar,
+ errfn,
+ paramtype,
+ sentinelKey,
+ errfnSentinel,
+ ):
+ assert isinstance(var, ExprVar)
+
+ if not isinstance(paramtype, list):
+ paramtype = ["Error deserializing " + paramtype]
+
+ block = Block()
+
+ # Read the data
+ block.addcode(
+ """
+ auto ${maybevar} = IPC::ReadParam<${ty}>(${reader});
+ if (!${maybevar}) {
+ $*{errfn}
+ }
+ auto& ${var} = *${maybevar};
+ """,
+ maybevar=ExprVar("maybe__" + var.name),
+ ty=cxxtype,
+ reader=readervar,
+ errfn=errfn(*paramtype),
+ var=var,
+ )
+
+ block.addstmts(
+ cls.readSentinel(readervar, sentinelKey, errfnSentinel(*paramtype))
+ )
+
+ return block
+
+ # Helper wrapper for checkedRead for use within _ParamTraits
+ @classmethod
+ def _checkedRead(cls, ipdltype, cxxtype, var, sentinelKey, what):
+ def errfn(msg):
+ return [cls.fatalError(cls.readervar, msg), StmtReturn(readResultError())]
+
+ return cls.checkedRead(
+ ipdltype,
+ cxxtype,
+ var,
+ cls.readervar,
+ errfn=errfn,
+ paramtype=what,
+ sentinelKey=sentinelKey,
+ errfnSentinel=errfnSentinel(readResultError()),
+ )
+
+ @classmethod
+ def generateDecl(cls, fortype, write, read, needsmove=False):
+ # ParamTraits impls are selected ignoring constness, and references.
+ pt = Class(
+ "ParamTraits",
+ specializes=Type(
+ fortype.name, T=fortype.T, inner=fortype.inner, ptr=fortype.ptr
+ ),
+ struct=True,
+ )
+
+ # typedef T paramType;
+ pt.addstmt(Typedef(fortype, "paramType"))
+
+ # static void Write(Message*, const T&);
+ if needsmove:
+ intype = Type("paramType", rvalref=True)
+ else:
+ intype = Type("paramType", ref=True, const=True)
+ writemthd = MethodDefn(
+ MethodDecl(
+ "Write",
+ params=[
+ Decl(Type("IPC::MessageWriter", ptr=True), cls.writervar.name),
+ Decl(intype, cls.var.name),
+ ],
+ methodspec=MethodSpec.STATIC,
+ )
+ )
+ writemthd.addstmts(write)
+ pt.addstmt(writemthd)
+
+ # static ReadResult<T> Read(MessageReader*);
+ readmthd = MethodDefn(
+ MethodDecl(
+ "Read",
+ params=[
+ Decl(Type("IPC::MessageReader", ptr=True), cls.readervar.name),
+ ],
+ ret=Type("IPC::ReadResult<paramType>"),
+ methodspec=MethodSpec.STATIC,
+ )
+ )
+ readmthd.addstmts(read)
+ pt.addstmt(readmthd)
+
+ # Split the class into declaration and definition
+ clsdecl, methoddefns = _splitClassDeclDefn(pt)
+
+ namespaces = [Namespace("IPC")]
+ clsns = _putInNamespaces(clsdecl, namespaces)
+ defns = _putInNamespaces(methoddefns, namespaces)
+ return clsns, defns
+
+ @classmethod
+ def actorPickling(cls, actortype, side):
+ """Generates pickling for IPDL actors. This is a |nullable| deserializer.
+ Write and read callers will perform nullability validation."""
+
+ cxxtype = _cxxBareType(actortype, side, fq=True)
+
+ write = StmtCode(
+ """
+ MOZ_RELEASE_ASSERT(
+ ${writervar}->GetActor(),
+ "Cannot serialize managed actors without an actor");
+
+ int32_t id;
+ if (!${var}) {
+ id = 0; // kNullActorId
+ } else {
+ id = ${var}->Id();
+ if (id == 1) { // kFreedActorId
+ ${var}->FatalError("Actor has been |delete|d");
+ }
+ MOZ_RELEASE_ASSERT(
+ ${writervar}->GetActor()->GetIPCChannel() == ${var}->GetIPCChannel(),
+ "Actor must be from the same channel as the"
+ " actor it's being sent over");
+ MOZ_RELEASE_ASSERT(
+ ${var}->CanSend(),
+ "Actor must still be open when sending");
+ }
+
+ ${write};
+ """,
+ var=cls.var,
+ writervar=cls.writervar,
+ write=cls.write(ExprVar("id"), cls.writervar),
+ )
+
+ # bool Read(..) impl
+ read = StmtCode(
+ """
+ MOZ_RELEASE_ASSERT(
+ ${readervar}->GetActor(),
+ "Cannot deserialize managed actors without an actor");
+ mozilla::Maybe<mozilla::ipc::IProtocol*> actor = ${readervar}->GetActor()
+ ->ReadActor(${readervar}, true, ${actortype}, ${protocolid});
+ if (actor.isSome()) {
+ return static_cast<${cxxtype}>(actor.ref());
+ }
+ return {};
+ """,
+ readervar=cls.readervar,
+ actortype=ExprLiteral.String(actortype.name()),
+ protocolid=_protocolId(actortype),
+ cxxtype=cxxtype,
+ )
+
+ return cls.generateDecl(cxxtype, [write], [read])
+
+ @classmethod
+ def structPickling(cls, structtype):
+ sd = structtype._ast
+ # NOTE: Not using _cxxBareType here as we don't have a side
+ cxxtype = Type(structtype.fullname())
+
+ write = []
+ read = []
+
+ # First serialize/deserialize all non-pod data in IPDL order. These need
+ # to be read/written first because they'll be used to invoke the IPDL
+ # struct's constructor.
+ ctorargs = []
+ for f in sd.fields_ipdl_order():
+ if pod_size(f.ipdltype) == pod_size_sentinel:
+ write.append(
+ cls.checkedWrite(
+ f.ipdltype,
+ ExprCall(f.getMethod(thisexpr=cls.var, sel=".")),
+ cls.writervar,
+ sentinelKey=f.basename,
+ )
+ )
+ read.append(
+ cls._checkedRead(
+ f.ipdltype,
+ f.bareType(fq=True),
+ f.argVar(),
+ f.basename,
+ "'"
+ + f.getMethod().name
+ + "' "
+ + "("
+ + f.ipdltype.name()
+ + ") member of "
+ + "'"
+ + structtype.name()
+ + "'",
+ )
+ )
+ if _cxxTypeCanMove(f.ipdltype):
+ ctorargs.append(ExprMove(f.argVar()))
+ else:
+ ctorargs.append(f.argVar())
+ else:
+ # We're going to bulk-read in this value later, so we'll just
+ # zero-initialize it for now.
+ ctorargs.append(ExprCode("${type}{0}", type=f.bareType(fq=True)))
+
+ resultvar = ExprVar("result__")
+ read.append(
+ StmtDecl(
+ Decl(_cxxReadResultType(Type("paramType")), resultvar.name),
+ initargs=[ExprVar("std::in_place")] + ctorargs,
+ )
+ )
+
+ # After non-pod data, bulk read/write pod data in member order. This has
+ # to be done after the result has been constructed, so that we have
+ # somewhere to read into.
+ for size, fields in itertools.groupby(
+ sd.fields_member_order(), lambda f: pod_size(f.ipdltype)
+ ):
+ if size != pod_size_sentinel:
+ fields = list(fields)
+ write.append(cls.checkedBulkWrite(cls.var, size, fields))
+ read.append(cls.checkedBulkRead(resultvar, size, fields))
+
+ read.append(StmtReturn(resultvar))
+
+ return cls.generateDecl(
+ cxxtype, write, read, needsmove=_cxxTypeNeedsMoveForSend(structtype)
+ )
+
+ @classmethod
+ def unionPickling(cls, uniontype):
+ # NOTE: Not using _cxxBareType here as we don't have a side
+ cxxtype = Type(uniontype.fullname())
+ ud = uniontype._ast
+
+ # Use typedef to set up an alias so it's easier to reference the struct type.
+ alias = "union__"
+ typevar = ExprVar("type")
+
+ prelude = [
+ Typedef(cxxtype, alias),
+ ]
+
+ writeswitch = StmtSwitch(typevar)
+ write = prelude + [
+ StmtDecl(Decl(Type.INT, typevar.name), init=ud.callType(cls.var)),
+ cls.checkedWrite(
+ None, typevar, cls.writervar, sentinelKey=uniontype.name()
+ ),
+ Whitespace.NL,
+ writeswitch,
+ ]
+
+ readswitch = StmtSwitch(typevar)
+ read = prelude + [
+ cls._checkedRead(
+ None,
+ Type.INT,
+ typevar,
+ uniontype.name(),
+ "type of union " + uniontype.name(),
+ ),
+ Whitespace.NL,
+ readswitch,
+ ]
+
+ for c in ud.components:
+ caselabel = CaseLabel(alias + "::" + c.enum())
+ origenum = c.enum()
+
+ writecase = StmtBlock()
+ wstmt = cls.checkedWrite(
+ c.ipdltype,
+ ExprCall(ExprSelect(cls.var, ".", c.getTypeName())),
+ cls.writervar,
+ sentinelKey=c.enum(),
+ )
+ writecase.addstmts([wstmt, StmtReturn()])
+ writeswitch.addcase(caselabel, writecase)
+
+ readcase = StmtBlock()
+ tmpvar = ExprVar("tmp")
+ readcase.addstmts(
+ [
+ cls._checkedRead(
+ c.ipdltype,
+ c.bareType(fq=True),
+ tmpvar,
+ origenum,
+ "variant " + origenum + " of union " + uniontype.name(),
+ ),
+ StmtReturn(ExprMove(tmpvar)),
+ ]
+ )
+ readswitch.addcase(caselabel, readcase)
+
+ # Add the error default case
+ writeswitch.addcase(
+ DefaultLabel(),
+ StmtBlock(
+ [
+ cls.fatalError(
+ cls.writervar, "unknown variant of union " + uniontype.name()
+ ),
+ StmtReturn(),
+ ]
+ ),
+ )
+ readswitch.addcase(
+ DefaultLabel(),
+ StmtBlock(
+ [
+ cls.fatalError(
+ cls.readervar, "unknown variant of union " + uniontype.name()
+ ),
+ StmtReturn(readResultError()),
+ ]
+ ),
+ )
+
+ return cls.generateDecl(
+ cxxtype, write, read, needsmove=_cxxTypeNeedsMoveForSend(uniontype)
+ )
+
+
+# --------------------------------------------------
+
+
+class _ComputeTypeDeps(TypeVisitor):
+ """Pass that gathers the C++ types that a particular IPDL type
+ (recursively) depends on. There are three kinds of dependencies: (i)
+ types that need forward declaration; (ii) types that need a |using|
+ stmt; (iii) IPDL structs or unions which must be fully declared
+ before this struct. Some types generate multiple kinds."""
+
+ def __init__(self, fortype, typesToIncludes=None):
+ ipdl.type.TypeVisitor.__init__(self)
+ self.usingTypedefs = []
+ self.forwardDeclStmts = []
+ self.fullDeclTypes = []
+ self.includeHeaders = set()
+ self.fortype = fortype
+ self.typesToIncludes = typesToIncludes
+
+ def maybeTypedef(self, fqname, name, templateargs=[]):
+ assert fqname.startswith("::")
+ if fqname != name:
+ self.usingTypedefs.append(Typedef(Type(fqname), name, templateargs))
+ if self.typesToIncludes is not None and fqname in self.typesToIncludes:
+ self.includeHeaders.add(self.typesToIncludes[fqname])
+
+ def visitImportedCxxType(self, t):
+ if t in self.visited:
+ return
+ self.visited.add(t)
+ self.maybeTypedef(t.fullname(), t.name())
+
+ def visitActorType(self, t):
+ if t in self.visited:
+ return
+ self.visited.add(t)
+
+ fqname, name = t.fullname(), t.name()
+
+ self.includeHeaders.add("mozilla/ipc/SideVariant.h")
+ self.maybeTypedef(_actorName(fqname, "Parent"), _actorName(name, "Parent"))
+ self.maybeTypedef(_actorName(fqname, "Child"), _actorName(name, "Child"))
+
+ self.forwardDeclStmts.extend(
+ [
+ _makeForwardDeclForActor(t.protocol, "parent"),
+ Whitespace.NL,
+ _makeForwardDeclForActor(t.protocol, "child"),
+ Whitespace.NL,
+ ]
+ )
+
+ def visitStructOrUnionType(self, su, defaultVisit):
+ if su in self.visited or su == self.fortype:
+ return
+ self.visited.add(su)
+ self.maybeTypedef(su.fullname(), su.name())
+
+ # Mutually recursive fields in unions are behind indirection, so we only
+ # need a forward decl, and don't need a full type declaration.
+ if isinstance(self.fortype, UnionType) and self.fortype.mutuallyRecursiveWith(
+ su
+ ):
+ self.forwardDeclStmts.append(_makeForwardDecl(su))
+ else:
+ self.fullDeclTypes.append(su)
+
+ return defaultVisit(self, su)
+
+ def visitStructType(self, t):
+ return self.visitStructOrUnionType(t, TypeVisitor.visitStructType)
+
+ def visitUnionType(self, t):
+ return self.visitStructOrUnionType(t, TypeVisitor.visitUnionType)
+
+ def visitArrayType(self, t):
+ return TypeVisitor.visitArrayType(self, t)
+
+ def visitMaybeType(self, m):
+ return TypeVisitor.visitMaybeType(self, m)
+
+ def visitShmemType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+ self.maybeTypedef("::mozilla::ipc::Shmem", "Shmem")
+
+ def visitByteBufType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+ self.maybeTypedef("::mozilla::ipc::ByteBuf", "ByteBuf")
+
+ def visitFDType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+ self.maybeTypedef("::mozilla::ipc::FileDescriptor", "FileDescriptor")
+
+ def visitEndpointType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+ self.includeHeaders.add("mozilla/ipc/Endpoint.h")
+ self.maybeTypedef("::mozilla::ipc::Endpoint", "Endpoint", ["FooSide"])
+ self.visitActorType(s.actor)
+
+ def visitManagedEndpointType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+ self.includeHeaders.add("mozilla/ipc/Endpoint.h")
+ self.maybeTypedef(
+ "::mozilla::ipc::ManagedEndpoint", "ManagedEndpoint", ["FooSide"]
+ )
+ self.visitActorType(s.actor)
+
+ def visitUniquePtrType(self, s):
+ if s in self.visited:
+ return
+ self.visited.add(s)
+
+ def visitVoidType(self, v):
+ assert 0
+
+ def visitMessageType(self, v):
+ assert 0
+
+ def visitProtocolType(self, v):
+ assert 0
+
+
+def _fieldStaticAssertions(sd):
+ staticasserts = []
+ for size, fields in itertools.groupby(
+ sd.fields_member_order(), lambda f: pod_size(f.ipdltype)
+ ):
+ if size == pod_size_sentinel:
+ continue
+
+ fields = list(fields)
+ if len(fields) == 1:
+ continue
+
+ staticasserts.append(
+ StmtCode(
+ """
+ static_assert(
+ (offsetof(${struct}, ${last}) - offsetof(${struct}, ${first})) == ${expected},
+ "Bad assumptions about field layout!");
+ """,
+ struct=sd.name,
+ first=fields[0].memberVar(),
+ last=fields[-1].memberVar(),
+ expected=ExprLiteral.Int(size * (len(fields) - 1)),
+ )
+ )
+
+ return staticasserts
+
+
+def _generateCxxStruct(sd):
+ """ """
+ # compute all the typedefs and forward decls we need to make
+ gettypedeps = _ComputeTypeDeps(sd.decl.type)
+ for f in sd.fields:
+ f.ipdltype.accept(gettypedeps)
+
+ usingTypedefs = gettypedeps.usingTypedefs
+ forwarddeclstmts = gettypedeps.forwardDeclStmts
+ fulldecltypes = gettypedeps.fullDeclTypes
+
+ struct = Class(sd.name, final=True)
+ struct.addstmts([Label.PRIVATE] + usingTypedefs + [Whitespace.NL, Label.PUBLIC])
+
+ constreftype = Type(sd.name, const=True, ref=True)
+
+ # Struct()
+ # We want the default constructor to be declared if it is available, but
+ # some of our members may not be default-constructible. Silence the
+ # warning which clang generates in that case.
+ #
+ # Members which need value initialization will be handled by wrapping
+ # the member in a template type when declaring them.
+ struct.addcode(
+ """
+ #ifdef __clang__
+ # pragma clang diagnostic push
+ # if __has_warning("-Wdefaulted-function-deleted")
+ # pragma clang diagnostic ignored "-Wdefaulted-function-deleted"
+ # endif
+ #endif
+ ${name}() = default;
+ #ifdef __clang__
+ # pragma clang diagnostic pop
+ #endif
+
+ """,
+ name=sd.name,
+ )
+
+ # If this is an empty struct (no fields), then the default ctor
+ # and "create-with-fields" ctors are equivalent.
+ if len(sd.fields):
+ assert len(sd.fields) == len(sd.packed_field_order)
+
+ # Struct(const field1& _f1, ...)
+ valctor = ConstructorDefn(
+ ConstructorDecl(
+ sd.name,
+ params=[
+ Decl(
+ f.forceMoveType()
+ if _cxxTypeNeedsMoveForData(f.ipdltype)
+ else f.constRefType(),
+ f.argVar().name,
+ )
+ for f in sd.fields_ipdl_order()
+ ],
+ force_inline=True,
+ )
+ )
+ valctor.memberinits = []
+ for f in sd.fields_member_order():
+ arg = f.argVar()
+ if _cxxTypeNeedsMoveForData(f.ipdltype):
+ arg = ExprMove(arg)
+ valctor.memberinits.append(ExprMemberInit(f.memberVar(), args=[arg]))
+
+ struct.addstmts([valctor, Whitespace.NL])
+
+ # If a constructor which moves each argument would be different from the
+ # `const T&` version, also generate that constructor.
+ if not all(
+ _cxxTypeNeedsMoveForData(f.ipdltype) or not _cxxTypeCanMove(f.ipdltype)
+ for f in sd.fields_ipdl_order()
+ ):
+ # Struct(field1&& _f1, ...)
+ valmovector = ConstructorDefn(
+ ConstructorDecl(
+ sd.name,
+ params=[
+ Decl(
+ f.forceMoveType()
+ if _cxxTypeCanMove(f.ipdltype)
+ else f.constRefType(),
+ f.argVar().name,
+ )
+ for f in sd.fields_ipdl_order()
+ ],
+ force_inline=True,
+ )
+ )
+
+ valmovector.memberinits = []
+ for f in sd.fields_member_order():
+ arg = f.argVar()
+ if _cxxTypeCanMove(f.ipdltype):
+ arg = ExprMove(arg)
+ valmovector.memberinits.append(
+ ExprMemberInit(f.memberVar(), args=[arg])
+ )
+
+ struct.addstmts([valmovector, Whitespace.NL])
+
+ # The default copy, move, and assignment constructors, and the default
+ # destructor, will do the right thing.
+
+ if "Comparable" in sd.attributes:
+ # bool operator==(const Struct& _o)
+ ovar = ExprVar("_o")
+ opeqeq = MethodDefn(
+ MethodDecl(
+ "operator==",
+ params=[Decl(constreftype, ovar.name)],
+ ret=Type.BOOL,
+ const=True,
+ )
+ )
+ for f in sd.fields_ipdl_order():
+ ifneq = StmtIf(
+ ExprNot(
+ ExprBinary(
+ ExprCall(f.getMethod()), "==", ExprCall(f.getMethod(ovar))
+ )
+ )
+ )
+ ifneq.addifstmt(StmtReturn.FALSE)
+ opeqeq.addstmt(ifneq)
+ opeqeq.addstmt(StmtReturn.TRUE)
+ struct.addstmts([opeqeq, Whitespace.NL])
+
+ # bool operator!=(const Struct& _o)
+ opneq = MethodDefn(
+ MethodDecl(
+ "operator!=",
+ params=[Decl(constreftype, ovar.name)],
+ ret=Type.BOOL,
+ const=True,
+ )
+ )
+ opneq.addstmt(StmtReturn(ExprNot(ExprCall(ExprVar("operator=="), args=[ovar]))))
+ struct.addstmts([opneq, Whitespace.NL])
+
+ # field1& f1()
+ # const field1& f1() const
+ for f in sd.fields_ipdl_order():
+ get = MethodDefn(
+ MethodDecl(
+ f.getMethod().name, params=[], ret=f.refType(), force_inline=True
+ )
+ )
+ get.addstmt(StmtReturn(f.refExpr()))
+
+ getconstdecl = deepcopy(get.decl)
+ getconstdecl.ret = f.constRefType()
+ getconstdecl.const = True
+ getconst = MethodDefn(getconstdecl)
+ getconst.addstmt(StmtReturn(f.constRefExpr()))
+
+ struct.addstmts([get, getconst, Whitespace.NL])
+
+ # private:
+ struct.addstmt(Label.PRIVATE)
+
+ # Static assertions to ensure our assumptions about field layout match
+ # what the compiler is actually producing. We define this as a member
+ # function, rather than throwing the assertions in the constructor or
+ # similar, because we don't want to evaluate the static assertions every
+ # time the header file containing the structure is included.
+ staticasserts = _fieldStaticAssertions(sd)
+ if staticasserts:
+ method = MethodDefn(
+ MethodDecl("StaticAssertions", params=[], ret=Type.VOID, const=True)
+ )
+ method.addstmts(staticasserts)
+ struct.addstmts([method])
+
+ # members
+ struct.addstmts(
+ [
+ StmtDecl(Decl(_effectiveMemberType(f), f.memberVar().name))
+ for f in sd.fields_member_order()
+ ]
+ )
+
+ return forwarddeclstmts, fulldecltypes, struct
+
+
+def _effectiveMemberType(f):
+ effective_type = f.bareType()
+ # Structs must be copyable for backwards compatibility reasons, so we use
+ # CopyableTArray<T> as their member type for arrays. This is not exposed
+ # in the method signatures, these keep using nsTArray<T>, which is a base
+ # class of CopyableTArray<T>.
+ if effective_type.name == "nsTArray":
+ effective_type.name = "CopyableTArray"
+ return Type("::mozilla::ipc::IPDLStructMember", T=[effective_type])
+
+
+# --------------------------------------------------
+
+
+def _generateCxxUnion(ud):
+ # This Union class basically consists of a type (enum) and a
+ # union for storage. The union can contain POD and non-POD
+ # types. Each type needs a copy/move ctor, assignment operators,
+ # and dtor.
+ #
+ # Rather than templating this class and only providing
+ # specializations for the types we support, which is slightly
+ # "unsafe" in that C++ code can add additional specializations
+ # without the IPDL compiler's knowledge, we instead explicitly
+ # implement non-templated methods for each supported type.
+ #
+ # The one complication that arises is that C++, for arcane
+ # reasons, does not allow the placement destructor of a
+ # builtin type, like int, to be directly invoked. So we need
+ # to hack around this by internally typedef'ing all
+ # constituent types. Sigh.
+ #
+ # So, for each type, this "Union" class needs:
+ # (private)
+ # - entry in the type enum
+ # - entry in the storage union
+ # - [type]ptr() method to get a type* from the underlying union
+ # - same as above to get a const type*
+ # - typedef to hack around placement delete limitations
+ # (public)
+ # - placement delete case for dtor
+ # - copy ctor
+ # - move ctor
+ # - case in generic copy ctor
+ # - copy operator= impl
+ # - move operator= impl
+ # - case in generic operator=
+ # - operator [type&]
+ # - operator [const type&] const
+ # - [type&] get_[type]()
+ # - [const type&] get_[type]() const
+ #
+ cls = Class(ud.name, final=True)
+ # const Union&, i.e., Union type with inparam semantics
+ inClsType = Type(ud.name, const=True, ref=True)
+ refClsType = Type(ud.name, ref=True)
+ rvalueRefClsType = Type(ud.name, rvalref=True)
+ typetype = Type("Type")
+ valuetype = Type("Value")
+ mtypevar = ExprVar("mType")
+ mvaluevar = ExprVar("mValue")
+ maybedtorvar = ExprVar("MaybeDestroy")
+ assertsanityvar = ExprVar("AssertSanity")
+ tnonevar = ExprVar("T__None")
+ tlastvar = ExprVar("T__Last")
+
+ def callAssertSanity(uvar=None, expectTypeVar=None):
+ func = assertsanityvar
+ args = []
+ if uvar is not None:
+ func = ExprSelect(uvar, ".", assertsanityvar.name)
+ if expectTypeVar is not None:
+ args.append(expectTypeVar)
+ return ExprCall(func, args=args)
+
+ def maybeDestroy():
+ return StmtExpr(ExprCall(maybedtorvar))
+
+ # compute all the typedefs and forward decls we need to make
+ gettypedeps = _ComputeTypeDeps(ud.decl.type)
+ for c in ud.components:
+ c.ipdltype.accept(gettypedeps)
+
+ usingTypedefs = gettypedeps.usingTypedefs
+ forwarddeclstmts = gettypedeps.forwardDeclStmts
+ fulldecltypes = gettypedeps.fullDeclTypes
+
+ # the |Type| enum, used to switch on the discunion's real type
+ cls.addstmt(Label.PUBLIC)
+ typeenum = TypeEnum(typetype.name)
+ typeenum.addId(tnonevar.name, 0)
+ firstid = ud.components[0].enum()
+ typeenum.addId(firstid, 1)
+ for c in ud.components[1:]:
+ typeenum.addId(c.enum())
+ typeenum.addId(tlastvar.name, ud.components[-1].enum())
+ cls.addstmts([StmtDecl(Decl(typeenum, "")), Whitespace.NL])
+
+ cls.addstmt(Label.PRIVATE)
+ cls.addstmts(
+ usingTypedefs
+ # hacky typedef's that allow placement dtors of builtins
+ + [Typedef(c.internalType(), c.typedef()) for c in ud.components]
+ )
+ cls.addstmt(Whitespace.NL)
+
+ # the C++ union the discunion use for storage
+ valueunion = TypeUnion(valuetype.name)
+ for c in ud.components:
+ valueunion.addComponent(c.unionType(), c.name)
+ cls.addstmts([StmtDecl(Decl(valueunion, "")), Whitespace.NL])
+
+ # for each constituent type T, add private accessors that
+ # return a pointer to the Value union storage casted to |T*|
+ # and |const T*|
+ for c in ud.components:
+ getptr = MethodDefn(
+ MethodDecl(
+ c.getPtrName(), params=[], ret=c.ptrToInternalType(), force_inline=True
+ )
+ )
+ getptr.addstmt(StmtReturn(c.ptrToSelfExpr()))
+
+ getptrconst = MethodDefn(
+ MethodDecl(
+ c.getConstPtrName(),
+ params=[],
+ ret=c.constPtrToType(),
+ const=True,
+ force_inline=True,
+ )
+ )
+ getptrconst.addstmt(StmtReturn(c.constptrToSelfExpr()))
+
+ cls.addstmts([getptr, getptrconst])
+ cls.addstmt(Whitespace.NL)
+
+ # add a helper method that invokes the placement dtor on the
+ # current underlying value, only if |aNewType| is different
+ # than the current type, and returns true if the underlying
+ # value needs to be re-constructed
+ maybedtor = MethodDefn(MethodDecl(maybedtorvar.name, ret=Type.VOID))
+ # wasn't /actually/ dtor'd, but it needs to be re-constructed
+ ifnone = StmtIf(ExprBinary(mtypevar, "==", tnonevar))
+ ifnone.addifstmt(StmtReturn())
+ # need to destroy. switch on underlying type
+ dtorswitch = StmtSwitch(mtypevar)
+ for c in ud.components:
+ dtorswitch.addcase(
+ CaseLabel(c.enum()), StmtBlock([StmtExpr(c.callDtor()), StmtBreak()])
+ )
+ dtorswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("not reached"), StmtBreak()])
+ )
+ maybedtor.addstmts([ifnone, dtorswitch])
+ cls.addstmts([maybedtor, Whitespace.NL])
+
+ # add helper methods that ensure the discunion has a
+ # valid type
+ sanity = MethodDefn(
+ MethodDecl(assertsanityvar.name, ret=Type.VOID, const=True, force_inline=True)
+ )
+ sanity.addstmts(
+ [
+ _abortIfFalse(ExprBinary(tnonevar, "<=", mtypevar), "invalid type tag"),
+ _abortIfFalse(ExprBinary(mtypevar, "<=", tlastvar), "invalid type tag"),
+ ]
+ )
+ cls.addstmt(sanity)
+
+ atypevar = ExprVar("aType")
+ sanity2 = MethodDefn(
+ MethodDecl(
+ assertsanityvar.name,
+ params=[Decl(typetype, atypevar.name)],
+ ret=Type.VOID,
+ const=True,
+ force_inline=True,
+ )
+ )
+ sanity2.addstmts(
+ [
+ StmtExpr(ExprCall(assertsanityvar)),
+ _abortIfFalse(ExprBinary(mtypevar, "==", atypevar), "unexpected type tag"),
+ ]
+ )
+ cls.addstmts([sanity2, Whitespace.NL])
+
+ # ---- begin public methods -----
+
+ # Union() default ctor
+ cls.addstmts(
+ [
+ Label.PUBLIC,
+ ConstructorDefn(
+ ConstructorDecl(ud.name, force_inline=True),
+ memberinits=[ExprMemberInit(mtypevar, [tnonevar])],
+ ),
+ Whitespace.NL,
+ ]
+ )
+
+ # Union(const T&) copy & Union(T&&) move ctors
+ othervar = ExprVar("aOther")
+ for c in ud.components:
+ if not _cxxTypeNeedsMoveForData(c.ipdltype):
+ copyctor = ConstructorDefn(
+ ConstructorDecl(ud.name, params=[Decl(c.constRefType(), othervar.name)])
+ )
+ copyctor.addstmts(
+ [
+ StmtExpr(c.callCtor(othervar)),
+ StmtExpr(ExprAssn(mtypevar, c.enumvar())),
+ ]
+ )
+ cls.addstmts([copyctor, Whitespace.NL])
+
+ if not _cxxTypeCanMove(c.ipdltype):
+ continue
+ movector = ConstructorDefn(
+ ConstructorDecl(ud.name, params=[Decl(c.forceMoveType(), othervar.name)])
+ )
+ movector.addstmts(
+ [
+ StmtExpr(c.callCtor(ExprMove(othervar))),
+ StmtExpr(ExprAssn(mtypevar, c.enumvar())),
+ ]
+ )
+ cls.addstmts([movector, Whitespace.NL])
+
+ unionNeedsMove = any(_cxxTypeNeedsMoveForData(c.ipdltype) for c in ud.components)
+
+ # Union(const Union&) copy ctor
+ if not unionNeedsMove:
+ copyctor = ConstructorDefn(
+ ConstructorDecl(ud.name, params=[Decl(inClsType, othervar.name)])
+ )
+ othertype = ud.callType(othervar)
+ copyswitch = StmtSwitch(othertype)
+ for c in ud.components:
+ copyswitch.addcase(
+ CaseLabel(c.enum()),
+ StmtBlock(
+ [
+ StmtExpr(
+ c.callCtor(
+ ExprCall(
+ ExprSelect(othervar, ".", c.getConstTypeName())
+ )
+ )
+ ),
+ StmtBreak(),
+ ]
+ ),
+ )
+ copyswitch.addcase(CaseLabel(tnonevar.name), StmtBlock([StmtBreak()]))
+ copyswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn()])
+ )
+ copyctor.addstmts(
+ [
+ StmtExpr(callAssertSanity(uvar=othervar)),
+ copyswitch,
+ StmtExpr(ExprAssn(mtypevar, othertype)),
+ ]
+ )
+ cls.addstmts([copyctor, Whitespace.NL])
+
+ # Union(Union&&) move ctor
+ movector = ConstructorDefn(
+ ConstructorDecl(ud.name, params=[Decl(rvalueRefClsType, othervar.name)])
+ )
+ othertypevar = ExprVar("t")
+ moveswitch = StmtSwitch(othertypevar)
+ for c in ud.components:
+ case = StmtBlock()
+ if c.recursive:
+ # This is sound as we set othervar.mTypeVar to T__None after the
+ # switch. The pointer in the union will be left dangling.
+ case.addstmts(
+ [
+ # ptr_C() = other.ptr_C()
+ StmtExpr(
+ ExprAssn(
+ c.callGetPtr(),
+ ExprCall(
+ ExprSelect(othervar, ".", ExprVar(c.getPtrName()))
+ ),
+ )
+ )
+ ]
+ )
+ else:
+ case.addstmts(
+ [
+ # new ... (Move(other.get_C()))
+ StmtExpr(
+ c.callCtor(
+ ExprMove(
+ ExprCall(ExprSelect(othervar, ".", c.getTypeName()))
+ )
+ )
+ ),
+ # other.MaybeDestroy(T__None)
+ StmtExpr(ExprCall(ExprSelect(othervar, ".", maybedtorvar))),
+ ]
+ )
+ case.addstmts([StmtBreak()])
+ moveswitch.addcase(CaseLabel(c.enum()), case)
+ moveswitch.addcase(CaseLabel(tnonevar.name), StmtBlock([StmtBreak()]))
+ moveswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn()])
+ )
+ movector.addstmts(
+ [
+ StmtExpr(callAssertSanity(uvar=othervar)),
+ StmtDecl(Decl(typetype, othertypevar.name), init=ud.callType(othervar)),
+ moveswitch,
+ StmtExpr(ExprAssn(ExprSelect(othervar, ".", mtypevar), tnonevar)),
+ StmtExpr(ExprAssn(mtypevar, othertypevar)),
+ ]
+ )
+ cls.addstmts([movector, Whitespace.NL])
+
+ # ~Union()
+ dtor = DestructorDefn(DestructorDecl(ud.name))
+ dtor.addstmt(maybeDestroy())
+ cls.addstmts([dtor, Whitespace.NL])
+
+ # type()
+ typemeth = MethodDefn(
+ MethodDecl("type", ret=typetype, const=True, force_inline=True)
+ )
+ typemeth.addstmt(StmtReturn(mtypevar))
+ cls.addstmts([typemeth, Whitespace.NL])
+
+ # Union& operator= methods
+ rhsvar = ExprVar("aRhs")
+ for c in ud.components:
+
+ def opeqBody(rhs):
+ return [
+ # might need to placement-delete old value first
+ maybeDestroy(),
+ StmtExpr(c.callCtor(rhs)),
+ StmtExpr(ExprAssn(mtypevar, c.enumvar())),
+ StmtReturn(ExprDeref(ExprVar.THIS)),
+ ]
+
+ if not _cxxTypeNeedsMoveForData(c.ipdltype):
+ # Union& operator=(const T&)
+ opeq = MethodDefn(
+ MethodDecl(
+ "operator=",
+ params=[Decl(c.constRefType(), rhsvar.name)],
+ ret=refClsType,
+ )
+ )
+ opeq.addstmts(opeqBody(rhsvar))
+ cls.addstmts([opeq, Whitespace.NL])
+
+ # Union& operator=(T&&)
+ if not _cxxTypeCanMove(c.ipdltype):
+ continue
+
+ opeq = MethodDefn(
+ MethodDecl(
+ "operator=",
+ params=[Decl(c.forceMoveType(), rhsvar.name)],
+ ret=refClsType,
+ )
+ )
+ opeq.addstmts(opeqBody(ExprMove(rhsvar)))
+ cls.addstmts([opeq, Whitespace.NL])
+
+ # Union& operator=(const Union&)
+ if not unionNeedsMove:
+ opeq = MethodDefn(
+ MethodDecl(
+ "operator=", params=[Decl(inClsType, rhsvar.name)], ret=refClsType
+ )
+ )
+ rhstypevar = ExprVar("t")
+ opeqswitch = StmtSwitch(rhstypevar)
+ for c in ud.components:
+ case = StmtBlock()
+ case.addstmts(
+ [
+ maybeDestroy(),
+ StmtExpr(
+ c.callCtor(
+ ExprCall(ExprSelect(rhsvar, ".", c.getConstTypeName()))
+ )
+ ),
+ StmtBreak(),
+ ]
+ )
+ opeqswitch.addcase(CaseLabel(c.enum()), case)
+ opeqswitch.addcase(
+ CaseLabel(tnonevar.name),
+ StmtBlock([maybeDestroy(), StmtBreak()]),
+ )
+ opeqswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("unreached"), StmtBreak()])
+ )
+ opeq.addstmts(
+ [
+ StmtExpr(callAssertSanity(uvar=rhsvar)),
+ StmtDecl(Decl(typetype, rhstypevar.name), init=ud.callType(rhsvar)),
+ opeqswitch,
+ StmtExpr(ExprAssn(mtypevar, rhstypevar)),
+ StmtReturn(ExprDeref(ExprVar.THIS)),
+ ]
+ )
+ cls.addstmts([opeq, Whitespace.NL])
+
+ # Union& operator=(Union&&)
+ opeq = MethodDefn(
+ MethodDecl(
+ "operator=", params=[Decl(rvalueRefClsType, rhsvar.name)], ret=refClsType
+ )
+ )
+ rhstypevar = ExprVar("t")
+ opeqswitch = StmtSwitch(rhstypevar)
+ for c in ud.components:
+ case = StmtBlock()
+ if c.recursive:
+ case.addstmts(
+ [
+ maybeDestroy(),
+ StmtExpr(
+ ExprAssn(
+ c.callGetPtr(),
+ ExprCall(ExprSelect(rhsvar, ".", ExprVar(c.getPtrName()))),
+ )
+ ),
+ ]
+ )
+ else:
+ case.addstmts(
+ [
+ maybeDestroy(),
+ StmtExpr(
+ c.callCtor(
+ ExprMove(ExprCall(ExprSelect(rhsvar, ".", c.getTypeName())))
+ )
+ ),
+ # other.MaybeDestroy()
+ StmtExpr(ExprCall(ExprSelect(rhsvar, ".", maybedtorvar))),
+ ]
+ )
+ case.addstmts([StmtBreak()])
+ opeqswitch.addcase(CaseLabel(c.enum()), case)
+ opeqswitch.addcase(
+ CaseLabel(tnonevar.name),
+ StmtBlock([maybeDestroy(), StmtBreak()]),
+ )
+ opeqswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("unreached"), StmtBreak()])
+ )
+ opeq.addstmts(
+ [
+ StmtExpr(callAssertSanity(uvar=rhsvar)),
+ StmtDecl(Decl(typetype, rhstypevar.name), init=ud.callType(rhsvar)),
+ opeqswitch,
+ StmtExpr(ExprAssn(ExprSelect(rhsvar, ".", mtypevar), tnonevar)),
+ StmtExpr(ExprAssn(mtypevar, rhstypevar)),
+ StmtReturn(ExprDeref(ExprVar.THIS)),
+ ]
+ )
+ cls.addstmts([opeq, Whitespace.NL])
+
+ if "Comparable" in ud.attributes:
+ # bool operator==(const T&)
+ for c in ud.components:
+ opeqeq = MethodDefn(
+ MethodDecl(
+ "operator==",
+ params=[Decl(c.constRefType(), rhsvar.name)],
+ ret=Type.BOOL,
+ const=True,
+ )
+ )
+ opeqeq.addstmt(
+ StmtReturn(ExprBinary(ExprCall(ExprVar(c.getTypeName())), "==", rhsvar))
+ )
+ cls.addstmts([opeqeq, Whitespace.NL])
+
+ # bool operator==(const Union&)
+ opeqeq = MethodDefn(
+ MethodDecl(
+ "operator==",
+ params=[Decl(inClsType, rhsvar.name)],
+ ret=Type.BOOL,
+ const=True,
+ )
+ )
+ iftypesmismatch = StmtIf(ExprBinary(ud.callType(), "!=", ud.callType(rhsvar)))
+ iftypesmismatch.addifstmt(StmtReturn.FALSE)
+ opeqeq.addstmts([iftypesmismatch, Whitespace.NL])
+
+ opeqeqswitch = StmtSwitch(ud.callType())
+ for c in ud.components:
+ case = StmtBlock()
+ case.addstmt(
+ StmtReturn(
+ ExprBinary(
+ ExprCall(ExprVar(c.getTypeName())),
+ "==",
+ ExprCall(ExprSelect(rhsvar, ".", c.getTypeName())),
+ )
+ )
+ )
+ opeqeqswitch.addcase(CaseLabel(c.enum()), case)
+ opeqeqswitch.addcase(
+ DefaultLabel(), StmtBlock([_logicError("unreached"), StmtReturn.FALSE])
+ )
+ opeqeq.addstmt(opeqeqswitch)
+
+ cls.addstmts([opeqeq, Whitespace.NL])
+
+ # accessors for each type: operator T&, operator const T&,
+ # T& get(), const T& get()
+ for c in ud.components:
+ getValueVar = ExprVar(c.getTypeName())
+ getConstValueVar = ExprVar(c.getConstTypeName())
+
+ getvalue = MethodDefn(
+ MethodDecl(getValueVar.name, ret=c.refType(), force_inline=True)
+ )
+ getvalue.addstmts(
+ [
+ StmtExpr(callAssertSanity(expectTypeVar=c.enumvar())),
+ StmtReturn(ExprDeref(c.callGetPtr())),
+ ]
+ )
+
+ getconstvalue = MethodDefn(
+ MethodDecl(
+ getConstValueVar.name,
+ ret=c.constRefType(),
+ const=True,
+ force_inline=True,
+ )
+ )
+ getconstvalue.addstmts(
+ [
+ StmtExpr(callAssertSanity(expectTypeVar=c.enumvar())),
+ StmtReturn(c.getConstValue()),
+ ]
+ )
+
+ cls.addstmts([getvalue, getconstvalue])
+
+ optype = MethodDefn(MethodDecl("", typeop=c.refType(), force_inline=True))
+ optype.addstmt(StmtReturn(ExprCall(getValueVar)))
+ opconsttype = MethodDefn(
+ MethodDecl("", const=True, typeop=c.constRefType(), force_inline=True)
+ )
+ opconsttype.addstmt(StmtReturn(ExprCall(getConstValueVar)))
+
+ cls.addstmts([optype, opconsttype, Whitespace.NL])
+ # private vars
+ cls.addstmts(
+ [
+ Label.PRIVATE,
+ StmtDecl(Decl(valuetype, mvaluevar.name)),
+ StmtDecl(Decl(typetype, mtypevar.name)),
+ ]
+ )
+
+ return forwarddeclstmts, fulldecltypes, cls
+
+
+# -----------------------------------------------------------------------------
+
+
+class _FindFriends(ipdl.ast.Visitor):
+ def __init__(self):
+ self.mytype = None # ProtocolType
+ self.vtype = None # ProtocolType
+ self.friends = set() # set<ProtocolType>
+
+ def findFriends(self, ptype):
+ self.mytype = ptype
+ for toplvl in ptype.toplevels():
+ self.walkDownTheProtocolTree(toplvl)
+ return self.friends
+
+ # TODO could make this into a _iterProtocolTreeHelper ...
+ def walkDownTheProtocolTree(self, ptype):
+ if ptype != self.mytype:
+ # don't want to |friend| ourself!
+ self.visit(ptype)
+ for mtype in ptype.manages:
+ if mtype is not ptype:
+ self.walkDownTheProtocolTree(mtype)
+
+ def visit(self, ptype):
+ # |vtype| is the type currently being visited
+ savedptype = self.vtype
+ self.vtype = ptype
+ ptype._ast.accept(self)
+ self.vtype = savedptype
+
+ def visitMessageDecl(self, md):
+ for it in self.iterActorParams(md):
+ if it.protocol == self.mytype:
+ self.friends.add(self.vtype)
+
+ def iterActorParams(self, md):
+ for param in md.inParams:
+ for actor in ipdl.type.iteractortypes(param.type):
+ yield actor
+ for ret in md.outParams:
+ for actor in ipdl.type.iteractortypes(ret.type):
+ yield actor
+
+
+class _GenerateProtocolActorCode(ipdl.ast.Visitor):
+ def __init__(self, myside):
+ self.side = myside # "parent" or "child"
+ self.prettyside = myside.title()
+ self.clsname = None
+ self.protocol = None
+ self.hdrfile = None
+ self.cppfile = None
+ self.ns = None
+ self.cls = None
+ self.protocolCxxIncludes = []
+ self.actorForwardDecls = []
+ self.usingDecls = []
+ self.externalIncludes = set()
+ self.nonForwardDeclaredHeaders = set()
+ self.typedefSet = set(
+ [
+ Typedef(Type("mozilla::ipc::ActorHandle"), "ActorHandle"),
+ Typedef(Type("base::ProcessId"), "ProcessId"),
+ Typedef(Type("mozilla::ipc::ProtocolId"), "ProtocolId"),
+ Typedef(Type("mozilla::ipc::Endpoint"), "Endpoint", ["FooSide"]),
+ Typedef(
+ Type("mozilla::ipc::ManagedEndpoint"),
+ "ManagedEndpoint",
+ ["FooSide"],
+ ),
+ Typedef(Type("mozilla::UniquePtr"), "UniquePtr", ["T"]),
+ Typedef(
+ Type("mozilla::ipc::ResponseRejectReason"), "ResponseRejectReason"
+ ),
+ ]
+ )
+
+ def lower(self, tu, clsname, cxxHeaderFile, cxxFile):
+ self.clsname = clsname
+ self.hdrfile = cxxHeaderFile
+ self.cppfile = cxxFile
+ tu.accept(self)
+
+ def standardTypedefs(self):
+ return [
+ Typedef(Type("mozilla::ipc::IProtocol"), "IProtocol"),
+ Typedef(Type("IPC::Message"), "Message"),
+ Typedef(Type("base::ProcessHandle"), "ProcessHandle"),
+ Typedef(Type("mozilla::ipc::MessageChannel"), "MessageChannel"),
+ Typedef(Type("mozilla::ipc::SharedMemory"), "SharedMemory"),
+ ]
+
+ def visitTranslationUnit(self, tu):
+ self.protocol = tu.protocol
+
+ hf = self.hdrfile
+ cf = self.cppfile
+
+ # make the C++ header
+ hf.addthings(
+ [_DISCLAIMER]
+ + _includeGuardStart(hf)
+ + [
+ Whitespace.NL,
+ CppDirective("include", '"' + _protocolHeaderName(tu.protocol) + '.h"'),
+ ]
+ )
+
+ for inc in tu.includes:
+ inc.accept(self)
+ for inc in tu.cxxIncludes:
+ inc.accept(self)
+
+ for using in tu.builtinUsing:
+ using.accept(self)
+ for using in tu.using:
+ using.accept(self)
+ for su in tu.structsAndUnions:
+ su.accept(self)
+
+ # this generates the actor's full impl in self.cls
+ tu.protocol.accept(self)
+
+ clsdecl, clsdefn = _splitClassDeclDefn(self.cls)
+
+ # XXX damn C++ ... return types in the method defn aren't in
+ # class scope
+ for stmt in clsdefn.stmts:
+ if isinstance(stmt, MethodDefn):
+ if stmt.decl.ret and stmt.decl.ret.name == "Result":
+ stmt.decl.ret.name = clsdecl.name + "::" + stmt.decl.ret.name
+
+ def setToIncludes(s):
+ return [CppDirective("include", '"%s"' % i) for i in sorted(iter(s))]
+
+ def makeNamespace(p, file):
+ if 0 == len(p.namespaces):
+ return file
+ ns = Namespace(p.namespaces[-1].name)
+ outerns = _putInNamespaces(ns, p.namespaces[:-1])
+ file.addthing(outerns)
+ return ns
+
+ if len(self.nonForwardDeclaredHeaders) != 0:
+ self.hdrfile.addthings(
+ [
+ Whitespace("// Headers for things that cannot be forward declared"),
+ Whitespace.NL,
+ ]
+ + setToIncludes(self.nonForwardDeclaredHeaders)
+ + [Whitespace.NL]
+ )
+ self.hdrfile.addthings(self.actorForwardDecls)
+ self.hdrfile.addthings(self.usingDecls)
+
+ hdrns = makeNamespace(self.protocol, self.hdrfile)
+ hdrns.addstmts(
+ [Whitespace.NL, Whitespace.NL, clsdecl, Whitespace.NL, Whitespace.NL]
+ )
+
+ actortype = ActorType(tu.protocol.decl.type)
+ traitsdecl, traitsdefn = _ParamTraits.actorPickling(actortype, self.side)
+
+ self.hdrfile.addthings([traitsdecl, Whitespace.NL] + _includeGuardEnd(hf))
+
+ # If the implementation type is not overridden, add an implicit import
+ # for the default implementation header file. Explicit implementation
+ # types will specify their headers manually with `include`.
+ if self.protocol.implAttribute(self.side) is None:
+ assert self.protocol.name.startswith("P")
+ self.externalIncludes.add(
+ "".join(n.name + "/" for n in self.protocol.namespaces)
+ + self.protocol.name[1:]
+ + self.side.capitalize()
+ + ".h"
+ )
+
+ # make the .cpp file
+ cf.addthings(
+ [
+ _DISCLAIMER,
+ Whitespace.NL,
+ CppDirective(
+ "include",
+ '"' + _protocolHeaderName(self.protocol, self.side) + '.h"',
+ ),
+ ]
+ + setToIncludes(self.externalIncludes)
+ )
+
+ cf.addthings(
+ (
+ [Whitespace.NL]
+ + [
+ CppDirective("include", '"%s.h"' % (inc))
+ for inc in self.protocolCxxIncludes
+ ]
+ + [Whitespace.NL]
+ + [
+ CppDirective("include", '"%s"' % filename)
+ for filename in ipdl.builtin.CppIncludes
+ ]
+ + [Whitespace.NL]
+ )
+ )
+
+ cppns = makeNamespace(self.protocol, cf)
+ cppns.addstmts(
+ [Whitespace.NL, Whitespace.NL, clsdefn, Whitespace.NL, Whitespace.NL]
+ )
+
+ cf.addthing(traitsdefn)
+
+ def visitUsingStmt(self, using):
+ if using.decl.fullname is not None:
+ self.typedefSet.add(
+ Typedef(Type(using.decl.fullname), using.decl.shortname)
+ )
+
+ if using.header is None:
+ return
+
+ if using.canBeForwardDeclared():
+ spec = using.type
+
+ self.usingDecls.extend(
+ [
+ _makeForwardDeclForQClass(
+ spec.baseid,
+ spec.quals,
+ cls=using.isClass(),
+ struct=using.isStruct(),
+ ),
+ Whitespace.NL,
+ ]
+ )
+ self.externalIncludes.add(using.header)
+ else:
+ self.nonForwardDeclaredHeaders.add(using.header)
+
+ def visitCxxInclude(self, inc):
+ self.externalIncludes.add(inc.file)
+
+ def visitInclude(self, inc):
+ if inc.tu.filetype == "header":
+ # Including a header will declare any globals defined by "using"
+ # statements into our scope. To serialize these, we also may need
+ # cxx include statements, so visit them as well.
+ for cxxinc in inc.tu.cxxIncludes:
+ cxxinc.accept(self)
+ for using in inc.tu.using:
+ using.accept(self)
+ for su in inc.tu.structsAndUnions:
+ su.accept(self)
+ else:
+ # Includes for protocols only include types explicitly exported by
+ # those protocols.
+ ip = inc.tu.protocol
+ if ip == self.protocol:
+ return
+
+ self.actorForwardDecls.extend(
+ [
+ _makeForwardDeclForActor(ip.decl.type, self.side),
+ _makeForwardDeclForActor(ip.decl.type, _otherSide(self.side)),
+ Whitespace.NL,
+ ]
+ )
+ self.protocolCxxIncludes.append(_protocolHeaderName(ip, self.side))
+
+ if ip.decl.fullname is not None:
+ self.typedefSet.add(
+ Typedef(
+ Type(_actorName(ip.decl.fullname, self.side.title())),
+ _actorName(ip.decl.shortname, self.side.title()),
+ )
+ )
+
+ self.typedefSet.add(
+ Typedef(
+ Type(
+ _actorName(ip.decl.fullname, _otherSide(self.side).title())
+ ),
+ _actorName(ip.decl.shortname, _otherSide(self.side).title()),
+ )
+ )
+
+ def visitStructDecl(self, sd):
+ if sd.decl.fullname is not None:
+ self.typedefSet.add(Typedef(Type(sd.fqClassName()), sd.name))
+
+ def visitUnionDecl(self, ud):
+ if ud.decl.fullname is not None:
+ self.typedefSet.add(Typedef(Type(ud.fqClassName()), ud.name))
+
+ def visitProtocol(self, p):
+ self.hdrfile.addcode(
+ """
+ #ifdef DEBUG
+ #include "prenv.h"
+ #endif // DEBUG
+
+ #include "mozilla/Tainting.h"
+ #include "mozilla/ipc/MessageChannel.h"
+ #include "mozilla/ipc/ProtocolUtils.h"
+ """
+ )
+
+ self.protocol = p
+ ptype = p.decl.type
+ toplevel = p.decl.type.toplevel()
+
+ hasAsyncReturns = False
+ for md in p.messageDecls:
+ if md.hasAsyncReturns():
+ hasAsyncReturns = True
+ break
+
+ if ptype.isToplevel():
+ inherits = [Inherit(Type("mozilla::ipc::IToplevelProtocol"))]
+ elif ptype.isRefcounted():
+ inherits = [Inherit(Type("mozilla::ipc::IRefCountedProtocol"))]
+ else:
+ inherits = [Inherit(Type("mozilla::ipc::IProtocol"))]
+
+ if ptype.isToplevel() and self.side == "parent":
+ self.hdrfile.addthings(
+ [_makeForwardDeclForQClass("nsIFile", []), Whitespace.NL]
+ )
+
+ self.cls = Class(self.clsname, inherits=inherits, abstract=True)
+
+ self.cls.addstmt(Label.PRIVATE)
+ friends = _FindFriends().findFriends(ptype)
+ if ptype.isManaged():
+ friends.update(ptype.managers)
+
+ # |friend| managed actors so that they can call our Dealloc*()
+ friends.update(ptype.manages)
+
+ # don't friend ourself if we're a self-managed protocol
+ friends.discard(ptype)
+
+ for friend in sorted(friends, key=lambda f: f.fullname()):
+ self.actorForwardDecls.extend(
+ [_makeForwardDeclForActor(friend, self.prettyside), Whitespace.NL]
+ )
+ self.cls.addstmt(
+ FriendClassDecl(_actorName(friend.fullname(), self.prettyside))
+ )
+
+ self.cls.addstmt(Label.PROTECTED)
+ for typedef in sorted(self.typedefSet):
+ self.cls.addstmt(typedef)
+
+ self.cls.addstmt(Whitespace.NL)
+
+ if hasAsyncReturns:
+ self.cls.addstmt(Label.PUBLIC)
+ for md in p.messageDecls:
+ if self.sendsMessage(md) and md.hasAsyncReturns():
+ self.cls.addstmt(
+ Typedef(_makePromise(md.returns, self.side), md.promiseName())
+ )
+ if self.receivesMessage(md) and md.hasAsyncReturns():
+ self.cls.addstmt(
+ Typedef(_makeResolver(md.returns, self.side), md.resolverName())
+ )
+ self.cls.addstmt(Whitespace.NL)
+
+ self.cls.addstmt(Label.PROTECTED)
+ # interface methods that the concrete subclass has to impl
+ for md in p.messageDecls:
+ isctor, isdtor = md.decl.type.isCtor(), md.decl.type.isDtor()
+
+ if self.receivesMessage(md):
+ # generate Recv/Answer* interface
+ implicit = not isdtor
+ returnsems = "resolver" if md.decl.type.isAsync() else "out"
+ recvDecl = MethodDecl(
+ md.recvMethod(),
+ params=md.makeCxxParams(
+ paramsems="move",
+ returnsems=returnsems,
+ side=self.side,
+ implicit=implicit,
+ direction="recv",
+ ),
+ ret=Type("mozilla::ipc::IPCResult"),
+ methodspec=MethodSpec.VIRTUAL,
+ )
+
+ # These method implementations cause problems when trying to
+ # override them with different types in a direct call class.
+ #
+ # For the `isdtor` case there's a simple solution: it doesn't
+ # make much sense to specify arguments and then completely
+ # ignore them, and the no-arg case isn't a problem for
+ # overriding.
+ if isctor or (isdtor and not md.inParams):
+ defaultRecv = MethodDefn(recvDecl)
+ defaultRecv.addcode("return IPC_OK();\n")
+ self.cls.addstmt(defaultRecv)
+ elif self.protocol.implAttribute(self.side) == "virtual":
+ # If we're using virtual calls, we need the methods to be
+ # declared on the base class.
+ recvDecl.methodspec = MethodSpec.PURE
+ self.cls.addstmt(StmtDecl(recvDecl))
+
+ # If we're using virtual calls, we need the methods to be declared on
+ # the base class.
+ if self.protocol.implAttribute(self.side) == "virtual":
+ for md in p.messageDecls:
+ managed = md.decl.type.constructedType()
+ if not ptype.isManagerOf(managed) or md.decl.type.isDtor():
+ continue
+
+ # add the Alloc interface for managed actors
+ actortype = md.actorDecl().bareType(self.side)
+
+ if managed.isRefcounted():
+ if not self.receivesMessage(md):
+ continue
+
+ actortype.ptr = False
+ actortype = _alreadyaddrefed(actortype)
+
+ self.cls.addstmt(
+ StmtDecl(
+ MethodDecl(
+ _allocMethod(managed, self.side),
+ params=md.makeCxxParams(
+ side=self.side, implicit=False, direction="recv"
+ ),
+ ret=actortype,
+ methodspec=MethodSpec.PURE,
+ )
+ )
+ )
+
+ # add the Dealloc interface for all managed non-refcounted actors,
+ # even without ctors. This is useful for protocols which use
+ # ManagedEndpoint for construction.
+ for managed in ptype.manages:
+ if managed.isRefcounted():
+ continue
+
+ self.cls.addstmt(
+ StmtDecl(
+ MethodDecl(
+ _deallocMethod(managed, self.side),
+ params=[
+ Decl(p.managedCxxType(managed, self.side), "aActor")
+ ],
+ ret=Type.BOOL,
+ methodspec=MethodSpec.PURE,
+ )
+ )
+ )
+
+ if ptype.isToplevel():
+ # void ProcessingError(code); default to no-op
+ processingerror = MethodDefn(
+ MethodDecl(
+ p.processingErrorVar().name,
+ params=[
+ Param(_Result.Type(), "aCode"),
+ Param(Type("char", const=True, ptr=True), "aReason"),
+ ],
+ methodspec=MethodSpec.OVERRIDE,
+ )
+ )
+
+ # bool ShouldContinueFromReplyTimeout(); default to |true|
+ shouldcontinue = MethodDefn(
+ MethodDecl(
+ p.shouldContinueFromTimeoutVar().name,
+ ret=Type.BOOL,
+ methodspec=MethodSpec.OVERRIDE,
+ )
+ )
+ shouldcontinue.addcode("return true;\n")
+
+ self.cls.addstmts(
+ [
+ processingerror,
+ shouldcontinue,
+ Whitespace.NL,
+ ]
+ )
+
+ self.cls.addstmts(([Label.PUBLIC] + self.standardTypedefs() + [Whitespace.NL]))
+
+ self.cls.addstmt(Label.PUBLIC)
+ # Actor()
+ ctor = ConstructorDefn(ConstructorDecl(self.clsname))
+ side = ExprVar("mozilla::ipc::" + self.side.title() + "Side")
+ if ptype.isToplevel():
+ name = ExprLiteral.String(_actorName(p.name, self.side))
+ ctor.memberinits = [
+ ExprMemberInit(
+ ExprVar("mozilla::ipc::IToplevelProtocol"),
+ [name, _protocolId(ptype), side],
+ )
+ ]
+ else:
+ baseCtor = (
+ ExprVar("mozilla::ipc::IRefCountedProtocol")
+ if ptype.isRefcounted()
+ else ExprVar("mozilla::ipc::IProtocol")
+ )
+ ctor.memberinits = [ExprMemberInit(baseCtor, [_protocolId(ptype), side])]
+
+ ctor.addcode("MOZ_COUNT_CTOR(${clsname});\n", clsname=self.clsname)
+ self.cls.addstmts([ctor, Whitespace.NL])
+
+ # ~Actor()
+ dtor = DestructorDefn(
+ DestructorDecl(self.clsname, methodspec=MethodSpec.VIRTUAL)
+ )
+ dtor.addcode("MOZ_COUNT_DTOR(${clsname});\n", clsname=self.clsname)
+
+ self.cls.addstmts([dtor, Whitespace.NL])
+
+ # ActorAlloc() and ActorDealloc()
+ actoralloc = MethodDefn(MethodDecl("ActorAlloc", methodspec=MethodSpec.FINAL))
+ actordealloc = MethodDefn(
+ MethodDecl("ActorDealloc", methodspec=MethodSpec.FINAL)
+ )
+
+ # Assert process type in ActorAlloc
+ procattr = p.procAttribute(self.side)
+ if procattr not in ("any", None):
+ if procattr == "anychild":
+ procattr_assertion = "!XRE_IsParentProcess()"
+ elif procattr == "anydom":
+ procattr_assertion = "XRE_IsParentProcess() || XRE_IsContentProcess()"
+ elif procattr == "compositor":
+ procattr_assertion = "XRE_IsParentProcess() || XRE_IsGPUProcess()"
+ else:
+ procattr_assertion = "XRE_Is%sProcess()" % procattr
+ actoralloc.addcode(
+ "MOZ_RELEASE_ASSERT(${assertion}, ${message});\n",
+ assertion=procattr_assertion,
+ message=ExprLiteral.String("Invalid process for `%s'" % self.clsname),
+ )
+
+ if ptype.isRefcounted():
+ # Perform AddRef/Release in ActorAlloc/ActorDealloc if refcounted.
+ actoralloc.addcode("AddRef();\n")
+ actordealloc.addcode("Release();\n")
+ elif not ptype.isToplevel():
+ # If we're a managed actor with [ManualDealloc], use DeallocManagee
+ # to invoke the relevant Dealloc method.
+ actordealloc.addcode(
+ """
+ if (Manager()) {
+ Manager()->DeallocManagee(${protocolId}, this);
+ }
+ """,
+ protocolId=_protocolId(ptype),
+ )
+
+ self.cls.addstmts([Label.PROTECTED, actoralloc, actordealloc])
+
+ self.cls.addstmt(Label.PUBLIC)
+ if ptype.hasOtherPid():
+ otherpidmeth = MethodDefn(
+ MethodDecl("OtherPid", ret=Type("::base::ProcessId"), const=True)
+ )
+ otherpidmeth.addcode(
+ """
+ ::base::ProcessId pid =
+ ::mozilla::ipc::IProtocol::ToplevelProtocol()->OtherPidMaybeInvalid();
+ MOZ_RELEASE_ASSERT(pid != ::base::kInvalidProcessId);
+ return pid;
+ """
+ )
+ self.cls.addstmts([otherpidmeth, Whitespace.NL])
+
+ if not ptype.isToplevel():
+ if 1 == len(p.managers):
+ # manager() const
+ managertype = p.managerActorType(self.side, ptr=True)
+ managermeth = MethodDefn(
+ MethodDecl("Manager", ret=managertype, const=True)
+ )
+ managermeth.addcode(
+ """
+ return static_cast<${type}>(IProtocol::Manager());
+ """,
+ type=managertype,
+ )
+
+ self.cls.addstmts([managermeth, Whitespace.NL])
+
+ def actorFromIter(itervar):
+ return ExprCode("${iter}.Get()->GetKey()", iter=itervar)
+
+ def forLoopOverHashtable(hashtable, itervar, const=False):
+ itermeth = "ConstIter" if const else "Iter"
+ return StmtFor(
+ init=ExprCode(
+ "auto ${itervar} = ${hashtable}.${itermeth}()",
+ itervar=itervar,
+ hashtable=hashtable,
+ itermeth=itermeth,
+ ),
+ cond=ExprCode("!${itervar}.Done()", itervar=itervar),
+ update=ExprCode("${itervar}.Next()", itervar=itervar),
+ )
+
+ # Managed[T](Array& inout) const
+ # const Array<T>& Managed() const
+ for managed in ptype.manages:
+ container = p.managedVar(managed, self.side)
+
+ meth = MethodDefn(
+ MethodDecl(
+ p.managedMethod(managed, self.side).name,
+ params=[
+ Decl(
+ _cxxArrayType(
+ p.managedCxxType(managed, self.side), ref=True
+ ),
+ "aArr",
+ )
+ ],
+ const=True,
+ )
+ )
+ meth.addcode("${container}.ToArray(aArr);\n", container=container)
+
+ refmeth = MethodDefn(
+ MethodDecl(
+ p.managedMethod(managed, self.side).name,
+ params=[],
+ ret=p.managedVarType(managed, self.side, const=True, ref=True),
+ const=True,
+ )
+ )
+ refmeth.addcode("return ${container};\n", container=container)
+
+ self.cls.addstmts([meth, refmeth, Whitespace.NL])
+
+ # AllManagedActors(Array& inout) const
+ arrvar = ExprVar("arr__")
+ managedmeth = MethodDefn(
+ MethodDecl(
+ "AllManagedActors",
+ params=[
+ Decl(
+ _cxxArrayType(_refptr(_cxxLifecycleProxyType()), ref=True),
+ arrvar.name,
+ )
+ ],
+ methodspec=MethodSpec.OVERRIDE,
+ const=True,
+ )
+ )
+
+ # Count the number of managed actors, and allocate space in the output array.
+ managedmeth.addcode(
+ """
+ uint32_t total = 0;
+ """
+ )
+ for managed in ptype.manages:
+ managedmeth.addcode(
+ """
+ total += ${container}.Count();
+ """,
+ container=p.managedVar(managed, self.side),
+ )
+ managedmeth.addcode(
+ """
+ arr__.SetCapacity(total);
+
+ """
+ )
+
+ for managed in ptype.manages:
+ managedmeth.addcode(
+ """
+ for (auto* key : ${container}) {
+ arr__.AppendElement(key->GetLifecycleProxy());
+ }
+
+ """,
+ container=p.managedVar(managed, self.side),
+ )
+
+ self.cls.addstmts([managedmeth, Whitespace.NL])
+
+ # AllManagedActorsCount() const
+ managedmeth = MethodDefn(
+ MethodDecl(
+ "AllManagedActorsCount",
+ ret=Type.UINT32,
+ methodspec=MethodSpec.OVERRIDE,
+ const=True,
+ )
+ )
+
+ # Count the number of managed actors.
+ managedmeth.addcode(
+ """
+ uint32_t total = 0;
+ """
+ )
+ for managed in ptype.manages:
+ managedmeth.addcode(
+ """
+ total += ${container}.Count();
+ """,
+ container=p.managedVar(managed, self.side),
+ )
+ managedmeth.addcode(
+ """
+ return total;
+
+ """
+ )
+
+ self.cls.addstmts([managedmeth, Whitespace.NL])
+
+ # OpenPEndpoint(...)/BindPEndpoint(...)
+ for managed in ptype.manages:
+ self.genManagedEndpoint(managed)
+
+ # OnMessageReceived()/OnCallReceived()
+
+ # save these away for use in message handler case stmts
+ msgvar = ExprVar("msg__")
+ self.msgvar = msgvar
+ replyvar = ExprVar("reply__")
+ self.replyvar = replyvar
+ var = ExprVar("v__")
+ self.var = var
+ # for ctor recv cases, we can't read the actor ID into a PFoo*
+ # because it doesn't exist on this side yet. Use a "special"
+ # actor handle instead
+ handlevar = ExprVar("handle__")
+ self.handlevar = handlevar
+
+ msgtype = ExprCode("msg__.type()")
+ self.asyncSwitch = StmtSwitch(msgtype)
+ self.syncSwitch = None
+ self.interruptSwitch = None
+ if toplevel.isSync() or toplevel.isInterrupt():
+ self.syncSwitch = StmtSwitch(msgtype)
+ if toplevel.isInterrupt():
+ self.interruptSwitch = StmtSwitch(msgtype)
+
+ # Add a handler for the MANAGED_ENDPOINT_BOUND and
+ # MANAGED_ENDPOINT_DROPPED message types for managed actors.
+ if not ptype.isToplevel():
+ clearawaitingmanagedendpointbind = """
+ if (!mAwaitingManagedEndpointBind) {
+ NS_WARNING("Unexpected managed endpoint lifecycle message after actor bound!");
+ return MsgNotAllowed;
+ }
+ mAwaitingManagedEndpointBind = false;
+ """
+ self.asyncSwitch.addcase(
+ CaseLabel("MANAGED_ENDPOINT_BOUND_MESSAGE_TYPE"),
+ StmtBlock(
+ [
+ StmtCode(clearawaitingmanagedendpointbind),
+ StmtReturn(_Result.Processed),
+ ]
+ ),
+ )
+ self.asyncSwitch.addcase(
+ CaseLabel("MANAGED_ENDPOINT_DROPPED_MESSAGE_TYPE"),
+ StmtBlock(
+ [
+ StmtCode(clearawaitingmanagedendpointbind),
+ *self.destroyActor(
+ None,
+ ExprVar.THIS,
+ why=_DestroyReason.ManagedEndpointDropped,
+ ),
+ StmtReturn(_Result.Processed),
+ ]
+ ),
+ )
+
+ # implement Send*() methods and add dispatcher cases to
+ # message switch()es
+ for md in p.messageDecls:
+ self.visitMessageDecl(md)
+
+ # add default cases
+ default = StmtCode(
+ """
+ return MsgNotKnown;
+ """
+ )
+ self.asyncSwitch.addcase(DefaultLabel(), default)
+ if toplevel.isSync() or toplevel.isInterrupt():
+ self.syncSwitch.addcase(DefaultLabel(), default)
+ if toplevel.isInterrupt():
+ self.interruptSwitch.addcase(DefaultLabel(), default)
+
+ self.cls.addstmts(self.implementManagerIface())
+
+ def makeHandlerMethod(name, switch, hasReply, dispatches=False):
+ params = [Decl(Type("Message", const=True, ref=True), msgvar.name)]
+ if hasReply:
+ params.append(Decl(Type("UniquePtr<Message>", ref=True), replyvar.name))
+
+ method = MethodDefn(
+ MethodDecl(
+ name,
+ methodspec=MethodSpec.OVERRIDE,
+ params=params,
+ ret=_Result.Type(),
+ )
+ )
+
+ if not switch:
+ method.addcode(
+ """
+ MOZ_ASSERT_UNREACHABLE("message protocol not supported");
+ return MsgNotKnown;
+ """
+ )
+ return method
+
+ if dispatches:
+ if hasReply:
+ ondeadactor = [StmtReturn(_Result.RouteError)]
+ else:
+ ondeadactor = [
+ self.logMessage(
+ None, ExprAddrOf(msgvar), "Ignored message for dead actor"
+ ),
+ StmtReturn(_Result.Processed),
+ ]
+
+ method.addcode(
+ """
+ int32_t route__ = ${msgvar}.routing_id();
+ if (MSG_ROUTING_CONTROL != route__) {
+ IProtocol* routed__ = Lookup(route__);
+ if (!routed__ || !routed__->GetLifecycleProxy()) {
+ $*{ondeadactor}
+ }
+
+ RefPtr<mozilla::ipc::ActorLifecycleProxy> proxy__ =
+ routed__->GetLifecycleProxy();
+ return proxy__->Get()->${name}($,{args});
+ }
+
+ """,
+ msgvar=msgvar,
+ ondeadactor=ondeadactor,
+ name=name,
+ args=[p.name for p in params],
+ )
+
+ # bug 509581: don't generate the switch stmt if there
+ # is only the default case; MSVC doesn't like that
+ if switch.nr_cases > 1:
+ method.addstmt(switch)
+ else:
+ method.addstmt(StmtReturn(_Result.NotKnown))
+
+ return method
+
+ dispatches = ptype.isToplevel() and ptype.isManager()
+ self.cls.addstmts(
+ [
+ makeHandlerMethod(
+ "OnMessageReceived",
+ self.asyncSwitch,
+ hasReply=False,
+ dispatches=dispatches,
+ ),
+ Whitespace.NL,
+ ]
+ )
+ self.cls.addstmts(
+ [
+ makeHandlerMethod(
+ "OnMessageReceived",
+ self.syncSwitch,
+ hasReply=True,
+ dispatches=dispatches,
+ ),
+ Whitespace.NL,
+ ]
+ )
+ self.cls.addstmts(
+ [
+ makeHandlerMethod(
+ "OnCallReceived",
+ self.interruptSwitch,
+ hasReply=True,
+ dispatches=dispatches,
+ ),
+ Whitespace.NL,
+ ]
+ )
+
+ clearsubtreevar = ExprVar("ClearSubtree")
+
+ if ptype.isToplevel():
+ # OnChannelClose()
+ onclose = MethodDefn(
+ MethodDecl("OnChannelClose", methodspec=MethodSpec.OVERRIDE)
+ )
+ onclose.addcode(
+ """
+ DestroySubtree(NormalShutdown);
+ ClearSubtree();
+ DeallocShmems();
+ if (GetLifecycleProxy()) {
+ GetLifecycleProxy()->Release();
+ }
+ """
+ )
+ self.cls.addstmts([onclose, Whitespace.NL])
+
+ # OnChannelError()
+ onerror = MethodDefn(
+ MethodDecl("OnChannelError", methodspec=MethodSpec.OVERRIDE)
+ )
+ onerror.addcode(
+ """
+ DestroySubtree(AbnormalShutdown);
+ ClearSubtree();
+ DeallocShmems();
+ if (GetLifecycleProxy()) {
+ GetLifecycleProxy()->Release();
+ }
+ """
+ )
+ self.cls.addstmts([onerror, Whitespace.NL])
+
+ if ptype.isToplevel() and ptype.isInterrupt():
+ processnative = MethodDefn(
+ MethodDecl("ProcessNativeEventsInInterruptCall", ret=Type.VOID)
+ )
+ processnative.addcode(
+ """
+ #ifdef XP_WIN
+ GetIPCChannel()->ProcessNativeEventsInInterruptCall();
+ #else
+ FatalError("This method is Windows-only");
+ #endif
+ """
+ )
+
+ self.cls.addstmts([processnative, Whitespace.NL])
+
+ # private methods
+ self.cls.addstmt(Label.PRIVATE)
+
+ # ClearSubtree()
+ clearsubtree = MethodDefn(MethodDecl(clearsubtreevar.name))
+ for managed in ptype.manages:
+ clearsubtree.addcode(
+ """
+ for (auto* key : ${container}) {
+ key->ClearSubtree();
+ }
+ for (auto* key : ${container}) {
+ // Recursively releasing ${container} kids.
+ auto* proxy = key->GetLifecycleProxy();
+ NS_IF_RELEASE(proxy);
+ }
+ ${container}.Clear();
+
+ """,
+ container=p.managedVar(managed, self.side),
+ )
+
+ # don't release our own IPC reference: either the manager will do it,
+ # or we're toplevel
+ self.cls.addstmts([clearsubtree, Whitespace.NL])
+
+ if not ptype.isToplevel():
+ self.cls.addstmts(
+ [
+ StmtDecl(
+ Decl(Type.BOOL, "mAwaitingManagedEndpointBind"),
+ init=ExprLiteral.FALSE,
+ ),
+ Whitespace.NL,
+ ]
+ )
+
+ for managed in ptype.manages:
+ self.cls.addstmts(
+ [
+ StmtDecl(
+ Decl(
+ p.managedVarType(managed, self.side),
+ p.managedVar(managed, self.side).name,
+ )
+ )
+ ]
+ )
+
+ def genManagedEndpoint(self, managed):
+ hereEp = "ManagedEndpoint<%s>" % _actorName(managed.name(), self.side)
+ thereEp = "ManagedEndpoint<%s>" % _actorName(
+ managed.name(), _otherSide(self.side)
+ )
+
+ actor = _HybridDecl(ipdl.type.ActorType(managed), "aActor")
+
+ # ManagedEndpoint<PThere> OpenPEndpoint(PHere* aActor)
+ openmeth = MethodDefn(
+ MethodDecl(
+ "Open%sEndpoint" % managed.name(),
+ params=[
+ Decl(self.protocol.managedCxxType(managed, self.side), actor.name)
+ ],
+ ret=Type(thereEp),
+ )
+ )
+ openmeth.addcode(
+ """
+ $*{bind}
+ // Mark our actor as awaiting the other side to be bound. This will
+ // be cleared when a `MANAGED_ENDPOINT_{DROPPED,BOUND}` message is
+ // received.
+ aActor->mAwaitingManagedEndpointBind = true;
+ return ${thereEp}(mozilla::ipc::PrivateIPDLInterface(), aActor);
+ """,
+ bind=self.bindManagedActor(actor, errfn=ExprCall(ExprVar(thereEp))),
+ thereEp=thereEp,
+ )
+
+ # void BindPEndpoint(ManagedEndpoint<PHere>&& aEndpoint, PHere* aActor)
+ bindmeth = MethodDefn(
+ MethodDecl(
+ "Bind%sEndpoint" % managed.name(),
+ params=[
+ Decl(Type(hereEp), "aEndpoint"),
+ Decl(self.protocol.managedCxxType(managed, self.side), actor.name),
+ ],
+ ret=Type.BOOL,
+ )
+ )
+ bindmeth.addcode(
+ """
+ return aEndpoint.Bind(mozilla::ipc::PrivateIPDLInterface(), aActor, this, ${container});
+ """,
+ container=self.protocol.managedVar(managed, self.side),
+ )
+
+ self.cls.addstmts([openmeth, bindmeth, Whitespace.NL])
+
+ def implementManagerIface(self):
+ p = self.protocol
+ protocolbase = Type("IProtocol", ptr=True)
+
+ methods = []
+
+ if p.decl.type.isToplevel():
+ # FIXME: This used to be declared conditionally based on whether
+ # shmem appeared somewhere in the protocol hierarchy, however that
+ # caused issues due to Shmem instances hidden within custom C++
+ # types.
+ self.asyncSwitch.addcase(
+ CaseLabel("SHMEM_CREATED_MESSAGE_TYPE"),
+ self.genShmemCreatedHandler(),
+ )
+ self.asyncSwitch.addcase(
+ CaseLabel("SHMEM_DESTROYED_MESSAGE_TYPE"),
+ self.genShmemDestroyedHandler(),
+ )
+
+ # Keep track of types created with an INOUT ctor. We need to call
+ # Register() or RegisterID() for them depending on the side the managee
+ # is created.
+ inoutCtorTypes = []
+ for msg in p.messageDecls:
+ msgtype = msg.decl.type
+ if msgtype.isCtor() and msgtype.isInout():
+ inoutCtorTypes.append(msgtype.constructedType())
+
+ # all protocols share the "same" RemoveManagee() implementation
+ pvar = ExprVar("aProtocolId")
+ listenervar = ExprVar("aListener")
+ removemanagee = MethodDefn(
+ MethodDecl(
+ p.removeManageeMethod().name,
+ params=[
+ Decl(_protocolIdType(), pvar.name),
+ Decl(protocolbase, listenervar.name),
+ ],
+ methodspec=MethodSpec.OVERRIDE,
+ )
+ )
+
+ if not len(p.managesStmts):
+ removemanagee.addcode(
+ """
+ FatalError("unreached");
+ return;
+ """
+ )
+ else:
+ switchontype = StmtSwitch(pvar)
+ for managee in p.managesStmts:
+ manageeipdltype = managee.decl.type
+ manageecxxtype = _cxxBareType(
+ ipdl.type.ActorType(manageeipdltype), self.side
+ )
+ case = ExprCode(
+ """
+ {
+ ${manageecxxtype} actor = static_cast<${manageecxxtype}>(aListener);
+
+ const bool removed = ${container}.EnsureRemoved(actor);
+ MOZ_RELEASE_ASSERT(removed, "actor not managed by this!");
+
+ auto* proxy = actor->GetLifecycleProxy();
+ NS_IF_RELEASE(proxy);
+ return;
+ }
+ """,
+ manageecxxtype=manageecxxtype,
+ container=p.managedVar(manageeipdltype, self.side),
+ )
+ switchontype.addcase(CaseLabel(_protocolId(manageeipdltype).name), case)
+ switchontype.addcase(
+ DefaultLabel(),
+ ExprCode(
+ """
+ FatalError("unreached");
+ return;
+ """
+ ),
+ )
+ removemanagee.addstmt(switchontype)
+
+ # The `DeallocManagee` method is called for managed actors to trigger
+ # deallocation when ActorLifecycleProxy is freed.
+ deallocmanagee = MethodDefn(
+ MethodDecl(
+ p.deallocManageeMethod().name,
+ params=[
+ Decl(_protocolIdType(), pvar.name),
+ Decl(protocolbase, listenervar.name),
+ ],
+ methodspec=MethodSpec.OVERRIDE,
+ )
+ )
+
+ if not len(p.managesStmts):
+ deallocmanagee.addcode(
+ """
+ FatalError("unreached");
+ return;
+ """
+ )
+ else:
+ switchontype = StmtSwitch(pvar)
+ for managee in p.managesStmts:
+ manageeipdltype = managee.decl.type
+ # Reference counted actor types don't have corresponding
+ # `Dealloc` methods, as they are deallocated by releasing the
+ # IPDL-held reference.
+ if manageeipdltype.isRefcounted():
+ continue
+
+ case = StmtCode(
+ """
+ ${concrete}->${dealloc}(static_cast<${type}>(aListener));
+ return;
+ """,
+ concrete=self.concreteThis(),
+ dealloc=_deallocMethod(manageeipdltype, self.side),
+ type=_cxxBareType(ipdl.type.ActorType(manageeipdltype), self.side),
+ )
+ switchontype.addcase(CaseLabel(_protocolId(manageeipdltype).name), case)
+ switchontype.addcase(
+ DefaultLabel(),
+ StmtCode(
+ """
+ FatalError("unreached");
+ return;
+ """
+ ),
+ )
+ deallocmanagee.addstmt(switchontype)
+
+ return methods + [removemanagee, deallocmanagee, Whitespace.NL]
+
+ def genShmemCreatedHandler(self):
+ assert self.protocol.decl.type.isToplevel()
+
+ return StmtCode(
+ """
+ {
+ if (!ShmemCreated(${msgvar})) {
+ return MsgPayloadError;
+ }
+ return MsgProcessed;
+ }
+ """,
+ msgvar=self.msgvar,
+ )
+
+ def genShmemDestroyedHandler(self):
+ assert self.protocol.decl.type.isToplevel()
+
+ return StmtCode(
+ """
+ {
+ if (!ShmemDestroyed(${msgvar})) {
+ return MsgPayloadError;
+ }
+ return MsgProcessed;
+ }
+ """,
+ msgvar=self.msgvar,
+ )
+
+ # -------------------------------------------------------------------------
+ # The next few functions are the crux of the IPDL code generator.
+ # They generate code for all the nasty work of message
+ # serialization/deserialization and dispatching handlers for
+ # received messages.
+ ##
+
+ def concreteThis(self):
+ implAttr = self.protocol.implAttribute(self.side)
+ if implAttr == "virtual":
+ return ExprVar.THIS
+
+ if implAttr is None:
+ assert self.protocol.name.startswith("P")
+ className = self.protocol.name[1:] + self.side.capitalize()
+ else:
+ assert isinstance(implAttr, ipdl.ast.StringLiteral)
+ className = implAttr.value
+
+ return ExprCode("static_cast<${className}*>(this)", className=className)
+
+ def thisCall(self, function, args):
+ return ExprCall(ExprSelect(self.concreteThis(), "->", function), args=args)
+
+ def visitMessageDecl(self, md):
+ isctor = md.decl.type.isCtor()
+ isdtor = md.decl.type.isDtor()
+ decltype = md.decl.type
+ sendmethod = None
+ movesendmethod = None
+ promisesendmethod = None
+ recvlbl, recvcase = None, None
+
+ def addRecvCase(lbl, case):
+ if decltype.isAsync():
+ self.asyncSwitch.addcase(lbl, case)
+ elif decltype.isSync():
+ self.syncSwitch.addcase(lbl, case)
+ elif decltype.isInterrupt():
+ self.interruptSwitch.addcase(lbl, case)
+ else:
+ assert 0
+
+ if self.sendsMessage(md):
+ isasync = decltype.isAsync()
+
+ # NOTE: Don't generate helper ctors for refcounted types.
+ #
+ # Safety concerns around providing your own actor to a ctor (namely
+ # that the return value won't be checked, and the argument will be
+ # `delete`-ed) are less critical with refcounted actors, due to the
+ # actor being held alive by the callsite.
+ #
+ # This allows refcounted actors to not implement crashing AllocPFoo
+ # methods on the sending side.
+ if isctor and not md.decl.type.constructedType().isRefcounted():
+ self.cls.addstmts([self.genHelperCtor(md), Whitespace.NL])
+
+ if isctor and isasync:
+ sendmethod, (recvlbl, recvcase) = self.genAsyncCtor(md)
+ elif isctor:
+ sendmethod = self.genBlockingCtorMethod(md)
+ elif isdtor and isasync:
+ sendmethod, (recvlbl, recvcase) = self.genAsyncDtor(md)
+ elif isdtor:
+ sendmethod = self.genBlockingDtorMethod(md)
+ elif isasync:
+ (
+ sendmethod,
+ movesendmethod,
+ promisesendmethod,
+ (recvlbl, recvcase),
+ ) = self.genAsyncSendMethod(md)
+ else:
+ sendmethod, movesendmethod = self.genBlockingSendMethod(md)
+
+ # XXX figure out what to do here
+ if isdtor and md.decl.type.constructedType().isToplevel():
+ sendmethod = None
+
+ if sendmethod is not None:
+ self.cls.addstmts([sendmethod, Whitespace.NL])
+ if movesendmethod is not None:
+ self.cls.addstmts([movesendmethod, Whitespace.NL])
+ if promisesendmethod is not None:
+ self.cls.addstmts([promisesendmethod, Whitespace.NL])
+ if recvcase is not None:
+ addRecvCase(recvlbl, recvcase)
+ recvlbl, recvcase = None, None
+
+ if self.receivesMessage(md):
+ if isctor:
+ recvlbl, recvcase = self.genCtorRecvCase(md)
+ elif isdtor:
+ recvlbl, recvcase = self.genDtorRecvCase(md)
+ else:
+ recvlbl, recvcase = self.genRecvCase(md)
+
+ # XXX figure out what to do here
+ if isdtor and md.decl.type.constructedType().isToplevel():
+ return
+
+ addRecvCase(recvlbl, recvcase)
+
+ def genAsyncCtor(self, md):
+ actor = md.actorDecl()
+ method = MethodDefn(self.makeSendMethodDecl(md))
+
+ msgvar, stmts = self.makeMessage(md, errfnSendCtor)
+ sendok, sendstmts = self.sendAsync(md, msgvar)
+
+ method.addcode(
+ """
+ $*{bind}
+
+ // Build our constructor message.
+ $*{stmts}
+
+ // Notify the other side about the newly created actor. This can
+ // fail if our manager has already been destroyed.
+ //
+ // NOTE: If the send call fails due to toplevel channel teardown,
+ // the `IProtocol::ChannelSend` wrapper absorbs the error for us,
+ // so we don't tear down actors unexpectedly.
+ $*{sendstmts}
+
+ // Warn, destroy the actor, and return null if the message failed to
+ // send. Otherwise, return the successfully created actor reference.
+ if (!${sendok}) {
+ NS_WARNING("Error sending ${actorname} constructor");
+ $*{destroy}
+ return nullptr;
+ }
+ return ${actor};
+ """,
+ bind=self.bindManagedActor(actor),
+ stmts=stmts,
+ sendstmts=sendstmts,
+ sendok=sendok,
+ destroy=self.destroyActor(
+ md, actor.var(), why=_DestroyReason.FailedConstructor
+ ),
+ actor=actor.var(),
+ actorname=actor.ipdltype.protocol.name() + self.side.capitalize(),
+ )
+
+ lbl = CaseLabel(md.pqReplyId())
+ case = StmtBlock()
+ case.addstmt(StmtReturn(_Result.Processed))
+ # TODO not really sure what to do with async ctor "replies" yet.
+ # destroy actor if there was an error? tricky ...
+
+ return method, (lbl, case)
+
+ def genBlockingCtorMethod(self, md):
+ actor = md.actorDecl()
+ method = MethodDefn(self.makeSendMethodDecl(md))
+
+ msgvar, stmts = self.makeMessage(md, errfnSendCtor)
+
+ replyvar = self.replyvar
+ sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar)
+ replystmts = self.deserializeReply(
+ md,
+ replyvar,
+ self.side,
+ errfnSendCtor,
+ errfnSentinel(ExprLiteral.NULL),
+ )
+
+ method.addcode(
+ """
+ $*{bind}
+
+ // Build our constructor message.
+ $*{stmts}
+
+ // Synchronously send the constructor message to the other side. If
+ // the send fails, e.g. due to the remote side shutting down, the
+ // actor will be destroyed and potentially freed.
+ UniquePtr<Message> ${replyvar};
+ $*{sendstmts}
+
+ if (!(${sendok})) {
+ // Warn, destroy the actor and return null if the message
+ // failed to send.
+ NS_WARNING("Error sending constructor");
+ $*{destroy}
+ return nullptr;
+ }
+
+ $*{replystmts}
+ return ${actor};
+ """,
+ bind=self.bindManagedActor(actor),
+ stmts=stmts,
+ replyvar=replyvar,
+ sendstmts=sendstmts,
+ sendok=sendok,
+ destroy=self.destroyActor(
+ md, actor.var(), why=_DestroyReason.FailedConstructor
+ ),
+ replystmts=replystmts,
+ actor=actor.var(),
+ actorname=actor.ipdltype.protocol.name() + self.side.capitalize(),
+ )
+
+ return method
+
+ def bindManagedActor(self, actordecl, errfn=ExprLiteral.NULL, idexpr=None):
+ actorproto = actordecl.ipdltype.protocol
+
+ if idexpr is None:
+ setManagerArgs = [ExprVar.THIS]
+ else:
+ setManagerArgs = [ExprVar.THIS, idexpr]
+
+ return [
+ StmtCode(
+ """
+ if (!${actor}) {
+ NS_WARNING("Cannot bind null ${actorname} actor");
+ return ${errfn};
+ }
+
+ ${actor}->SetManagerAndRegister($,{setManagerArgs});
+ ${container}.Insert(${actor});
+ """,
+ actor=actordecl.var(),
+ actorname=actorproto.name() + self.side.capitalize(),
+ errfn=errfn,
+ setManagerArgs=setManagerArgs,
+ container=self.protocol.managedVar(actorproto, self.side),
+ )
+ ]
+
+ def genHelperCtor(self, md):
+ helperdecl = self.makeSendMethodDecl(md)
+ helperdecl.params = helperdecl.params[1:]
+ helper = MethodDefn(helperdecl)
+
+ helper.addstmts(
+ [
+ self.callAllocActor(md, retsems="out", side=self.side),
+ StmtReturn(
+ ExprCall(
+ ExprVar(helperdecl.name), args=md.makeCxxArgs(paramsems="move")
+ )
+ ),
+ ]
+ )
+ return helper
+
+ def genAsyncDtor(self, md):
+ actorvar = ExprVar("actor")
+ method = MethodDefn(self.makeDtorMethodDecl(md, actorvar))
+
+ method.addstmt(self.dtorPrologue(actorvar))
+
+ msgvar, stmts = self.makeMessage(md, errfnSendDtor, actorvar)
+ sendok, sendstmts = self.sendAsync(md, msgvar, actorvar)
+ method.addstmts(
+ stmts
+ + sendstmts
+ + [Whitespace.NL]
+ + self.dtorEpilogue(md, actorvar)
+ + [StmtReturn(sendok)]
+ )
+
+ lbl = CaseLabel(md.pqReplyId())
+ case = StmtBlock()
+ case.addstmt(StmtReturn(_Result.Processed))
+ # TODO if the dtor is "inherently racy", keep the actor alive
+ # until the other side acks
+
+ return method, (lbl, case)
+
+ def genBlockingDtorMethod(self, md):
+ actorvar = ExprVar("actor")
+ method = MethodDefn(self.makeDtorMethodDecl(md, actorvar))
+
+ method.addstmt(self.dtorPrologue(actorvar))
+
+ msgvar, stmts = self.makeMessage(md, errfnSendDtor, actorvar)
+
+ replyvar = self.replyvar
+ sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar, actorvar)
+ method.addstmts(
+ stmts
+ + [Whitespace.NL, StmtDecl(Decl(Type("UniquePtr<Message>"), replyvar.name))]
+ + sendstmts
+ )
+
+ destmts = self.deserializeReply(
+ md, replyvar, self.side, errfnSend, errfnSentinel(), actorvar
+ )
+ ifsendok = StmtIf(ExprLiteral.FALSE)
+ ifsendok.addifstmts(destmts)
+ ifsendok.addifstmts(
+ [Whitespace.NL, StmtExpr(ExprAssn(sendok, ExprLiteral.FALSE, "&="))]
+ )
+
+ method.addstmt(ifsendok)
+
+ method.addstmts(
+ self.dtorEpilogue(md, actorvar) + [Whitespace.NL, StmtReturn(sendok)]
+ )
+
+ return method
+
+ def destroyActor(self, md, actorexpr, why=_DestroyReason.Deletion):
+ if md and md.decl.type.isCtor():
+ destroyedType = md.decl.type.constructedType()
+ else:
+ destroyedType = self.protocol.decl.type
+
+ return [
+ StmtCode(
+ """
+ IProtocol* mgr = ${actor}->Manager();
+ ${actor}->DestroySubtree(${why});
+ ${actor}->ClearSubtree();
+ mgr->RemoveManagee(${protoId}, ${actor});
+ """,
+ actor=actorexpr,
+ why=why,
+ protoId=_protocolId(destroyedType),
+ )
+ ]
+
+ def dtorPrologue(self, actorexpr):
+ return StmtCode(
+ """
+ if (!${actor} || !${actor}->CanSend()) {
+ NS_WARNING("Attempt to __delete__ missing or closed actor");
+ return false;
+ }
+ """,
+ actor=actorexpr,
+ )
+
+ def dtorEpilogue(self, md, actorexpr):
+ return self.destroyActor(md, actorexpr)
+
+ def genRecvAsyncReplyCase(self, md):
+ lbl = CaseLabel(md.pqReplyId())
+ case = StmtBlock()
+ resolve, reason, prologue, desrej, desstmts = self.deserializeAsyncReply(
+ md, self.side, errfnRecv, errfnSentinel(_Result.ValuError)
+ )
+
+ if len(md.returns) > 1:
+ resolvetype = _tuple([d.bareType(self.side) for d in md.returns])
+ resolvearg = ExprCall(
+ ExprVar("std::make_tuple"), args=[ExprMove(p.var()) for p in md.returns]
+ )
+ else:
+ resolvetype = md.returns[0].bareType(self.side)
+ resolvearg = ExprMove(md.returns[0].var())
+
+ case.addcode(
+ """
+ $*{prologue}
+
+ UniquePtr<MessageChannel::UntypedCallbackHolder> untypedCallback =
+ GetIPCChannel()->PopCallback(${msgvar}, Id());
+
+ typedef MessageChannel::CallbackHolder<${resolvetype}> CallbackHolder;
+ auto* callback = static_cast<CallbackHolder*>(untypedCallback.get());
+ if (!callback) {
+ FatalError("Error unknown callback");
+ return MsgProcessingError;
+ }
+
+ if (${resolve}) {
+ $*{desstmts}
+ callback->Resolve(${resolvearg});
+ } else {
+ $*{desrej}
+ callback->Reject(std::move(${reason}));
+ }
+ return MsgProcessed;
+ """,
+ prologue=prologue,
+ msgvar=self.msgvar,
+ resolve=resolve,
+ resolvetype=resolvetype,
+ desstmts=desstmts,
+ resolvearg=resolvearg,
+ desrej=desrej,
+ reason=reason,
+ )
+
+ return (lbl, case)
+
+ def genAsyncSendMethod(self, md):
+ decl = self.makeSendMethodDecl(md)
+ if "VirtualSendImpl" in md.attributes:
+ decl.methodspec = MethodSpec.VIRTUAL
+ method = MethodDefn(decl)
+ msgvar, stmts = self.makeMessage(md, errfnSend)
+ retvar, sendstmts = self.sendAsync(md, msgvar)
+
+ method.addstmts(stmts + [Whitespace.NL] + sendstmts + [StmtReturn(retvar)])
+
+ movemethod = None
+
+ # Add the promise overload if we need one.
+ if md.returns:
+ decl = self.makeSendMethodDecl(md, promise=True)
+ if "VirtualSendImpl" in md.attributes:
+ decl.methodspec = MethodSpec.VIRTUAL
+ promisemethod = MethodDefn(decl)
+ stmts = self.sendAsyncWithPromise(md)
+ promisemethod.addstmts(stmts)
+
+ (lbl, case) = self.genRecvAsyncReplyCase(md)
+ else:
+ (promisemethod, lbl, case) = (None, None, None)
+
+ return method, movemethod, promisemethod, (lbl, case)
+
+ def genBlockingSendMethod(self, md):
+ method = MethodDefn(self.makeSendMethodDecl(md))
+
+ msgvar, serstmts = self.makeMessage(md, errfnSend)
+ replyvar = self.replyvar
+
+ sendok, sendstmts = self.sendBlocking(md, msgvar, replyvar)
+ failif = StmtIf(ExprNot(sendok))
+ failif.addifstmt(StmtReturn.FALSE)
+
+ desstmts = self.deserializeReply(
+ md, replyvar, self.side, errfnSend, errfnSentinel()
+ )
+
+ method.addstmts(
+ serstmts
+ + [Whitespace.NL, StmtDecl(Decl(Type("UniquePtr<Message>"), replyvar.name))]
+ + sendstmts
+ + [failif]
+ + desstmts
+ + [Whitespace.NL, StmtReturn.TRUE]
+ )
+
+ movemethod = None
+
+ return method, movemethod
+
+ def genCtorRecvCase(self, md):
+ lbl = CaseLabel(md.pqMsgId())
+ case = StmtBlock()
+ actorhandle = self.handlevar
+
+ stmts = self.deserializeMessage(
+ md, self.side, errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
+ )
+
+ idvar, saveIdStmts = self.saveActorId(md)
+ case.addstmts(
+ stmts
+ + [
+ StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
+ for r in md.returns
+ ]
+ # alloc the actor, register it under the foreign ID
+ + [self.callAllocActor(md, retsems="in", side=self.side)]
+ + self.bindManagedActor(
+ md.actorDecl(), errfn=_Result.ValuError, idexpr=_actorHId(actorhandle)
+ )
+ + [Whitespace.NL]
+ + saveIdStmts
+ + self.invokeRecvHandler(md)
+ + self.makeReply(md, errfnRecv, idvar)
+ + [Whitespace.NL, StmtReturn(_Result.Processed)]
+ )
+
+ return lbl, case
+
+ def genDtorRecvCase(self, md):
+ lbl = CaseLabel(md.pqMsgId())
+ case = StmtBlock()
+
+ stmts = self.deserializeMessage(
+ md, self.side, errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
+ )
+
+ idvar, saveIdStmts = self.saveActorId(md)
+ case.addstmts(
+ stmts
+ + [
+ StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
+ for r in md.returns
+ ]
+ + self.invokeRecvHandler(md)
+ + [Whitespace.NL]
+ + saveIdStmts
+ + self.makeReply(md, errfnRecv, routingId=idvar)
+ + [Whitespace.NL]
+ + self.dtorEpilogue(md, ExprVar.THIS)
+ + [Whitespace.NL, StmtReturn(_Result.Processed)]
+ )
+
+ return lbl, case
+
+ def genRecvCase(self, md):
+ lbl = CaseLabel(md.pqMsgId())
+ case = StmtBlock()
+
+ stmts = self.deserializeMessage(
+ md, self.side, errfn=errfnRecv, errfnSent=errfnSentinel(_Result.ValuError)
+ )
+
+ idvar, saveIdStmts = self.saveActorId(md)
+ declstmts = [
+ StmtDecl(Decl(r.bareType(self.side), r.var().name), initargs=[])
+ for r in md.returns
+ ]
+ if md.decl.type.isAsync() and md.returns:
+ declstmts = self.makeResolver(md, errfnRecv, routingId=idvar)
+ case.addstmts(
+ stmts
+ + saveIdStmts
+ + declstmts
+ + self.invokeRecvHandler(md)
+ + [Whitespace.NL]
+ + self.makeReply(md, errfnRecv, routingId=idvar)
+ + [StmtReturn(_Result.Processed)]
+ )
+
+ return lbl, case
+
+ # helper methods
+
+ def makeMessage(self, md, errfn, fromActor=None):
+ msgvar = self.msgvar
+ writervar = ExprVar("writer__")
+ routingId = self.protocol.routingId(fromActor)
+ this = fromActor or ExprVar.THIS
+
+ stmts = (
+ [
+ StmtDecl(
+ Decl(Type("UniquePtr<IPC::Message>"), msgvar.name),
+ init=ExprCall(ExprVar(md.pqMsgCtorFunc()), args=[routingId]),
+ ),
+ StmtDecl(
+ Decl(Type("IPC::MessageWriter"), writervar.name),
+ initargs=[ExprDeref(msgvar), this],
+ ),
+ ]
+ + [Whitespace.NL]
+ + [
+ _ParamTraits.checkedWrite(
+ p.ipdltype,
+ p.var(),
+ ExprAddrOf(writervar),
+ sentinelKey=p.name,
+ )
+ for p in md.params
+ ]
+ + [Whitespace.NL]
+ + self.setMessageFlags(md, msgvar)
+ )
+ return msgvar, stmts
+
+ def makeResolver(self, md, errfn, routingId):
+ if routingId is None:
+ routingId = self.protocol.routingId()
+ if not md.decl.type.isAsync() or not md.hasReply():
+ return []
+
+ def paramValue(idx):
+ assert idx < len(md.returns)
+ if len(md.returns) > 1:
+ return ExprCode("std::get<${idx}>(aParam)", idx=idx)
+ return ExprVar("aParam")
+
+ serializeParams = [
+ _ParamTraits.checkedWrite(
+ p.ipdltype,
+ paramValue(idx),
+ ExprAddrOf(ExprVar("writer__")),
+ sentinelKey=p.name,
+ )
+ for idx, p in enumerate(md.returns)
+ ]
+
+ return [
+ StmtCode(
+ """
+ UniquePtr<IPC::Message> ${replyvar}(${replyCtor}(${routingId}));
+ ${replyvar}->set_seqno(${msgvar}.seqno());
+
+ RefPtr<mozilla::ipc::IPDLResolverInner> resolver__ =
+ new mozilla::ipc::IPDLResolverInner(std::move(${replyvar}), this);
+
+ ${resolvertype} resolver = [resolver__ = std::move(resolver__)](${resolveType} aParam) {
+ resolver__->Resolve([&] (IPC::Message* ${replyvar}, IProtocol* self__) {
+ IPC::MessageWriter writer__(*${replyvar}, self__);
+ $*{serializeParams}
+ ${logSendingReply}
+ });
+ };
+ """,
+ msgvar=self.msgvar,
+ resolvertype=Type(md.resolverName()),
+ routingId=routingId,
+ resolveType=_resolveType(md.returns, self.side),
+ replyvar=self.replyvar,
+ replyCtor=ExprVar(md.pqReplyCtorFunc()),
+ serializeParams=serializeParams,
+ logSendingReply=self.logMessage(
+ md,
+ self.replyvar,
+ "Sending reply ",
+ actor=ExprVar("self__"),
+ ),
+ )
+ ]
+
+ def makeReply(self, md, errfn, routingId):
+ if routingId is None:
+ routingId = self.protocol.routingId()
+ # TODO special cases for async ctor/dtor replies
+ if not md.decl.type.hasReply():
+ return []
+ if md.decl.type.isAsync() and md.decl.type.hasReply():
+ return []
+
+ replyvar = self.replyvar
+ return (
+ [
+ StmtExpr(
+ ExprAssn(
+ replyvar,
+ ExprCall(ExprVar(md.pqReplyCtorFunc()), args=[routingId]),
+ )
+ ),
+ StmtDecl(
+ Decl(Type("IPC::MessageWriter"), "writer__"),
+ initargs=[ExprDeref(replyvar), ExprVar.THIS],
+ ),
+ Whitespace.NL,
+ ]
+ + [
+ _ParamTraits.checkedWrite(
+ r.ipdltype,
+ r.var(),
+ ExprAddrOf(ExprVar("writer__")),
+ sentinelKey=r.name,
+ )
+ for r in md.returns
+ ]
+ + self.setMessageFlags(md, replyvar)
+ + [self.logMessage(md, replyvar, "Sending reply ")]
+ )
+
+ def setMessageFlags(self, md, var, seqno=None):
+ stmts = []
+
+ if seqno:
+ stmts.append(
+ StmtExpr(ExprCall(ExprSelect(var, "->", "set_seqno"), args=[seqno]))
+ )
+
+ return stmts + [Whitespace.NL]
+
+ def deserializeMessage(self, md, side, errfn, errfnSent):
+ msgvar = self.msgvar
+ msgexpr = ExprAddrOf(msgvar)
+ readervar = ExprVar("reader__")
+ isctor = md.decl.type.isCtor()
+ stmts = [
+ self.logMessage(md, msgexpr, "Received ", receiving=True),
+ self.profilerLabel(md),
+ Whitespace.NL,
+ ]
+
+ if 0 == len(md.params):
+ return stmts
+
+ start, reads = 0, []
+ if isctor:
+ # return the raw actor handle so that its ID can be used
+ # to construct the "real" actor
+ handlevar = self.handlevar
+ handletype = Type("ActorHandle")
+ reads = [
+ _ParamTraits.checkedRead(
+ None,
+ handletype,
+ handlevar,
+ ExprAddrOf(readervar),
+ errfn,
+ "'%s'" % handletype.name,
+ sentinelKey="actor",
+ errfnSentinel=errfnSent,
+ )
+ ]
+ start = 1
+
+ def maybeTainted(p, side):
+ if md.decl.type.tainted and "NoTaint" not in p.attributes:
+ return Type("Tainted", T=p.bareType(side))
+ return p.bareType(side)
+
+ reads.extend(
+ [
+ _ParamTraits.checkedRead(
+ p.ipdltype,
+ maybeTainted(p, side),
+ p.var(),
+ ExprAddrOf(readervar),
+ errfn,
+ "'%s'" % p.ipdltype.name(),
+ sentinelKey=p.name,
+ errfnSentinel=errfnSent,
+ )
+ for p in md.params[start:]
+ ]
+ )
+
+ stmts.extend(
+ (
+ [
+ StmtDecl(
+ Decl(Type("IPC::MessageReader"), readervar.name),
+ initargs=[msgvar, ExprVar.THIS],
+ )
+ ]
+ + [Whitespace.NL]
+ + reads
+ + [StmtCode("${reader}.EndRead();\n", reader=readervar)]
+ )
+ )
+
+ return stmts
+
+ def deserializeAsyncReply(self, md, side, errfn, errfnSent):
+ msgvar = self.msgvar
+ readervar = ExprVar("reader__")
+ msgexpr = ExprAddrOf(msgvar)
+ isctor = md.decl.type.isCtor()
+ resolve = ExprVar("resolve__")
+ reason = ExprVar("reason__")
+
+ # NOTE: The `resolve__` and `reason__` parameters don't have sentinels,
+ # as they are serialized by the IPDLResolverInner type in
+ # ProtocolUtils.cpp rather than by generated code.
+ desresolve = [
+ StmtCode(
+ """
+ bool resolve__ = false;
+ if (!IPC::ReadParam(&${readervar}, &resolve__)) {
+ FatalError("Error deserializing bool");
+ return MsgValueError;
+ }
+ """,
+ readervar=readervar,
+ ),
+ ]
+ desrej = [
+ StmtCode(
+ """
+ ResponseRejectReason reason__{};
+ if (!IPC::ReadParam(&${readervar}, &reason__)) {
+ FatalError("Error deserializing ResponseRejectReason");
+ return MsgValueError;
+ }
+ ${readervar}.EndRead();
+ """,
+ readervar=readervar,
+ ),
+ ]
+ prologue = [
+ self.logMessage(md, msgexpr, "Received ", receiving=True),
+ self.profilerLabel(md),
+ Whitespace.NL,
+ ]
+
+ if not md.returns:
+ return prologue
+
+ prologue.extend(
+ [
+ StmtDecl(
+ Decl(Type("IPC::MessageReader"), readervar.name),
+ initargs=[msgvar, ExprVar.THIS],
+ )
+ ]
+ + desresolve
+ )
+
+ start, reads = 0, []
+ if isctor:
+ # return the raw actor handle so that its ID can be used
+ # to construct the "real" actor
+ handlevar = self.handlevar
+ handletype = Type("ActorHandle")
+ reads = [
+ _ParamTraits.checkedRead(
+ None,
+ handletype,
+ handlevar,
+ ExprAddrOf(readervar),
+ errfn,
+ "'%s'" % handletype.name,
+ sentinelKey="actor",
+ errfnSentinel=errfnSent,
+ )
+ ]
+ start = 1
+
+ stmts = (
+ reads
+ + [
+ _ParamTraits.checkedRead(
+ p.ipdltype,
+ p.bareType(side),
+ p.var(),
+ ExprAddrOf(readervar),
+ errfn,
+ "'%s'" % p.ipdltype.name(),
+ sentinelKey=p.name,
+ errfnSentinel=errfnSent,
+ )
+ for p in md.returns[start:]
+ ]
+ + [StmtCode("${reader}.EndRead();", reader=readervar)]
+ )
+
+ return resolve, reason, prologue, desrej, stmts
+
+ def deserializeReply(self, md, replyexpr, side, errfn, errfnSentinel, actor=None):
+ stmts = [
+ Whitespace.NL,
+ self.logMessage(md, replyexpr, "Received reply ", actor, receiving=True),
+ ]
+ if 0 == len(md.returns):
+ return stmts
+
+ def tempvar(r):
+ return ExprVar(r.var().name + "__reply")
+
+ readervar = ExprVar("reader__")
+ stmts.extend(
+ [
+ Whitespace.NL,
+ StmtDecl(
+ Decl(Type("IPC::MessageReader"), readervar.name),
+ initargs=[ExprDeref(self.replyvar), ExprVar.THIS],
+ ),
+ ]
+ + [Whitespace.NL]
+ + [
+ _ParamTraits.checkedRead(
+ r.ipdltype,
+ r.bareType(side),
+ tempvar(r),
+ ExprAddrOf(readervar),
+ errfn,
+ "'%s'" % r.ipdltype.name(),
+ sentinelKey=r.name,
+ errfnSentinel=errfnSentinel,
+ )
+ for r in md.returns
+ ]
+ # Move-assign the values out of the variables created with
+ # checkedRead into outparams.
+ + [
+ StmtExpr(ExprAssn(ExprDeref(r.var()), ExprMove(tempvar(r))))
+ for r in md.returns
+ ]
+ + [StmtCode("${reader}.EndRead();", reader=readervar)]
+ )
+
+ return stmts
+
+ def sendAsync(self, md, msgexpr, actor=None):
+ sendok = ExprVar("sendok__")
+ resolvefn = ExprVar("aResolve")
+ rejectfn = ExprVar("aReject")
+
+ stmts = [
+ Whitespace.NL,
+ self.logMessage(md, msgexpr, "Sending ", actor),
+ self.profilerLabel(md),
+ ]
+ stmts.append(Whitespace.NL)
+
+ # Generate the actual call expression.
+ send = ExprVar("ChannelSend")
+ if actor is not None:
+ send = ExprSelect(actor, "->", send.name)
+ if md.returns:
+ stmts.append(
+ StmtExpr(
+ ExprCall(
+ send,
+ args=[
+ ExprMove(msgexpr),
+ ExprVar(md.pqReplyId()),
+ ExprMove(resolvefn),
+ ExprMove(rejectfn),
+ ],
+ )
+ )
+ )
+ retvar = None
+ else:
+ stmts.append(
+ StmtDecl(
+ Decl(Type.BOOL, sendok.name),
+ init=ExprCall(send, args=[ExprMove(msgexpr)]),
+ )
+ )
+ retvar = sendok
+
+ return (retvar, stmts)
+
+ def sendBlocking(self, md, msgexpr, replyexpr, actor=None):
+ send = ExprVar("ChannelSend")
+ if md.decl.type.isInterrupt():
+ send = ExprVar("ChannelCall")
+ if actor is not None:
+ send = ExprSelect(actor, "->", send.name)
+
+ sendok = ExprVar("sendok__")
+ self.externalIncludes.add("mozilla/ProfilerMarkers.h")
+ return (
+ sendok,
+ (
+ [
+ Whitespace.NL,
+ self.logMessage(md, msgexpr, "Sending ", actor),
+ self.profilerLabel(md),
+ ]
+ + [
+ Whitespace.NL,
+ StmtDecl(Decl(Type.BOOL, sendok.name), init=ExprLiteral.FALSE),
+ StmtBlock(
+ [
+ StmtExpr(
+ ExprCall(
+ ExprVar("AUTO_PROFILER_TRACING_MARKER"),
+ [
+ ExprLiteral.String("Sync IPC"),
+ ExprLiteral.String(
+ self.protocol.name
+ + "::"
+ + md.prettyMsgName()
+ ),
+ ExprVar("IPC"),
+ ],
+ )
+ ),
+ StmtExpr(
+ ExprAssn(
+ sendok,
+ ExprCall(
+ send,
+ args=[ExprMove(msgexpr), ExprAddrOf(replyexpr)],
+ ),
+ )
+ ),
+ ]
+ ),
+ ]
+ ),
+ )
+
+ def sendAsyncWithPromise(self, md):
+ # Create a new promise, and forward to the callback send overload.
+ promise = _makePromise(md.returns, self.side, resolver=True)
+
+ if len(md.returns) > 1:
+ resolvetype = _tuple([d.bareType(self.side) for d in md.returns])
+ else:
+ resolvetype = md.returns[0].bareType(self.side)
+
+ resolve = ExprCode(
+ """
+ [promise__](${resolvetype}&& aValue) {
+ promise__->Resolve(std::move(aValue), __func__);
+ }
+ """,
+ resolvetype=resolvetype,
+ )
+ reject = ExprCode(
+ """
+ [promise__](ResponseRejectReason&& aReason) {
+ promise__->Reject(std::move(aReason), __func__);
+ }
+ """,
+ resolvetype=resolvetype,
+ )
+
+ args = [ExprMove(p.var()) for p in md.params] + [resolve, reject]
+ stmt = StmtCode(
+ """
+ RefPtr<${promise}> promise__ = new ${promise}(__func__);
+ promise__->UseDirectTaskDispatch(__func__);
+ ${send}($,{args});
+ return promise__;
+ """,
+ promise=promise,
+ send=md.sendMethod(),
+ args=args,
+ )
+ return [stmt]
+
+ def callAllocActor(self, md, retsems, side):
+ actortype = md.actorDecl().bareType(self.side)
+ if md.decl.type.constructedType().isRefcounted():
+ actortype.ptr = False
+ actortype = _refptr(actortype)
+
+ callalloc = self.thisCall(
+ _allocMethod(md.decl.type.constructedType(), side),
+ args=md.makeCxxArgs(retsems=retsems, retcallsems="out", implicit=False),
+ )
+
+ return StmtDecl(Decl(actortype, md.actorDecl().var().name), init=callalloc)
+
+ def invokeRecvHandler(self, md):
+ retsems = "in"
+ if md.decl.type.isAsync() and md.returns:
+ retsems = "resolver"
+ okdecl = StmtDecl(
+ Decl(Type("mozilla::ipc::IPCResult"), "__ok"),
+ init=self.thisCall(
+ md.recvMethod(),
+ md.makeCxxArgs(
+ paramsems="move",
+ retsems=retsems,
+ retcallsems="out",
+ ),
+ ),
+ )
+ failif = StmtIf(ExprNot(ExprVar("__ok")))
+ failif.addifstmts(
+ [
+ _protocolErrorBreakpoint("Handler returned error code!"),
+ Whitespace(
+ "// Error handled in mozilla::ipc::IPCResult\n", indent=True
+ ),
+ StmtReturn(_Result.ProcessingError),
+ ]
+ )
+ return [okdecl, failif]
+
+ def makeDtorMethodDecl(self, md, actorvar):
+ decl = self.makeSendMethodDecl(md)
+ decl.params.insert(
+ 0,
+ Decl(
+ _cxxInType(
+ ipdl.type.ActorType(md.decl.type.constructedType()),
+ side=self.side,
+ direction="send",
+ ),
+ actorvar.name,
+ ),
+ )
+ decl.methodspec = MethodSpec.STATIC
+ return decl
+
+ def makeSendMethodDecl(self, md, promise=False, paramsems="in"):
+ implicit = md.decl.type.hasImplicitActorParam()
+ if md.decl.type.isAsync() and md.returns:
+ if promise:
+ returnsems = "promise"
+ rettype = _refptr(Type(md.promiseName()))
+ else:
+ returnsems = "callback"
+ rettype = Type.VOID
+ else:
+ assert not promise
+ returnsems = "out"
+ rettype = Type.BOOL
+ decl = MethodDecl(
+ md.sendMethod(),
+ params=md.makeCxxParams(
+ paramsems,
+ returnsems=returnsems,
+ side=self.side,
+ implicit=implicit,
+ direction="send",
+ ),
+ warn_unused=(
+ (self.side == "parent" and returnsems != "callback")
+ or (md.decl.type.isCtor() and not md.decl.type.isAsync())
+ ),
+ ret=rettype,
+ )
+ if md.decl.type.isCtor():
+ decl.ret = md.actorDecl().bareType(self.side)
+ return decl
+
+ def logMessage(self, md, msgptr, pfx, actor=None, receiving=False):
+ actorname = _actorName(self.protocol.name, self.side)
+ return StmtCode(
+ """
+ if (mozilla::ipc::LoggingEnabledFor(${protocolname}, ${side})) {
+ mozilla::ipc::LogMessageForProtocol(
+ ${actorname},
+ ${actor}->ToplevelProtocol()->OtherPidMaybeInvalid(),
+ ${pfx},
+ ${msgptr}->type(),
+ mozilla::ipc::MessageDirection::${direction});
+ }
+ """,
+ protocolname=ExprLiteral.String(self.protocol.name),
+ side=_cxxSide(self.side),
+ actorname=ExprLiteral.String(actorname),
+ actor=actor or ExprVar.THIS,
+ pfx=ExprLiteral.String(pfx),
+ msgptr=msgptr,
+ direction="eReceiving" if receiving else "eSending",
+ )
+
+ def profilerLabel(self, md):
+ self.externalIncludes.add("mozilla/ProfilerLabels.h")
+ return StmtCode(
+ """
+ AUTO_PROFILER_LABEL("${name}::${msgname}", OTHER);
+ """,
+ name=self.protocol.name,
+ msgname=md.prettyMsgName(),
+ )
+
+ def saveActorId(self, md):
+ idvar = ExprVar("id__")
+ if md.decl.type.hasReply():
+ # only save the ID if we're actually going to use it, to
+ # avoid unused-variable warnings
+ saveIdStmts = [
+ StmtDecl(Decl(_actorIdType(), idvar.name), self.protocol.routingId())
+ ]
+ else:
+ saveIdStmts = []
+ return idvar, saveIdStmts
+
+
+class _GenerateProtocolParentCode(_GenerateProtocolActorCode):
+ def __init__(self):
+ _GenerateProtocolActorCode.__init__(self, "parent")
+
+ def sendsMessage(self, md):
+ return not md.decl.type.isIn()
+
+ def receivesMessage(self, md):
+ return md.decl.type.isInout() or md.decl.type.isIn()
+
+
+class _GenerateProtocolChildCode(_GenerateProtocolActorCode):
+ def __init__(self):
+ _GenerateProtocolActorCode.__init__(self, "child")
+
+ def sendsMessage(self, md):
+ return not md.decl.type.isOut()
+
+ def receivesMessage(self, md):
+ return md.decl.type.isInout() or md.decl.type.isOut()
+
+
+# -----------------------------------------------------------------------------
+# Utility passes
+##
+
+
+def _splitClassDeclDefn(cls):
+ """Destructively split |cls| methods into declarations and
+ definitions (if |not methodDecl.force_inline|). Return classDecl,
+ methodDefns."""
+ defns = Block()
+
+ for i, stmt in enumerate(cls.stmts):
+ if isinstance(stmt, MethodDefn) and not stmt.decl.force_inline:
+ decl, defn = _splitMethodDeclDefn(stmt, cls)
+ cls.stmts[i] = StmtDecl(decl)
+ if defn:
+ defns.addstmts([defn, Whitespace.NL])
+
+ return cls, defns
+
+
+def _splitMethodDeclDefn(md, cls):
+ # Pure methods have decls but no defns.
+ if md.decl.methodspec == MethodSpec.PURE:
+ return md.decl, None
+
+ saveddecl = deepcopy(md.decl)
+ md.decl.cls = cls
+ # Don't emit method specifiers on method defns.
+ md.decl.methodspec = MethodSpec.NONE
+ md.decl.warn_unused = False
+ md.decl.only_for_definition = True
+ for param in md.decl.params:
+ if isinstance(param, Param):
+ param.default = None
+ return saveddecl, md
+
+
+def _splitFuncDeclDefn(fun):
+ assert not fun.decl.force_inline
+ return StmtDecl(fun.decl), fun
diff --git a/ipc/ipdl/ipdl/parser.py b/ipc/ipdl/ipdl/parser.py
new file mode 100644
index 0000000000..1857131868
--- /dev/null
+++ b/ipc/ipdl/ipdl/parser.py
@@ -0,0 +1,680 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import os
+from ply import lex, yacc
+
+from ipdl.ast import *
+
+# -----------------------------------------------------------------------------
+
+
+class ParseError(Exception):
+ def __init__(self, loc, fmt, *args):
+ self.loc = loc
+ self.error = (
+ "%s%s: error: %s" % (Parser.includeStackString(), loc, fmt)
+ ) % args
+
+ def __str__(self):
+ return self.error
+
+
+def _safeLinenoValue(t):
+ lineno, value = 0, "???"
+ if hasattr(t, "lineno"):
+ lineno = t.lineno
+ if hasattr(t, "value"):
+ value = t.value
+ return lineno, value
+
+
+def _error(loc, fmt, *args):
+ raise ParseError(loc, fmt, *args)
+
+
+class Parser:
+ # when we reach an |include [protocol] foo;| statement, we need to
+ # save the current parser state and create a new one. this "stack" is
+ # where that state is saved
+ #
+ # there is one Parser per file
+ current = None
+ parseStack = []
+ parsed = {}
+
+ def __init__(self, type, name, debug=False):
+ assert type and name
+ self.type = type
+ self.debug = debug
+ self.filename = None
+ self.includedirs = None
+ self.loc = None # not always up to date
+ self.lexer = None
+ self.parser = None
+ self.tu = TranslationUnit(type, name)
+ self.direction = None
+
+ def parse(self, input, filename, includedirs):
+ assert os.path.isabs(filename)
+
+ if self.tu.name in Parser.parsed:
+ priorTU = Parser.parsed[self.tu.name].tu
+ if os.path.normcase(priorTU.filename) != os.path.normcase(filename):
+ _error(
+ Loc(filename),
+ "Trying to load `%s' from a file when we'd already seen it in file `%s'"
+ % (self.tu.name, priorTU.filename),
+ )
+
+ return priorTU
+
+ self.lexer = lex.lex(debug=self.debug)
+ self.parser = yacc.yacc(debug=self.debug, write_tables=False)
+ self.filename = filename
+ self.includedirs = includedirs
+ self.tu.filename = filename
+
+ Parser.parsed[self.tu.name] = self
+ Parser.parseStack.append(Parser.current)
+ Parser.current = self
+
+ try:
+ ast = self.parser.parse(input=input, lexer=self.lexer, debug=self.debug)
+ finally:
+ Parser.current = Parser.parseStack.pop()
+
+ return ast
+
+ def resolveIncludePath(self, filepath):
+ """Return the absolute path from which the possibly partial
+ |filepath| should be read, or |None| if |filepath| cannot be located."""
+ for incdir in self.includedirs + [""]:
+ realpath = os.path.join(incdir, filepath)
+ if os.path.isfile(realpath):
+ return os.path.abspath(realpath)
+ return None
+
+ # returns a GCC-style string representation of the include stack.
+ # e.g.,
+ # in file included from 'foo.ipdl', line 120:
+ # in file included from 'bar.ipd', line 12:
+ # which can be printed above a proper error message or warning
+ @staticmethod
+ def includeStackString():
+ s = ""
+ for parse in Parser.parseStack[1:]:
+ s += " in file included from `%s', line %d:\n" % (
+ parse.loc.filename,
+ parse.loc.lineno,
+ )
+ return s
+
+
+def locFromTok(p, num):
+ return Loc(Parser.current.filename, p.lineno(num))
+
+
+# -----------------------------------------------------------------------------
+
+reserved = set(
+ (
+ "async",
+ "both",
+ "child",
+ "class",
+ "from",
+ "include",
+ "intr",
+ "manager",
+ "manages",
+ "namespace",
+ "nullable",
+ "or",
+ "parent",
+ "protocol",
+ "returns",
+ "struct",
+ "sync",
+ "union",
+ "UniquePtr",
+ "using",
+ )
+)
+tokens = [
+ "COLONCOLON",
+ "ID",
+ "STRING",
+] + [r.upper() for r in reserved]
+
+t_COLONCOLON = "::"
+
+literals = "(){}[]<>;:,?="
+t_ignore = " \f\t\v"
+
+
+def t_linecomment(t):
+ r"//[^\n]*"
+
+
+def t_multilinecomment(t):
+ r"/\*(\n|.)*?\*/"
+ t.lexer.lineno += t.value.count("\n")
+
+
+def t_NL(t):
+ r"(?:\r\n|\n|\n)+"
+ t.lexer.lineno += len(t.value)
+
+
+def t_ID(t):
+ r"[a-zA-Z_][a-zA-Z0-9_]*"
+ if t.value in reserved:
+ t.type = t.value.upper()
+ return t
+
+
+def t_STRING(t):
+ r'"[^"\n]*"'
+ t.value = StringLiteral(Loc(Parser.current.filename, t.lineno), t.value[1:-1])
+ return t
+
+
+def t_error(t):
+ _error(
+ Loc(Parser.current.filename, t.lineno),
+ "lexically invalid characters `%s",
+ t.value,
+ )
+
+
+# -----------------------------------------------------------------------------
+
+
+def p_TranslationUnit(p):
+ """TranslationUnit : Preamble NamespacedStuff"""
+ tu = Parser.current.tu
+ tu.loc = Loc(tu.filename)
+ for stmt in p[1]:
+ if isinstance(stmt, CxxInclude):
+ tu.addCxxInclude(stmt)
+ elif isinstance(stmt, Include):
+ tu.addInclude(stmt)
+ elif isinstance(stmt, UsingStmt):
+ tu.addUsingStmt(stmt)
+ else:
+ assert 0
+
+ for thing in p[2]:
+ if isinstance(thing, StructDecl):
+ tu.addStructDecl(thing)
+ elif isinstance(thing, UnionDecl):
+ tu.addUnionDecl(thing)
+ elif isinstance(thing, Protocol):
+ if tu.protocol is not None:
+ _error(thing.loc, "only one protocol definition per file")
+ tu.protocol = thing
+ else:
+ assert 0
+
+ # The "canonical" namespace of the tu, what it's considered to be
+ # in for the purposes of C++: |#include "foo/bar/TU.h"|
+ if tu.protocol:
+ assert tu.filetype == "protocol"
+ tu.namespaces = tu.protocol.namespaces
+ tu.name = tu.protocol.name
+ else:
+ assert tu.filetype == "header"
+ # There's not really a canonical "thing" in headers. So
+ # somewhat arbitrarily use the namespace of the last
+ # interesting thing that was declared.
+ for thing in reversed(tu.structsAndUnions):
+ tu.namespaces = thing.namespaces
+ break
+
+ p[0] = tu
+
+
+# --------------------
+# Preamble
+
+
+def p_Preamble(p):
+ """Preamble : Preamble PreambleStmt ';'
+ |"""
+ if 1 == len(p):
+ p[0] = []
+ else:
+ p[1].append(p[2])
+ p[0] = p[1]
+
+
+def p_PreambleStmt(p):
+ """PreambleStmt : CxxIncludeStmt
+ | IncludeStmt
+ | UsingStmt"""
+ p[0] = p[1]
+
+
+def p_CxxIncludeStmt(p):
+ """CxxIncludeStmt : INCLUDE STRING"""
+ p[0] = CxxInclude(locFromTok(p, 1), p[2].value)
+
+
+def p_IncludeStmt(p):
+ """IncludeStmt : INCLUDE PROTOCOL ID
+ | INCLUDE ID"""
+ loc = locFromTok(p, 1)
+
+ Parser.current.loc = loc
+ if 4 == len(p):
+ id = p[3]
+ type = "protocol"
+ else:
+ id = p[2]
+ type = "header"
+ inc = Include(loc, type, id)
+
+ path = Parser.current.resolveIncludePath(inc.file)
+ if path is None:
+ raise ParseError(loc, "can't locate include file `%s'" % (inc.file))
+
+ inc.tu = Parser(type, id).parse(open(path).read(), path, Parser.current.includedirs)
+ p[0] = inc
+
+
+def p_UsingKind(p):
+ """UsingKind : CLASS
+ | STRUCT
+ |"""
+ p[0] = p[1] if 2 == len(p) else None
+
+
+def p_UsingStmt(p):
+ """UsingStmt : Attributes USING UsingKind CxxType FROM STRING"""
+ p[0] = UsingStmt(
+ locFromTok(p, 2),
+ attributes=p[1],
+ kind=p[3],
+ cxxTypeSpec=p[4],
+ cxxHeader=p[6].value,
+ )
+
+
+# --------------------
+# Namespaced stuff
+
+
+def p_NamespacedStuff(p):
+ """NamespacedStuff : NamespacedStuff NamespaceThing
+ | NamespaceThing"""
+ if 2 == len(p):
+ p[0] = p[1]
+ else:
+ p[1].extend(p[2])
+ p[0] = p[1]
+
+
+def p_NamespaceThing(p):
+ """NamespaceThing : NAMESPACE ID '{' NamespacedStuff '}'
+ | StructDecl
+ | UnionDecl
+ | ProtocolDefn"""
+ if 2 == len(p):
+ p[0] = [p[1]]
+ else:
+ for thing in p[4]:
+ thing.addOuterNamespace(Namespace(locFromTok(p, 1), p[2]))
+ p[0] = p[4]
+
+
+def p_StructDecl(p):
+ """StructDecl : Attributes STRUCT ID '{' StructFields '}' ';'
+ | Attributes STRUCT ID '{' '}' ';'"""
+ if 8 == len(p):
+ p[0] = StructDecl(locFromTok(p, 2), p[3], p[5], p[1])
+ else:
+ p[0] = StructDecl(locFromTok(p, 2), p[3], [], p[1])
+
+
+def p_StructFields(p):
+ """StructFields : StructFields StructField ';'
+ | StructField ';'"""
+ if 3 == len(p):
+ p[0] = [p[1]]
+ else:
+ p[1].append(p[2])
+ p[0] = p[1]
+
+
+def p_StructField(p):
+ """StructField : Type ID"""
+ p[0] = StructField(locFromTok(p, 1), p[1], p[2])
+
+
+def p_UnionDecl(p):
+ """UnionDecl : Attributes UNION ID '{' ComponentTypes '}' ';'"""
+ p[0] = UnionDecl(locFromTok(p, 2), p[3], p[5], p[1])
+
+
+def p_ComponentTypes(p):
+ """ComponentTypes : ComponentTypes Type ';'
+ | Type ';'"""
+ if 3 == len(p):
+ p[0] = [p[1]]
+ else:
+ p[1].append(p[2])
+ p[0] = p[1]
+
+
+def p_ProtocolDefn(p):
+ """ProtocolDefn : Attributes OptionalSendSemantics \
+ PROTOCOL ID '{' ProtocolBody '}' ';'"""
+ protocol = p[6]
+ protocol.loc = locFromTok(p, 3)
+ protocol.name = p[4]
+ protocol.attributes = p[1]
+ protocol.sendSemantics = p[2]
+ p[0] = protocol
+
+ if Parser.current.type == "header":
+ _error(
+ protocol.loc,
+ "can't define a protocol in a header. Do it in a protocol spec instead.",
+ )
+
+
+def p_ProtocolBody(p):
+ """ProtocolBody : ManagersStmtOpt"""
+ p[0] = p[1]
+
+
+# --------------------
+# manager/manages stmts
+
+
+def p_ManagersStmtOpt(p):
+ """ManagersStmtOpt : ManagersStmt ManagesStmtsOpt
+ | ManagesStmtsOpt"""
+ if 2 == len(p):
+ p[0] = p[1]
+ else:
+ p[2].managers = p[1]
+ p[0] = p[2]
+
+
+def p_ManagersStmt(p):
+ """ManagersStmt : MANAGER ManagerList ';'"""
+ if 1 == len(p):
+ p[0] = []
+ else:
+ p[0] = p[2]
+
+
+def p_ManagerList(p):
+ """ManagerList : ID
+ | ManagerList OR ID"""
+ if 2 == len(p):
+ p[0] = [Manager(locFromTok(p, 1), p[1])]
+ else:
+ p[1].append(Manager(locFromTok(p, 3), p[3]))
+ p[0] = p[1]
+
+
+def p_ManagesStmtsOpt(p):
+ """ManagesStmtsOpt : ManagesStmt ManagesStmtsOpt
+ | MessageDeclsOpt"""
+ if 2 == len(p):
+ p[0] = p[1]
+ else:
+ p[2].managesStmts.insert(0, p[1])
+ p[0] = p[2]
+
+
+def p_ManagesStmt(p):
+ """ManagesStmt : MANAGES ID ';'"""
+ p[0] = ManagesStmt(locFromTok(p, 1), p[2])
+
+
+# --------------------
+# Message decls
+
+
+def p_MessageDeclsOpt(p):
+ """MessageDeclsOpt : MessageDeclThing MessageDeclsOpt
+ |"""
+ if 1 == len(p):
+ # we fill in |loc| in the Protocol rule
+ p[0] = Protocol(None)
+ else:
+ p[2].messageDecls.insert(0, p[1])
+ p[0] = p[2]
+
+
+def p_MessageDeclThing(p):
+ """MessageDeclThing : MessageDirectionLabel ':' MessageDecl ';'
+ | MessageDecl ';'"""
+ if 3 == len(p):
+ p[0] = p[1]
+ else:
+ p[0] = p[3]
+
+
+def p_MessageDirectionLabel(p):
+ """MessageDirectionLabel : PARENT
+ | CHILD
+ | BOTH"""
+ if p[1] == "parent":
+ Parser.current.direction = IN
+ elif p[1] == "child":
+ Parser.current.direction = OUT
+ elif p[1] == "both":
+ Parser.current.direction = INOUT
+ else:
+ assert 0
+
+
+def p_MessageDecl(p):
+ """MessageDecl : Attributes SendSemantics MessageBody"""
+ msg = p[3]
+ msg.attributes = p[1]
+ msg.sendSemantics = p[2]
+
+ if Parser.current.direction is None:
+ _error(msg.loc, "missing message direction")
+ msg.direction = Parser.current.direction
+
+ p[0] = msg
+
+
+def p_MessageBody(p):
+ """MessageBody : ID MessageInParams MessageOutParams"""
+ # FIXME/cjones: need better loc info: use one of the quals
+ name = p[1]
+ msg = MessageDecl(locFromTok(p, 1))
+ msg.name = name
+ msg.addInParams(p[2])
+ msg.addOutParams(p[3])
+
+ p[0] = msg
+
+
+def p_MessageInParams(p):
+ """MessageInParams : '(' ParamList ')'"""
+ p[0] = p[2]
+
+
+def p_MessageOutParams(p):
+ """MessageOutParams : RETURNS '(' ParamList ')'
+ |"""
+ if 1 == len(p):
+ p[0] = []
+ else:
+ p[0] = p[3]
+
+
+# --------------------
+# Attributes
+def p_Attributes(p):
+ """Attributes : '[' AttributeList ']'
+ |"""
+ p[0] = {}
+ if 4 == len(p):
+ for attr in p[2]:
+ if attr.name in p[0]:
+ _error(attr.loc, "Repeated extended attribute `%s'", attr.name)
+ p[0][attr.name] = attr
+
+
+def p_AttributeList(p):
+ """AttributeList : Attribute ',' AttributeList
+ | Attribute"""
+ p[0] = [p[1]]
+ if 4 == len(p):
+ p[0] += p[3]
+
+
+def p_Attribute(p):
+ """Attribute : ID AttributeValue"""
+ p[0] = Attribute(locFromTok(p, 1), p[1], p[2])
+
+
+def p_AttributeValue(p):
+ """AttributeValue : '=' ID
+ | '=' STRING
+ |"""
+ if 1 == len(p):
+ p[0] = None
+ else:
+ p[0] = p[2]
+
+
+def p_SendSemantics(p):
+ """SendSemantics : ASYNC
+ | SYNC
+ | INTR"""
+ if p[1] == "async":
+ p[0] = ASYNC
+ elif p[1] == "sync":
+ p[0] = SYNC
+ else:
+ assert p[1] == "intr"
+ p[0] = INTR
+
+
+def p_OptionalSendSemantics(p):
+ """OptionalSendSemantics : SendSemantics
+ |"""
+ if 2 == len(p):
+ p[0] = p[1]
+ else:
+ p[0] = ASYNC
+
+
+# --------------------
+# Minor stuff
+
+
+def p_ParamList(p):
+ """ParamList : ParamList ',' Param
+ | Param
+ |"""
+ if 1 == len(p):
+ p[0] = []
+ elif 2 == len(p):
+ p[0] = [p[1]]
+ else:
+ p[1].append(p[3])
+ p[0] = p[1]
+
+
+def p_Param(p):
+ """Param : Attributes Type ID"""
+ p[0] = Param(locFromTok(p, 2), p[2], p[3], p[1])
+
+
+def p_Type(p):
+ """Type : MaybeNullable BasicType"""
+ # only some types are nullable; we check this in the type checker
+ p[2].nullable = p[1]
+ p[0] = p[2]
+
+
+def p_BasicType(p):
+ """BasicType : CxxID
+ | CxxID '[' ']'
+ | CxxID '?'
+ | CxxUniquePtrInst"""
+ # ID == CxxType; we forbid qnames here,
+ # in favor of the |using| declaration
+ if not isinstance(p[1], TypeSpec):
+ assert (len(p[1]) == 2) or (len(p[1]) == 3)
+ if 2 == len(p[1]):
+ # p[1] is CxxID. isunique = False
+ p[1] = p[1] + (False,)
+ loc, id, isunique = p[1]
+ p[1] = TypeSpec(loc, id)
+ p[1].uniqueptr = isunique
+ if 4 == len(p):
+ p[1].array = True
+ if 3 == len(p):
+ p[1].maybe = True
+ p[0] = p[1]
+
+
+def p_MaybeNullable(p):
+ """MaybeNullable : NULLABLE
+ |"""
+ p[0] = 2 == len(p)
+
+
+# --------------------
+# C++ stuff
+
+
+def p_CxxType(p):
+ """CxxType : QualifiedID
+ | CxxID"""
+ if isinstance(p[1], QualifiedId):
+ p[0] = p[1]
+ else:
+ loc, id = p[1]
+ p[0] = QualifiedId(loc, id)
+
+
+def p_QualifiedID(p):
+ """QualifiedID : QualifiedID COLONCOLON CxxID
+ | CxxID COLONCOLON CxxID"""
+ if isinstance(p[1], QualifiedId):
+ loc, id = p[3]
+ p[1].qualify(id)
+ p[0] = p[1]
+ else:
+ loc1, id1 = p[1]
+ _, id2 = p[3]
+ p[0] = QualifiedId(loc1, id2, [id1])
+
+
+def p_CxxID(p):
+ """CxxID : ID
+ | CxxTemplateInst"""
+ if isinstance(p[1], tuple):
+ p[0] = p[1]
+ else:
+ p[0] = (locFromTok(p, 1), str(p[1]))
+
+
+def p_CxxTemplateInst(p):
+ """CxxTemplateInst : ID '<' ID '>'"""
+ p[0] = (locFromTok(p, 1), str(p[1]) + "<" + str(p[3]) + ">")
+
+
+def p_CxxUniquePtrInst(p):
+ """CxxUniquePtrInst : UNIQUEPTR '<' ID '>'"""
+ p[0] = (locFromTok(p, 1), str(p[3]), True)
+
+
+def p_error(t):
+ lineno, value = _safeLinenoValue(t)
+ _error(Loc(Parser.current.filename, lineno), "bad syntax near `%s'", value)
diff --git a/ipc/ipdl/ipdl/type.py b/ipc/ipdl/ipdl/type.py
new file mode 100644
index 0000000000..3f091f0dd6
--- /dev/null
+++ b/ipc/ipdl/ipdl/type.py
@@ -0,0 +1,1764 @@
+# vim: set ts=4 sw=4 tw=99 et:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import os
+import sys
+
+from ipdl.ast import CxxInclude, Decl, Loc, QualifiedId, StructDecl
+from ipdl.ast import UnionDecl, UsingStmt, Visitor, StringLiteral
+from ipdl.ast import ASYNC, SYNC, INTR
+from ipdl.ast import IN, OUT, INOUT
+from ipdl.ast import NOT_NESTED, INSIDE_SYNC_NESTED, INSIDE_CPOW_NESTED
+from ipdl.ast import priorityList
+import ipdl.builtin as builtin
+from ipdl.util import hash_str
+
+# Used to get the list of Gecko process types
+# xpcom/geckoprocesstypes_generator/geckoprocesstypes/__init__.py
+import geckoprocesstypes
+
+_DELETE_MSG = "__delete__"
+
+
+class TypeVisitor:
+ def __init__(self):
+ self.visited = set()
+
+ def defaultVisit(self, node, *args):
+ raise Exception(
+ "INTERNAL ERROR: no visitor for node type `%s'" % (node.__class__.__name__)
+ )
+
+ def visitVoidType(self, v, *args):
+ pass
+
+ def visitBuiltinCType(self, b, *args):
+ pass
+
+ def visitImportedCxxType(self, t, *args):
+ pass
+
+ def visitMessageType(self, m, *args):
+ for param in m.params:
+ param.accept(self, *args)
+ for ret in m.returns:
+ ret.accept(self, *args)
+ if m.cdtype is not None:
+ m.cdtype.accept(self, *args)
+
+ def visitProtocolType(self, p, *args):
+ # NB: don't visit manager and manages. a naive default impl
+ # could result in an infinite loop
+ pass
+
+ def visitActorType(self, a, *args):
+ a.protocol.accept(self, *args)
+
+ def visitStructType(self, s, *args):
+ if s in self.visited:
+ return
+
+ self.visited.add(s)
+ for field in s.fields:
+ field.accept(self, *args)
+
+ def visitUnionType(self, u, *args):
+ if u in self.visited:
+ return
+
+ self.visited.add(u)
+ for component in u.components:
+ component.accept(self, *args)
+
+ def visitArrayType(self, a, *args):
+ a.basetype.accept(self, *args)
+
+ def visitMaybeType(self, m, *args):
+ m.basetype.accept(self, *args)
+
+ def visitUniquePtrType(self, m, *args):
+ m.basetype.accept(self, *args)
+
+ def visitNotNullType(self, m, *args):
+ m.basetype.accept(self, *args)
+
+ def visitShmemType(self, s, *args):
+ pass
+
+ def visitByteBufType(self, s, *args):
+ pass
+
+ def visitShmemChmodType(self, c, *args):
+ c.shmem.accept(self)
+
+ def visitFDType(self, s, *args):
+ pass
+
+ def visitEndpointType(self, s, *args):
+ pass
+
+ def visitManagedEndpointType(self, s, *args):
+ pass
+
+
+class Type:
+ def __cmp__(self, o):
+ return cmp(self.fullname(), o.fullname())
+
+ def __eq__(self, o):
+ return self.__class__ == o.__class__ and self.fullname() == o.fullname()
+
+ def __hash__(self):
+ return hash_str(self.fullname())
+
+ # Is this a C++ type?
+ def isCxx(self):
+ return False
+
+ # Is this an IPDL type?
+
+ def isIPDL(self):
+ return False
+
+ # Is this type neither compound nor an array?
+
+ def isAtom(self):
+ return False
+
+ def isRefcounted(self):
+ return False
+
+ # Should this type be wrapped in `NotNull<T>` unless marked `nullable`?
+
+ def supportsNullable(self):
+ return False
+
+ def typename(self):
+ return self.__class__.__name__
+
+ def name(self):
+ raise NotImplementedError()
+
+ def fullname(self):
+ raise NotImplementedError()
+
+ def accept(self, visitor, *args):
+ visit = getattr(visitor, "visit" + self.__class__.__name__, None)
+ if visit is None:
+ return getattr(visitor, "defaultVisit")(self, *args)
+ return visit(self, *args)
+
+
+class VoidType(Type):
+ def isCxx(self):
+ return True
+
+ def isIPDL(self):
+ return False
+
+ def isAtom(self):
+ return True
+
+ def name(self):
+ return "void"
+
+ def fullname(self):
+ return "void"
+
+
+VOID = VoidType()
+
+# --------------------
+
+
+class BuiltinCType(Type):
+ def __init__(self, name):
+ self._name = name
+
+ def isCxx(self):
+ return True
+
+ def isAtom(self):
+ return True
+
+ def isSendMoveOnly(self):
+ return False
+
+ def isDataMoveOnly(self):
+ return False
+
+ def name(self):
+ return self._name
+
+ def fullname(self):
+ return self._name
+
+
+class ImportedCxxType(Type):
+ def __init__(self, qname, refcounted, sendmoveonly, datamoveonly):
+ assert isinstance(qname, QualifiedId)
+ self.loc = qname.loc
+ self.qname = qname
+ self.refcounted = refcounted
+ self.sendmoveonly = sendmoveonly
+ self.datamoveonly = datamoveonly
+
+ def isCxx(self):
+ return True
+
+ def isAtom(self):
+ return True
+
+ def isRefcounted(self):
+ return self.refcounted
+
+ def supportsNullable(self):
+ return self.refcounted
+
+ def isSendMoveOnly(self):
+ return self.sendmoveonly
+
+ def isDataMoveOnly(self):
+ return self.datamoveonly
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+# --------------------
+
+
+class IPDLType(Type):
+ def isIPDL(self):
+ return True
+
+ def isMessage(self):
+ return False
+
+ def isProtocol(self):
+ return False
+
+ def isActor(self):
+ return False
+
+ def isStruct(self):
+ return False
+
+ def isUnion(self):
+ return False
+
+ def isArray(self):
+ return False
+
+ def isMaybe(self):
+ return False
+
+ def isUniquePtr(self):
+ return False
+
+ def isNotNull(self):
+ return False
+
+ def isAtom(self):
+ return True
+
+ def isCompound(self):
+ return False
+
+ def isShmem(self):
+ return False
+
+ def isByteBuf(self):
+ return False
+
+ def isFD(self):
+ return False
+
+ def isEndpoint(self):
+ return False
+
+ def isManagedEndpoint(self):
+ return False
+
+ def hasBaseType(self):
+ return False
+
+
+class SendSemanticsType(IPDLType):
+ def __init__(self, nestedRange, sendSemantics):
+ self.nestedRange = nestedRange
+ self.sendSemantics = sendSemantics
+
+ def isAsync(self):
+ return self.sendSemantics == ASYNC
+
+ def isSync(self):
+ return self.sendSemantics == SYNC
+
+ def isInterrupt(self):
+ return self.sendSemantics is INTR
+
+ def sendSemanticsSatisfiedBy(self, greater):
+ def _unwrap(nr):
+ if isinstance(nr, dict):
+ return _unwrap(nr["nested"])
+ elif isinstance(nr, int):
+ return nr
+ else:
+ raise ValueError("Got unexpected nestedRange value: %s" % nr)
+
+ lesser = self
+ lnr0, gnr0, lnr1, gnr1 = (
+ _unwrap(lesser.nestedRange[0]),
+ _unwrap(greater.nestedRange[0]),
+ _unwrap(lesser.nestedRange[1]),
+ _unwrap(greater.nestedRange[1]),
+ )
+ if lnr0 < gnr0 or lnr1 > gnr1:
+ return False
+
+ # Protocols that use intr semantics are not allowed to use
+ # message nesting.
+ if greater.isInterrupt() and lesser.nestedRange != (NOT_NESTED, NOT_NESTED):
+ return False
+
+ if lesser.isAsync():
+ return True
+ elif lesser.isSync() and not greater.isAsync():
+ return True
+ elif greater.isInterrupt():
+ return True
+
+ return False
+
+
+class MessageType(SendSemanticsType):
+ def __init__(
+ self,
+ nested,
+ prio,
+ replyPrio,
+ sendSemantics,
+ direction,
+ ctor=False,
+ dtor=False,
+ cdtype=None,
+ compress=False,
+ tainted=False,
+ lazySend=False,
+ ):
+ assert not (ctor and dtor)
+ assert not (ctor or dtor) or cdtype is not None
+
+ SendSemanticsType.__init__(self, (nested, nested), sendSemantics)
+ self.nested = nested
+ self.prio = prio
+ self.replyPrio = replyPrio
+ self.direction = direction
+ self.params = []
+ self.returns = []
+ self.ctor = ctor
+ self.dtor = dtor
+ self.cdtype = cdtype
+ self.compress = compress
+ self.tainted = tainted
+ self.lazySend = lazySend
+
+ def isMessage(self):
+ return True
+
+ def isCtor(self):
+ return self.ctor
+
+ def isDtor(self):
+ return self.dtor
+
+ def constructedType(self):
+ return self.cdtype
+
+ def isIn(self):
+ return self.direction is IN
+
+ def isOut(self):
+ return self.direction is OUT
+
+ def isInout(self):
+ return self.direction is INOUT
+
+ def hasReply(self):
+ return len(self.returns) or self.isSync() or self.isInterrupt()
+
+ def hasImplicitActorParam(self):
+ return self.isCtor()
+
+
+class ProtocolType(SendSemanticsType):
+ def __init__(self, qname, nested, sendSemantics, refcounted, needsotherpid):
+ SendSemanticsType.__init__(self, (NOT_NESTED, nested), sendSemantics)
+ self.qname = qname
+ self.managers = [] # ProtocolType
+ self.manages = []
+ self.hasDelete = False
+ self.refcounted = refcounted
+ self.needsotherpid = needsotherpid
+
+ def isProtocol(self):
+ return True
+
+ def isRefcounted(self):
+ return self.refcounted
+
+ def hasOtherPid(self):
+ return all(top.needsotherpid for top in self.toplevels())
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+ def addManager(self, mgrtype):
+ assert mgrtype.isIPDL() and mgrtype.isProtocol()
+ self.managers.append(mgrtype)
+
+ def managedBy(self, mgr):
+ self.managers = list(mgr)
+
+ def toplevel(self):
+ if self.isToplevel():
+ return self
+ for mgr in self.managers:
+ if mgr is not self:
+ return mgr.toplevel()
+
+ def toplevels(self):
+ if self.isToplevel():
+ return [self]
+ toplevels = list()
+ for mgr in self.managers:
+ if mgr is not self:
+ toplevels.extend(mgr.toplevels())
+ return set(toplevels)
+
+ def isManagerOf(self, pt):
+ for managed in self.manages:
+ if pt is managed:
+ return True
+ return False
+
+ def isManagedBy(self, pt):
+ return pt in self.managers
+
+ def isManager(self):
+ return len(self.manages) > 0
+
+ def isManaged(self):
+ return 0 < len(self.managers)
+
+ def isToplevel(self):
+ return not self.isManaged()
+
+ def manager(self):
+ assert 1 == len(self.managers)
+ for mgr in self.managers:
+ return mgr
+
+
+class ActorType(IPDLType):
+ def __init__(self, protocol):
+ self.protocol = protocol
+
+ def isActor(self):
+ return True
+
+ def isRefcounted(self):
+ return self.protocol.isRefcounted()
+
+ def supportsNullable(self):
+ return True
+
+ def name(self):
+ return self.protocol.name()
+
+ def fullname(self):
+ return self.protocol.fullname()
+
+
+class _CompoundType(IPDLType):
+ def __init__(self):
+ self.defined = False # bool
+ self.mutualRec = set() # set(_CompoundType | ArrayType)
+
+ def isAtom(self):
+ return False
+
+ def isCompound(self):
+ return True
+
+ def itercomponents(self):
+ raise Exception('"pure virtual" method')
+
+ def mutuallyRecursiveWith(self, t, exploring=None):
+ """|self| is mutually recursive with |t| iff |self| and |t|
+ are in a cycle in the type graph rooted at |self|. This function
+ looks for such a cycle and returns True if found."""
+ if exploring is None:
+ exploring = set()
+
+ if t.isAtom():
+ return False
+ elif t is self or t in self.mutualRec:
+ return True
+ elif t.hasBaseType():
+ isrec = self.mutuallyRecursiveWith(t.basetype, exploring)
+ if isrec:
+ self.mutualRec.add(t)
+ return isrec
+ elif t in exploring:
+ return False
+
+ exploring.add(t)
+ for c in t.itercomponents():
+ if self.mutuallyRecursiveWith(c, exploring):
+ self.mutualRec.add(c)
+ return True
+ exploring.remove(t)
+
+ return False
+
+
+class StructType(_CompoundType):
+ def __init__(self, qname, fields):
+ _CompoundType.__init__(self)
+ self.qname = qname
+ self.fields = fields # [ Type ]
+
+ def isStruct(self):
+ return True
+
+ def itercomponents(self):
+ for f in self.fields:
+ yield f
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class UnionType(_CompoundType):
+ def __init__(self, qname, components):
+ _CompoundType.__init__(self)
+ self.qname = qname
+ self.components = components # [ Type ]
+
+ def isUnion(self):
+ return True
+
+ def itercomponents(self):
+ for c in self.components:
+ yield c
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class ArrayType(IPDLType):
+ def __init__(self, basetype):
+ self.basetype = basetype
+
+ def isAtom(self):
+ return False
+
+ def isArray(self):
+ return True
+
+ def hasBaseType(self):
+ return True
+
+ def name(self):
+ return self.basetype.name() + "[]"
+
+ def fullname(self):
+ return self.basetype.fullname() + "[]"
+
+
+class MaybeType(IPDLType):
+ def __init__(self, basetype):
+ self.basetype = basetype
+
+ def isAtom(self):
+ return False
+
+ def isMaybe(self):
+ return True
+
+ def hasBaseType(self):
+ return True
+
+ def name(self):
+ return self.basetype.name() + "?"
+
+ def fullname(self):
+ return self.basetype.fullname() + "?"
+
+
+class ShmemType(IPDLType):
+ def __init__(self, qname):
+ self.qname = qname
+
+ def isShmem(self):
+ return True
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class ByteBufType(IPDLType):
+ def __init__(self, qname):
+ self.qname = qname
+
+ def isByteBuf(self):
+ return True
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class FDType(IPDLType):
+ def __init__(self, qname):
+ self.qname = qname
+
+ def isFD(self):
+ return True
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class EndpointType(IPDLType):
+ def __init__(self, qname, actor):
+ self.qname = qname
+ self.actor = actor
+
+ def isEndpoint(self):
+ return True
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class ManagedEndpointType(IPDLType):
+ def __init__(self, qname, actor):
+ self.qname = qname
+ self.actor = actor
+
+ def isManagedEndpoint(self):
+ return True
+
+ def name(self):
+ return self.qname.baseid
+
+ def fullname(self):
+ return str(self.qname)
+
+
+class UniquePtrType(IPDLType):
+ def __init__(self, basetype):
+ self.basetype = basetype
+
+ def isAtom(self):
+ return False
+
+ def isUniquePtr(self):
+ return True
+
+ def hasBaseType(self):
+ return True
+
+ def name(self):
+ return "UniquePtr<" + self.basetype.name() + ">"
+
+ def fullname(self):
+ return "mozilla::UniquePtr<" + self.basetype.fullname() + ">"
+
+
+class NotNullType(IPDLType):
+ def __init__(self, basetype):
+ self.basetype = basetype
+
+ def isAtom(self):
+ return False
+
+ def isNotNull(self):
+ return True
+
+ def hasBaseType(self):
+ return True
+
+ def name(self):
+ return "NotNull<" + self.basetype.name() + ">"
+
+ def fullname(self):
+ return "mozilla::NotNull<" + self.basetype.fullname() + ">"
+
+
+def iteractortypes(t, visited=None):
+ """Iterate over any actor(s) buried in |type|."""
+ if visited is None:
+ visited = set()
+
+ # XXX |yield| semantics makes it hard to use TypeVisitor
+ if not t.isIPDL():
+ return
+ elif t.isActor():
+ yield t
+ elif t.hasBaseType():
+ for actor in iteractortypes(t.basetype, visited):
+ yield actor
+ elif t.isCompound() and t not in visited:
+ visited.add(t)
+ for c in t.itercomponents():
+ for actor in iteractortypes(c, visited):
+ yield actor
+
+
+def hasshmem(type):
+ """Return true iff |type| is shmem or has it buried within."""
+
+ class found(BaseException):
+ pass
+
+ class findShmem(TypeVisitor):
+ def visitShmemType(self, s):
+ raise found()
+
+ try:
+ type.accept(findShmem())
+ except found:
+ return True
+ return False
+
+
+# --------------------
+_builtinloc = Loc("<builtin>", 0)
+
+
+def makeBuiltinUsing(tname):
+ quals = tname.split("::")
+ base = quals.pop()
+ quals = quals[0:]
+ return UsingStmt(_builtinloc, QualifiedId(_builtinloc, base, quals))
+
+
+builtinUsing = [makeBuiltinUsing(t) for t in builtin.Types]
+builtinHeaderIncludes = [CxxInclude(_builtinloc, f) for f in builtin.HeaderIncludes]
+
+
+def errormsg(loc, fmt, *args):
+ while not isinstance(loc, Loc):
+ if loc is None:
+ loc = Loc.NONE
+ else:
+ loc = loc.loc
+ return "%s: error: %s" % (str(loc), fmt % args)
+
+
+# --------------------
+
+
+class SymbolTable:
+ def __init__(self, errors):
+ self.errors = errors
+ self.scopes = [{}] # stack({})
+ self.currentScope = self.scopes[0]
+
+ def enterScope(self):
+ assert isinstance(self.scopes[0], dict)
+ assert isinstance(self.currentScope, dict)
+
+ self.scopes.append({})
+ self.currentScope = self.scopes[-1]
+
+ def exitScope(self):
+ symtab = self.scopes.pop()
+ assert self.currentScope is symtab
+
+ self.currentScope = self.scopes[-1]
+
+ assert isinstance(self.scopes[0], dict)
+ assert isinstance(self.currentScope, dict)
+
+ def lookup(self, sym):
+ # NB: since IPDL doesn't allow any aliased names of different types,
+ # it doesn't matter in which order we walk the scope chain to resolve
+ # |sym|
+ for scope in self.scopes:
+ decl = scope.get(sym, None)
+ if decl is not None:
+ return decl
+ return None
+
+ def declare(self, decl):
+ assert decl.progname or decl.shortname or decl.fullname
+ assert decl.loc
+ assert decl.type
+
+ def tryadd(name):
+ olddecl = self.lookup(name)
+ if olddecl is not None:
+ self.errors.append(
+ errormsg(
+ decl.loc,
+ "redeclaration of symbol `%s', first declared at %s",
+ name,
+ olddecl.loc,
+ )
+ )
+ return
+ self.currentScope[name] = decl
+ decl.scope = self.currentScope
+
+ if decl.progname:
+ tryadd(decl.progname)
+ if decl.shortname:
+ tryadd(decl.shortname)
+ if decl.fullname:
+ tryadd(decl.fullname)
+
+
+class TypeCheck:
+ """This pass sets the .decl attribute of AST nodes for which that is relevant;
+ a decl says where, with what type, and under what name(s) a node was
+ declared.
+
+ With this information, it type checks the AST."""
+
+ def __init__(self):
+ # NB: no IPDL compile will EVER print a warning. A program has
+ # one of two attributes: it is either well typed, or not well typed.
+ self.errors = [] # [ string ]
+
+ def check(self, tu, errout=sys.stderr):
+ def runpass(tcheckpass):
+ tu.accept(tcheckpass)
+ if len(self.errors):
+ self.reportErrors(errout)
+ return False
+ return True
+
+ # tag each relevant node with "decl" information, giving type, name,
+ # and location of declaration
+ if not runpass(GatherDecls(builtinUsing, self.errors)):
+ return False
+
+ # now that the nodes have decls, type checking is much easier.
+ if not runpass(CheckTypes(self.errors)):
+ return False
+
+ return True
+
+ def reportErrors(self, errout):
+ for error in self.errors:
+ print(error, file=errout)
+
+
+class TcheckVisitor(Visitor):
+ def __init__(self, errors):
+ self.errors = errors
+
+ def error(self, loc, fmt, *args):
+ self.errors.append(errormsg(loc, fmt, *args))
+
+
+class GatherDecls(TcheckVisitor):
+ def __init__(self, builtinUsing, errors):
+ TcheckVisitor.__init__(self, errors)
+
+ # |self.symtab| is the symbol table for the translation unit
+ # currently being visited
+ self.symtab = None
+ self.builtinUsing = builtinUsing
+
+ def declare(
+ self, loc, type, shortname=None, fullname=None, progname=None, attributes={}
+ ):
+ d = Decl(loc)
+ d.type = type
+ d.progname = progname
+ d.shortname = shortname
+ d.fullname = fullname
+ d.attributes = attributes
+ self.symtab.declare(d)
+ return d
+
+ # Check that only attributes allowed by an attribute spec are present
+ # within the given attribute dictionary. The spec value may be either
+ # `None`, for a valueless attribute, a list of valid attribute values, or a
+ # callable which returns a truthy value if the attribute is valid.
+ def checkAttributes(self, attributes, spec):
+ for attr in attributes.values():
+ if attr.name not in spec:
+ self.error(attr.loc, "unknown attribute `%s'", attr.name)
+ continue
+
+ aspec = spec[attr.name]
+ if aspec is None:
+ if attr.value is not None:
+ self.error(
+ attr.loc,
+ "unexpected value for valueless attribute `%s'",
+ attr.name,
+ )
+ elif isinstance(aspec, (list, tuple)):
+ if not any(
+ isinstance(attr.value, s)
+ if isinstance(s, type)
+ else attr.value == s
+ for s in aspec
+ ):
+ self.error(
+ attr.loc,
+ "invalid value for attribute `%s', expected one of: %s",
+ attr.name,
+ ", ".join(
+ s.__name__ if isinstance(s, type) else str(s) for s in aspec
+ ),
+ )
+ elif callable(aspec):
+ if not aspec(attr.value):
+ self.error(attr.loc, "invalid value for attribute `%s'", attr.name)
+ else:
+ raise Exception("INTERNAL ERROR: Invalid attribute spec")
+
+ def visitTranslationUnit(self, tu):
+ # all TranslationUnits declare symbols in global scope
+ if hasattr(tu, "visited"):
+ return
+ tu.visited = True
+ savedSymtab = self.symtab
+ self.symtab = SymbolTable(self.errors)
+
+ # pretend like the translation unit "using"-ed these for the
+ # sake of type checking and C++ code generation
+ tu.builtinUsing = self.builtinUsing
+
+ # for everyone's sanity, enforce that the filename and tu name
+ # match
+ basefilename = os.path.basename(tu.filename)
+ expectedfilename = "%s.ipdl" % (tu.name)
+ if not tu.protocol:
+ # header
+ expectedfilename += "h"
+ if basefilename != expectedfilename:
+ self.error(
+ tu.loc,
+ "expected file for translation unit `%s' to be named `%s'; instead it's named `%s'", # NOQA: E501
+ tu.name,
+ expectedfilename,
+ basefilename,
+ )
+
+ if tu.protocol:
+ assert tu.name == tu.protocol.name
+
+ p = tu.protocol
+
+ proc_options = [
+ "any",
+ "anychild", # non-Parent process
+ "anydom", # Parent or Content process
+ "compositor", # Parent or GPU process
+ ] + [p.proc_typename for p in geckoprocesstypes.process_types]
+
+ self.checkAttributes(
+ p.attributes,
+ {
+ "ManualDealloc": None,
+ "NestedUpTo": ("not", "inside_sync", "inside_cpow"),
+ "NeedsOtherPid": None,
+ "ChildImpl": ("virtual", StringLiteral),
+ "ParentImpl": ("virtual", StringLiteral),
+ "ChildProc": proc_options,
+ "ParentProc": proc_options,
+ },
+ )
+
+ # FIXME/cjones: it's a little weird and counterintuitive
+ # to put both the namespace and non-namespaced name in the
+ # global scope. try to figure out something better; maybe
+ # a type-neutral |using| that works for C++ and protocol
+ # types?
+ qname = p.qname()
+ fullname = str(qname)
+ p.decl = self.declare(
+ loc=p.loc,
+ type=ProtocolType(
+ qname,
+ p.nestedUpTo(),
+ p.sendSemantics,
+ "ManualDealloc" not in p.attributes,
+ "NeedsOtherPid" in p.attributes,
+ ),
+ shortname=p.name,
+ fullname=fullname,
+ )
+
+ p.parentEndpointDecl = self.declare(
+ loc=p.loc,
+ type=EndpointType(
+ QualifiedId(
+ p.loc, "Endpoint<" + fullname + "Parent>", ["mozilla", "ipc"]
+ ),
+ ActorType(p.decl.type),
+ ),
+ shortname="Endpoint<" + p.name + "Parent>",
+ )
+ p.childEndpointDecl = self.declare(
+ loc=p.loc,
+ type=EndpointType(
+ QualifiedId(
+ p.loc, "Endpoint<" + fullname + "Child>", ["mozilla", "ipc"]
+ ),
+ ActorType(p.decl.type),
+ ),
+ shortname="Endpoint<" + p.name + "Child>",
+ )
+
+ p.parentManagedEndpointDecl = self.declare(
+ loc=p.loc,
+ type=ManagedEndpointType(
+ QualifiedId(
+ p.loc,
+ "ManagedEndpoint<" + fullname + "Parent>",
+ ["mozilla", "ipc"],
+ ),
+ ActorType(p.decl.type),
+ ),
+ shortname="ManagedEndpoint<" + p.name + "Parent>",
+ )
+ p.childManagedEndpointDecl = self.declare(
+ loc=p.loc,
+ type=ManagedEndpointType(
+ QualifiedId(
+ p.loc,
+ "ManagedEndpoint<" + fullname + "Child>",
+ ["mozilla", "ipc"],
+ ),
+ ActorType(p.decl.type),
+ ),
+ shortname="ManagedEndpoint<" + p.name + "Child>",
+ )
+
+ # XXX ugh, this sucks. but we need this information to compute
+ # what friend decls we need in generated C++
+ p.decl.type._ast = p
+
+ # make sure we have decls for all dependent protocols
+ for pinc in tu.includes:
+ pinc.accept(self)
+
+ # declare imported (and builtin) C and C++ types
+ for ctype in builtin.CTypes:
+ self.declare(
+ loc=_builtinloc,
+ type=BuiltinCType(ctype),
+ shortname=ctype,
+ )
+ for using in tu.builtinUsing:
+ using.accept(self)
+ for using in tu.using:
+ using.accept(self)
+
+ # first pass to "forward-declare" all structs and unions in
+ # order to support recursive definitions
+ for su in tu.structsAndUnions:
+ self.declareStructOrUnion(su)
+
+ # second pass to check each definition
+ for su in tu.structsAndUnions:
+ su.accept(self)
+
+ if tu.protocol:
+ # grab symbols in the protocol itself
+ p.accept(self)
+
+ self.symtab = savedSymtab
+
+ def declareStructOrUnion(self, su):
+ if hasattr(su, "decl"):
+ self.symtab.declare(su.decl)
+ return
+
+ qname = su.qname()
+ fullname = str(qname)
+
+ if isinstance(su, StructDecl):
+ sutype = StructType(qname, [])
+ elif isinstance(su, UnionDecl):
+ sutype = UnionType(qname, [])
+ else:
+ assert 0 and "unknown type"
+
+ # XXX more suckage. this time for pickling structs/unions
+ # declared in headers.
+ sutype._ast = su
+
+ su.decl = self.declare(
+ loc=su.loc, type=sutype, shortname=su.name, fullname=fullname
+ )
+
+ def visitInclude(self, inc):
+ if inc.tu is None:
+ self.error(
+ inc.loc,
+ "(type checking here will be unreliable because of an earlier error)",
+ )
+ return
+ inc.tu.accept(self)
+ if inc.tu.protocol:
+ self.symtab.declare(inc.tu.protocol.decl)
+ self.symtab.declare(inc.tu.protocol.parentEndpointDecl)
+ self.symtab.declare(inc.tu.protocol.childEndpointDecl)
+ self.symtab.declare(inc.tu.protocol.parentManagedEndpointDecl)
+ self.symtab.declare(inc.tu.protocol.childManagedEndpointDecl)
+ else:
+ # This is a header. Import its "exported" globals into
+ # our scope.
+ for using in inc.tu.using:
+ using.accept(self)
+ for su in inc.tu.structsAndUnions:
+ self.declareStructOrUnion(su)
+
+ def visitStructDecl(self, sd):
+ # If we've already processed this struct, don't do it again.
+ if hasattr(sd, "visited"):
+ return
+
+ stype = sd.decl.type
+
+ self.symtab.enterScope()
+ sd.visited = True
+
+ self.checkAttributes(sd.attributes, {"Comparable": None})
+
+ for f in sd.fields:
+ ftypedecl = self.symtab.lookup(str(f.typespec))
+ if ftypedecl is None:
+ self.error(
+ f.loc,
+ "field `%s' of struct `%s' has unknown type `%s'",
+ f.name,
+ sd.name,
+ str(f.typespec),
+ )
+ continue
+
+ f.decl = self.declare(
+ loc=f.loc,
+ type=self._canonicalType(ftypedecl.type, f.typespec),
+ shortname=f.name,
+ fullname=None,
+ )
+ stype.fields.append(f.decl.type)
+
+ self.symtab.exitScope()
+
+ def visitUnionDecl(self, ud):
+ utype = ud.decl.type
+
+ # If we've already processed this union, don't do it again.
+ if len(utype.components):
+ return
+
+ self.checkAttributes(ud.attributes, {"Comparable": None})
+
+ for c in ud.components:
+ cdecl = self.symtab.lookup(str(c))
+ if cdecl is None:
+ self.error(
+ c.loc, "unknown component type `%s' of union `%s'", str(c), ud.name
+ )
+ continue
+ utype.components.append(self._canonicalType(cdecl.type, c))
+
+ def visitUsingStmt(self, using):
+ fullname = str(using.type)
+
+ self.checkAttributes(
+ using.attributes,
+ {
+ "MoveOnly": (None, "data", "send"),
+ "RefCounted": None,
+ },
+ )
+
+ if fullname == "::mozilla::ipc::Shmem":
+ ipdltype = ShmemType(using.type)
+ elif fullname == "::mozilla::ipc::ByteBuf":
+ ipdltype = ByteBufType(using.type)
+ elif fullname == "::mozilla::ipc::FileDescriptor":
+ ipdltype = FDType(using.type)
+ else:
+ ipdltype = ImportedCxxType(
+ using.type,
+ using.isRefcounted(),
+ using.isSendMoveOnly(),
+ using.isDataMoveOnly(),
+ )
+ existingType = self.symtab.lookup(ipdltype.fullname())
+ if existingType and existingType.fullname == ipdltype.fullname():
+ if ipdltype.isRefcounted() != existingType.type.isRefcounted():
+ self.error(
+ using.loc,
+ "inconsistent refcounted status of type `%s`",
+ str(using.type),
+ )
+ if (
+ ipdltype.isSendMoveOnly() != existingType.type.isSendMoveOnly()
+ or ipdltype.isDataMoveOnly() != existingType.type.isDataMoveOnly()
+ ):
+ self.error(
+ using.loc,
+ "inconsistent moveonly status of type `%s`",
+ str(using.type),
+ )
+ using.decl = existingType
+ return
+ using.decl = self.declare(
+ loc=using.loc,
+ type=ipdltype,
+ shortname=using.type.baseid,
+ fullname=fullname,
+ )
+
+ def visitProtocol(self, p):
+ # protocol scope
+ self.symtab.enterScope()
+
+ seenmgrs = set()
+ for mgr in p.managers:
+ if mgr.name in seenmgrs:
+ self.error(mgr.loc, "manager `%s' appears multiple times", mgr.name)
+ continue
+
+ seenmgrs.add(mgr.name)
+ mgr.of = p
+ mgr.accept(self)
+
+ for managed in p.managesStmts:
+ managed.manager = p
+ managed.accept(self)
+
+ setattr(self, "currentProtocolDecl", p.decl)
+ for msg in p.messageDecls:
+ msg.accept(self)
+ del self.currentProtocolDecl
+
+ p.decl.type.hasDelete = not not self.symtab.lookup(_DELETE_MSG)
+ if not (p.decl.type.hasDelete or p.decl.type.isToplevel()):
+ self.error(
+ p.loc,
+ "destructor declaration `%s(...)' required for managed protocol `%s'",
+ _DELETE_MSG,
+ p.name,
+ )
+
+ if not p.decl.type.isToplevel() and p.decl.type.needsotherpid:
+ self.error(p.loc, "[NeedsOtherPid] only applies to toplevel protocols")
+
+ if p.decl.type.isToplevel():
+ if not p.decl.type.isRefcounted():
+ self.error(p.loc, "Toplevel protocols cannot be [ManualDealloc]")
+
+ if "ChildProc" not in p.attributes:
+ self.error(p.loc, "Toplevel protocols must specify [ChildProc]")
+
+ if p.decl.type.isManager() and not p.decl.type.isRefcounted():
+ self.error(p.loc, "[ManualDealloc] protocols cannot be managers")
+
+ # FIXME/cjones declare all the little C++ thingies that will
+ # be generated. they're not relevant to IPDL itself, but
+ # those ("invisible") symbols can clash with others in the
+ # IPDL spec, and we'd like to catch those before C++ compilers
+ # are allowed to obfuscate the error
+
+ self.symtab.exitScope()
+
+ def visitManager(self, mgr):
+ mgrdecl = self.symtab.lookup(mgr.name)
+ pdecl = mgr.of.decl
+ assert pdecl
+
+ pname, mgrname = pdecl.shortname, mgr.name
+ loc = mgr.loc
+
+ if mgrdecl is None:
+ self.error(
+ loc,
+ "protocol `%s' referenced as |manager| of `%s' has not been declared",
+ mgrname,
+ pname,
+ )
+ elif not isinstance(mgrdecl.type, ProtocolType):
+ self.error(
+ loc,
+ "entity `%s' referenced as |manager| of `%s' is not of `protocol' type; instead it is of type `%s'", # NOQA: E501
+ mgrname,
+ pname,
+ mgrdecl.type.typename(),
+ )
+ else:
+ mgr.decl = mgrdecl
+ pdecl.type.addManager(mgrdecl.type)
+
+ def visitManagesStmt(self, mgs):
+ mgsdecl = self.symtab.lookup(mgs.name)
+ pdecl = mgs.manager.decl
+ assert pdecl
+
+ pname, mgsname = pdecl.shortname, mgs.name
+ loc = mgs.loc
+
+ if mgsdecl is None:
+ self.error(
+ loc,
+ "protocol `%s', managed by `%s', has not been declared",
+ mgsname,
+ pname,
+ )
+ elif not isinstance(mgsdecl.type, ProtocolType):
+ self.error(
+ loc,
+ "%s declares itself managing a non-`protocol' entity `%s' of type `%s'",
+ pname,
+ mgsname,
+ mgsdecl.type.typename(),
+ )
+ else:
+ mgs.decl = mgsdecl
+ pdecl.type.manages.append(mgsdecl.type)
+
+ def visitMessageDecl(self, md):
+ msgname = md.name
+ loc = md.loc
+
+ self.checkAttributes(
+ md.attributes,
+ {
+ "Tainted": None,
+ "Compress": (None, "all"),
+ "Priority": priorityList,
+ "ReplyPriority": priorityList,
+ "Nested": ("not", "inside_sync", "inside_cpow"),
+ "LegacyIntr": None,
+ "VirtualSendImpl": None,
+ "LazySend": None,
+ },
+ )
+
+ if md.sendSemantics is INTR and "LegacyIntr" not in md.attributes:
+ self.error(
+ loc,
+ "intr message `%s' allowed only with [LegacyIntr]; DO NOT USE IN SHIPPING CODE",
+ msgname,
+ )
+
+ if md.sendSemantics is INTR and "Priority" in md.attributes:
+ self.error(loc, "intr message `%s' cannot specify [Priority]", msgname)
+
+ if md.sendSemantics is INTR and "Nested" in md.attributes:
+ self.error(loc, "intr message `%s' cannot specify [Nested]", msgname)
+
+ if md.sendSemantics is not ASYNC and "LazySend" in md.attributes:
+ self.error(loc, "non-async message `%s' cannot specify [LazySend]", msgname)
+
+ if md.sendSemantics is not ASYNC and "ReplyPriority" in md.attributes:
+ self.error(
+ loc, "non-async message `%s' cannot specify [ReplyPriority]", msgname
+ )
+
+ if not md.outParams and "ReplyPriority" in md.attributes:
+ self.error(
+ loc, "non-returns message `%s' cannot specify [ReplyPriority]", msgname
+ )
+
+ isctor = False
+ isdtor = False
+ cdtype = None
+
+ decl = self.symtab.lookup(msgname)
+ if decl is not None and decl.type.isProtocol():
+ # probably a ctor. we'll check validity later.
+ msgname += "Constructor"
+ isctor = True
+ cdtype = decl.type
+ elif decl is not None:
+ self.error(
+ loc,
+ "message name `%s' already declared as `%s'",
+ msgname,
+ decl.type.typename(),
+ )
+ # if we error here, no big deal; move on to find more
+
+ if _DELETE_MSG == msgname:
+ isdtor = True
+ cdtype = self.currentProtocolDecl.type
+
+ # enter message scope
+ self.symtab.enterScope()
+
+ msgtype = MessageType(
+ nested=md.nested(),
+ prio=md.priority(),
+ replyPrio=md.replyPriority(),
+ sendSemantics=md.sendSemantics,
+ direction=md.direction,
+ ctor=isctor,
+ dtor=isdtor,
+ cdtype=cdtype,
+ compress=md.attributes.get("Compress"),
+ tainted="Tainted" in md.attributes,
+ lazySend="LazySend" in md.attributes,
+ )
+
+ # replace inparam Param nodes with proper Decls
+ def paramToDecl(param):
+ self.checkAttributes(
+ param.attributes,
+ {
+ # Passback indicates that the argument is unused by the Parent and is
+ # merely returned to the Child later.
+ # AllValid indicates that the entire span of values representable by
+ # the type are acceptable. e.g. 0-255 in a uint8
+ "NoTaint": ("passback", "allvalid")
+ },
+ )
+
+ ptname = param.typespec.basename()
+ ploc = param.typespec.loc
+
+ if "NoTaint" in param.attributes and "Tainted" not in md.attributes:
+ self.error(
+ ploc,
+ "argument typename `%s' of message `%s' has a NoTaint attribute, but the message lacks the Tainted attribute",
+ ptname,
+ msgname,
+ )
+
+ ptdecl = self.symtab.lookup(ptname)
+ if ptdecl is None:
+ self.error(
+ ploc,
+ "argument typename `%s' of message `%s' has not been declared",
+ ptname,
+ msgname,
+ )
+ ptype = VOID
+ else:
+ ptype = self._canonicalType(ptdecl.type, param.typespec)
+ return self.declare(
+ loc=ploc, type=ptype, progname=param.name, attributes=param.attributes
+ )
+
+ for i, inparam in enumerate(md.inParams):
+ pdecl = paramToDecl(inparam)
+ msgtype.params.append(pdecl.type)
+ md.inParams[i] = pdecl
+ for i, outparam in enumerate(md.outParams):
+ pdecl = paramToDecl(outparam)
+ msgtype.returns.append(pdecl.type)
+ md.outParams[i] = pdecl
+
+ self.symtab.exitScope()
+
+ md.decl = self.declare(loc=loc, type=msgtype, progname=msgname)
+ md.protocolDecl = self.currentProtocolDecl
+ md.decl._md = md
+
+ def _canonicalType(self, itype, typespec):
+ loc = typespec.loc
+ if typespec.uniqueptr:
+ itype = UniquePtrType(itype)
+
+ if itype.isIPDL() and itype.isProtocol():
+ itype = ActorType(itype)
+
+ if itype.supportsNullable():
+ if not typespec.nullable:
+ itype = NotNullType(itype)
+ elif typespec.nullable:
+ self.error(
+ loc, "`nullable' qualifier for type `%s' is unsupported", itype.name()
+ )
+
+ if typespec.array:
+ itype = ArrayType(itype)
+
+ if typespec.maybe:
+ itype = MaybeType(itype)
+
+ return itype
+
+
+# -----------------------------------------------------------------------------
+
+
+def checkcycles(p, stack=None):
+ cycles = []
+
+ if stack is None:
+ stack = []
+
+ for cp in p.manages:
+ # special case for self-managed protocols
+ if cp is p:
+ continue
+
+ if cp in stack:
+ return [stack + [p, cp]]
+ cycles += checkcycles(cp, stack + [p])
+
+ return cycles
+
+
+def formatcycles(cycles):
+ r = []
+ for cycle in cycles:
+ s = " -> ".join([ptype.name() for ptype in cycle])
+ r.append("`%s'" % s)
+ return ", ".join(r)
+
+
+def fullyDefined(t, exploring=None):
+ """The rules for "full definition" of a type are
+ defined(atom) := true
+ defined(array basetype) := defined(basetype)
+ defined(struct f1 f2...) := defined(f1) and defined(f2) and ...
+ defined(union c1 c2 ...) := defined(c1) or defined(c2) or ..."""
+ if exploring is None:
+ exploring = set()
+
+ if t.isAtom():
+ return True
+ elif t.hasBaseType():
+ return fullyDefined(t.basetype, exploring)
+ elif t.defined:
+ return True
+ assert t.isCompound()
+
+ if t in exploring:
+ return False
+
+ exploring.add(t)
+ for c in t.itercomponents():
+ cdefined = fullyDefined(c, exploring)
+ if t.isStruct() and not cdefined:
+ t.defined = False
+ break
+ elif t.isUnion() and cdefined:
+ t.defined = True
+ break
+ else:
+ if t.isStruct():
+ t.defined = True
+ elif t.isUnion():
+ t.defined = False
+ exploring.remove(t)
+
+ return t.defined
+
+
+class CheckTypes(TcheckVisitor):
+ def __init__(self, errors):
+ TcheckVisitor.__init__(self, errors)
+ self.visited = set()
+ self.ptype = None
+
+ def visitInclude(self, inc):
+ if inc.tu.filename in self.visited:
+ return
+ self.visited.add(inc.tu.filename)
+ if inc.tu.protocol:
+ inc.tu.protocol.accept(self)
+
+ def visitStructDecl(self, sd):
+ if not fullyDefined(sd.decl.type):
+ self.error(sd.decl.loc, "struct `%s' is only partially defined", sd.name)
+
+ def visitUnionDecl(self, ud):
+ if not fullyDefined(ud.decl.type):
+ self.error(ud.decl.loc, "union `%s' is only partially defined", ud.name)
+
+ def visitProtocol(self, p):
+ self.ptype = p.decl.type
+
+ # check that we require no more "power" than our manager protocols
+ ptype, pname = p.decl.type, p.decl.shortname
+
+ for mgrtype in ptype.managers:
+ if mgrtype is not None and not ptype.sendSemanticsSatisfiedBy(mgrtype):
+ self.error(
+ p.decl.loc,
+ "protocol `%s' requires more powerful send semantics than its manager `%s' provides", # NOQA: E501
+ pname,
+ mgrtype.name(),
+ )
+
+ if ptype.isInterrupt() and ptype.nestedRange != (NOT_NESTED, NOT_NESTED):
+ self.error(
+ p.decl.loc, "intr protocol `%s' cannot specify [NestedUpTo]", p.name
+ )
+
+ if ptype.isToplevel():
+ cycles = checkcycles(p.decl.type)
+ if cycles:
+ self.error(
+ p.decl.loc,
+ "cycle(s) detected in manager/manages hierarchy: %s",
+ formatcycles(cycles),
+ )
+
+ if 1 == len(ptype.managers) and ptype is ptype.manager():
+ self.error(
+ p.decl.loc, "top-level protocol `%s' cannot manage itself", p.name
+ )
+
+ return Visitor.visitProtocol(self, p)
+
+ def visitManagesStmt(self, mgs):
+ pdecl = mgs.manager.decl
+ ptype, pname = pdecl.type, pdecl.shortname
+
+ mgsdecl = mgs.decl
+ mgstype, mgsname = mgsdecl.type, mgsdecl.shortname
+
+ loc = mgs.loc
+
+ # we added this information; sanity check it
+ assert ptype.isManagerOf(mgstype)
+
+ # check that the "managed" protocol agrees
+ if not mgstype.isManagedBy(ptype):
+ self.error(
+ loc,
+ "|manages| declaration in protocol `%s' does not match any |manager| declaration in protocol `%s'", # NOQA: E501
+ pname,
+ mgsname,
+ )
+
+ def visitManager(self, mgr):
+ pdecl = mgr.of.decl
+ ptype, pname = pdecl.type, pdecl.shortname
+
+ mgrdecl = mgr.decl
+ mgrtype, mgrname = mgrdecl.type, mgrdecl.shortname
+
+ # we added this information; sanity check it
+ assert ptype.isManagedBy(mgrtype)
+
+ loc = mgr.loc
+
+ # check that the "manager" protocol agrees
+ if not mgrtype.isManagerOf(ptype):
+ self.error(
+ loc,
+ "|manager| declaration in protocol `%s' does not match any |manages| declaration in protocol `%s'", # NOQA: E501
+ pname,
+ mgrname,
+ )
+
+ def visitMessageDecl(self, md):
+ mtype, mname = md.decl.type, md.decl.progname
+ ptype, pname = md.protocolDecl.type, md.protocolDecl.shortname
+
+ loc = md.decl.loc
+
+ if mtype.nested == INSIDE_SYNC_NESTED and not mtype.isSync():
+ self.error(
+ loc,
+ "inside_sync nested messages must be sync (here, message `%s' in protocol `%s')",
+ mname,
+ pname,
+ )
+
+ if mtype.nested == INSIDE_CPOW_NESTED and (mtype.isOut() or mtype.isInout()):
+ self.error(
+ loc,
+ "inside_cpow nested parent-to-child messages are verboten (here, message `%s' in protocol `%s')", # NOQA: E501
+ mname,
+ pname,
+ )
+
+ # We allow inside_sync messages that are themselves sync to be sent from the
+ # parent. Normal and inside_cpow nested messages that are sync can only come from
+ # the child.
+ if (
+ mtype.isSync()
+ and mtype.nested == NOT_NESTED
+ and (mtype.isOut() or mtype.isInout())
+ ):
+ self.error(
+ loc,
+ "sync parent-to-child messages are verboten (here, message `%s' in protocol `%s')",
+ mname,
+ pname,
+ )
+
+ if not mtype.sendSemanticsSatisfiedBy(ptype):
+ self.error(
+ loc,
+ "message `%s' requires more powerful send semantics than its protocol `%s' provides", # NOQA: E501
+ mname,
+ pname,
+ )
+
+ if (mtype.isCtor() or mtype.isDtor()) and mtype.isAsync() and mtype.returns:
+ self.error(
+ loc, "asynchronous ctor/dtor message `%s' declares return values", mname
+ )
+
+ if mtype.compress and (not mtype.isAsync() or mtype.isCtor() or mtype.isDtor()):
+ if mtype.isCtor() or mtype.isDtor():
+ message_type = "constructor" if mtype.isCtor() else "destructor"
+ error_message = (
+ "%s messages can't use compression (here, in protocol `%s')"
+ % (message_type, pname)
+ )
+ else:
+ error_message = (
+ "message `%s' in protocol `%s' requests compression but is not async"
+ % (mname, pname) # NOQA: E501
+ )
+
+ self.error(loc, error_message)
+
+ if mtype.isCtor() and not ptype.isManagerOf(mtype.constructedType()):
+ self.error(
+ loc,
+ "ctor for protocol `%s', which is not managed by protocol `%s'",
+ mname[: -len("constructor")],
+ pname,
+ )
diff --git a/ipc/ipdl/ipdl/util.py b/ipc/ipdl/ipdl/util.py
new file mode 100644
index 0000000000..60d9c904e2
--- /dev/null
+++ b/ipc/ipdl/ipdl/util.py
@@ -0,0 +1,12 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import zlib
+
+
+# The built-in hash over the str type is non-deterministic, so we need to do
+# this instead.
+def hash_str(s):
+ assert isinstance(s, str)
+ return zlib.adler32(s.encode("utf-8"))
diff --git a/ipc/ipdl/message-metadata.ini b/ipc/ipdl/message-metadata.ini
new file mode 100644
index 0000000000..50ad642537
--- /dev/null
+++ b/ipc/ipdl/message-metadata.ini
@@ -0,0 +1,36 @@
+#############################################################
+# #
+# Any changes to this file must be reviewed by an IPC peer. #
+# #
+#############################################################
+
+[PContent::AccumulateChildKeyedHistograms]
+segment_capacity = 16384
+[PContent::AccumulateChildHistograms]
+segment_capacity = 16384
+[PContent::StoreAndBroadcastBlobURLRegistration]
+segment_capacity = 8192
+[PHttpChannel::Redirect1Begin]
+segment_capacity = 8192
+[PHttpBackgroundChannel::OnStartRequest]
+segment_capacity = 8192
+[PHttpBackgroundChannel::OnTransportAndData]
+segment_capacity = 8192
+[PNecko::PHttpChannelConstructor]
+segment_capacity = 8192
+[PMessagePort::PostMessages]
+segment_capacity = 12288
+[PMessagePort::ReceiveData]
+segment_capacity = 12288
+
+#------------------------------------------------------------
+# Small-size messages.
+#------------------------------------------------------------
+[PCompositorBridge::DidComposite]
+segment_capacity = 128
+[PBrowser::RealMouseMoveEvent]
+segment_capacity = 192
+[PCompositorBridge::PTextureConstructor]
+segment_capacity = 192
+[PHttpBackgroundChannel::OnStopRequest]
+segment_capacity = 192
diff --git a/ipc/ipdl/moz.build b/ipc/ipdl/moz.build
new file mode 100644
index 0000000000..320c2e2f85
--- /dev/null
+++ b/ipc/ipdl/moz.build
@@ -0,0 +1,22 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += ["test"]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+# Generated by ipdl.py
+SOURCES += ["!IPCMessageTypeName.cpp"]
+
+FINAL_LIBRARY = "xul"
+
+# We #include some things in the dom/plugins/ directory that rely on
+# toolkit libraries.
+if CONFIG["MOZ_WIDGET_TOOLKIT"] == "gtk":
+ CXXFLAGS += CONFIG["MOZ_GTK3_CFLAGS"]
+
+# Add libFuzzer configuration directives
+include("/tools/fuzzing/libfuzzer-config.mozbuild")
diff --git a/ipc/ipdl/msgtype-components b/ipc/ipdl/msgtype-components
new file mode 100644
index 0000000000..4a01d3a71c
--- /dev/null
+++ b/ipc/ipdl/msgtype-components
@@ -0,0 +1,12 @@
+#!/usr/bin/python
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import sys
+
+msgid = int(sys.argv[1])
+protocol = (msgid >> 16)
+msg = (msgid - (protocol << 16))
+
+print('protocol', protocol, 'message', msg)
diff --git a/ipc/ipdl/sync-messages.ini b/ipc/ipdl/sync-messages.ini
new file mode 100644
index 0000000000..63fac60c8d
--- /dev/null
+++ b/ipc/ipdl/sync-messages.ini
@@ -0,0 +1,300 @@
+#############################################################
+# #
+# AVOID ADDING NEW MESSAGES TO THIS FILE #
+# #
+# New sync IPC messages will only be approved in #
+# exceptional circumstances, and must be reviewed by an IPC #
+# peer. Please be prepared with a detailed justification #
+# before requesting IPC peer review. #
+# #
+#############################################################
+
+# gtests
+[PQuotaTest::Try_Success_CustomErr_QmIpcFail]
+description = Only used by gtests
+[PQuotaTest::Try_Success_CustomErr_IpcFail]
+description = Only used by gtests
+[PQuotaTest::TryInspect_Success_CustomErr_QmIpcFail]
+description = Only used by gtests
+[PQuotaTest::TryInspect_Success_CustomErr_IpcFail]
+description = Only used by gtests
+
+# The rest
+[PHeapSnapshotTempFileHelper::OpenHeapSnapshotTempFile]
+description = legacy sync IPC - please add detailed description
+[PBackgroundMutableFile::GetFileId]
+description = legacy sync IPC - please add detailed description
+[PBackgroundIndexedDBUtils::GetFileReferences]
+description = legacy sync IPC - please add detailed description
+[PBrowser::SyncMessage]
+description = JS MessageManager implementation
+[PBrowser::NotifyIMEMouseButtonEvent]
+description = legacy sync IPC - please add detailed description
+[PBrowser::RequestIMEToCommitComposition]
+description = legacy sync IPC - please add detailed description
+[PBrowser::GetInputContext]
+description = legacy sync IPC - please add detailed description
+[PBrowser::RequestNativeKeyBindings]
+description = legacy sync IPC - please add detailed description
+[PBrowser::DispatchWheelEvent]
+description = Only used by automation tests
+[PBrowser::DispatchMouseEvent]
+description = Only used by automation tests
+[PBrowser::DispatchKeyboardEvent]
+description = Only used by automation tests
+[PBrowser::DispatchTouchEvent]
+description = Only used by automation tests
+[PBrowser::EnsureLayersConnected]
+description = legacy sync IPC - please add detailed description
+[PBrowser::SetSystemFont]
+description = test only
+[PBrowser::GetSystemFont]
+description = test only
+[PContent::SyncMessage]
+description = JS MessageManager implementation
+[PContent::IsSecureURI]
+description = legacy sync IPC - please add detailed description
+[PContent::PURLClassifier]
+description = legacy sync IPC - please add detailed description
+[PContent::GetClipboard]
+description = Legacy synchronous clipboard API
+[PContent::ClipboardHasType]
+description = Legacy synchronous clipboard API
+[PContent::GetExternalClipboardFormats]
+description = Retrieve supported clipboard formats synchronously
+[PContent::GetIconForExtension]
+description = legacy sync IPC - please add detailed description
+[PContent::BeginDriverCrashGuard]
+description = legacy sync IPC - please add detailed description
+[PContent::EndDriverCrashGuard]
+description = legacy sync IPC - please add detailed description
+[PContent::GetFontListShmBlock]
+description = for bug 1514869 - layout code needs synchronous access to font list, but this is used only once per block, after which content directly reads the shared memory
+[PContent::InitializeFamily]
+description = for bug 1514869 - layout is blocked on needing sync access to a specific font family - used once per family, then the data is cached in shared memory
+[PContent::InitOtherFamilyNames]
+description = for bug 1514869 - layout is blocked on font lookup, needs complete family-name information - not used after loading is complete
+[PContent::GetHyphDict]
+description = for bug 1487212 - layout requires hyphenation data from a given omnijar resource - only called once per locale by a given content process
+[PGMP::StartPlugin]
+description = legacy sync IPC - please add detailed description
+[PGMPVideoDecoder::NeedShmem]
+description = legacy sync IPC - please add detailed description
+[PGMPVideoEncoder::NeedShmem]
+description = legacy sync IPC - please add detailed description
+[PRemoteDecoderManager::Readback]
+description = legacy sync IPC - please add detailed description
+[PBackgroundStorage::Preload]
+description = legacy sync IPC - please add detailed description
+[PBackgroundLSDatabase::PBackgroundLSSnapshot]
+description = See corresponding comment in PBackgroundLSDatabase.ipdl
+[PBackgroundLSSnapshot::SyncCheckpoint]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundLSSnapshot::SyncCheckpointAndNotify]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundLSSnapshot::SyncFinish]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundLSSnapshot::LoadValueAndMoreItems]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundLSSnapshot::LoadKeys]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundLSSnapshot::IncreasePeakUsage]
+description = See corresponding comment in PBackgroundLSSnapshot.ipdl
+[PBackgroundSessionStorageCache::Load]
+description = See corresponding comment in PBackgroundSessionStorageCache.ipdl
+[PRemoteSpellcheckEngine::SetDictionary]
+description = legacy sync IPC - please add detailed description
+[PGPU::AddLayerTreeIdMapping]
+description = legacy sync IPC - please add detailed description
+[PGPU::GetDeviceStatus]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceiveMultiTouchInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceiveMouseInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceivePanGestureInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceivePinchGestureInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceiveTapGestureInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceiveScrollWheelInputEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ProcessUnhandledEvent]
+description = legacy sync IPC - please add detailed description
+[PAPZInputBridge::ReceiveKeyboardInputEvent]
+description = legacy sync IPC - please add detailed description
+[PCanvasManager::GetSnapshot]
+description = Retrieving canvas contents is synchronous (see also, PWebGL::GetFrontBufferSnapshot).
+[PCompositorBridge::Initialize]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::WillClose]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::Pause]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::Resume]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::NotifyChildCreated]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::MapAndNotifyChildCreated]
+description = bug 1350660
+[PCompositorBridge::NotifyChildRecreated]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::FlushRendering]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::WaitOnTransactionProcessed]
+description = bug 1364626
+[PCompositorBridge::StartFrameTimeRecording]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::StopFrameTimeRecording]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::SyncWithCompositor]
+description = legacy sync IPC - please add detailed description
+[PCompositorBridge::CheckContentOnlyTDR]
+description = legacy sync IPC - please add detailed description
+[PCompositorWidget::Initialize]
+description = Fallable initialization for the widget. Must be called right after construction before any other messages are sent
+platform = win
+[PCompositorWidget::EnterPresentLock]
+description = Obtain exclusive access to the widget surface. Used to ensure events don't change the surface while it's being used as a render target
+platform = win
+[PCompositorWidget::LeavePresentLock]
+description = Release the exclusive lock that EnterPresentLock obtained
+platform = win
+[PCompositorWidget::ClearTransparentWindow]
+description = Synchronously clear the widget surface. Does not rely on (Enter|Leave)PresentLock. When call returns, window surface has been fully updated with cleared pixel values.
+platform = win
+[PImageBridge::NewCompositable]
+description = legacy sync IPC - please add detailed description
+[PUiCompositorController::Pause]
+description = legacy sync IPC - please add detailed description
+[PUiCompositorController::Resume]
+description = legacy sync IPC - please add detailed description
+[PUiCompositorController::ResumeAndResize]
+description = legacy sync IPC - please add detailed description
+[PWebRenderBridge::EnsureConnected]
+description = legacy sync IPC - please add detailed description
+[PWebRenderBridge::GetSnapshot]
+description = legacy sync IPC - please add detailed description
+[PWebRenderBridge::SetTestSampleTime]
+description = test only
+[PWebRenderBridge::LeaveTestMode]
+description = test only
+[PWebRenderBridge::GetAnimationValue]
+description = test only
+[PWebRenderBridge::SetAsyncScrollOffset]
+description = test only
+[PWebRenderBridge::SetAsyncZoom]
+description = test only
+[PWebRenderBridge::GetAPZTestData]
+description = test only
+[PWebRenderBridge::GetFrameUniformity]
+description = test only
+[PWebRenderBridge::ShutdownSync]
+description = bug 1377024
+[PWebRenderBridge::SyncWithCompositor]
+description = WebRender equivalent for PCompositorBridge::SyncWithCompositor
+[PHal::GetCurrentBatteryInformation]
+description = legacy sync IPC - please add detailed description
+[PHal::GetCurrentNetworkInformation]
+description = legacy sync IPC - please add detailed description
+[PHal::GetWakeLockInfo]
+description = legacy sync IPC - please add detailed description
+[PHandlerService::FillHandlerInfo]
+description = legacy sync IPC - please add detailed description
+[PHandlerService::GetMIMEInfoFromOS]
+description = Lets unprivileged child processes synchronously get MIME type/handler information from the OS
+[PHandlerService::ExistsForProtocolOS]
+description = bug 1382323
+[PHandlerService::ExistsForProtocol]
+description = legacy sync IPC - please add detailed description
+[PHandlerService::Exists]
+description = legacy sync IPC - please add detailed description
+[PHandlerService::GetTypeFromExtension]
+description = legacy sync IPC - please add detailed description
+[PHandlerService::GetApplicationDescription]
+description = Lets unprivileged child processes synchronously get a description of the app that handles a given protocol scheme
+[PClientSource::WorkerSyncPing]
+description = Synchronous ping allowing worker thread to confirm actor is created. Necessary to avoid racing with ClientHandle actors on main thread.
+[PRemoteSandboxBroker::LaunchApp]
+description = Synchronous launch of a child process that in turn launches and sandboxes another process. Called on a dedicated thread and targets a dedicated process, so this shouldn't block anything.
+[PSandboxTesting::GetSpecialDirectory]
+description = Testing only - get a special directory path.
+# WebGL internals
+[PWebGL::Initialize]
+description = Initialization of WebGL contexts is synchronous by spec.
+[PWebGL::GetFrontBuffer]
+description = Publishing a WebGL frame for compositing is synchronous for now to ensure DOM transaction atomicity.
+[PWebGL::OnMemoryPressure]
+description = Synchronous to ensure immediate memory pressure relief.
+# WebGL spec-synchronous functions
+[PWebGL::CheckFramebufferStatus]
+description = Checking framebuffer completenss must ask the driver.
+[PWebGL::ClientWaitSync]
+description = Checking fence-sync completenss must ask the driver.
+[PWebGL::CreateOpaqueFramebuffer]
+description = Must synchronously check for allocation success.
+[PWebGL::DrawingBufferSize]
+description = The returned size might be smaller than requested due to allocation failure.
+[PWebGL::Finish]
+description = Synchronous by spec, but not generally used.
+[PWebGL::GetBufferSubData]
+description = Retrieving buffer contents is synchronous in the worst case.
+[PWebGL::GetFrontBufferSnapshot]
+description = Retrieving canvas contents is synchronous.
+[PWebGL::ReadPixels]
+description = Retrieving WebGL framebuffer contents is synchronous.
+# WebGL reflection functions
+[PWebGL::GetBufferParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetCompileResult]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetError]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetFragDataLocation]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetFramebufferAttachmentParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetIndexedParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetInternalformatParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetLinkResult]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetNumber]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetQueryParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetRenderbufferParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetSamplerParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetShaderPrecisionFormat]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetString]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetTexParameter]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetUniform]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::GetVertexAttrib]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::IsEnabled]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::ValidateProgram]
+description = Reflection is cold code, but synchronous by spec.
+[PWebGL::SyncPing]
+description = Used to throttle a lot of async WebGL command messages.
+# -
+[PIPCClientCerts::FindObjects]
+description = Finds certificates and private keys in the parent process. As this is called from PKCS#11, there is no way to make this asynchronous.
+[PIPCClientCerts::Sign]
+description = Performs a signature on given data with a key corresponding to the given identifier. This is called from PKCS#11, so there is no way to make this asynchronous.
+# -
+[PRemoteQuotaObject::MaybeUpdateSize]
+description = This must be synchronous until quota file streams become non-blocking. The synchronous message is never used on the main thread or the PBackground thread or a DOM worker threed.
+
+#############################################################
+# AVOID ADDING NEW MESSAGES TO THIS FILE #
+# see comment at top of file #
+#############################################################
diff --git a/ipc/ipdl/test/README.txt b/ipc/ipdl/test/README.txt
new file mode 100644
index 0000000000..ca6db8bb3c
--- /dev/null
+++ b/ipc/ipdl/test/README.txt
@@ -0,0 +1,13 @@
+There are two major categories of tests, segregated into different
+top-level directories under test/.
+
+The first category (ipdl/) is IPDL-compiler tests. These tests check
+that the IPDL compiler is successfully compiling correct
+specifications, and successfully rejecting erroneous specifications.
+
+To run these tests yourself locally, the correct invocation is
+ make -C obj-dir/ipc/ipdl/test/ipdl check
+
+The second category (cxx/) is C++ tests of IPDL semantics. These
+tests check that async/sync/rpc semantics are implemented correctly,
+ctors/dtors behave as they should, etc.
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.cpp b/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.cpp
new file mode 100644
index 0000000000..7683808535
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.cpp
@@ -0,0 +1,27 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/ipc/IOThreadChild.h"
+
+#include "IPDLUnitTestProcessChild.h"
+#include "IPDLUnitTests.h"
+
+#include "nsRegion.h"
+
+using mozilla::ipc::IOThreadChild;
+
+namespace mozilla {
+namespace _ipdltest {
+
+bool IPDLUnitTestProcessChild::Init(int aArgc, char* aArgv[]) {
+ // FIXME(nika): this is quite clearly broken and needs to be fixed.
+ IPDLUnitTestChildInit(IOThreadChild::TakeChannel(), ParentPid(),
+ IOThreadChild::message_loop());
+
+ return true;
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.h b/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.h
new file mode 100644
index 0000000000..94578e3520
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestProcessChild.h
@@ -0,0 +1,28 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTestThreadChild_h
+#define mozilla__ipdltest_IPDLUnitTestThreadChild_h 1
+
+#include "mozilla/ipc/ProcessChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class IPDLUnitTestProcessChild : public mozilla::ipc::ProcessChild {
+ typedef mozilla::ipc::ProcessChild ProcessChild;
+
+ public:
+ using ProcessChild::ProcessChild;
+
+ ~IPDLUnitTestProcessChild() {}
+
+ virtual bool Init(int aArgc, char* aArgv[]) override;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_IPDLUnitTestThreadChild_h
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.cpp b/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.cpp
new file mode 100644
index 0000000000..660e5928d3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.cpp
@@ -0,0 +1,19 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "IPDLUnitTestSubprocess.h"
+
+using mozilla::ipc::GeckoChildProcessHost;
+
+namespace mozilla {
+namespace _ipdltest {
+
+IPDLUnitTestSubprocess::IPDLUnitTestSubprocess()
+ : GeckoChildProcessHost(GeckoProcessType_IPDLUnitTest) {}
+
+IPDLUnitTestSubprocess::~IPDLUnitTestSubprocess() {}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.h b/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.h
new file mode 100644
index 0000000000..384cf25ce9
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestSubprocess.h
@@ -0,0 +1,34 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTestTestSubprocess_h
+#define mozilla__ipdltest_IPDLUnitTestTestSubprocess_h 1
+
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+
+namespace mozilla {
+namespace _ipdltest {
+//-----------------------------------------------------------------------------
+
+class IPDLUnitTestSubprocess : public mozilla::ipc::GeckoChildProcessHost {
+ public:
+ IPDLUnitTestSubprocess();
+
+ /**
+ * Asynchronously launch the plugin process.
+ */
+ // Could override parent Launch, but don't need to here
+ // bool Launch();
+
+ private:
+ ~IPDLUnitTestSubprocess();
+
+ DISALLOW_EVIL_CONSTRUCTORS(IPDLUnitTestSubprocess);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_IPDLUnitTestTestSubprocess_h
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestTypes.h b/ipc/ipdl/test/cxx/IPDLUnitTestTypes.h
new file mode 100644
index 0000000000..02696f7df7
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestTypes.h
@@ -0,0 +1,43 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTestTypes_h
+#define mozilla__ipdltest_IPDLUnitTestTypes_h
+
+#include "mozilla/ipc/ProtocolUtils.h" // ActorDestroyReason
+
+namespace mozilla {
+namespace _ipdltest {
+
+struct DirtyRect {
+ int x;
+ int y;
+ int w;
+ int h;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+namespace IPC {
+template <>
+struct ParamTraits<mozilla::_ipdltest::DirtyRect> {
+ typedef mozilla::_ipdltest::DirtyRect paramType;
+ static void Write(MessageWriter* aWriter, const paramType& aParam) {
+ WriteParam(aWriter, aParam.x);
+ WriteParam(aWriter, aParam.y);
+ WriteParam(aWriter, aParam.w);
+ WriteParam(aWriter, aParam.h);
+ }
+ static bool Read(MessageReader* aReader, void** aIter, paramType* aResult) {
+ return (ReadParam(aReader, aIter, &aResult->x) &&
+ ReadParam(aReader, aIter, &aResult->y) &&
+ ReadParam(aReader, aIter, &aResult->w) &&
+ ReadParam(aReader, aIter, &aResult->h));
+ }
+};
+} // namespace IPC
+
+#endif // ifndef mozilla__ipdltest_IPDLUnitTestTypes_h
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTestUtils.h b/ipc/ipdl/test/cxx/IPDLUnitTestUtils.h
new file mode 100644
index 0000000000..e454ae7b61
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTestUtils.h
@@ -0,0 +1,28 @@
+
+#ifndef mozilla__ipdltest_IPDLUnitTestUtils
+#define mozilla__ipdltest_IPDLUnitTestUtils 1
+
+#include "ipc/IPCMessageUtils.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+struct Bad {};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+namespace IPC {
+
+template <>
+struct ParamTraits<mozilla::_ipdltest::Bad> {
+ typedef mozilla::_ipdltest::Bad paramType;
+
+ // Defined in TestActorPunning.cpp.
+ static void Write(MessageWriter* aWriter, const paramType& aParam);
+ static bool Read(MessageReader* aReader, paramType* aResult);
+};
+
+} // namespace IPC
+
+#endif // mozilla__ipdltest_IPDLUnitTestUtils
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTests.h b/ipc/ipdl/test/cxx/IPDLUnitTests.h
new file mode 100644
index 0000000000..28fc4ee372
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTests.h
@@ -0,0 +1,85 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTests_h
+#define mozilla__ipdltest_IPDLUnitTests_h 1
+
+#include "base/message_loop.h"
+#include "base/process.h"
+#include "chrome/common/ipc_channel.h"
+
+#include "nsCOMPtr.h"
+#include "nsDebug.h"
+#include "nsServiceManagerUtils.h" // do_GetService()
+#include "nsWidgetsCID.h" // NS_APPSHELL_CID
+#include "nsXULAppAPI.h"
+
+#define MOZ_IPDL_TESTFAIL_LABEL "TEST-UNEXPECTED-FAIL"
+#define MOZ_IPDL_TESTPASS_LABEL "TEST-PASS"
+#define MOZ_IPDL_TESTINFO_LABEL "TEST-INFO"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// both processes
+const char* IPDLUnitTestName();
+
+// NB: these are named like the similar functions in
+// xpcom/test/TestHarness.h. The names should nominally be kept in
+// sync.
+
+inline void fail(const char* fmt, ...) {
+ va_list ap;
+
+ fprintf(stderr, MOZ_IPDL_TESTFAIL_LABEL " | %s | ", IPDLUnitTestName());
+
+ va_start(ap, fmt);
+ vfprintf(stderr, fmt, ap);
+ va_end(ap);
+
+ fputc('\n', stderr);
+
+ MOZ_CRASH("failed test");
+}
+
+inline void passed(const char* fmt, ...) {
+ va_list ap;
+
+ printf(MOZ_IPDL_TESTPASS_LABEL " | %s | ", IPDLUnitTestName());
+
+ va_start(ap, fmt);
+ vprintf(fmt, ap);
+ va_end(ap);
+
+ fputc('\n', stdout);
+}
+
+//-----------------------------------------------------------------------------
+// parent process only
+
+class IPDLUnitTestSubprocess;
+
+extern void* gParentActor;
+extern IPDLUnitTestSubprocess* gSubprocess;
+
+void IPDLUnitTestMain(void* aData);
+
+void QuitParent();
+
+//-----------------------------------------------------------------------------
+// child process only
+
+extern void* gChildActor;
+
+void IPDLUnitTestChildInit(IPC::Channel* transport, base::ProcessId parentPid,
+ MessageLoop* worker);
+
+void QuitChild();
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_IPDLUnitTests_h
diff --git a/ipc/ipdl/test/cxx/IPDLUnitTests.template.cpp b/ipc/ipdl/test/cxx/IPDLUnitTests.template.cpp
new file mode 100644
index 0000000000..113e7cd287
--- /dev/null
+++ b/ipc/ipdl/test/cxx/IPDLUnitTests.template.cpp
@@ -0,0 +1,345 @@
+//
+// Autogenerated from Python template. Hands off.
+//
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "IPDLUnitTests.h"
+
+#include "base/command_line.h"
+#include "base/string_util.h"
+#include "base/task.h"
+#include "base/thread.h"
+
+#include "nsRegion.h"
+
+#include "IPDLUnitTestSubprocess.h"
+
+// clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${INCLUDES}
+//-----------------------------------------------------------------------------
+// clang-format on
+
+using namespace std;
+
+using base::Thread;
+
+namespace mozilla {
+namespace _ipdltest {
+
+void* gParentActor;
+IPDLUnitTestSubprocess* gSubprocess;
+
+void* gChildActor;
+
+// Note: in threaded mode, this will be non-null (for both parent and
+// child, since they share one set of globals).
+Thread* gChildThread;
+MessageLoop* gParentMessageLoop;
+bool gParentDone;
+bool gChildDone;
+
+void DeleteChildActor();
+
+//-----------------------------------------------------------------------------
+// data/functions accessed by both parent and child processes
+
+char* gIPDLUnitTestName = nullptr;
+
+const char* IPDLUnitTestName() {
+ if (!gIPDLUnitTestName) {
+#if defined(XP_WIN)
+ vector<wstring> args = CommandLine::ForCurrentProcess()->GetLooseValues();
+ gIPDLUnitTestName = ::strdup(WideToUTF8(args[0]).c_str());
+#else
+ vector<string> argv = CommandLine::ForCurrentProcess()->argv();
+ gIPDLUnitTestName = ::moz_xstrdup(argv[1].c_str());
+#endif
+ }
+ return gIPDLUnitTestName;
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+namespace {
+
+enum IPDLUnitTestType {
+ NoneTest = 0,
+
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${ENUM_VALUES}
+
+ LastTest = ${LAST_ENUM}
+//-----------------------------------------------------------------------------
+//clang-format on
+};
+
+IPDLUnitTestType IPDLUnitTestFromString(const char* const aString) {
+ if (!aString) return static_cast<IPDLUnitTestType>(0);
+// clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${STRING_TO_ENUMS}
+//-----------------------------------------------------------------------------
+ // clang-format on
+ else return static_cast<IPDLUnitTestType>(0);
+}
+
+IPDLUnitTestType IPDLUnitTest() {
+ return IPDLUnitTestFromString(::mozilla::_ipdltest::IPDLUnitTestName());
+}
+
+} // namespace
+
+//-----------------------------------------------------------------------------
+// parent process only
+
+namespace mozilla {
+namespace _ipdltest {
+
+void DeferredParentShutdown();
+
+void IPDLUnitTestThreadMain(char* testString);
+
+void IPDLUnitTestMain(void* aData) {
+ char* testString = reinterpret_cast<char*>(aData);
+
+ // Check if we are to run the test using threads instead:
+ const char* prefix = "thread:";
+ const int prefixLen = strlen(prefix);
+ if (!strncmp(testString, prefix, prefixLen)) {
+ IPDLUnitTestThreadMain(testString + prefixLen);
+ return;
+ }
+
+ IPDLUnitTestType test = IPDLUnitTestFromString(testString);
+ if (!test) {
+ // use this instead of |fail()| because we don't know what the test is
+ fprintf(stderr, MOZ_IPDL_TESTFAIL_LABEL "| %s | unknown unit test %s\n",
+ "<--->", testString);
+ MOZ_CRASH("can't continue");
+ }
+ gIPDLUnitTestName = testString;
+
+ // Check whether this test is enabled for processes:
+ switch (test) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${PARENT_ENABLED_CASES_PROC}
+//-----------------------------------------------------------------------------
+ // clang-format on
+
+ default:
+ fail("not reached");
+ return; // unreached
+ }
+
+ printf(MOZ_IPDL_TESTINFO_LABEL "| running test | %s\n", gIPDLUnitTestName);
+
+ std::vector<std::string> testCaseArgs;
+ testCaseArgs.push_back(testString);
+
+ gSubprocess = new IPDLUnitTestSubprocess();
+ if (!gSubprocess->SyncLaunch(testCaseArgs))
+ fail("problem launching subprocess");
+
+ IPC::Channel* transport = gSubprocess->GetChannel();
+ if (!transport) fail("no transport");
+
+ base::ProcessId child = base::GetProcId(gSubprocess->GetChildProcessHandle());
+
+ switch (test) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${PARENT_MAIN_CASES_PROC}
+//-----------------------------------------------------------------------------
+ // clang-format on
+
+ default:
+ fail("not reached");
+ return; // unreached
+ }
+}
+
+void IPDLUnitTestThreadMain(char* testString) {
+ IPDLUnitTestType test = IPDLUnitTestFromString(testString);
+ if (!test) {
+ // use this instead of |fail()| because we don't know what the test is
+ fprintf(stderr, MOZ_IPDL_TESTFAIL_LABEL "| %s | unknown unit test %s\n",
+ "<--->", testString);
+ MOZ_CRASH("can't continue");
+ }
+ gIPDLUnitTestName = testString;
+
+ // Check whether this test is enabled for threads:
+ switch (test) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${PARENT_ENABLED_CASES_THREAD}
+//-----------------------------------------------------------------------------
+ // clang-format on
+
+ default:
+ fail("not reached");
+ return; // unreached
+ }
+
+ printf(MOZ_IPDL_TESTINFO_LABEL "| running test | %s\n", gIPDLUnitTestName);
+
+ std::vector<std::string> testCaseArgs;
+ testCaseArgs.push_back(testString);
+
+ gChildThread = new Thread("ParentThread");
+ if (!gChildThread->Start()) fail("starting parent thread");
+
+ gParentMessageLoop = MessageLoop::current();
+ MessageLoop* childMessageLoop = gChildThread->message_loop();
+
+ switch (test) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${PARENT_MAIN_CASES_THREAD}
+//-----------------------------------------------------------------------------
+ // clang-format on
+
+ default:
+ fail("not reached");
+ return; // unreached
+ }
+}
+
+void DeleteParentActor() {
+ if (!gParentActor) return;
+
+ switch (IPDLUnitTest()) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${PARENT_DELETE_CASES}
+//-----------------------------------------------------------------------------
+ // clang-format on
+ default:
+ ::mozilla::_ipdltest::fail("???");
+ }
+}
+
+void QuitXPCOM() {
+ DeleteParentActor();
+
+ static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
+ nsCOMPtr<nsIAppShell> appShell(do_GetService(kAppShellCID));
+ appShell->Exit();
+}
+
+void DeleteSubprocess(MessageLoop* uiLoop) {
+ // pong to QuitXPCOM
+ gSubprocess->Destroy();
+ gSubprocess = nullptr;
+ uiLoop->PostTask(NewRunnableFunction("QuitXPCOM", QuitXPCOM));
+}
+
+void DeferredParentShutdown() {
+ // ping to DeleteSubprocess
+ XRE_GetIOMessageLoop()->PostTask(NewRunnableFunction(
+ "DeleteSubprocess", DeleteSubprocess, MessageLoop::current()));
+}
+
+void TryThreadedShutdown() {
+ // Stop if either:
+ // - the child has not finished,
+ // - the parent has not finished,
+ // - or this code has already executed.
+ // Remember: this TryThreadedShutdown() task is enqueued
+ // by both parent and child (though always on parent's msg loop).
+ if (!gChildDone || !gParentDone || !gChildThread) return;
+
+ delete gChildThread;
+ gChildThread = 0;
+ DeferredParentShutdown();
+}
+
+void ChildCompleted() {
+ // Executes on the parent message loop once child has completed.
+ gChildDone = true;
+ TryThreadedShutdown();
+}
+
+void QuitParent() {
+ if (gChildThread) {
+ gParentDone = true;
+ MessageLoop::current()->PostTask(
+ NewRunnableFunction("TryThreadedShutdown", TryThreadedShutdown));
+ } else {
+ // defer "real" shutdown to avoid *Channel::Close() racing with the
+ // deletion of the subprocess
+ MessageLoop::current()->PostTask(
+ NewRunnableFunction("DeferredParentShutdown", DeferredParentShutdown));
+ }
+}
+
+static void ChildDie() {
+ DeleteChildActor();
+ XRE_ShutdownChildProcess();
+}
+
+void QuitChild() {
+ if (gChildThread) { // Threaded-mode test
+ gParentMessageLoop->PostTask(
+ NewRunnableFunction("ChildCompleted", ChildCompleted));
+ } else { // Process-mode test
+ MessageLoop::current()->PostTask(NewRunnableFunction("ChildDie", ChildDie));
+ }
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+//-----------------------------------------------------------------------------
+// child process only
+
+namespace mozilla {
+namespace _ipdltest {
+
+void DeleteChildActor() {
+ if (!gChildActor) return;
+
+ switch (IPDLUnitTest()) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${CHILD_DELETE_CASES}
+//-----------------------------------------------------------------------------
+ // clang-format on
+ default:
+ ::mozilla::_ipdltest::fail("???");
+ }
+}
+
+void IPDLUnitTestChildInit(IPC::Channel* transport, base::ProcessId parentPid,
+ MessageLoop* worker) {
+ switch (IPDLUnitTest()) {
+ // clang-format off
+//-----------------------------------------------------------------------------
+//===== TEMPLATED =====
+${CHILD_INIT_CASES}
+//-----------------------------------------------------------------------------
+ // clang-format on
+
+ default:
+ fail("not reached");
+ return; // unreached
+ }
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/Makefile.in b/ipc/ipdl/test/cxx/Makefile.in
new file mode 100644
index 0000000000..b32533a648
--- /dev/null
+++ b/ipc/ipdl/test/cxx/Makefile.in
@@ -0,0 +1,45 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+IPDLTESTSRCS = $(filter Test%,$(CPPSRCS))
+IPDLTESTS = $(IPDLTESTSRCS:.cpp=)
+
+EXTRA_PROTOCOLS = \
+ TestEndpointBridgeSub \
+ $(NULL)
+
+IPDLTESTHDRS = $(addprefix $(srcdir)/,$(addsuffix .h,$(IPDLTESTS)))
+
+TESTER_TEMPLATE := $(srcdir)/IPDLUnitTests.template.cpp
+GENTESTER := $(srcdir)/genIPDLUnitTests.py
+
+include $(topsrcdir)/config/rules.mk
+
+
+IPDLUNITTEST_BIN = $(DEPTH)/dist/bin/ipdlunittest$(BIN_SUFFIX)
+
+IPDLUnitTests.cpp : Makefile.in moz.build $(GENTESTER) $(TESTER_TEMPLATE) $(IPDLTESTHDRS)
+ $(PYTHON3) $(GENTESTER) $(TESTER_TEMPLATE) -t $(IPDLTESTS) -e $(EXTRA_PROTOCOLS) > $@
+
+check-proc::
+ @$(EXIT_ON_ERROR) \
+ for test in $(IPDLTESTS); do \
+ $(RUN_TEST_PROGRAM) $(IPDLUNITTEST_BIN) $$test ; \
+ done
+
+check-thread::
+ @$(EXIT_ON_ERROR) \
+ for test in $(IPDLTESTS); do \
+ $(RUN_TEST_PROGRAM) $(IPDLUNITTEST_BIN) thread:$$test ; \
+ done
+
+check:: check-proc check-thread
+
+check-valgrind::
+ @$(EXIT_ON_ERROR) \
+ for test in $(IPDLTESTS); do \
+ $(RUN_TEST_PROGRAM) -g -d \
+ valgrind -a '--leak-check=full --trace-children=yes -q' \
+ $(IPDLUNITTEST_BIN) $$test ; \
+ done
diff --git a/ipc/ipdl/test/cxx/PTestActorPunning.ipdl b/ipc/ipdl/test/cxx/PTestActorPunning.ipdl
new file mode 100644
index 0000000000..0aec430d9f
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestActorPunning.ipdl
@@ -0,0 +1,28 @@
+
+include protocol PTestActorPunningPunned;
+include protocol PTestActorPunningSub;
+include "mozilla/_ipdltest/IPDLUnitTestUtils.h";
+include "mozilla/_ipdltest/TestActorPunning.h";
+
+using struct mozilla::_ipdltest::Bad from "mozilla/_ipdltest/IPDLUnitTestUtils.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestActorPunningChild", ParentImpl="TestActorPunningParent"]
+protocol PTestActorPunning {
+ manages PTestActorPunningPunned;
+ manages PTestActorPunningSub;
+
+child:
+ async Start();
+
+parent:
+ async PTestActorPunningPunned();
+ async PTestActorPunningSub();
+ async Pun(PTestActorPunningSub a, Bad bad);
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestActorPunningPunned.ipdl b/ipc/ipdl/test/cxx/PTestActorPunningPunned.ipdl
new file mode 100644
index 0000000000..5cca8a8ab5
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestActorPunningPunned.ipdl
@@ -0,0 +1,18 @@
+
+include protocol PTestActorPunning;
+
+include "mozilla/_ipdltest/TestActorPunning.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestActorPunningPunnedChild", ParentImpl="TestActorPunningPunnedParent"]
+protocol PTestActorPunningPunned {
+ manager PTestActorPunning;
+
+child:
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltes
diff --git a/ipc/ipdl/test/cxx/PTestActorPunningSub.ipdl b/ipc/ipdl/test/cxx/PTestActorPunningSub.ipdl
new file mode 100644
index 0000000000..0cb522255c
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestActorPunningSub.ipdl
@@ -0,0 +1,19 @@
+
+include protocol PTestActorPunning;
+
+include "mozilla/_ipdltest/TestActorPunning.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestActorPunningSubChild", ParentImpl="TestActorPunningSubParent"]
+protocol PTestActorPunningSub {
+ manager PTestActorPunning;
+
+child:
+ async Bad();
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltes
diff --git a/ipc/ipdl/test/cxx/PTestAsyncReturns.ipdl b/ipc/ipdl/test/cxx/PTestAsyncReturns.ipdl
new file mode 100644
index 0000000000..42ef17d1e8
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestAsyncReturns.ipdl
@@ -0,0 +1,20 @@
+include "mozilla/_ipdltest/TestAsyncReturns.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestAsyncReturnsChild", ParentImpl="TestAsyncReturnsParent"]
+protocol PTestAsyncReturns {
+
+child:
+ async Ping() returns (bool one);
+ async NoReturn() returns (bool unused);
+
+parent:
+ async Pong() returns (uint32_t param1, uint32_t param2);
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestBadActor.ipdl b/ipc/ipdl/test/cxx/PTestBadActor.ipdl
new file mode 100644
index 0000000000..991e6eb945
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestBadActor.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestBadActorSub;
+
+include "mozilla/_ipdltest/TestBadActor.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+// Test that a parent sending a reentrant __delete__ message
+// is not killed if a child's message races with the reply.
+
+[ManualDealloc, ChildImpl="TestBadActorChild", ParentImpl="TestBadActorParent"]
+intr protocol PTestBadActor {
+ manages PTestBadActorSub;
+
+child:
+ async PTestBadActorSub();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestBadActorSub.ipdl b/ipc/ipdl/test/cxx/PTestBadActorSub.ipdl
new file mode 100644
index 0000000000..aadd8b6739
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestBadActorSub.ipdl
@@ -0,0 +1,20 @@
+include protocol PTestBadActor;
+
+include "mozilla/_ipdltest/TestBadActor.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestBadActorSubChild", ParentImpl="TestBadActorSubParent"]
+intr protocol PTestBadActorSub {
+ manager PTestBadActor;
+
+child:
+ [LegacyIntr] intr __delete__();
+
+parent:
+ async Ping();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestCancel.ipdl b/ipc/ipdl/test/cxx/PTestCancel.ipdl
new file mode 100644
index 0000000000..4ad902e8e1
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestCancel.ipdl
@@ -0,0 +1,39 @@
+include "mozilla/_ipdltest/TestCancel.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_sync, ChildImpl="TestCancelChild", ParentImpl="TestCancelParent"]
+sync protocol PTestCancel
+{
+// Test1
+child:
+ [Nested=inside_sync] sync Test1_1();
+parent:
+ async Done1();
+
+// Test2
+child:
+ async Start2();
+ [Nested=inside_sync] sync Test2_2();
+parent:
+ sync Test2_1();
+
+// Test3
+child:
+ [Nested=inside_sync] sync Test3_1();
+parent:
+ async Start3();
+ [Nested=inside_sync] sync Test3_2();
+
+parent:
+ async Done();
+
+child:
+ [Nested=inside_sync] sync CheckChild() returns (uint32_t reply);
+parent:
+ [Nested=inside_sync] sync CheckParent() returns (uint32_t reply);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestCrashCleanup.ipdl b/ipc/ipdl/test/cxx/PTestCrashCleanup.ipdl
new file mode 100644
index 0000000000..43d955f1c7
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestCrashCleanup.ipdl
@@ -0,0 +1,20 @@
+include "mozilla/_ipdltest/TestCrashCleanup.h";
+
+// See bug 538586: if the top-level protocol's actor is deleted before
+// the "connection error" notification comes in from the IO thread,
+// IPDL teardown never occurs, even if Channel::Close() is called
+// after the error.
+
+namespace mozilla {
+namespace _ipdltest {
+
+// NB: needs to be RPC so that the parent blocks on the child's crash.
+[ManualDealloc, ChildImpl="TestCrashCleanupChild", ParentImpl="TestCrashCleanupParent"]
+intr protocol PTestCrashCleanup {
+child:
+ [LegacyIntr] intr DIEDIEDIE();
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestDataStructures.ipdl b/ipc/ipdl/test/cxx/PTestDataStructures.ipdl
new file mode 100644
index 0000000000..64b6970666
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDataStructures.ipdl
@@ -0,0 +1,109 @@
+include protocol PTestDataStructuresSub;
+include PTestDataStructuresCommon;
+
+include "mozilla/GfxMessageUtils.h";
+include "mozilla/_ipdltest/TestDataStructures.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestDataStructuresChild", ParentImpl="TestDataStructuresParent"]
+sync protocol PTestDataStructures {
+ manages PTestDataStructuresSub;
+
+child:
+ async PTestDataStructuresSub(int i);
+
+ async Start();
+
+parent:
+ async __delete__();
+
+ sync Test1(int[] i1)
+ returns (int[] o1);
+
+ sync Test2(PTestDataStructuresSub[] i1)
+ returns (PTestDataStructuresSub[] o1);
+
+ sync Test3(IntDouble i1,
+ IntDouble i2)
+ returns (IntDouble o1,
+ IntDouble o2);
+
+ sync Test4(IntDouble[] i1)
+ returns (IntDouble[] o1);
+
+ sync Test5(IntDoubleArrays i1,
+ IntDoubleArrays i2,
+ IntDoubleArrays i3)
+ returns (IntDoubleArrays o1,
+ IntDoubleArrays o2,
+ IntDoubleArrays o3);
+
+ sync Test6(IntDoubleArrays[] i1)
+ returns (IntDoubleArrays[] o1);
+
+ sync Test7_0(ActorWrapper a1)
+ returns (ActorWrapper o1);
+
+ sync Test7(Actors i1,
+ Actors i2,
+ Actors i3)
+ returns (Actors o1,
+ Actors o2,
+ Actors o3);
+
+ sync Test8(Actors[] i1)
+ returns (Actors[] o1);
+
+ sync Test9(Unions i1,
+ Unions i2,
+ Unions i3,
+ Unions i4)
+ returns (Unions o1,
+ Unions o2,
+ Unions o3,
+ Unions o4);
+
+ sync Test10(Unions[] i1)
+ returns (Unions[] o1);
+
+ sync Test11(SIntDouble i)
+ returns (SIntDouble o);
+
+ sync Test12(SIntDoubleArrays i)
+ returns (SIntDoubleArrays o);
+
+ sync Test13(SActors i)
+ returns (SActors o);
+
+ sync Test14(Structs i)
+ returns (Structs o);
+
+ sync Test15(WithStructs i1,
+ WithStructs i2,
+ WithStructs i3,
+ WithStructs i4,
+ WithStructs i5)
+ returns (WithStructs o1,
+ WithStructs o2,
+ WithStructs o3,
+ WithStructs o4,
+ WithStructs o5);
+
+ sync Test16(WithUnions i)
+ returns (WithUnions o);
+
+ sync Test17(Op[] ops);
+
+ // test that the ParamTraits<nsTArray>::Read() workaround for
+ // nsTArray's incorrect memmove() semantics works properly
+ // (nsIntRegion isn't memmove()able)
+ sync Test18(nsIntRegion[] ops);
+
+ sync Dummy(ShmemUnion su) returns (ShmemUnion rsu);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
diff --git a/ipc/ipdl/test/cxx/PTestDataStructuresCommon.ipdlh b/ipc/ipdl/test/cxx/PTestDataStructuresCommon.ipdlh
new file mode 100644
index 0000000000..39d7f482b3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDataStructuresCommon.ipdlh
@@ -0,0 +1,107 @@
+include protocol PTestDataStructuresSub;
+
+using struct mozilla::null_t from "mozilla/ipc/IPCCore.h";
+using nsIntRegion from "nsRegion.h";
+
+namespace mozilla {
+namespace _foo {
+
+union IntDouble {
+ int;
+ double;
+};
+
+struct SIntDouble {
+ int i;
+ double d;
+};
+
+union IntDoubleArrays {
+ int;
+ int[];
+ double[];
+};
+
+struct SIntDoubleArrays {
+ int i;
+ int[] ai;
+ double[] ad;
+};
+
+struct ActorWrapper {
+ PTestDataStructuresSub actor;
+};
+
+union Actors {
+ int;
+ int[];
+ PTestDataStructuresSub[];
+};
+
+struct SActors {
+ int i;
+ int[] ai;
+ PTestDataStructuresSub[] ap;
+};
+
+union Unions {
+ int;
+ int[];
+ PTestDataStructuresSub[];
+ Actors[];
+};
+
+struct Structs {
+ int i;
+ int[] ai;
+ PTestDataStructuresSub[] ap;
+ SActors[] aa;
+};
+
+union WithStructs {
+ int;
+ int[];
+ PTestDataStructuresSub[];
+ SActors[];
+ Structs[];
+};
+
+struct WithUnions {
+ int i;
+ int[] ai;
+ PTestDataStructuresSub[] ap;
+ Actors[] aa;
+ Unions[] au;
+};
+
+struct CommonAttrs { bool dummy; };
+struct FooAttrs { int dummy; };
+struct BarAttrs { float dummy; };
+union SpecificAttrs {
+ FooAttrs;
+ BarAttrs;
+};
+struct Attrs {
+ CommonAttrs common;
+ SpecificAttrs specific;
+};
+struct SetAttrs {
+ PTestDataStructuresSub x;
+ Attrs attrs;
+};
+union Op { null_t; SetAttrs; };
+
+struct ShmemStruct {
+ int i;
+ Shmem mem;
+};
+
+union ShmemUnion {
+ int;
+ Shmem;
+};
+
+struct Empty { };
+
+} // namespace _foo
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestDataStructuresSub.ipdl b/ipc/ipdl/test/cxx/PTestDataStructuresSub.ipdl
new file mode 100644
index 0000000000..4f546a8d29
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDataStructuresSub.ipdl
@@ -0,0 +1,18 @@
+include PTestDataStructuresCommon;
+include protocol PTestDataStructures;
+
+include "mozilla/_ipdltest/TestDataStructures.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestDataStructuresSub", ParentImpl="TestDataStructuresSub"]
+sync protocol PTestDataStructuresSub {
+ manager PTestDataStructures;
+
+parent:
+ sync __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestDemon.ipdl b/ipc/ipdl/test/cxx/PTestDemon.ipdl
new file mode 100644
index 0000000000..f5af2396e6
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDemon.ipdl
@@ -0,0 +1,24 @@
+include "mozilla/_ipdltest/TestDemon.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_cpow, ChildImpl="TestDemonChild", ParentImpl="TestDemonParent"]
+sync protocol PTestDemon
+{
+child:
+ async Start();
+
+both:
+ async AsyncMessage(int n);
+ [Nested=inside_sync] sync HiPrioSyncMessage();
+
+parent:
+ sync SyncMessage(int n);
+
+ [Nested=inside_cpow] async UrgentAsyncMessage(int n);
+ [Nested=inside_cpow] sync UrgentSyncMessage(int n);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestDesc.ipdl b/ipc/ipdl/test/cxx/PTestDesc.ipdl
new file mode 100644
index 0000000000..d18d2d8598
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDesc.ipdl
@@ -0,0 +1,24 @@
+include protocol PTestDescSub;
+include protocol PTestDescSubsub;
+
+include "mozilla/_ipdltest/TestDesc.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestDescChild", ParentImpl="TestDescParent"]
+intr protocol PTestDesc {
+ manages PTestDescSub;
+child:
+ [LegacyIntr] intr PTestDescSub(nullable PTestDescSubsub dummy);
+
+ async Test(PTestDescSubsub a);
+
+ async __delete__();
+
+parent:
+ async Ok(PTestDescSubsub a);
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestDescSub.ipdl b/ipc/ipdl/test/cxx/PTestDescSub.ipdl
new file mode 100644
index 0000000000..a05451c639
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDescSub.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestDesc;
+include protocol PTestDescSubsub;
+
+include "mozilla/_ipdltest/TestDesc.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestDescSubChild", ParentImpl="TestDescSubParent"]
+intr protocol PTestDescSub {
+ manager PTestDesc;
+ manages PTestDescSubsub;
+
+child:
+ async __delete__();
+
+ [LegacyIntr] intr PTestDescSubsub();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestDescSubsub.ipdl b/ipc/ipdl/test/cxx/PTestDescSubsub.ipdl
new file mode 100644
index 0000000000..542a03e2d2
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestDescSubsub.ipdl
@@ -0,0 +1,18 @@
+
+include protocol PTestDescSub;
+
+include "mozilla/_ipdltest/TestDesc.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestDescSubsubChild", ParentImpl="TestDescSubsubParent"]
+intr protocol PTestDescSubsub {
+ manager PTestDescSub;
+
+child:
+ [LegacyIntr] intr __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestEndpointBridgeMain.ipdl b/ipc/ipdl/test/cxx/PTestEndpointBridgeMain.ipdl
new file mode 100644
index 0000000000..c51967b1fa
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestEndpointBridgeMain.ipdl
@@ -0,0 +1,25 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+include protocol PTestEndpointBridgeMainSub;
+include protocol PTestEndpointBridgeSub;
+
+include "mozilla/_ipdltest/TestEndpointBridgeMain.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestEndpointBridgeMainChild", ParentImpl="TestEndpointBridgeMainParent"]
+protocol PTestEndpointBridgeMain {
+
+child:
+ async Start();
+
+parent:
+ async Bridged(Endpoint<PTestEndpointBridgeMainSubParent> endpoint);
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestEndpointBridgeMainSub.ipdl b/ipc/ipdl/test/cxx/PTestEndpointBridgeMainSub.ipdl
new file mode 100644
index 0000000000..e899fca7aa
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestEndpointBridgeMainSub.ipdl
@@ -0,0 +1,28 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+include protocol PTestEndpointBridgeMain;
+include protocol PTestEndpointBridgeSub;
+
+include "mozilla/_ipdltest/TestEndpointBridgeMain.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+// (Bridge protocols can have different semantics than the endpoints
+// they bridge)
+[ManualDealloc, ChildImpl="TestEndpointBridgeMainSubChild", ParentImpl="TestEndpointBridgeMainSubParent"]
+intr protocol PTestEndpointBridgeMainSub {
+child:
+ async Hi();
+ [LegacyIntr] intr HiRpc();
+
+parent:
+ async Hello();
+ sync HelloSync();
+ [LegacyIntr] intr HelloRpc();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestEndpointBridgeSub.ipdl b/ipc/ipdl/test/cxx/PTestEndpointBridgeSub.ipdl
new file mode 100644
index 0000000000..ab12e3bdb5
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestEndpointBridgeSub.ipdl
@@ -0,0 +1,25 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+include protocol PTestEndpointBridgeMainSub;
+
+include "mozilla/_ipdltest/TestEndpointBridgeMain.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestEndpointBridgeSubChild", ParentImpl="TestEndpointBridgeSubParent"]
+protocol PTestEndpointBridgeSub {
+child:
+ async Ping();
+
+ async Bridged(Endpoint<PTestEndpointBridgeMainSubChild> endpoint);
+
+parent:
+ async BridgeEm();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestEndpointOpens.ipdl b/ipc/ipdl/test/cxx/PTestEndpointOpens.ipdl
new file mode 100644
index 0000000000..6cb20bf8eb
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestEndpointOpens.ipdl
@@ -0,0 +1,22 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+include protocol PTestEndpointOpensOpened;
+
+include "mozilla/_ipdltest/TestEndpointOpens.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestEndpointOpensChild", ParentImpl="TestEndpointOpensParent"]
+protocol PTestEndpointOpens {
+child:
+ async Start();
+
+parent:
+ async StartSubprotocol(Endpoint<PTestEndpointOpensOpenedParent> endpoint);
+
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestEndpointOpensOpened.ipdl b/ipc/ipdl/test/cxx/PTestEndpointOpensOpened.ipdl
new file mode 100644
index 0000000000..7f72828c30
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestEndpointOpensOpened.ipdl
@@ -0,0 +1,25 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+include "mozilla/_ipdltest/TestEndpointOpens.h";
+
+namespace mozilla {
+namespace _ipdltest2 {
+
+// (Opens protocols can have different semantics than the endpoints
+// that opened them)
+[ManualDealloc, ChildImpl="TestEndpointOpensOpenedChild", ParentImpl="TestEndpointOpensOpenedParent"]
+intr protocol PTestEndpointOpensOpened {
+child:
+ async Hi();
+ [LegacyIntr] intr HiRpc();
+
+parent:
+ async Hello();
+ sync HelloSync();
+ [LegacyIntr] intr HelloRpc();
+ async __delete__();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest2
diff --git a/ipc/ipdl/test/cxx/PTestFailedCtor.ipdl b/ipc/ipdl/test/cxx/PTestFailedCtor.ipdl
new file mode 100644
index 0000000000..0144f66dba
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestFailedCtor.ipdl
@@ -0,0 +1,17 @@
+include protocol PTestFailedCtorSub;
+
+include "mozilla/_ipdltest/TestFailedCtor.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestFailedCtorChild", ParentImpl="TestFailedCtorParent"]
+intr protocol PTestFailedCtor {
+ manages PTestFailedCtorSub;
+child:
+ [LegacyIntr] intr PTestFailedCtorSub();
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestFailedCtorSub.ipdl b/ipc/ipdl/test/cxx/PTestFailedCtorSub.ipdl
new file mode 100644
index 0000000000..97bc4d4bf8
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestFailedCtorSub.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestFailedCtor;
+include protocol PTestFailedCtorSubsub;
+
+include "mozilla/_ipdltest/TestFailedCtor.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestFailedCtorSubChild", ParentImpl="TestFailedCtorSubParent"]
+intr protocol PTestFailedCtorSub {
+ manager PTestFailedCtor;
+ manages PTestFailedCtorSubsub;
+
+parent:
+ async PTestFailedCtorSubsub();
+ sync Sync();
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestFailedCtorSubsub.ipdl b/ipc/ipdl/test/cxx/PTestFailedCtorSubsub.ipdl
new file mode 100644
index 0000000000..84cb2a0eb8
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestFailedCtorSubsub.ipdl
@@ -0,0 +1,18 @@
+
+include protocol PTestFailedCtorSub;
+
+include "mozilla/_ipdltest/TestFailedCtor.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestFailedCtorSubsub", ParentImpl="TestFailedCtorSubsub"]
+intr protocol PTestFailedCtorSubsub {
+ manager PTestFailedCtorSub;
+
+parent:
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestHandle.ipdl b/ipc/ipdl/test/cxx/PTestHandle.ipdl
new file mode 100644
index 0000000000..b0a65f69c0
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestHandle.ipdl
@@ -0,0 +1,17 @@
+include protocol PTestJSON;
+
+include "mozilla/_ipdltest/TestJSON.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestHandleChild", ParentImpl="TestHandleParent"]
+protocol PTestHandle {
+ manager PTestJSON;
+
+child:
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestHangs.ipdl b/ipc/ipdl/test/cxx/PTestHangs.ipdl
new file mode 100644
index 0000000000..cadc1eda2e
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestHangs.ipdl
@@ -0,0 +1,22 @@
+
+include "mozilla/_ipdltest/TestHangs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestHangsChild", ParentImpl="TestHangsParent"]
+intr protocol PTestHangs {
+both:
+ [LegacyIntr] intr StackFrame();
+
+parent:
+ async Nonce();
+
+child:
+ async Start();
+ [LegacyIntr] intr Hang();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestHighestPrio.ipdl b/ipc/ipdl/test/cxx/PTestHighestPrio.ipdl
new file mode 100644
index 0000000000..877ba427b6
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestHighestPrio.ipdl
@@ -0,0 +1,21 @@
+include "mozilla/_ipdltest/TestHighestPrio.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_cpow, ChildImpl="TestHighestPrioChild", ParentImpl="TestHighestPrioParent"]
+sync protocol PTestHighestPrio
+{
+parent:
+ [Nested=inside_cpow] async Msg1();
+ [Nested=inside_sync] sync Msg2();
+ [Nested=inside_cpow] async Msg3();
+ [Nested=inside_cpow] sync Msg4();
+
+child:
+ async Start();
+ [Nested=inside_sync] sync StartInner();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestIndirectProtocolParam.ipdlh b/ipc/ipdl/test/cxx/PTestIndirectProtocolParam.ipdlh
new file mode 100644
index 0000000000..a81fcdee46
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestIndirectProtocolParam.ipdlh
@@ -0,0 +1,15 @@
+include protocol PTestIndirectProtocolParamSecond;
+
+namespace mozilla {
+namespace _ipdltest {
+
+struct IndirectParamStruct {
+ PTestIndirectProtocolParamSecond actor;
+};
+
+union IndirectParamUnion {
+ IndirectParamStruct;
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestIndirectProtocolParamFirst.ipdl b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamFirst.ipdl
new file mode 100644
index 0000000000..5364d79ffb
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamFirst.ipdl
@@ -0,0 +1,20 @@
+include protocol PTestIndirectProtocolParamManage;
+// FIXME/bug 792908 protocol PTestIndirectProtocolParamSecond is
+// already included in PTestIndirectProtocolParam.ipdlh
+include protocol PTestIndirectProtocolParamSecond;
+include PTestIndirectProtocolParam;
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl=virtual, ParentImpl=virtual]
+sync protocol PTestIndirectProtocolParamFirst {
+ manager PTestIndirectProtocolParamManage;
+parent:
+ sync Test(IndirectParamUnion actor);
+both:
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestIndirectProtocolParamManage.ipdl b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamManage.ipdl
new file mode 100644
index 0000000000..8d3c6f81b1
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamManage.ipdl
@@ -0,0 +1,18 @@
+include protocol PTestIndirectProtocolParamFirst;
+include protocol PTestIndirectProtocolParamSecond;
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl=virtual, ParentImpl=virtual]
+sync protocol PTestIndirectProtocolParamManage {
+ manages PTestIndirectProtocolParamFirst;
+ manages PTestIndirectProtocolParamSecond;
+both:
+ async PTestIndirectProtocolParamFirst();
+ async PTestIndirectProtocolParamSecond();
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestIndirectProtocolParamSecond.ipdl b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamSecond.ipdl
new file mode 100644
index 0000000000..27545ca2cb
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestIndirectProtocolParamSecond.ipdl
@@ -0,0 +1,14 @@
+include protocol PTestIndirectProtocolParamManage;
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl=virtual, ParentImpl=virtual]
+sync protocol PTestIndirectProtocolParamSecond {
+ manager PTestIndirectProtocolParamManage;
+both:
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestInterruptErrorCleanup.ipdl b/ipc/ipdl/test/cxx/PTestInterruptErrorCleanup.ipdl
new file mode 100644
index 0000000000..ab6754cc1b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestInterruptErrorCleanup.ipdl
@@ -0,0 +1,14 @@
+include "mozilla/_ipdltest/TestInterruptErrorCleanup.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestInterruptErrorCleanupChild", ParentImpl="TestInterruptErrorCleanupParent"]
+intr protocol PTestInterruptErrorCleanup {
+child:
+ [LegacyIntr] intr Error();
+ [LegacyIntr] intr __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestInterruptRaces.ipdl b/ipc/ipdl/test/cxx/PTestInterruptRaces.ipdl
new file mode 100644
index 0000000000..aa66966938
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestInterruptRaces.ipdl
@@ -0,0 +1,27 @@
+include "mozilla/_ipdltest/TestInterruptRaces.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestInterruptRacesChild", ParentImpl="TestInterruptRacesParent"]
+intr protocol PTestInterruptRaces {
+both:
+ [LegacyIntr] intr Race() returns (bool hasReply);
+ [LegacyIntr] intr StackFrame() returns ();
+ [LegacyIntr] intr StackFrame3() returns ();
+
+parent:
+ sync StartRace();
+ [LegacyIntr] intr Parent();
+ sync GetAnsweredParent() returns (bool answeredParent);
+
+child:
+ async Start();
+ async Wakeup();
+ async Wakeup3();
+ [LegacyIntr] intr Child();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestInterruptShutdownRace.ipdl b/ipc/ipdl/test/cxx/PTestInterruptShutdownRace.ipdl
new file mode 100644
index 0000000000..84bc6f0a97
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestInterruptShutdownRace.ipdl
@@ -0,0 +1,19 @@
+include "mozilla/_ipdltest/TestInterruptShutdownRace.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestInterruptShutdownRaceChild", ParentImpl="TestInterruptShutdownRaceParent"]
+intr protocol PTestInterruptShutdownRace {
+parent:
+ sync StartDeath();
+ async Orphan();
+
+child:
+ async Start();
+ [LegacyIntr] intr Exit();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestJSON.ipdl b/ipc/ipdl/test/cxx/PTestJSON.ipdl
new file mode 100644
index 0000000000..c785abe77a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestJSON.ipdl
@@ -0,0 +1,49 @@
+include protocol PTestHandle;
+
+include "mozilla/_ipdltest/TestJSON.h";
+
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+using struct mozilla::null_t from "mozilla/ipc/IPCCore.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+union Key {
+// int;
+// double;
+ nsString;
+};
+
+struct KeyValue {
+ Key key;
+ JSONVariant value;
+};
+
+union JSONVariant {
+ void_t;
+ null_t;
+ bool;
+ int;
+ double;
+ nsString;
+ PTestHandle;
+ KeyValue[];
+ JSONVariant[];
+};
+
+[ManualDealloc, ChildImpl="TestJSONChild", ParentImpl="TestJSONParent"]
+sync protocol PTestJSON {
+ manages PTestHandle;
+
+child:
+ async Start();
+
+parent:
+ async PTestHandle();
+ sync Test(JSONVariant i)
+ returns (JSONVariant o);
+ async __delete__();
+};
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestLatency.ipdl b/ipc/ipdl/test/cxx/PTestLatency.ipdl
new file mode 100644
index 0000000000..d868d119a2
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestLatency.ipdl
@@ -0,0 +1,28 @@
+include "mozilla/_ipdltest/TestLatency.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestLatencyChild", ParentImpl="TestLatencyParent"]
+intr protocol PTestLatency {
+
+child:
+ async __delete__();
+ async Ping();
+ async Ping5();
+ [LegacyIntr] intr Rpc();
+ async Spam();
+ [LegacyIntr] intr Synchro();
+ [Compress] async CompressedSpam(uint32_t seqno);
+ [LegacyIntr] intr Synchro2() returns (uint32_t lastSeqno,
+ uint32_t numMessagesDispatched);
+
+parent:
+ async Pong();
+ async Pong5();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestManyChildAllocs.ipdl b/ipc/ipdl/test/cxx/PTestManyChildAllocs.ipdl
new file mode 100644
index 0000000000..6f8a0e1187
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestManyChildAllocs.ipdl
@@ -0,0 +1,22 @@
+include protocol PTestManyChildAllocsSub;
+
+include "mozilla/_ipdltest/TestManyChildAllocs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestManyChildAllocsChild", ParentImpl="TestManyChildAllocsParent"]
+protocol PTestManyChildAllocs {
+ manages PTestManyChildAllocsSub;
+
+child:
+ async Go(); // start allocating
+
+parent:
+ async Done();
+
+ async PTestManyChildAllocsSub();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestManyChildAllocsSub.ipdl b/ipc/ipdl/test/cxx/PTestManyChildAllocsSub.ipdl
new file mode 100644
index 0000000000..e20c2badfd
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestManyChildAllocsSub.ipdl
@@ -0,0 +1,22 @@
+include protocol PTestManyChildAllocs;
+
+include "mozilla/_ipdltest/TestManyChildAllocs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestManyChildAllocsSubChild", ParentImpl="TestManyChildAllocsSubParent"]
+protocol PTestManyChildAllocsSub {
+ manager PTestManyChildAllocs;
+
+child:
+ async __delete__();
+
+parent:
+ async Hello();
+
+ // empty
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestMultiMgrs.ipdl b/ipc/ipdl/test/cxx/PTestMultiMgrs.ipdl
new file mode 100644
index 0000000000..65272fa991
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestMultiMgrs.ipdl
@@ -0,0 +1,25 @@
+include protocol PTestMultiMgrsLeft;
+include protocol PTestMultiMgrsRight;
+
+include "mozilla/_ipdltest/TestMultiMgrs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestMultiMgrsChild", ParentImpl="TestMultiMgrsParent"]
+protocol PTestMultiMgrs {
+ manages PTestMultiMgrsLeft;
+ manages PTestMultiMgrsRight;
+
+parent:
+ async OK();
+
+child:
+ async PTestMultiMgrsLeft();
+ async PTestMultiMgrsRight();
+ async Check();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestMultiMgrsBottom.ipdl b/ipc/ipdl/test/cxx/PTestMultiMgrsBottom.ipdl
new file mode 100644
index 0000000000..be85b1547b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestMultiMgrsBottom.ipdl
@@ -0,0 +1,18 @@
+include protocol PTestMultiMgrsLeft;
+include protocol PTestMultiMgrsRight;
+
+include "mozilla/_ipdltest/TestMultiMgrs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestMultiMgrsBottomChild", ParentImpl="TestMultiMgrsBottomParent"]
+protocol PTestMultiMgrsBottom {
+ manager PTestMultiMgrsLeft or PTestMultiMgrsRight;
+
+child:
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestMultiMgrsLeft.ipdl b/ipc/ipdl/test/cxx/PTestMultiMgrsLeft.ipdl
new file mode 100644
index 0000000000..3796ff315e
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestMultiMgrsLeft.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestMultiMgrs;
+include protocol PTestMultiMgrsBottom;
+
+include "mozilla/_ipdltest/TestMultiMgrs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestMultiMgrsLeftChild", ParentImpl="TestMultiMgrsLeftParent"]
+protocol PTestMultiMgrsLeft {
+ manager PTestMultiMgrs;
+
+ manages PTestMultiMgrsBottom;
+
+child:
+ async PTestMultiMgrsBottom();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestMultiMgrsRight.ipdl b/ipc/ipdl/test/cxx/PTestMultiMgrsRight.ipdl
new file mode 100644
index 0000000000..174ada5ca3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestMultiMgrsRight.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestMultiMgrs;
+include protocol PTestMultiMgrsBottom;
+
+include "mozilla/_ipdltest/TestMultiMgrs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestMultiMgrsRightChild", ParentImpl="TestMultiMgrsRightParent"]
+protocol PTestMultiMgrsRight {
+ manager PTestMultiMgrs;
+
+ manages PTestMultiMgrsBottom;
+
+child:
+ async PTestMultiMgrsBottom();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestNestedLoops.ipdl b/ipc/ipdl/test/cxx/PTestNestedLoops.ipdl
new file mode 100644
index 0000000000..168461ab41
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestNestedLoops.ipdl
@@ -0,0 +1,22 @@
+
+include "mozilla/_ipdltest/TestNestedLoops.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestNestedLoopsChild", ParentImpl="TestNestedLoopsParent"]
+intr protocol PTestNestedLoops {
+
+child:
+ async Start();
+ [LegacyIntr] intr R();
+ async __delete__();
+
+parent:
+ async Nonce();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestPaintThread.ipdl b/ipc/ipdl/test/cxx/PTestPaintThread.ipdl
new file mode 100644
index 0000000000..00d46c9757
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestPaintThread.ipdl
@@ -0,0 +1,15 @@
+include "mozilla/_ipdltest/TestOffMainThreadPainting.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+// This is supposed to be analagous to PPaintingBridge.
+[ManualDealloc, ChildImpl="TestPaintThreadChild", ParentImpl="TestPaintThreadParent"]
+sync protocol PTestPaintThread
+{
+parent:
+ sync FinishedPaint(uint64_t aTxnId);
+};
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestPriority.ipdl b/ipc/ipdl/test/cxx/PTestPriority.ipdl
new file mode 100644
index 0000000000..8b85368072
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestPriority.ipdl
@@ -0,0 +1,24 @@
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl=virtual, ParentImpl=virtual]
+sync protocol PTestPriority {
+parent:
+ [Priority=input] async PMsg1();
+ [Priority=input] sync PMsg2();
+ [Priority=vsync] async PMsg3();
+ [Priority=vsync] sync PMsg4();
+ [Priority=mediumhigh] async PMsg5();
+ [Priority=mediumhigh] sync PMsg6();
+ [Priority=control] async PMsg7();
+ [Priority=control] sync PMsg8();
+
+child:
+ [Priority=input] async CMsg1();
+ [Priority=vsync] async CMsg2();
+ [Priority=mediumhigh] async CMsg3();
+ [Priority=control] async CMsg4();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestRPC.ipdl b/ipc/ipdl/test/cxx/PTestRPC.ipdl
new file mode 100644
index 0000000000..4d459eeb03
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRPC.ipdl
@@ -0,0 +1,24 @@
+include "mozilla/_ipdltest/TestRPC.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_sync, ChildImpl="TestRPCChild", ParentImpl="TestRPCParent"]
+sync protocol PTestRPC
+{
+parent:
+ [Nested=inside_sync] sync Test1_Start() returns (uint32_t result);
+ [Nested=inside_sync] sync Test1_InnerEvent() returns (uint32_t result);
+ async Test2_Start();
+ [Nested=inside_sync] sync Test2_OutOfOrder();
+
+child:
+ async Start();
+ [Nested=inside_sync] sync Test1_InnerQuery() returns (uint32_t result);
+ [Nested=inside_sync] sync Test1_NoReenter() returns (uint32_t result);
+ [Nested=inside_sync] sync Test2_FirstUrgent();
+ [Nested=inside_sync] sync Test2_SecondUrgent();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestRaceDeadlock.ipdl b/ipc/ipdl/test/cxx/PTestRaceDeadlock.ipdl
new file mode 100644
index 0000000000..125919f9af
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRaceDeadlock.ipdl
@@ -0,0 +1,23 @@
+include "mozilla/_ipdltest/TestRaceDeadlock.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestRaceDeadlockChild", ParentImpl="TestRaceDeadlockParent"]
+intr protocol PTestRaceDeadlock {
+both:
+ async StartRace();
+
+parent:
+ [LegacyIntr] intr Lose();
+
+child:
+ [LegacyIntr] intr Win();
+ [LegacyIntr] intr Rpc();
+ async __delete__();
+
+/* Tests that race resolution does not cause deadlocks */
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestRaceDeferral.ipdl b/ipc/ipdl/test/cxx/PTestRaceDeferral.ipdl
new file mode 100644
index 0000000000..f165fa1cea
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRaceDeferral.ipdl
@@ -0,0 +1,22 @@
+include "mozilla/_ipdltest/TestRaceDeferral.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestRaceDeferralChild", ParentImpl="TestRaceDeferralParent"]
+intr protocol PTestRaceDeferral {
+parent:
+ [LegacyIntr] intr Lose();
+
+child:
+ async StartRace();
+ [LegacyIntr] intr Win();
+ [LegacyIntr] intr Rpc();
+ async __delete__();
+
+// Test that messages deferred due to race resolution are
+// re-considered when the winner makes later RPCs
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestRacyInterruptReplies.ipdl b/ipc/ipdl/test/cxx/PTestRacyInterruptReplies.ipdl
new file mode 100644
index 0000000000..37b7973e6d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRacyInterruptReplies.ipdl
@@ -0,0 +1,20 @@
+include "mozilla/_ipdltest/TestRacyInterruptReplies.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestRacyInterruptRepliesChild", ParentImpl="TestRacyInterruptRepliesParent"]
+intr protocol PTestRacyInterruptReplies {
+child:
+ [LegacyIntr] intr R_() returns (int replyNum);
+ async _A();
+ async ChildTest();
+ async __delete__();
+
+parent:
+ [LegacyIntr] intr _R() returns (int replyNum);
+ async A_();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestRacyReentry.ipdl b/ipc/ipdl/test/cxx/PTestRacyReentry.ipdl
new file mode 100644
index 0000000000..b9579cef24
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRacyReentry.ipdl
@@ -0,0 +1,23 @@
+include "mozilla/_ipdltest/TestRacyReentry.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestRacyReentryChild", ParentImpl="TestRacyReentryParent"]
+intr protocol PTestRacyReentry {
+
+parent:
+ [LegacyIntr] intr E();
+ async __delete__();
+
+child:
+ async Start();
+
+ async N();
+ [LegacyIntr] intr H();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestRacyUndefer.ipdl b/ipc/ipdl/test/cxx/PTestRacyUndefer.ipdl
new file mode 100644
index 0000000000..6256eca9db
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestRacyUndefer.ipdl
@@ -0,0 +1,30 @@
+include "mozilla/_ipdltest/TestRacyUndefer.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestRacyUndeferChild", ParentImpl="TestRacyUndeferParent"]
+intr protocol PTestRacyUndefer {
+
+child:
+ async Start();
+
+ async AwakenSpam();
+ async AwakenRaceWinTwice();
+
+ [LegacyIntr] intr Race();
+
+ async __delete__();
+
+parent:
+
+ [LegacyIntr] intr Spam();
+ [LegacyIntr] intr RaceWinTwice();
+
+ async Done();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSanity.ipdl b/ipc/ipdl/test/cxx/PTestSanity.ipdl
new file mode 100644
index 0000000000..3b3e130d4a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSanity.ipdl
@@ -0,0 +1,21 @@
+
+include "mozilla/_ipdltest/TestSanity.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestSanityChild", ParentImpl="TestSanityParent"]
+protocol PTestSanity {
+
+child:
+ async Ping(int zero, float zeroPtFive, int8_t dummy);
+ async __delete__();
+
+parent:
+ async Pong(int one, float zeroPtTwoFive, uint8_t dummy);
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSelfManage.ipdl b/ipc/ipdl/test/cxx/PTestSelfManage.ipdl
new file mode 100644
index 0000000000..19f81a5ae7
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSelfManage.ipdl
@@ -0,0 +1,21 @@
+include protocol PTestSelfManageRoot;
+
+include "mozilla/_ipdltest/TestSelfManageRoot.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestSelfManageChild", ParentImpl="TestSelfManageParent"]
+protocol PTestSelfManage {
+ manager PTestSelfManageRoot or PTestSelfManage;
+ manages PTestSelfManage;
+
+child:
+ async PTestSelfManage();
+ async __delete__();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSelfManageRoot.ipdl b/ipc/ipdl/test/cxx/PTestSelfManageRoot.ipdl
new file mode 100644
index 0000000000..29953228af
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSelfManageRoot.ipdl
@@ -0,0 +1,20 @@
+include protocol PTestSelfManage;
+
+include "mozilla/_ipdltest/TestSelfManageRoot.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestSelfManageRootChild", ParentImpl="TestSelfManageRootParent"]
+protocol PTestSelfManageRoot {
+ manages PTestSelfManage;
+
+child:
+ async PTestSelfManage();
+ async __delete__();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestShmem.ipdl b/ipc/ipdl/test/cxx/PTestShmem.ipdl
new file mode 100644
index 0000000000..7eb6dfdc36
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestShmem.ipdl
@@ -0,0 +1,17 @@
+include "mozilla/_ipdltest/TestShmem.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestShmemChild", ParentImpl="TestShmemParent"]
+protocol PTestShmem {
+child:
+ async Give(Shmem mem, Shmem unsafe, uint32_t expectedSize);
+
+parent:
+ async Take(Shmem mem, Shmem unsafe, uint32_t expectedSize);
+ async __delete__();
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestShutdown.ipdl b/ipc/ipdl/test/cxx/PTestShutdown.ipdl
new file mode 100644
index 0000000000..e57defa46a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestShutdown.ipdl
@@ -0,0 +1,29 @@
+include protocol PTestShutdownSub;
+
+include "mozilla/_ipdltest/TestShutdown.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestShutdownChild", ParentImpl="TestShutdownParent"]
+intr protocol PTestShutdown {
+ manages PTestShutdownSub;
+
+child:
+ async Start();
+
+parent:
+ // NB: we test deletion and crashing only, not shutdown, because
+ // crashing is the same code path as shutdown, and other IPDL unit
+ // tests check shutdown semantics
+ async PTestShutdownSub(bool expectCrash);
+
+ // Used to synchronize between parent and child, to avoid races
+ // around flushing socket write queues
+ sync Sync();
+
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestShutdownSub.ipdl b/ipc/ipdl/test/cxx/PTestShutdownSub.ipdl
new file mode 100644
index 0000000000..e91caca740
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestShutdownSub.ipdl
@@ -0,0 +1,23 @@
+include protocol PTestShutdown;
+include protocol PTestShutdownSubsub;
+
+include "mozilla/_ipdltest/TestShutdown.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestShutdownSubChild", ParentImpl="TestShutdownSubParent"]
+intr protocol PTestShutdownSub {
+ manager PTestShutdown;
+ manages PTestShutdownSubsub;
+
+both:
+ [LegacyIntr] intr StackFrame();
+
+parent:
+ async PTestShutdownSubsub(bool expectParentDeleted);
+ sync __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestShutdownSubsub.ipdl b/ipc/ipdl/test/cxx/PTestShutdownSubsub.ipdl
new file mode 100644
index 0000000000..3b1cc5cb6b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestShutdownSubsub.ipdl
@@ -0,0 +1,17 @@
+include protocol PTestShutdownSub;
+
+include "mozilla/_ipdltest/TestShutdown.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestShutdownSubsubChild", ParentImpl="TestShutdownSubsubParent"]
+sync protocol PTestShutdownSubsub {
+ manager PTestShutdownSub;
+
+parent:
+ sync __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestStackHooks.ipdl b/ipc/ipdl/test/cxx/PTestStackHooks.ipdl
new file mode 100644
index 0000000000..3026dfbfbe
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestStackHooks.ipdl
@@ -0,0 +1,28 @@
+include "mozilla/_ipdltest/TestStackHooks.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestStackHooksChild", ParentImpl="TestStackHooksParent"]
+intr protocol PTestStackHooks {
+child:
+ async Start();
+
+ // These tests are more fruitful running child->parent, because
+ // children can send |sync| messages
+parent:
+ async Async();
+ sync Sync();
+ [LegacyIntr] intr Rpc();
+
+both:
+ [LegacyIntr] intr StackFrame();
+
+parent:
+ async __delete__();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSyncError.ipdl b/ipc/ipdl/test/cxx/PTestSyncError.ipdl
new file mode 100644
index 0000000000..a4b6d428e8
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSyncError.ipdl
@@ -0,0 +1,20 @@
+include "mozilla/_ipdltest/TestSyncError.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestSyncErrorChild", ParentImpl="TestSyncErrorParent"]
+sync protocol PTestSyncError {
+
+child:
+ async Start();
+
+parent:
+ sync Error();
+ async __delete__();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSyncHang.ipdl b/ipc/ipdl/test/cxx/PTestSyncHang.ipdl
new file mode 100644
index 0000000000..05521d6ed2
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSyncHang.ipdl
@@ -0,0 +1,16 @@
+include "mozilla/_ipdltest/TestSyncHang.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+
+[ManualDealloc, ChildImpl="TestSyncHangChild", ParentImpl="TestSyncHangParent"]
+protocol PTestSyncHang {
+
+child:
+ async UnusedMessage();
+};
+
+
+} // namespace mozilla
+} // namespace _ipdltest
diff --git a/ipc/ipdl/test/cxx/PTestSyncWakeup.ipdl b/ipc/ipdl/test/cxx/PTestSyncWakeup.ipdl
new file mode 100644
index 0000000000..807f558dfa
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestSyncWakeup.ipdl
@@ -0,0 +1,23 @@
+include "mozilla/_ipdltest/TestSyncWakeup.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, ChildImpl="TestSyncWakeupChild", ParentImpl="TestSyncWakeupParent"]
+intr protocol PTestSyncWakeup {
+both:
+ [LegacyIntr] intr StackFrame();
+
+child:
+ async Start();
+ async Note1();
+ async Note2();
+
+parent:
+ sync Sync1();
+ sync Sync2();
+ async __delete__();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestUniquePtrIPC.ipdl b/ipc/ipdl/test/cxx/PTestUniquePtrIPC.ipdl
new file mode 100644
index 0000000000..b436dcbbb3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestUniquePtrIPC.ipdl
@@ -0,0 +1,26 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include "mozilla/_ipdltest/TestUniquePtrIPC.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+struct DummyStruct {
+ int x;
+};
+
+[ManualDealloc, ChildImpl="TestUniquePtrIPCChild", ParentImpl="TestUniquePtrIPCParent"]
+protocol PTestUniquePtrIPC
+{
+child:
+ async TestMessage(UniquePtr<int> a1, UniquePtr<DummyStruct> a2,
+ DummyStruct a3, UniquePtr<int> a4);
+ async TestSendReference(UniquePtr<DummyStruct> a);
+};
+
+}
+}
diff --git a/ipc/ipdl/test/cxx/PTestUrgency.ipdl b/ipc/ipdl/test/cxx/PTestUrgency.ipdl
new file mode 100644
index 0000000000..7653d12102
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestUrgency.ipdl
@@ -0,0 +1,22 @@
+include "mozilla/_ipdltest/TestUrgency.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_cpow, ChildImpl="TestUrgencyChild", ParentImpl="TestUrgencyParent"]
+sync protocol PTestUrgency
+{
+parent:
+ [Nested=inside_sync] sync Test1() returns (uint32_t result);
+ async Test2();
+ sync Test3() returns (uint32_t result);
+ sync FinalTest_Begin();
+
+child:
+ async Start();
+ [Nested=inside_sync] sync Reply1() returns (uint32_t result);
+ [Nested=inside_sync] sync Reply2() returns (uint32_t result);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/PTestUrgentHangs.ipdl b/ipc/ipdl/test/cxx/PTestUrgentHangs.ipdl
new file mode 100644
index 0000000000..2c19a7afe1
--- /dev/null
+++ b/ipc/ipdl/test/cxx/PTestUrgentHangs.ipdl
@@ -0,0 +1,31 @@
+include "mozilla/_ipdltest/TestUrgentHangs.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ManualDealloc, NestedUpTo=inside_sync, ChildImpl="TestUrgentHangsChild", ParentImpl="TestUrgentHangsParent"]
+sync protocol PTestUrgentHangs
+{
+parent:
+ [Nested=inside_sync] sync Test1_2();
+
+ [Nested=inside_sync] sync TestInner();
+ [Nested=inside_cpow] sync TestInnerUrgent();
+
+child:
+ [Nested=inside_sync] sync Test1_1();
+ [Nested=inside_sync] sync Test1_3();
+
+ [Nested=inside_sync] sync Test2();
+
+ [Nested=inside_sync] sync Test3();
+
+ async Test4();
+ [Nested=inside_sync] sync Test4_1();
+
+ async Test5();
+ [Nested=inside_sync] sync Test5_1();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/README.txt b/ipc/ipdl/test/cxx/README.txt
new file mode 100644
index 0000000000..0fe6c07320
--- /dev/null
+++ b/ipc/ipdl/test/cxx/README.txt
@@ -0,0 +1,61 @@
+To add a new IPDL C++ unit test, you need to create (at least) the
+following files (for a test "TestFoo"):
+
+ - PTestFoo.ipdl, specifying the top-level protocol used for the test
+
+ - TestFoo.h, declaring the top-level parent/child actors used for
+ the test
+
+ - TestFoo.cpp, defining the top-level actors
+
+ - (make sure all are in the namespace mozilla::_ipdltest)
+
+Next
+
+ - add PTestFoo.ipdl to ipdl.mk
+
+ - append TestFoo to the variable IPDLTESTS in Makefile.in
+
+You must define three methods in your |TestFooParent| class:
+
+ - static methods |bool RunTestInProcesses()| and
+ |bool RunTestInThreads()|. These methods control whether
+ to execute the test using actors in separate processes and
+ threads respectively. Generally, both should return true.
+
+ - an instance method |void Main()|. The test harness wil first
+ initialize the processes or threads, create and open both actors,
+ and then kick off the test using |Main()|. Make sure you define
+ it.
+
+If your test passes its criteria, please call
+|MOZ_IPDL_TESTPASS("msg")| and "exit gracefully".
+
+If your tests fails, please call |MOZ_IPDL_TESTFAIL("msg")| and "exit
+ungracefully", preferably by abort()ing.
+
+
+If all goes well, running
+
+ make -C $OBJDIR/ipc/ipdl/test/cxx
+
+will update the file IPDLUnitTests.cpp (the test launcher), and your
+new code will be built automatically.
+
+
+You can launch your new test by invoking one of
+
+ make -C $OBJDIR/ipc/ipdl/test/cxx check-proc (test process-based tests)
+ make -C $OBJDIR/ipc/ipdl/test/cxx check-threads (test thread-based tests)
+ make -C $OBJDIR/ipc/ipdl/test/cxx check (tests both)
+
+If you want to launch only your test, run
+
+ cd $OBJDIR/dist/bin
+ ./run-mozilla.sh ./ipdlunittest TestFoo (test in two processes, if appl.)
+ ./run-mozilla.sh ./ipdlunittest thread:TestFoo (test in two threads, if appl.)
+
+
+For a bare-bones example of adding a test, take a look at
+PTestSanity.ipdl, TestSanity.h, TestSanity.cpp, and how "TestSanity"
+is included in ipdl.mk and Makefile.in.
diff --git a/ipc/ipdl/test/cxx/TestActorPunning.cpp b/ipc/ipdl/test/cxx/TestActorPunning.cpp
new file mode 100644
index 0000000000..5825796f54
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestActorPunning.cpp
@@ -0,0 +1,125 @@
+#include "TestActorPunning.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#include "mozilla/Unused.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+void TestActorPunningParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestActorPunningParent::RecvPun(
+ PTestActorPunningSubParent* a, const Bad& bad) {
+ if (a->SendBad()) fail("bad!");
+ fail("shouldn't have received this message in the first place");
+ return IPC_OK();
+}
+
+// By default, fatal errors kill the parent process, but this makes it
+// hard to test, so instead we use the previous behavior and kill the
+// child process.
+void TestActorPunningParent::HandleFatalError(const char* aErrorMsg) {
+ if (!!strcmp(aErrorMsg, "Error deserializing 'PTestActorPunningSubParent'")) {
+ fail("wrong fatal error");
+ }
+
+ ipc::ScopedProcessHandle otherProcessHandle;
+ if (!base::OpenProcessHandle(OtherPid(), &otherProcessHandle.rwget())) {
+ fail("couldn't open child process");
+ } else {
+ if (!base::KillProcess(otherProcessHandle, 0, false)) {
+ fail("terminating child process");
+ }
+ }
+}
+
+PTestActorPunningPunnedParent*
+TestActorPunningParent::AllocPTestActorPunningPunnedParent() {
+ return new TestActorPunningPunnedParent();
+}
+
+bool TestActorPunningParent::DeallocPTestActorPunningPunnedParent(
+ PTestActorPunningPunnedParent* a) {
+ delete a;
+ return true;
+}
+
+PTestActorPunningSubParent*
+TestActorPunningParent::AllocPTestActorPunningSubParent() {
+ return new TestActorPunningSubParent();
+}
+
+bool TestActorPunningParent::DeallocPTestActorPunningSubParent(
+ PTestActorPunningSubParent* a) {
+ delete a;
+ return true;
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+PTestActorPunningPunnedChild*
+TestActorPunningChild::AllocPTestActorPunningPunnedChild() {
+ return new TestActorPunningPunnedChild();
+}
+
+bool TestActorPunningChild::DeallocPTestActorPunningPunnedChild(
+ PTestActorPunningPunnedChild*) {
+ fail("should have died by now");
+ return true;
+}
+
+PTestActorPunningSubChild*
+TestActorPunningChild::AllocPTestActorPunningSubChild() {
+ return new TestActorPunningSubChild();
+}
+
+bool TestActorPunningChild::DeallocPTestActorPunningSubChild(
+ PTestActorPunningSubChild*) {
+ fail("should have died by now");
+ return true;
+}
+
+mozilla::ipc::IPCResult TestActorPunningChild::RecvStart() {
+ SendPTestActorPunningSubConstructor();
+ SendPTestActorPunningPunnedConstructor();
+ PTestActorPunningSubChild* a = SendPTestActorPunningSubConstructor();
+ // We can't assert whether this succeeds or fails, due to race
+ // conditions.
+ SendPun(a, Bad());
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestActorPunningSubChild::RecvBad() {
+ fail("things are going really badly right now");
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+namespace IPC {
+using namespace mozilla::_ipdltest;
+using namespace mozilla::ipc;
+
+/*static*/ void ParamTraits<Bad>::Write(MessageWriter* aWriter,
+ const paramType& aParam) {
+ // Skip past the sentinel for the actor as well as the actor.
+ int32_t* ptr = aWriter->GetInt32PtrForTest(2 * sizeof(int32_t));
+ ActorHandle* ah = reinterpret_cast<ActorHandle*>(ptr);
+ if (ah->mId != -3)
+ fail("guessed wrong offset (value is %d, should be -3)", ah->mId);
+ ah->mId = -2;
+}
+
+/*static*/ bool ParamTraits<Bad>::Read(MessageReader* aReader,
+ paramType* aResult) {
+ return true;
+}
+
+} // namespace IPC
diff --git a/ipc/ipdl/test/cxx/TestActorPunning.h b/ipc/ipdl/test/cxx/TestActorPunning.h
new file mode 100644
index 0000000000..cd88106c0c
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestActorPunning.h
@@ -0,0 +1,100 @@
+#ifndef mozilla__ipdltest_TestActorPunning_h
+#define mozilla__ipdltest_TestActorPunning_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestActorPunningParent.h"
+#include "mozilla/_ipdltest/PTestActorPunningPunnedParent.h"
+#include "mozilla/_ipdltest/PTestActorPunningSubParent.h"
+#include "mozilla/_ipdltest/PTestActorPunningChild.h"
+#include "mozilla/_ipdltest/PTestActorPunningPunnedChild.h"
+#include "mozilla/_ipdltest/PTestActorPunningSubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestActorPunningParent : public PTestActorPunningParent {
+ friend class PTestActorPunningParent;
+
+ public:
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ PTestActorPunningPunnedParent* AllocPTestActorPunningPunnedParent();
+ bool DeallocPTestActorPunningPunnedParent(PTestActorPunningPunnedParent* a);
+
+ PTestActorPunningSubParent* AllocPTestActorPunningSubParent();
+ bool DeallocPTestActorPunningSubParent(PTestActorPunningSubParent* a);
+
+ mozilla::ipc::IPCResult RecvPun(PTestActorPunningSubParent* a,
+ const Bad& bad);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown == why) fail("should have died from error!");
+ passed("ok");
+ QuitParent();
+ }
+
+ virtual void HandleFatalError(const char* aErrorMsg) override;
+};
+
+class TestActorPunningPunnedParent : public PTestActorPunningPunnedParent {
+ public:
+ TestActorPunningPunnedParent() {}
+ virtual ~TestActorPunningPunnedParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestActorPunningSubParent : public PTestActorPunningSubParent {
+ public:
+ TestActorPunningSubParent() {}
+ virtual ~TestActorPunningSubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestActorPunningChild : public PTestActorPunningChild {
+ friend class PTestActorPunningChild;
+
+ public:
+ TestActorPunningChild() {}
+ virtual ~TestActorPunningChild() {}
+
+ protected:
+ PTestActorPunningPunnedChild* AllocPTestActorPunningPunnedChild();
+ bool DeallocPTestActorPunningPunnedChild(PTestActorPunningPunnedChild* a);
+
+ PTestActorPunningSubChild* AllocPTestActorPunningSubChild();
+ bool DeallocPTestActorPunningSubChild(PTestActorPunningSubChild* a);
+
+ mozilla::ipc::IPCResult RecvStart();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ fail("should have been killed off!");
+ }
+};
+
+class TestActorPunningPunnedChild : public PTestActorPunningPunnedChild {
+ public:
+ TestActorPunningPunnedChild() {}
+ virtual ~TestActorPunningPunnedChild() {}
+};
+
+class TestActorPunningSubChild : public PTestActorPunningSubChild {
+ public:
+ TestActorPunningSubChild() {}
+ virtual ~TestActorPunningSubChild() {}
+
+ mozilla::ipc::IPCResult RecvBad();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestActorPunning_h
diff --git a/ipc/ipdl/test/cxx/TestAsyncReturns.cpp b/ipc/ipdl/test/cxx/TestAsyncReturns.cpp
new file mode 100644
index 0000000000..76597143c0
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestAsyncReturns.cpp
@@ -0,0 +1,101 @@
+#include "TestAsyncReturns.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+#include "mozilla/AbstractThread.h"
+#include "mozilla/Unused.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+static uint32_t sMagic1 = 0x105b59fb;
+static uint32_t sMagic2 = 0x09b6f5e3;
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestAsyncReturnsParent::TestAsyncReturnsParent() {
+ MOZ_COUNT_CTOR(TestAsyncReturnsParent);
+}
+
+TestAsyncReturnsParent::~TestAsyncReturnsParent() {
+ MOZ_COUNT_DTOR(TestAsyncReturnsParent);
+}
+
+void TestAsyncReturnsParent::Main() {
+ SendNoReturn()->Then(
+ MessageLoop::current()->SerialEventTarget(), __func__,
+ [](bool unused) { fail("resolve handler should not be called"); },
+ [](ResponseRejectReason&& aReason) {
+ // MozPromise asserts in debug build if the
+ // handler is not called
+ if (aReason != ResponseRejectReason::ChannelClosed) {
+ fail("reject with wrong reason");
+ }
+ passed("reject handler called on channel close");
+ });
+ SendPing()->Then(
+ MessageLoop::current()->SerialEventTarget(), __func__,
+ [this](bool one) {
+ if (one) {
+ passed("take one argument");
+ } else {
+ fail("get one argument but has wrong value");
+ }
+
+ // Also try with the callback-based API.
+ SendPing(
+ [this](bool one) {
+ if (one) {
+ passed("take one argument");
+ } else {
+ fail("get one argument but has wrong value");
+ }
+ Close();
+ },
+ [](ResponseRejectReason&& aReason) { fail("sending Ping"); });
+ },
+ [](ResponseRejectReason&& aReason) { fail("sending Ping"); });
+}
+
+mozilla::ipc::IPCResult TestAsyncReturnsParent::RecvPong(
+ PongResolver&& aResolve) {
+ aResolve(std::tuple<const uint32_t&, const uint32_t&>(sMagic1, sMagic2));
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestAsyncReturnsChild::TestAsyncReturnsChild() {
+ MOZ_COUNT_CTOR(TestAsyncReturnsChild);
+}
+
+TestAsyncReturnsChild::~TestAsyncReturnsChild() {
+ MOZ_COUNT_DTOR(TestAsyncReturnsChild);
+}
+
+mozilla::ipc::IPCResult TestAsyncReturnsChild::RecvNoReturn(
+ NoReturnResolver&& aResolve) {
+ // Not resolving the promise intentionally
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestAsyncReturnsChild::RecvPing(
+ PingResolver&& aResolve) {
+ SendPong()->Then(
+ MessageLoop::current()->SerialEventTarget(), __func__,
+ [aResolve](const std::tuple<uint32_t, uint32_t>& aParam) {
+ if (std::get<0>(aParam) == sMagic1 && std::get<1>(aParam) == sMagic2) {
+ passed("take two arguments");
+ } else {
+ fail("get two argument but has wrong value");
+ }
+ aResolve(true);
+ },
+ [](ResponseRejectReason&& aReason) { fail("sending Pong"); });
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestAsyncReturns.h b/ipc/ipdl/test/cxx/TestAsyncReturns.h
new file mode 100644
index 0000000000..5dad3da0ab
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestAsyncReturns.h
@@ -0,0 +1,54 @@
+#ifndef mozilla__ipdltest_TestAsyncReturns_h
+#define mozilla__ipdltest_TestAsyncReturns_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestAsyncReturnsParent.h"
+#include "mozilla/_ipdltest/PTestAsyncReturnsChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestAsyncReturnsParent : public PTestAsyncReturnsParent {
+ friend class PTestAsyncReturnsParent;
+
+ public:
+ TestAsyncReturnsParent();
+ virtual ~TestAsyncReturnsParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPong(PongResolver&& aResolve);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestAsyncReturnsChild : public PTestAsyncReturnsChild {
+ friend class PTestAsyncReturnsChild;
+
+ public:
+ TestAsyncReturnsChild();
+ virtual ~TestAsyncReturnsChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPing(PingResolver&& aResolve);
+ mozilla::ipc::IPCResult RecvNoReturn(NoReturnResolver&& aResolve);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestAsyncReturns_h
diff --git a/ipc/ipdl/test/cxx/TestBadActor.cpp b/ipc/ipdl/test/cxx/TestBadActor.cpp
new file mode 100644
index 0000000000..6c6991dbb2
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestBadActor.cpp
@@ -0,0 +1,59 @@
+#include "TestBadActor.h"
+#include "IPDLUnitTests.h"
+#include "mozilla/Unused.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+void TestBadActorParent::Main() {
+ // This test is designed to test a race condition where the child sends us
+ // a message on an actor that we've already destroyed. The child process
+ // should die, and the parent process should not abort.
+
+ PTestBadActorSubParent* child = SendPTestBadActorSubConstructor();
+ if (!child) fail("Sending constructor");
+
+ Unused << child->Call__delete__(child);
+}
+
+// By default, fatal errors kill the parent process, but this makes it
+// hard to test, so instead we use the previous behavior and kill the
+// child process.
+void TestBadActorParent::HandleFatalError(const char* aErrorMsg) {
+ if (!!strcmp(aErrorMsg, "incoming message racing with actor deletion")) {
+ fail("wrong fatal error");
+ }
+
+ ipc::ScopedProcessHandle otherProcessHandle;
+ if (!base::OpenProcessHandle(OtherPid(), &otherProcessHandle.rwget())) {
+ fail("couldn't open child process");
+ } else {
+ if (!base::KillProcess(otherProcessHandle, 0, false)) {
+ fail("terminating child process");
+ }
+ }
+}
+
+PTestBadActorSubParent* TestBadActorParent::AllocPTestBadActorSubParent() {
+ return new TestBadActorSubParent();
+}
+
+mozilla::ipc::IPCResult TestBadActorSubParent::RecvPing() {
+ fail("Shouldn't have received ping.");
+ return IPC_FAIL_NO_REASON(this);
+}
+
+PTestBadActorSubChild* TestBadActorChild::AllocPTestBadActorSubChild() {
+ return new TestBadActorSubChild();
+}
+
+mozilla::ipc::IPCResult TestBadActorChild::RecvPTestBadActorSubConstructor(
+ PTestBadActorSubChild* actor) {
+ if (!actor->SendPing()) {
+ fail("Couldn't send ping to an actor which supposedly isn't dead yet.");
+ }
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestBadActor.h b/ipc/ipdl/test/cxx/TestBadActor.h
new file mode 100644
index 0000000000..cefe0288f4
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestBadActor.h
@@ -0,0 +1,84 @@
+#ifndef mozilla__ipdltest_TestBadActor_h
+#define mozilla__ipdltest_TestBadActor_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestBadActorParent.h"
+#include "mozilla/_ipdltest/PTestBadActorChild.h"
+
+#include "mozilla/_ipdltest/PTestBadActorSubParent.h"
+#include "mozilla/_ipdltest/PTestBadActorSubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestBadActorParent : public PTestBadActorParent {
+ friend class PTestBadActorParent;
+
+ public:
+ TestBadActorParent() {}
+ virtual ~TestBadActorParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction");
+ passed("ok");
+ QuitParent();
+ }
+
+ virtual void HandleFatalError(const char* aErrorMsg) override;
+
+ PTestBadActorSubParent* AllocPTestBadActorSubParent();
+
+ bool DeallocPTestBadActorSubParent(PTestBadActorSubParent* actor) {
+ delete actor;
+ return true;
+ }
+};
+
+class TestBadActorSubParent : public PTestBadActorSubParent {
+ friend class PTestBadActorSubParent;
+
+ public:
+ TestBadActorSubParent() {}
+ virtual ~TestBadActorSubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+ mozilla::ipc::IPCResult RecvPing();
+};
+
+class TestBadActorChild : public PTestBadActorChild {
+ friend class PTestBadActorChild;
+
+ public:
+ TestBadActorChild() {}
+ virtual ~TestBadActorChild() {}
+
+ protected:
+ virtual PTestBadActorSubChild* AllocPTestBadActorSubChild();
+
+ virtual bool DeallocPTestBadActorSubChild(PTestBadActorSubChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual mozilla::ipc::IPCResult RecvPTestBadActorSubConstructor(
+ PTestBadActorSubChild* actor);
+};
+
+class TestBadActorSubChild : public PTestBadActorSubChild {
+ public:
+ TestBadActorSubChild() {}
+ virtual ~TestBadActorSubChild() {}
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // mozilla__ipdltest_TestBadActor_h
diff --git a/ipc/ipdl/test/cxx/TestCancel.cpp b/ipc/ipdl/test/cxx/TestCancel.cpp
new file mode 100644
index 0000000000..2f97aa2e93
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestCancel.cpp
@@ -0,0 +1,115 @@
+#include "TestCancel.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestCancelParent::TestCancelParent() { MOZ_COUNT_CTOR(TestCancelParent); }
+
+TestCancelParent::~TestCancelParent() { MOZ_COUNT_DTOR(TestCancelParent); }
+
+void TestCancelParent::Main() {
+ if (SendTest1_1()) fail("sending Test1_1");
+
+ uint32_t value = 0;
+ if (!SendCheckChild(&value)) fail("Test1 CheckChild");
+
+ if (value != 12) fail("Test1 CheckChild reply");
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvDone1() {
+ if (!SendStart2()) fail("sending Start2");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvTest2_1() {
+ if (SendTest2_2()) fail("sending Test2_2");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvStart3() {
+ if (SendTest3_1()) fail("sending Test3_1");
+
+ uint32_t value = 0;
+ if (!SendCheckChild(&value)) fail("Test1 CheckChild");
+
+ if (value != 12) fail("Test1 CheckChild reply");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvTest3_2() {
+ GetIPCChannel()->CancelCurrentTransaction();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvDone() {
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "ipc::IToplevelProtocol::Close", this, &TestCancelParent::Close));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelParent::RecvCheckParent(uint32_t* reply) {
+ *reply = 12;
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+mozilla::ipc::IPCResult TestCancelChild::RecvTest1_1() {
+ GetIPCChannel()->CancelCurrentTransaction();
+
+ uint32_t value = 0;
+ if (!SendCheckParent(&value)) fail("Test1 CheckParent");
+
+ if (value != 12) fail("Test1 CheckParent reply");
+
+ if (!SendDone1()) fail("Test1 CheckParent");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelChild::RecvStart2() {
+ if (!SendTest2_1()) fail("sending Test2_1");
+
+ if (!SendStart3()) fail("sending Start3");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelChild::RecvTest2_2() {
+ GetIPCChannel()->CancelCurrentTransaction();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelChild::RecvTest3_1() {
+ if (SendTest3_2()) fail("sending Test3_2");
+
+ uint32_t value = 0;
+ if (!SendCheckParent(&value)) fail("Test1 CheckParent");
+
+ if (value != 12) fail("Test1 CheckParent reply");
+
+ if (!SendDone()) fail("sending Done");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestCancelChild::RecvCheckChild(uint32_t* reply) {
+ *reply = 12;
+ return IPC_OK();
+}
+
+TestCancelChild::TestCancelChild() { MOZ_COUNT_CTOR(TestCancelChild); }
+
+TestCancelChild::~TestCancelChild() { MOZ_COUNT_DTOR(TestCancelChild); }
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestCancel.h b/ipc/ipdl/test/cxx/TestCancel.h
new file mode 100644
index 0000000000..7d944d6a69
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestCancel.h
@@ -0,0 +1,54 @@
+#ifndef mozilla__ipdltest_TestCancel_h
+#define mozilla__ipdltest_TestCancel_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestCancelParent.h"
+#include "mozilla/_ipdltest/PTestCancelChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestCancelParent : public PTestCancelParent {
+ public:
+ TestCancelParent();
+ virtual ~TestCancelParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvDone1();
+ mozilla::ipc::IPCResult RecvTest2_1();
+ mozilla::ipc::IPCResult RecvStart3();
+ mozilla::ipc::IPCResult RecvTest3_2();
+ mozilla::ipc::IPCResult RecvDone();
+
+ mozilla::ipc::IPCResult RecvCheckParent(uint32_t* reply);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestCancelChild : public PTestCancelChild {
+ public:
+ TestCancelChild();
+ virtual ~TestCancelChild();
+
+ mozilla::ipc::IPCResult RecvTest1_1();
+ mozilla::ipc::IPCResult RecvStart2();
+ mozilla::ipc::IPCResult RecvTest2_2();
+ mozilla::ipc::IPCResult RecvTest3_1();
+
+ mozilla::ipc::IPCResult RecvCheckChild(uint32_t* reply);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { QuitChild(); }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestCancel_h
diff --git a/ipc/ipdl/test/cxx/TestCrashCleanup.cpp b/ipc/ipdl/test/cxx/TestCrashCleanup.cpp
new file mode 100644
index 0000000000..6a19cc0f65
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestCrashCleanup.cpp
@@ -0,0 +1,100 @@
+#include "TestCrashCleanup.h"
+
+#include "base/task.h"
+#include "mozilla/CondVar.h"
+#include "mozilla/Mutex.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#include "IPDLUnitTestSubprocess.h"
+
+using mozilla::CondVar;
+using mozilla::Mutex;
+using mozilla::MutexAutoLock;
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+namespace {
+
+// NB: this test does its own shutdown, rather than going through
+// QuitParent(), because it's testing degenerate edge cases
+
+void DeleteSubprocess(Mutex* mutex, CondVar* cvar) {
+ MutexAutoLock lock(*mutex);
+
+ gSubprocess->Destroy();
+ gSubprocess = nullptr;
+
+ cvar->Notify();
+}
+
+void DeleteTheWorld() {
+ delete static_cast<TestCrashCleanupParent*>(gParentActor);
+ gParentActor = nullptr;
+
+ // needs to be synchronous to avoid affecting event ordering on
+ // the main thread
+ Mutex mutex MOZ_UNANNOTATED("TestCrashCleanup.DeleteTheWorld.mutex");
+ CondVar cvar(mutex, "TestCrashCleanup.DeleteTheWorld.cvar");
+
+ MutexAutoLock lock(mutex);
+
+ XRE_GetIOMessageLoop()->PostTask(
+ NewRunnableFunction("DeleteSubprocess", DeleteSubprocess, &mutex, &cvar));
+
+ cvar.Wait();
+}
+
+void Done() {
+ static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
+ nsCOMPtr<nsIAppShell> appShell(do_GetService(kAppShellCID));
+ appShell->Exit();
+
+ passed(__FILE__);
+}
+
+} // namespace
+
+TestCrashCleanupParent::TestCrashCleanupParent() : mCleanedUp(false) {
+ MOZ_COUNT_CTOR(TestCrashCleanupParent);
+}
+
+TestCrashCleanupParent::~TestCrashCleanupParent() {
+ MOZ_COUNT_DTOR(TestCrashCleanupParent);
+
+ if (!mCleanedUp) fail("should have been ActorDestroy()d!");
+}
+
+void TestCrashCleanupParent::Main() {
+ // NB: has to be enqueued before IO thread's error notification
+ MessageLoop::current()->PostTask(
+ NewRunnableFunction("DeleteTheWorld", DeleteTheWorld));
+
+ if (CallDIEDIEDIE()) fail("expected an error!");
+
+ Close();
+
+ MessageLoop::current()->PostTask(NewRunnableFunction("Done", Done));
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestCrashCleanupChild::TestCrashCleanupChild() {
+ MOZ_COUNT_CTOR(TestCrashCleanupChild);
+}
+
+TestCrashCleanupChild::~TestCrashCleanupChild() {
+ MOZ_COUNT_DTOR(TestCrashCleanupChild);
+}
+
+mozilla::ipc::IPCResult TestCrashCleanupChild::AnswerDIEDIEDIE() {
+ _exit(0);
+ MOZ_CRASH("unreached");
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestCrashCleanup.h b/ipc/ipdl/test/cxx/TestCrashCleanup.h
new file mode 100644
index 0000000000..30371264e6
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestCrashCleanup.h
@@ -0,0 +1,49 @@
+#ifndef mozilla__ipdltest_TestCrashCleanup_h
+#define mozilla__ipdltest_TestCrashCleanup_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestCrashCleanupParent.h"
+#include "mozilla/_ipdltest/PTestCrashCleanupChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestCrashCleanupParent : public PTestCrashCleanupParent {
+ public:
+ TestCrashCleanupParent();
+ virtual ~TestCrashCleanupParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ mCleanedUp = true;
+ }
+
+ bool mCleanedUp;
+};
+
+class TestCrashCleanupChild : public PTestCrashCleanupChild {
+ friend class PTestCrashCleanupChild;
+
+ public:
+ TestCrashCleanupChild();
+ virtual ~TestCrashCleanupChild();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerDIEDIEDIE();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ fail("should have 'crashed'!");
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestCrashCleanup_h
diff --git a/ipc/ipdl/test/cxx/TestDataStructures.cpp b/ipc/ipdl/test/cxx/TestDataStructures.cpp
new file mode 100644
index 0000000000..5b1cabfe7d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDataStructures.cpp
@@ -0,0 +1,888 @@
+#include "TestDataStructures.h"
+
+#include "mozilla/Unused.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+typedef nsTArray<nsIntRegion> RegionArray;
+
+namespace mozilla {
+namespace _ipdltest {
+
+static const uint32_t nactors = 10;
+
+#define test_assert(_cond, _msg) \
+ if (!(_cond)) fail(_msg)
+
+template <typename T>
+static void assert_arrays_equal(const nsTArray<T>& a, const nsTArray<T>& b) {
+ test_assert(a == b, "arrays equal");
+}
+
+inline static TestDataStructuresSub& Cast(PTestDataStructuresSubParent* a) {
+ return *static_cast<TestDataStructuresSub*>(a);
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestDataStructuresParent::TestDataStructuresParent() {
+ MOZ_COUNT_CTOR(TestDataStructuresParent);
+}
+
+TestDataStructuresParent::~TestDataStructuresParent() {
+ MOZ_COUNT_DTOR(TestDataStructuresParent);
+}
+
+void TestDataStructuresParent::Main() {
+ for (uint32_t i = 0; i < nactors; ++i)
+ if (!SendPTestDataStructuresSubConstructor(i)) fail("can't alloc actor");
+
+ if (!SendStart()) fail("can't send Start()");
+}
+
+bool TestDataStructuresParent::DeallocPTestDataStructuresSubParent(
+ PTestDataStructuresSubParent* actor) {
+ test_assert(Cast(actor).mI == Cast(mKids[0]).mI, "dtor sent to wrong actor");
+ mKids.RemoveElementAt(0);
+ delete actor;
+ if (mKids.Length() > 0) return true;
+
+ return true;
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest1(nsTArray<int>&& ia,
+ nsTArray<int>* oa) {
+ test_assert(5 == ia.Length(), "wrong length");
+ for (int i = 0; i < 5; ++i) test_assert(i == ia[i], "wrong value");
+
+ *oa = ia;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest2(
+ nsTArray<PTestDataStructuresSubParent*>&& i1,
+ nsTArray<PTestDataStructuresSubParent*>* o1) {
+ test_assert(nactors == i1.Length(), "wrong #actors");
+ for (uint32_t i = 0; i < i1.Length(); ++i)
+ test_assert(i == Cast(i1[i]).mI, "wrong mI value");
+ *o1 = i1;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest3(const IntDouble& i1,
+ const IntDouble& i2,
+ IntDouble* o1,
+ IntDouble* o2) {
+ test_assert(42 == i1.get_int(), "wrong value");
+ test_assert(4.0 == i2.get_double(), "wrong value");
+
+ *o1 = i1;
+ *o2 = i2;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest4(
+ nsTArray<IntDouble>&& i1, nsTArray<IntDouble>* o1) {
+ test_assert(4 == i1.Length(), "wrong length");
+ test_assert(1 == i1[0].get_int(), "wrong value");
+ test_assert(2.0 == i1[1].get_double(), "wrong value");
+ test_assert(3 == i1[2].get_int(), "wrong value");
+ test_assert(4.0 == i1[3].get_double(), "wrong value");
+
+ *o1 = i1;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest5(
+ const IntDoubleArrays& i1, const IntDoubleArrays& i2,
+ const IntDoubleArrays& i3, IntDoubleArrays* o1, IntDoubleArrays* o2,
+ IntDoubleArrays* o3) {
+ test_assert(42 == i1.get_int(), "wrong value");
+
+ const nsTArray<int>& i2a = i2.get_ArrayOfint();
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ const nsTArray<double>& i3a = i3.get_ArrayOfdouble();
+ test_assert(3 == i3a.Length(), "wrong length");
+ test_assert(1.0 == i3a[0], "wrong value");
+ test_assert(2.0 == i3a[1], "wrong value");
+ test_assert(3.0 == i3a[2], "wrong value");
+
+ *o1 = i1;
+ *o2 = i2a;
+ *o3 = i3a;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest7_0(
+ const ActorWrapper& i1, ActorWrapper* o1) {
+ if (i1.actorChild() != nullptr)
+ fail("child side actor should always be null");
+
+ if (i1.actorParent() != mKids[0])
+ fail("should have got back same actor on parent side");
+
+ o1->actorParent() = mKids[0];
+ // malicious behavior
+ o1->actorChild() =
+ reinterpret_cast<PTestDataStructuresSubChild*>(uintptr_t(0xdeadbeef));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest6(
+ nsTArray<IntDoubleArrays>&& i1, nsTArray<IntDoubleArrays>* o1) {
+ test_assert(3 == i1.Length(), "wrong length");
+
+ IntDoubleArrays id1(i1[0]);
+ test_assert(42 == id1.get_int(), "wrong value");
+
+ nsTArray<int> i2a(i1[1].get_ArrayOfint());
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ nsTArray<double> i3a(i1[2].get_ArrayOfdouble());
+ test_assert(3 == i3a.Length(), "wrong length");
+ test_assert(1.0 == i3a[0], "wrong value");
+ test_assert(2.0 == i3a[1], "wrong value");
+ test_assert(3.0 == i3a[2], "wrong value");
+
+ o1->AppendElement(id1);
+ o1->AppendElement(IntDoubleArrays(i2a));
+ o1->AppendElement(IntDoubleArrays(i3a));
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest7(
+ const Actors& i1, const Actors& i2, const Actors& i3, Actors* o1,
+ Actors* o2, Actors* o3) {
+ test_assert(42 == i1.get_int(), "wrong value");
+
+ nsTArray<int> i2a(i2.get_ArrayOfint());
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ assert_arrays_equal(mKids, i3.get_ArrayOfPTestDataStructuresSubParent());
+
+ *o1 = 42;
+ *o2 = i2a;
+ *o3 = mKids;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest8(
+ nsTArray<Actors>&& i1, nsTArray<Actors>* o1) {
+ test_assert(3 == i1.Length(), "wrong length");
+ test_assert(42 == i1[0].get_int(), "wrong value");
+
+ const nsTArray<int>& i2a = i1[1].get_ArrayOfint();
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ assert_arrays_equal(mKids, i1[2].get_ArrayOfPTestDataStructuresSubParent());
+
+ *o1 = i1;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest9(
+ const Unions& i1, const Unions& i2, const Unions& i3, const Unions& i4,
+ Unions* o1, Unions* o2, Unions* o3, Unions* o4) {
+ test_assert(42 == i1.get_int(), "wrong value");
+
+ const nsTArray<int>& i2a = i2.get_ArrayOfint();
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ assert_arrays_equal(mKids, i3.get_ArrayOfPTestDataStructuresSubParent());
+
+ const nsTArray<PTestDataStructuresSubParent*>& i4a =
+ i4.get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubParent();
+ assert_arrays_equal(mKids, i4a);
+
+ *o1 = i1;
+ *o2 = i2;
+ *o3 = i3;
+ *o4 = i4;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest10(
+ nsTArray<Unions>&& i1, nsTArray<Unions>* o1) {
+ test_assert(42 == i1[0].get_int(), "wrong value");
+
+ const nsTArray<int>& i2a = i1[1].get_ArrayOfint();
+ test_assert(3 == i2a.Length(), "wrong length");
+ test_assert(1 == i2a[0], "wrong value");
+ test_assert(2 == i2a[1], "wrong value");
+ test_assert(3 == i2a[2], "wrong value");
+
+ assert_arrays_equal(mKids, i1[2].get_ArrayOfPTestDataStructuresSubParent());
+
+ const nsTArray<PTestDataStructuresSubParent*>& i4a =
+ i1[3].get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubParent();
+ assert_arrays_equal(mKids, i4a);
+
+ *o1 = i1;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest11(
+ const SIntDouble& i, SIntDouble* o) {
+ test_assert(1 == i.i(), "wrong value");
+ test_assert(2.0 == i.d(), "wrong value");
+ *o = i;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest12(
+ const SIntDoubleArrays& i, SIntDoubleArrays* o) {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ nsTArray<double> ad;
+ ad.AppendElement(.5);
+ ad.AppendElement(1.0);
+ ad.AppendElement(2.0);
+
+ test_assert(42 == i.i(), "wrong value");
+ assert_arrays_equal(ai, i.ai());
+ assert_arrays_equal(ad, i.ad());
+
+ *o = i;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest13(const SActors& i,
+ SActors* o) {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ test_assert(42 == i.i(), "wrong value");
+ assert_arrays_equal(ai, i.ai());
+ assert_arrays_equal(mKids, i.apParent());
+
+ *o = i;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest14(const Structs& i,
+ Structs* o) {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ test_assert(42 == i.i(), "wrong value");
+ assert_arrays_equal(ai, i.ai());
+ assert_arrays_equal(mKids, i.apParent());
+
+ const SActors& ia = i.aa()[0];
+ test_assert(42 == ia.i(), "wrong value");
+ assert_arrays_equal(ai, ia.ai());
+ assert_arrays_equal(mKids, ia.apParent());
+
+ *o = i;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest15(
+ const WithStructs& i1, const WithStructs& i2, const WithStructs& i3,
+ const WithStructs& i4, const WithStructs& i5, WithStructs* o1,
+ WithStructs* o2, WithStructs* o3, WithStructs* o4, WithStructs* o5) {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ test_assert(i1 == int(42), "wrong value");
+ assert_arrays_equal(i2.get_ArrayOfint(), ai);
+ assert_arrays_equal(i3.get_ArrayOfPTestDataStructuresSubParent(), mKids);
+
+ const SActors& ia = i4.get_ArrayOfSActors()[0];
+ test_assert(42 == ia.i(), "wrong value");
+ assert_arrays_equal(ai, ia.ai());
+ assert_arrays_equal(mKids, ia.apParent());
+
+ const Structs& is = i5.get_ArrayOfStructs()[0];
+ test_assert(42 == is.i(), "wrong value");
+ assert_arrays_equal(ai, is.ai());
+ assert_arrays_equal(mKids, is.apParent());
+
+ const SActors& isa = is.aa()[0];
+ test_assert(42 == isa.i(), "wrong value");
+ assert_arrays_equal(ai, isa.ai());
+ assert_arrays_equal(mKids, isa.apParent());
+
+ *o1 = i1;
+ *o2 = i2;
+ *o3 = i3;
+ *o4 = i4;
+ *o5 = i5;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest16(
+ const WithUnions& i, WithUnions* o) {
+ test_assert(i.i() == 42, "wrong value");
+
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+ assert_arrays_equal(ai, i.ai());
+
+ assert_arrays_equal(i.apParent(), mKids);
+
+ assert_arrays_equal(mKids,
+ i.aa()[0].get_ArrayOfPTestDataStructuresSubParent());
+
+ const nsTArray<Unions>& iau = i.au();
+ test_assert(iau[0] == 42, "wrong value");
+ assert_arrays_equal(ai, iau[1].get_ArrayOfint());
+ assert_arrays_equal(mKids, iau[2].get_ArrayOfPTestDataStructuresSubParent());
+ assert_arrays_equal(
+ mKids,
+ iau[3].get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubParent());
+
+ *o = i;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest17(
+ nsTArray<Op>&& sa) {
+ test_assert(sa.Length() == 1 && Op::TSetAttrs == sa[0].type(), "wrong value");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDataStructuresParent::RecvTest18(RegionArray&& ra) {
+ for (RegionArray::index_type i = 0; i < ra.Length(); ++i) {
+ // if |ra| has been realloc()d and given a different allocator
+ // chunk, this loop will nondeterministically crash or iloop.
+ for (auto iter = ra[i].RectIter(); !iter.Done(); iter.Next()) {
+ Unused << iter.Get();
+ }
+ }
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestDataStructuresChild::TestDataStructuresChild() {
+ MOZ_COUNT_CTOR(TestDataStructuresChild);
+}
+
+TestDataStructuresChild::~TestDataStructuresChild() {
+ MOZ_COUNT_DTOR(TestDataStructuresChild);
+}
+
+mozilla::ipc::IPCResult TestDataStructuresChild::RecvStart() {
+ puts("[TestDataStructuresChild] starting");
+
+ Test1();
+ Test2();
+ Test3();
+ Test4();
+ Test5();
+ Test6();
+ Test7_0();
+ Test7();
+ Test8();
+ Test9();
+ Test10();
+ Test11();
+ Test12();
+ Test13();
+ Test14();
+ Test15();
+ Test16();
+ Test17();
+ if (OtherPid() != base::GetCurrentProcId()) {
+ // FIXME/bug 703317 allocation of nsIntRegion uses a global
+ // region pool which breaks threads
+ Test18();
+ }
+
+ for (uint32_t i = 0; i < nactors; ++i)
+ if (!PTestDataStructuresSubChild::Send__delete__(mKids[i]))
+ fail("can't send dtor");
+
+ Close();
+
+ return IPC_OK();
+}
+
+void TestDataStructuresChild::Test1() {
+ nsTArray<int> ia;
+
+ for (int i = 0; i < 5; ++i) ia.AppendElement(i);
+
+ nsTArray<int> oa;
+ if (!SendTest1(ia, &oa)) fail("can't send Test1");
+
+ assert_arrays_equal(ia, oa);
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test2() {
+ nsTArray<PTestDataStructuresSubChild*> oa;
+ if (!SendTest2(mKids, &oa)) fail("can't send Test2");
+ assert_arrays_equal(mKids, oa);
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test3() {
+ int i1i = 42;
+ double i2d = 4.0;
+ IntDouble i1(i1i);
+ IntDouble i2(i2d);
+ IntDouble o1, o2;
+
+ SendTest3(i1, i2, &o1, &o2);
+
+ test_assert(i1i == o1.get_int(), "wrong value");
+ test_assert(i2d == o2.get_double(), "wrong value");
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test4() {
+ nsTArray<IntDouble> i1;
+ i1.AppendElement(IntDouble(int(1)));
+ i1.AppendElement(IntDouble(2.0));
+ i1.AppendElement(IntDouble(int(3)));
+ i1.AppendElement(IntDouble(4.0));
+
+ nsTArray<IntDouble> o1;
+ if (!SendTest4(i1, &o1)) fail("can't send Test4");
+
+ // TODO Union::operator==()
+ test_assert(i1.Length() == o1.Length(), "wrong length");
+ test_assert(1 == o1[0].get_int(), "wrong value");
+ test_assert(2.0 == o1[1].get_double(), "wrong value");
+ test_assert(3 == o1[2].get_int(), "wrong value");
+ test_assert(4.0 == o1[3].get_double(), "wrong value");
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test5() {
+ IntDoubleArrays i1(int(42));
+ nsTArray<int> i2;
+ i2.AppendElement(1);
+ i2.AppendElement(2);
+ i2.AppendElement(3);
+ nsTArray<double> i3;
+ i3.AppendElement(1.0);
+ i3.AppendElement(2.0);
+ i3.AppendElement(3.0);
+
+ IntDoubleArrays o1, o2, o3;
+ if (!SendTest5(i1, IntDoubleArrays(i2), IntDoubleArrays(i3), &o1, &o2, &o3))
+ fail("can't send Test5");
+
+ test_assert(42 == o1.get_int(), "wrong value");
+ assert_arrays_equal(i2, o2.get_ArrayOfint());
+ assert_arrays_equal(i3, o3.get_ArrayOfdouble());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test6() {
+ IntDoubleArrays id1(int(42));
+ nsTArray<int> id2;
+ id2.AppendElement(1);
+ id2.AppendElement(2);
+ id2.AppendElement(3);
+ nsTArray<double> id3;
+ id3.AppendElement(1.0);
+ id3.AppendElement(2.0);
+ id3.AppendElement(3.0);
+
+ nsTArray<IntDoubleArrays> i1;
+ i1.AppendElement(id1);
+ i1.AppendElement(IntDoubleArrays(id2));
+ i1.AppendElement(IntDoubleArrays(id3));
+
+ nsTArray<IntDoubleArrays> o1;
+ if (!SendTest6(i1, &o1)) fail("can't send Test6");
+
+ test_assert(3 == o1.Length(), "wrong length");
+ IntDoubleArrays od1(o1[0]);
+ nsTArray<int> od2(o1[1].get_ArrayOfint());
+ nsTArray<double> od3(o1[2].get_ArrayOfdouble());
+
+ test_assert(42 == od1.get_int(), "wrong value");
+ assert_arrays_equal(id2, od2);
+ assert_arrays_equal(id3, od3);
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test7_0() {
+ ActorWrapper iaw;
+ if (iaw.actorChild() != nullptr || iaw.actorParent() != nullptr)
+ fail("actor members should be null initially");
+
+ iaw.actorChild() = mKids[0];
+ if (iaw.actorParent() != nullptr)
+ fail("parent should be null on child side after set");
+
+ ActorWrapper oaw;
+ if (!SendTest7_0(iaw, &oaw)) fail("sending Test7_0");
+
+ if (oaw.actorParent() != nullptr)
+ fail(
+ "parent accessor on actor-struct members should always be null in "
+ "child");
+
+ if (oaw.actorChild() != mKids[0])
+ fail("should have got back same child-side actor");
+}
+
+void TestDataStructuresChild::Test7() {
+ Actors i1(42);
+ nsTArray<int> i2a;
+ i2a.AppendElement(1);
+ i2a.AppendElement(2);
+ i2a.AppendElement(3);
+
+ Actors o1, o2, o3;
+ if (!SendTest7(i1, Actors(i2a), Actors(mKids), &o1, &o2, &o3))
+ fail("can't send Test7");
+
+ test_assert(42 == o1.get_int(), "wrong value");
+ assert_arrays_equal(i2a, o2.get_ArrayOfint());
+ assert_arrays_equal(mKids, o3.get_ArrayOfPTestDataStructuresSubChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test8() {
+ Actors i1e(42);
+ nsTArray<int> i2a;
+ i2a.AppendElement(1);
+ i2a.AppendElement(2);
+ i2a.AppendElement(3);
+
+ nsTArray<Actors> i1;
+ i1.AppendElement(i1e);
+ i1.AppendElement(i2a);
+ i1.AppendElement(mKids);
+
+ nsTArray<Actors> o1;
+ if (!SendTest8(i1, &o1)) fail("can't send Test8");
+
+ test_assert(3 == o1.Length(), "wrong length");
+ test_assert(42 == o1[0].get_int(), "wrong value");
+ assert_arrays_equal(i2a, o1[1].get_ArrayOfint());
+ assert_arrays_equal(mKids, o1[2].get_ArrayOfPTestDataStructuresSubChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test9() {
+ Unions i1(int(42));
+
+ nsTArray<int> i2a;
+ i2a.AppendElement(1);
+ i2a.AppendElement(2);
+ i2a.AppendElement(3);
+
+ nsTArray<Actors> i4a;
+ i4a.AppendElement(mKids);
+
+ Unions o1, o2, o3, o4;
+ if (!SendTest9(i1, Unions(i2a), Unions(mKids), Unions(i4a), &o1, &o2, &o3,
+ &o4))
+ fail("can't send Test9");
+
+ test_assert(42 == o1.get_int(), "wrong value");
+ assert_arrays_equal(i2a, o2.get_ArrayOfint());
+ assert_arrays_equal(mKids, o3.get_ArrayOfPTestDataStructuresSubChild());
+ assert_arrays_equal(
+ mKids,
+ o4.get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test10() {
+ Unions i1a(int(42));
+
+ nsTArray<int> i2a;
+ i2a.AppendElement(1);
+ i2a.AppendElement(2);
+ i2a.AppendElement(3);
+
+ nsTArray<Actors> i4a;
+ i4a.AppendElement(mKids);
+
+ nsTArray<Unions> i1;
+ i1.AppendElement(i1a);
+ i1.AppendElement(Unions(i2a));
+ i1.AppendElement(Unions(mKids));
+ i1.AppendElement(Unions(i4a));
+
+ nsTArray<Unions> o1;
+ if (!SendTest10(i1, &o1)) fail("can't send Test10");
+
+ test_assert(4 == o1.Length(), "wrong length");
+ test_assert(42 == o1[0].get_int(), "wrong value");
+ assert_arrays_equal(i2a, o1[1].get_ArrayOfint());
+ assert_arrays_equal(mKids, o1[2].get_ArrayOfPTestDataStructuresSubChild());
+ assert_arrays_equal(
+ mKids,
+ o1[3].get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test11() {
+ SIntDouble i(1, 2.0);
+ SIntDouble o;
+
+ if (!SendTest11(i, &o)) fail("sending Test11");
+
+ test_assert(1 == o.i() && 2.0 == o.d(), "wrong values");
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test12() {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ nsTArray<double> ad;
+ ad.AppendElement(.5);
+ ad.AppendElement(1.0);
+ ad.AppendElement(2.0);
+
+ SIntDoubleArrays i(42, ai, ad);
+ SIntDoubleArrays o;
+
+ if (!SendTest12(i, &o)) fail("sending Test12");
+
+ test_assert(42 == o.i(), "wrong value");
+ assert_arrays_equal(ai, o.ai());
+ assert_arrays_equal(ad, o.ad());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test13() {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ SActors i;
+ i.i() = 42;
+ i.ai() = ai;
+ i.apChild() = mKids;
+
+ SActors o;
+ if (!SendTest13(i, &o)) fail("can't send Test13");
+
+ test_assert(42 == o.i(), "wrong value");
+ assert_arrays_equal(ai, o.ai());
+ assert_arrays_equal(mKids, o.apChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test14() {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ SActors ia;
+ ia.i() = 42;
+ ia.ai() = ai;
+ ia.apChild() = mKids;
+ nsTArray<SActors> aa;
+ aa.AppendElement(ia);
+
+ Structs i;
+ i.i() = 42;
+ i.ai() = ai;
+ i.apChild() = mKids;
+ i.aa() = aa;
+
+ Structs o;
+ if (!SendTest14(i, &o)) fail("can't send Test14");
+
+ test_assert(42 == o.i(), "wrong value");
+ assert_arrays_equal(ai, o.ai());
+ assert_arrays_equal(mKids, o.apChild());
+
+ const SActors& os = o.aa()[0];
+ test_assert(42 == os.i(), "wrong value");
+ assert_arrays_equal(ai, os.ai());
+ assert_arrays_equal(mKids, os.apChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test15() {
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+
+ SActors ia;
+ ia.i() = 42;
+ ia.ai() = ai;
+ ia.apChild() = mKids;
+ nsTArray<SActors> iaa;
+ iaa.AppendElement(ia);
+
+ Structs is;
+ is.i() = 42;
+ is.ai() = ai;
+ is.apChild() = mKids;
+ is.aa() = iaa;
+ nsTArray<Structs> isa;
+ isa.AppendElement(is);
+
+ WithStructs o1, o2, o3, o4, o5;
+ if (!SendTest15(WithStructs(42), WithStructs(ai), WithStructs(mKids),
+ WithStructs(iaa), WithStructs(isa), &o1, &o2, &o3, &o4, &o5))
+ fail("sending Test15");
+
+ test_assert(o1 == int(42), "wrong value");
+ assert_arrays_equal(o2.get_ArrayOfint(), ai);
+ assert_arrays_equal(o3.get_ArrayOfPTestDataStructuresSubChild(), mKids);
+
+ const SActors& oa = o4.get_ArrayOfSActors()[0];
+ test_assert(42 == oa.i(), "wrong value");
+ assert_arrays_equal(ai, oa.ai());
+ assert_arrays_equal(mKids, oa.apChild());
+
+ const Structs& os = o5.get_ArrayOfStructs()[0];
+ test_assert(42 == os.i(), "wrong value");
+ assert_arrays_equal(ai, os.ai());
+ assert_arrays_equal(mKids, os.apChild());
+
+ const SActors& osa = os.aa()[0];
+ test_assert(42 == osa.i(), "wrong value");
+ assert_arrays_equal(ai, osa.ai());
+ assert_arrays_equal(mKids, osa.apChild());
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test16() {
+ WithUnions i;
+
+ i.i() = 42;
+
+ nsTArray<int> ai;
+ ai.AppendElement(1);
+ ai.AppendElement(2);
+ ai.AppendElement(3);
+ i.ai() = ai;
+
+ i.apChild() = mKids;
+
+ nsTArray<Actors> iaa;
+ iaa.AppendElement(mKids);
+ i.aa() = iaa;
+
+ nsTArray<Unions> iau;
+ iau.AppendElement(int(42));
+ iau.AppendElement(ai);
+ iau.AppendElement(mKids);
+ iau.AppendElement(iaa);
+ i.au() = iau;
+
+ WithUnions o;
+ if (!SendTest16(i, &o)) fail("sending Test16");
+
+ test_assert(42 == o.i(), "wrong value");
+ assert_arrays_equal(o.ai(), ai);
+ assert_arrays_equal(o.apChild(), mKids);
+
+ const Actors& oaa = o.aa()[0];
+ assert_arrays_equal(oaa.get_ArrayOfPTestDataStructuresSubChild(), mKids);
+
+ const nsTArray<Unions>& oau = o.au();
+ test_assert(oau[0] == 42, "wrong value");
+ assert_arrays_equal(oau[1].get_ArrayOfint(), ai);
+ assert_arrays_equal(oau[2].get_ArrayOfPTestDataStructuresSubChild(), mKids);
+ assert_arrays_equal(
+ oau[3].get_ArrayOfActors()[0].get_ArrayOfPTestDataStructuresSubChild(),
+ mKids);
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test17() {
+ Attrs attrs;
+ attrs.common() = CommonAttrs(true);
+ attrs.specific() = BarAttrs(1.0f);
+
+ nsTArray<Op> ops;
+ ops.AppendElement(SetAttrs(nullptr, mKids[0], attrs));
+
+ if (!SendTest17(ops)) fail("sending Test17");
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+void TestDataStructuresChild::Test18() {
+ const int nelements = 1000;
+ RegionArray ra;
+ // big enough to hopefully force a realloc to a different chunk of
+ // memory on the receiving side, if the workaround isn't working
+ // correctly. But SetCapacity() here because we don't want to
+ // crash on the sending side.
+ ra.SetCapacity(nelements);
+ for (int i = 0; i < nelements; ++i) {
+ nsIntRegion r;
+ r.Or(nsIntRect(0, 0, 10, 10), nsIntRect(10, 10, 10, 10));
+ ra.AppendElement(r);
+ }
+
+ if (!SendTest18(ra)) fail("sending Test18");
+
+ printf(" passed %s\n", __FUNCTION__);
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestDataStructures.h b/ipc/ipdl/test/cxx/TestDataStructures.h
new file mode 100644
index 0000000000..dc25b5282c
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDataStructures.h
@@ -0,0 +1,180 @@
+#ifndef mozilla__ipdltest_TestDataStructures_h
+#define mozilla__ipdltest_TestDataStructures_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestDataStructuresParent.h"
+#include "mozilla/_ipdltest/PTestDataStructuresChild.h"
+
+#include "mozilla/_ipdltest/PTestDataStructuresSubParent.h"
+#include "mozilla/_ipdltest/PTestDataStructuresSubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Subprotocol actors
+
+class TestDataStructuresSub : public PTestDataStructuresSubParent,
+ public PTestDataStructuresSubChild {
+ public:
+ explicit TestDataStructuresSub(uint32_t i) : mI(i) {}
+ virtual ~TestDataStructuresSub() {}
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (Deletion != why) fail("unexpected destruction!");
+ }
+ uint32_t mI;
+};
+
+//-----------------------------------------------------------------------------
+// Main actors
+
+class TestDataStructuresParent : public PTestDataStructuresParent {
+ friend class PTestDataStructuresParent;
+
+ public:
+ TestDataStructuresParent();
+ virtual ~TestDataStructuresParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ PTestDataStructuresSubParent* AllocPTestDataStructuresSubParent(
+ const int& i) {
+ PTestDataStructuresSubParent* actor = new TestDataStructuresSub(i);
+ mKids.AppendElement(actor);
+ return actor;
+ }
+
+ bool DeallocPTestDataStructuresSubParent(PTestDataStructuresSubParent* actor);
+
+ mozilla::ipc::IPCResult RecvTest1(nsTArray<int>&& i1, nsTArray<int>* o1);
+
+ mozilla::ipc::IPCResult RecvTest2(
+ nsTArray<PTestDataStructuresSubParent*>&& i1,
+ nsTArray<PTestDataStructuresSubParent*>* o1);
+
+ mozilla::ipc::IPCResult RecvTest3(const IntDouble& i1, const IntDouble& i2,
+ IntDouble* o1, IntDouble* o2);
+
+ mozilla::ipc::IPCResult RecvTest4(nsTArray<IntDouble>&& i1,
+ nsTArray<IntDouble>* o1);
+
+ mozilla::ipc::IPCResult RecvTest5(const IntDoubleArrays& i1,
+ const IntDoubleArrays& i2,
+ const IntDoubleArrays& i3,
+ IntDoubleArrays* o1, IntDoubleArrays* o2,
+ IntDoubleArrays* o3);
+
+ mozilla::ipc::IPCResult RecvTest6(nsTArray<IntDoubleArrays>&& i1,
+ nsTArray<IntDoubleArrays>* o1);
+
+ mozilla::ipc::IPCResult RecvTest7_0(const ActorWrapper& i1, ActorWrapper* o1);
+
+ mozilla::ipc::IPCResult RecvTest7(const Actors& i1, const Actors& i2,
+ const Actors& i3, Actors* o1, Actors* o2,
+ Actors* o3);
+
+ mozilla::ipc::IPCResult RecvTest8(nsTArray<Actors>&& i1,
+ nsTArray<Actors>* o1);
+
+ mozilla::ipc::IPCResult RecvTest9(const Unions& i1, const Unions& i2,
+ const Unions& i3, const Unions& i4,
+ Unions* o1, Unions* o2, Unions* o3,
+ Unions* o4);
+
+ mozilla::ipc::IPCResult RecvTest10(nsTArray<Unions>&& i1,
+ nsTArray<Unions>* o1);
+
+ mozilla::ipc::IPCResult RecvTest11(const SIntDouble& i, SIntDouble* o);
+
+ mozilla::ipc::IPCResult RecvTest12(const SIntDoubleArrays& i,
+ SIntDoubleArrays* o);
+
+ mozilla::ipc::IPCResult RecvTest13(const SActors& i, SActors* o);
+
+ mozilla::ipc::IPCResult RecvTest14(const Structs& i, Structs* o);
+
+ mozilla::ipc::IPCResult RecvTest15(
+ const WithStructs& i1, const WithStructs& i2, const WithStructs& i3,
+ const WithStructs& i4, const WithStructs& i5, WithStructs* o1,
+ WithStructs* o2, WithStructs* o3, WithStructs* o4, WithStructs* o5);
+
+ mozilla::ipc::IPCResult RecvTest16(const WithUnions& i, WithUnions* o);
+
+ mozilla::ipc::IPCResult RecvTest17(nsTArray<Op>&& sa);
+
+ mozilla::ipc::IPCResult RecvTest18(nsTArray<nsIntRegion>&& ra);
+
+ mozilla::ipc::IPCResult RecvDummy(const ShmemUnion& su, ShmemUnion* rsu) {
+ *rsu = su;
+ return IPC_OK();
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ nsTArray<PTestDataStructuresSubParent*> mKids;
+};
+
+class TestDataStructuresChild : public PTestDataStructuresChild {
+ friend class PTestDataStructuresChild;
+
+ public:
+ TestDataStructuresChild();
+ virtual ~TestDataStructuresChild();
+
+ protected:
+ PTestDataStructuresSubChild* AllocPTestDataStructuresSubChild(const int& i) {
+ PTestDataStructuresSubChild* actor = new TestDataStructuresSub(i);
+ mKids.AppendElement(actor);
+ return actor;
+ }
+
+ bool DeallocPTestDataStructuresSubChild(PTestDataStructuresSubChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ mozilla::ipc::IPCResult RecvStart();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ private:
+ void Test1();
+ void Test2();
+ void Test3();
+ void Test4();
+ void Test5();
+ void Test6();
+ void Test7_0();
+ void Test7();
+ void Test8();
+ void Test9();
+ void Test10();
+ void Test11();
+ void Test12();
+ void Test13();
+ void Test14();
+ void Test15();
+ void Test16();
+ void Test17();
+ void Test18();
+
+ nsTArray<PTestDataStructuresSubChild*> mKids;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestDataStructures_h
diff --git a/ipc/ipdl/test/cxx/TestDemon.cpp b/ipc/ipdl/test/cxx/TestDemon.cpp
new file mode 100644
index 0000000000..396974bb56
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDemon.cpp
@@ -0,0 +1,362 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=4 et :
+ */
+#include "TestDemon.h"
+
+#include <stdlib.h>
+
+#include "IPDLUnitTests.h" // fail etc.
+#if defined(XP_UNIX)
+# include <sys/time.h>
+# include <unistd.h>
+#else
+# include <time.h>
+# include <windows.h>
+#endif
+
+namespace mozilla {
+namespace _ipdltest {
+
+const int kMaxStackHeight = 4;
+
+static LazyLogModule sLogModule("demon");
+
+#define DEMON_LOG(...) MOZ_LOG(sLogModule, LogLevel::Debug, (__VA_ARGS__))
+
+static int gStackHeight = 0;
+static bool gFlushStack = false;
+
+static int Choose(int count) {
+#if defined(XP_UNIX)
+ return random() % count;
+#else
+ return rand() % count;
+#endif
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestDemonParent::TestDemonParent() : mDone(false), mIncoming(), mOutgoing() {
+ MOZ_COUNT_CTOR(TestDemonParent);
+}
+
+TestDemonParent::~TestDemonParent() { MOZ_COUNT_DTOR(TestDemonParent); }
+
+void TestDemonParent::Main() {
+ if (!getenv("MOZ_TEST_IPC_DEMON")) {
+ QuitParent();
+ return;
+ }
+#if defined(XP_UNIX)
+ srandom(time(nullptr));
+#else
+ srand(time(nullptr));
+#endif
+
+ DEMON_LOG("Start demon");
+
+ if (!SendStart()) fail("sending Start");
+
+ RunUnlimitedSequence();
+}
+
+#ifdef DEBUG
+bool TestDemonParent::ShouldContinueFromReplyTimeout() {
+ return Choose(2) == 0;
+}
+
+bool TestDemonParent::ArtificialTimeout() { return Choose(5) == 0; }
+
+void TestDemonParent::ArtificialSleep() {
+ if (Choose(2) == 0) {
+ // Sleep for anywhere from 0 to 100 milliseconds.
+ unsigned micros = Choose(100) * 1000;
+# ifdef XP_UNIX
+ usleep(micros);
+# else
+ Sleep(micros / 1000);
+# endif
+ }
+}
+#endif
+
+mozilla::ipc::IPCResult TestDemonParent::RecvAsyncMessage(const int& n) {
+ DEMON_LOG("Start RecvAsync [%d]", n);
+
+ MOZ_ASSERT(n == mIncoming[0]);
+ mIncoming[0]++;
+
+ RunLimitedSequence();
+
+ DEMON_LOG("End RecvAsync [%d]", n);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDemonParent::RecvHiPrioSyncMessage() {
+ DEMON_LOG("Start RecvHiPrioSyncMessage");
+ RunLimitedSequence();
+ DEMON_LOG("End RecvHiPrioSyncMessage");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDemonParent::RecvSyncMessage(const int& n) {
+ DEMON_LOG("Start RecvSync [%d]", n);
+
+ MOZ_ASSERT(n == mIncoming[0]);
+ mIncoming[0]++;
+
+ RunLimitedSequence(ASYNC_ONLY);
+
+ DEMON_LOG("End RecvSync [%d]", n);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDemonParent::RecvUrgentAsyncMessage(const int& n) {
+ DEMON_LOG("Start RecvUrgentAsyncMessage [%d]", n);
+
+ MOZ_ASSERT(n == mIncoming[2]);
+ mIncoming[2]++;
+
+ RunLimitedSequence(ASYNC_ONLY);
+
+ DEMON_LOG("End RecvUrgentAsyncMessage [%d]", n);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDemonParent::RecvUrgentSyncMessage(const int& n) {
+ DEMON_LOG("Start RecvUrgentSyncMessage [%d]", n);
+
+ MOZ_ASSERT(n == mIncoming[2]);
+ mIncoming[2]++;
+
+ RunLimitedSequence(ASYNC_ONLY);
+
+ DEMON_LOG("End RecvUrgentSyncMessage [%d]", n);
+ return IPC_OK();
+}
+
+void TestDemonParent::RunUnlimitedSequence() {
+ if (mDone) {
+ return;
+ }
+
+ gFlushStack = false;
+ DoAction();
+
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestDemonParent::RunUnlimitedSequence", this,
+ &TestDemonParent::RunUnlimitedSequence));
+}
+
+void TestDemonParent::RunLimitedSequence(int flags) {
+ if (gStackHeight >= kMaxStackHeight) {
+ return;
+ }
+ gStackHeight++;
+
+ int count = Choose(20);
+ for (int i = 0; i < count; i++) {
+ if (!DoAction(flags)) {
+ gFlushStack = true;
+ }
+ if (gFlushStack) {
+ gStackHeight--;
+ return;
+ }
+ }
+
+ gStackHeight--;
+}
+
+static bool AllowAsync(int outgoing, int incoming) {
+ return incoming >= outgoing - 5;
+}
+
+bool TestDemonParent::DoAction(int flags) {
+ if (flags & ASYNC_ONLY) {
+ if (AllowAsync(mOutgoing[0], mIncoming[0])) {
+ DEMON_LOG("SendAsyncMessage [%d]", mOutgoing[0]);
+ return SendAsyncMessage(mOutgoing[0]++);
+ } else {
+ return true;
+ }
+ } else {
+ switch (Choose(3)) {
+ case 0:
+ if (AllowAsync(mOutgoing[0], mIncoming[0])) {
+ DEMON_LOG("SendAsyncMessage [%d]", mOutgoing[0]);
+ return SendAsyncMessage(mOutgoing[0]++);
+ } else {
+ return true;
+ }
+
+ case 1: {
+ DEMON_LOG("Start SendHiPrioSyncMessage");
+ bool r = SendHiPrioSyncMessage();
+ DEMON_LOG("End SendHiPrioSyncMessage result=%d", r);
+ return r;
+ }
+
+ case 2:
+ DEMON_LOG("Cancel");
+ GetIPCChannel()->CancelCurrentTransaction();
+ return true;
+ }
+ }
+ MOZ_CRASH();
+ return false;
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestDemonChild::TestDemonChild() : mIncoming(), mOutgoing() {
+ MOZ_COUNT_CTOR(TestDemonChild);
+}
+
+TestDemonChild::~TestDemonChild() { MOZ_COUNT_DTOR(TestDemonChild); }
+
+mozilla::ipc::IPCResult TestDemonChild::RecvStart() {
+#ifdef XP_UNIX
+ srandom(time(nullptr));
+#else
+ srand(time(nullptr));
+#endif
+
+ DEMON_LOG("RecvStart");
+
+ RunUnlimitedSequence();
+ return IPC_OK();
+}
+
+#ifdef DEBUG
+void TestDemonChild::ArtificialSleep() {
+ if (Choose(2) == 0) {
+ // Sleep for anywhere from 0 to 100 milliseconds.
+ unsigned micros = Choose(100) * 1000;
+# ifdef XP_UNIX
+ usleep(micros);
+# else
+ Sleep(micros / 1000);
+# endif
+ }
+}
+#endif
+
+mozilla::ipc::IPCResult TestDemonChild::RecvAsyncMessage(const int& n) {
+ DEMON_LOG("Start RecvAsyncMessage [%d]", n);
+
+ MOZ_ASSERT(n == mIncoming[0]);
+ mIncoming[0]++;
+
+ RunLimitedSequence();
+
+ DEMON_LOG("End RecvAsyncMessage [%d]", n);
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestDemonChild::RecvHiPrioSyncMessage() {
+ DEMON_LOG("Start RecvHiPrioSyncMessage");
+ RunLimitedSequence();
+ DEMON_LOG("End RecvHiPrioSyncMessage");
+ return IPC_OK();
+}
+
+void TestDemonChild::RunUnlimitedSequence() {
+ gFlushStack = false;
+ DoAction();
+
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestDemonChild::RunUnlimitedSequence", this,
+ &TestDemonChild::RunUnlimitedSequence));
+}
+
+void TestDemonChild::RunLimitedSequence() {
+ if (gStackHeight >= kMaxStackHeight) {
+ return;
+ }
+ gStackHeight++;
+
+ int count = Choose(20);
+ for (int i = 0; i < count; i++) {
+ if (!DoAction()) {
+ gFlushStack = true;
+ }
+ if (gFlushStack) {
+ gStackHeight--;
+ return;
+ }
+ }
+
+ gStackHeight--;
+}
+
+bool TestDemonChild::DoAction() {
+ switch (Choose(6)) {
+ case 0:
+ if (AllowAsync(mOutgoing[0], mIncoming[0])) {
+ DEMON_LOG("SendAsyncMessage [%d]", mOutgoing[0]);
+ return SendAsyncMessage(mOutgoing[0]++);
+ } else {
+ return true;
+ }
+
+ case 1: {
+ DEMON_LOG("Start SendHiPrioSyncMessage");
+ bool r = SendHiPrioSyncMessage();
+ DEMON_LOG("End SendHiPrioSyncMessage result=%d", r);
+ return r;
+ }
+
+ case 2: {
+ DEMON_LOG("Start SendSyncMessage [%d]", mOutgoing[0]);
+ bool r = SendSyncMessage(mOutgoing[0]++);
+ switch (GetIPCChannel()->LastSendError()) {
+ case SyncSendError::PreviousTimeout:
+ case SyncSendError::SendingCPOWWhileDispatchingSync:
+ case SyncSendError::SendingCPOWWhileDispatchingUrgent:
+ case SyncSendError::NotConnectedBeforeSend:
+ case SyncSendError::CancelledBeforeSend:
+ mOutgoing[0]--;
+ break;
+ default:
+ break;
+ }
+ DEMON_LOG("End SendSyncMessage result=%d", r);
+ return r;
+ }
+
+ case 3:
+ DEMON_LOG("SendUrgentAsyncMessage [%d]", mOutgoing[2]);
+ return SendUrgentAsyncMessage(mOutgoing[2]++);
+
+ case 4: {
+ DEMON_LOG("Start SendUrgentSyncMessage [%d]", mOutgoing[2]);
+ bool r = SendUrgentSyncMessage(mOutgoing[2]++);
+ switch (GetIPCChannel()->LastSendError()) {
+ case SyncSendError::PreviousTimeout:
+ case SyncSendError::SendingCPOWWhileDispatchingSync:
+ case SyncSendError::SendingCPOWWhileDispatchingUrgent:
+ case SyncSendError::NotConnectedBeforeSend:
+ case SyncSendError::CancelledBeforeSend:
+ mOutgoing[2]--;
+ break;
+ default:
+ break;
+ }
+ DEMON_LOG("End SendUrgentSyncMessage result=%d", r);
+ return r;
+ }
+
+ case 5:
+ DEMON_LOG("Cancel");
+ GetIPCChannel()->CancelCurrentTransaction();
+ return true;
+ }
+ MOZ_CRASH();
+ return false;
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestDemon.h b/ipc/ipdl/test/cxx/TestDemon.h
new file mode 100644
index 0000000000..ba5b003436
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDemon.h
@@ -0,0 +1,91 @@
+#ifndef mozilla__ipdltest_TestDemon_h
+#define mozilla__ipdltest_TestDemon_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestDemonParent.h"
+#include "mozilla/_ipdltest/PTestDemonChild.h"
+
+using namespace mozilla::ipc;
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestDemonParent : public PTestDemonParent {
+ public:
+ TestDemonParent();
+ virtual ~TestDemonParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+#ifdef DEBUG
+ bool ShouldContinueFromReplyTimeout() override;
+ bool ArtificialTimeout() override;
+
+ bool NeedArtificialSleep() override { return true; }
+ void ArtificialSleep() override;
+#endif
+
+ mozilla::ipc::IPCResult RecvAsyncMessage(const int& n);
+ mozilla::ipc::IPCResult RecvHiPrioSyncMessage();
+
+ mozilla::ipc::IPCResult RecvSyncMessage(const int& n);
+ mozilla::ipc::IPCResult RecvUrgentAsyncMessage(const int& n);
+ mozilla::ipc::IPCResult RecvUrgentSyncMessage(const int& n);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ mDone = true;
+ printf("Parent ActorDestroy\n");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ bool mDone;
+ int mIncoming[3];
+ int mOutgoing[3];
+
+ enum {
+ ASYNC_ONLY = 1,
+ };
+
+ void RunUnlimitedSequence();
+ void RunLimitedSequence(int flags = 0);
+ bool DoAction(int flags = 0);
+};
+
+class TestDemonChild : public PTestDemonChild {
+ public:
+ TestDemonChild();
+ virtual ~TestDemonChild();
+
+ mozilla::ipc::IPCResult RecvStart();
+
+#ifdef DEBUG
+ bool NeedArtificialSleep() override { return true; }
+ void ArtificialSleep() override;
+#endif
+
+ mozilla::ipc::IPCResult RecvAsyncMessage(const int& n);
+ mozilla::ipc::IPCResult RecvHiPrioSyncMessage();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { _exit(0); }
+
+ virtual void IntentionalCrash() override { _exit(0); }
+
+ private:
+ int mIncoming[3];
+ int mOutgoing[3];
+
+ void RunUnlimitedSequence();
+ void RunLimitedSequence();
+ bool DoAction();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestDemon_h
diff --git a/ipc/ipdl/test/cxx/TestDesc.cpp b/ipc/ipdl/test/cxx/TestDesc.cpp
new file mode 100644
index 0000000000..2ae199457d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDesc.cpp
@@ -0,0 +1,78 @@
+#include "TestDesc.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+void TestDescParent::Main() {
+ PTestDescSubParent* p = CallPTestDescSubConstructor(0);
+ if (!p) fail("can't allocate Sub");
+
+ PTestDescSubsubParent* pp = p->CallPTestDescSubsubConstructor();
+ if (!pp) fail("can't allocate Subsub");
+
+ if (!SendTest(pp)) fail("can't send Subsub");
+}
+
+mozilla::ipc::IPCResult TestDescParent::RecvOk(PTestDescSubsubParent* a) {
+ if (!a) fail("didn't receive Subsub");
+
+ if (!PTestDescSubsubParent::Call__delete__(a)) fail("deleting Subsub");
+
+ Close();
+
+ return IPC_OK();
+}
+
+PTestDescSubParent* TestDescParent::AllocPTestDescSubParent(
+ PTestDescSubsubParent* dummy) {
+ if (dummy) fail("actor supposed to be null");
+ return new TestDescSubParent();
+}
+bool TestDescParent::DeallocPTestDescSubParent(PTestDescSubParent* actor) {
+ delete actor;
+ return true;
+}
+
+PTestDescSubsubParent* TestDescSubParent::AllocPTestDescSubsubParent() {
+ return new TestDescSubsubParent();
+}
+bool TestDescSubParent::DeallocPTestDescSubsubParent(
+ PTestDescSubsubParent* actor) {
+ delete actor;
+ return true;
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+mozilla::ipc::IPCResult TestDescChild::RecvTest(PTestDescSubsubChild* a) {
+ if (!a) fail("didn't receive Subsub");
+ if (!SendOk(a)) fail("couldn't send Ok()");
+ return IPC_OK();
+}
+
+PTestDescSubChild* TestDescChild::AllocPTestDescSubChild(
+ PTestDescSubsubChild* dummy) {
+ if (dummy) fail("actor supposed to be null");
+ return new TestDescSubChild();
+}
+bool TestDescChild::DeallocPTestDescSubChild(PTestDescSubChild* actor) {
+ delete actor;
+ return true;
+}
+
+PTestDescSubsubChild* TestDescSubChild::AllocPTestDescSubsubChild() {
+ return new TestDescSubsubChild();
+}
+bool TestDescSubChild::DeallocPTestDescSubsubChild(
+ PTestDescSubsubChild* actor) {
+ delete actor;
+ return true;
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestDesc.h b/ipc/ipdl/test/cxx/TestDesc.h
new file mode 100644
index 0000000000..c9fa04f89c
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestDesc.h
@@ -0,0 +1,115 @@
+#ifndef mozilla_ipdltest_TestDesc_h
+#define mozilla_ipdltest_TestDesc_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestDescParent.h"
+#include "mozilla/_ipdltest/PTestDescChild.h"
+
+#include "mozilla/_ipdltest/PTestDescSubParent.h"
+#include "mozilla/_ipdltest/PTestDescSubChild.h"
+
+#include "mozilla/_ipdltest/PTestDescSubsubParent.h"
+#include "mozilla/_ipdltest/PTestDescSubsubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Top-level
+//
+class TestDescParent : public PTestDescParent {
+ friend class PTestDescParent;
+
+ public:
+ TestDescParent() {}
+ virtual ~TestDescParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvOk(PTestDescSubsubParent* a);
+
+ protected:
+ PTestDescSubParent* AllocPTestDescSubParent(PTestDescSubsubParent*);
+ bool DeallocPTestDescSubParent(PTestDescSubParent* actor);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestDescChild : public PTestDescChild {
+ friend class PTestDescChild;
+
+ public:
+ TestDescChild() {}
+ virtual ~TestDescChild() {}
+
+ protected:
+ PTestDescSubChild* AllocPTestDescSubChild(PTestDescSubsubChild*);
+
+ bool DeallocPTestDescSubChild(PTestDescSubChild* actor);
+
+ mozilla::ipc::IPCResult RecvTest(PTestDescSubsubChild* a);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+//-----------------------------------------------------------------------------
+// First descendent
+//
+class TestDescSubParent : public PTestDescSubParent {
+ friend class PTestDescSubParent;
+
+ public:
+ TestDescSubParent() {}
+ virtual ~TestDescSubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+ PTestDescSubsubParent* AllocPTestDescSubsubParent();
+ bool DeallocPTestDescSubsubParent(PTestDescSubsubParent* actor);
+};
+
+class TestDescSubChild : public PTestDescSubChild {
+ friend class PTestDescSubChild;
+
+ public:
+ TestDescSubChild() {}
+ virtual ~TestDescSubChild() {}
+
+ protected:
+ PTestDescSubsubChild* AllocPTestDescSubsubChild();
+ bool DeallocPTestDescSubsubChild(PTestDescSubsubChild* actor);
+};
+
+//-----------------------------------------------------------------------------
+// Grand-descendent
+//
+class TestDescSubsubParent : public PTestDescSubsubParent {
+ public:
+ TestDescSubsubParent() {}
+ virtual ~TestDescSubsubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestDescSubsubChild : public PTestDescSubsubChild {
+ public:
+ TestDescSubsubChild() {}
+ virtual ~TestDescSubsubChild() {}
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipdltest_TestDesc_h
diff --git a/ipc/ipdl/test/cxx/TestEndpointBridgeMain.cpp b/ipc/ipdl/test/cxx/TestEndpointBridgeMain.cpp
new file mode 100644
index 0000000000..4a4366f0ba
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestEndpointBridgeMain.cpp
@@ -0,0 +1,226 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+#include "TestEndpointBridgeMain.h"
+
+#include "base/task.h"
+#include "IPDLUnitTests.h" // fail etc.
+#include "IPDLUnitTestSubprocess.h"
+
+using namespace std;
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// main process
+void TestEndpointBridgeMainParent::Main() {
+ if (!SendStart()) {
+ fail("sending Start");
+ }
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainParent::RecvBridged(
+ Endpoint<PTestEndpointBridgeMainSubParent>&& endpoint) {
+ TestEndpointBridgeMainSubParent* a = new TestEndpointBridgeMainSubParent();
+ if (!endpoint.Bind(a)) {
+ fail("Bind failed");
+ }
+ return IPC_OK();
+}
+
+void TestEndpointBridgeMainParent::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+ passed("ok");
+ QuitParent();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainSubParent::RecvHello() {
+ if (!SendHi()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainSubParent::RecvHelloSync() {
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainSubParent::AnswerHelloRpc() {
+ if (!CallHiRpc()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+void TestEndpointBridgeMainSubParent::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+
+ // ActorDestroy() is just a callback from IPDL-generated code,
+ // which needs the top-level actor (this) to stay alive a little
+ // longer so other things can be cleaned up.
+ MessageLoop::current()->PostTask(
+ do_AddRef(new DeleteTask<TestEndpointBridgeMainSubParent>(this)));
+}
+
+//-----------------------------------------------------------------------------
+// sub process --- child of main
+TestEndpointBridgeMainChild* gEndpointBridgeMainChild;
+
+TestEndpointBridgeMainChild::TestEndpointBridgeMainChild()
+ : mSubprocess(nullptr) {
+ gEndpointBridgeMainChild = this;
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainChild::RecvStart() {
+ vector<string> subsubArgs;
+ subsubArgs.push_back("TestEndpointBridgeSub");
+
+ mSubprocess = new IPDLUnitTestSubprocess();
+ if (!mSubprocess->SyncLaunch(subsubArgs)) {
+ fail("problem launching subprocess");
+ }
+
+ IPC::Channel* transport = mSubprocess->GetChannel();
+ if (!transport) {
+ fail("no transport");
+ }
+
+ TestEndpointBridgeSubParent* bsp = new TestEndpointBridgeSubParent();
+ bsp->Open(transport, base::GetProcId(mSubprocess->GetChildProcessHandle()));
+
+ bsp->Main();
+ return IPC_OK();
+}
+
+void TestEndpointBridgeMainChild::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+ // NB: this is kosher because QuitChild() joins with the IO thread
+ mSubprocess->Destroy();
+ mSubprocess = nullptr;
+ QuitChild();
+}
+
+void TestEndpointBridgeSubParent::Main() {
+ if (!SendPing()) {
+ fail("sending Ping");
+ }
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeSubParent::RecvBridgeEm() {
+ Endpoint<PTestEndpointBridgeMainSubParent> parent;
+ Endpoint<PTestEndpointBridgeMainSubChild> child;
+ nsresult rv;
+ rv = PTestEndpointBridgeMainSub::CreateEndpoints(
+ gEndpointBridgeMainChild->OtherPid(), OtherPid(), &parent, &child);
+ if (NS_FAILED(rv)) {
+ fail("opening PTestEndpointOpensOpened");
+ }
+
+ if (!gEndpointBridgeMainChild->SendBridged(std::move(parent))) {
+ fail("SendBridge failed for parent");
+ }
+ if (!SendBridged(std::move(child))) {
+ fail("SendBridge failed for child");
+ }
+
+ return IPC_OK();
+}
+
+void TestEndpointBridgeSubParent::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+ gEndpointBridgeMainChild->Close();
+
+ // ActorDestroy() is just a callback from IPDL-generated code,
+ // which needs the top-level actor (this) to stay alive a little
+ // longer so other things can be cleaned up.
+ MessageLoop::current()->PostTask(
+ do_AddRef(new DeleteTask<TestEndpointBridgeSubParent>(this)));
+}
+
+//-----------------------------------------------------------------------------
+// subsub process --- child of sub
+
+static TestEndpointBridgeSubChild* gBridgeSubChild;
+
+TestEndpointBridgeSubChild::TestEndpointBridgeSubChild() {
+ gBridgeSubChild = this;
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeSubChild::RecvPing() {
+ if (!SendBridgeEm()) {
+ fail("sending BridgeEm");
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeSubChild::RecvBridged(
+ Endpoint<PTestEndpointBridgeMainSubChild>&& endpoint) {
+ TestEndpointBridgeMainSubChild* a = new TestEndpointBridgeMainSubChild();
+
+ if (!endpoint.Bind(a)) {
+ fail("failed to Bind");
+ }
+
+ if (!a->SendHello()) {
+ fail("sending Hello");
+ }
+
+ return IPC_OK();
+}
+
+void TestEndpointBridgeSubChild::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+ QuitChild();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainSubChild::RecvHi() {
+ if (!SendHelloSync()) {
+ fail("sending HelloSync");
+ }
+ if (!CallHelloRpc()) {
+ fail("calling HelloRpc");
+ }
+ if (!mGotHi) {
+ fail("didn't answer HiRpc");
+ }
+
+ // Need to close the channel without message-processing frames on
+ // the C++ stack
+ MessageLoop::current()->PostTask(
+ NewNonOwningRunnableMethod("ipc::IToplevelProtocol::Close", this,
+ &TestEndpointBridgeMainSubChild::Close));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointBridgeMainSubChild::AnswerHiRpc() {
+ mGotHi = true; // d00d
+ return IPC_OK();
+}
+
+void TestEndpointBridgeMainSubChild::ActorDestroy(ActorDestroyReason why) {
+ if (NormalShutdown != why) {
+ fail("unexpected destruction!");
+ }
+
+ gBridgeSubChild->Close();
+
+ // ActorDestroy() is just a callback from IPDL-generated code,
+ // which needs the top-level actor (this) to stay alive a little
+ // longer so other things can be cleaned up.
+ MessageLoop::current()->PostTask(
+ do_AddRef(new DeleteTask<TestEndpointBridgeMainSubChild>(this)));
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestEndpointBridgeMain.h b/ipc/ipdl/test/cxx/TestEndpointBridgeMain.h
new file mode 100644
index 0000000000..88ac12d71b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestEndpointBridgeMain.h
@@ -0,0 +1,132 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+#ifndef mozilla__ipdltest_TestEndpointBridgeMain_h
+#define mozilla__ipdltest_TestEndpointBridgeMain_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestEndpointBridgeMainParent.h"
+#include "mozilla/_ipdltest/PTestEndpointBridgeMainChild.h"
+
+#include "mozilla/_ipdltest/PTestEndpointBridgeSubParent.h"
+#include "mozilla/_ipdltest/PTestEndpointBridgeSubChild.h"
+
+#include "mozilla/_ipdltest/PTestEndpointBridgeMainSubParent.h"
+#include "mozilla/_ipdltest/PTestEndpointBridgeMainSubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// "Main" process
+//
+class TestEndpointBridgeMainParent : public PTestEndpointBridgeMainParent {
+ friend class PTestEndpointBridgeMainParent;
+
+ public:
+ TestEndpointBridgeMainParent() {}
+ virtual ~TestEndpointBridgeMainParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvBridged(
+ mozilla::ipc::Endpoint<PTestEndpointBridgeMainSubParent>&& endpoint);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+class TestEndpointBridgeMainSubParent
+ : public PTestEndpointBridgeMainSubParent {
+ friend class PTestEndpointBridgeMainSubParent;
+
+ public:
+ explicit TestEndpointBridgeMainSubParent() {}
+ virtual ~TestEndpointBridgeMainSubParent() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvHello();
+ mozilla::ipc::IPCResult RecvHelloSync();
+ mozilla::ipc::IPCResult AnswerHelloRpc();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+//-----------------------------------------------------------------------------
+// "Sub" process --- child of "main"
+//
+class TestEndpointBridgeSubParent;
+
+class TestEndpointBridgeMainChild : public PTestEndpointBridgeMainChild {
+ friend class PTestEndpointBridgeMainChild;
+
+ public:
+ TestEndpointBridgeMainChild();
+ virtual ~TestEndpointBridgeMainChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ IPDLUnitTestSubprocess* mSubprocess;
+};
+
+class TestEndpointBridgeSubParent : public PTestEndpointBridgeSubParent {
+ friend class PTestEndpointBridgeSubParent;
+
+ public:
+ TestEndpointBridgeSubParent() {}
+ virtual ~TestEndpointBridgeSubParent() {}
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvBridgeEm();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+//-----------------------------------------------------------------------------
+// "Subsub" process --- child of "sub"
+//
+class TestEndpointBridgeSubChild : public PTestEndpointBridgeSubChild {
+ friend class PTestEndpointBridgeSubChild;
+
+ public:
+ TestEndpointBridgeSubChild();
+ virtual ~TestEndpointBridgeSubChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvPing();
+
+ mozilla::ipc::IPCResult RecvBridged(
+ Endpoint<PTestEndpointBridgeMainSubChild>&& endpoint);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+class TestEndpointBridgeMainSubChild : public PTestEndpointBridgeMainSubChild {
+ friend class PTestEndpointBridgeMainSubChild;
+
+ public:
+ explicit TestEndpointBridgeMainSubChild() : mGotHi(false) {}
+ virtual ~TestEndpointBridgeMainSubChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvHi();
+ mozilla::ipc::IPCResult AnswerHiRpc();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ bool mGotHi;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestEndpointBridgeMain_h
diff --git a/ipc/ipdl/test/cxx/TestEndpointOpens.cpp b/ipc/ipdl/test/cxx/TestEndpointOpens.cpp
new file mode 100644
index 0000000000..ca141f7b58
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestEndpointOpens.cpp
@@ -0,0 +1,242 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+#include "base/task.h"
+#include "base/thread.h"
+
+#include "TestEndpointOpens.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+using namespace mozilla::ipc;
+
+using base::ProcessHandle;
+using base::Thread;
+
+namespace mozilla {
+// NB: this is generally bad style, but I am lazy.
+using namespace _ipdltest;
+using namespace _ipdltest2;
+
+static MessageLoop* gMainThread;
+
+static void AssertNotMainThread() {
+ if (!gMainThread) {
+ fail("gMainThread is not initialized");
+ }
+ if (MessageLoop::current() == gMainThread) {
+ fail("unexpectedly called on the main thread");
+ }
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+// Thread on which TestEndpointOpensOpenedParent runs
+static Thread* gParentThread;
+
+void TestEndpointOpensParent::Main() {
+ if (!SendStart()) {
+ fail("sending Start");
+ }
+}
+
+static void OpenParent(TestEndpointOpensOpenedParent* aParent,
+ Endpoint<PTestEndpointOpensOpenedParent>&& aEndpoint) {
+ AssertNotMainThread();
+
+ // Open the actor on the off-main thread to park it there.
+ // Messages will be delivered to this thread's message loop
+ // instead of the main thread's.
+ if (!aEndpoint.Bind(aParent)) {
+ fail("binding Parent");
+ }
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensParent::RecvStartSubprotocol(
+ mozilla::ipc::Endpoint<PTestEndpointOpensOpenedParent>&& endpoint) {
+ gMainThread = MessageLoop::current();
+
+ gParentThread = new Thread("ParentThread");
+ if (!gParentThread->Start()) {
+ fail("starting parent thread");
+ }
+
+ TestEndpointOpensOpenedParent* a = new TestEndpointOpensOpenedParent();
+ gParentThread->message_loop()->PostTask(
+ NewRunnableFunction("OpenParent", OpenParent, a, std::move(endpoint)));
+
+ return IPC_OK();
+}
+
+void TestEndpointOpensParent::ActorDestroy(ActorDestroyReason why) {
+ // Stops the thread and joins it
+ delete gParentThread;
+
+ if (NormalShutdown != why) {
+ fail("unexpected destruction A!");
+ }
+ passed("ok");
+ QuitParent();
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensOpenedParent::RecvHello() {
+ AssertNotMainThread();
+ if (!SendHi()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensOpenedParent::RecvHelloSync() {
+ AssertNotMainThread();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensOpenedParent::AnswerHelloRpc() {
+ AssertNotMainThread();
+ if (!CallHiRpc()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+static void ShutdownTestEndpointOpensOpenedParent(
+ TestEndpointOpensOpenedParent* parent, Transport* transport) {
+ delete parent;
+}
+
+void TestEndpointOpensOpenedParent::ActorDestroy(ActorDestroyReason why) {
+ AssertNotMainThread();
+
+ if (NormalShutdown != why) {
+ fail("unexpected destruction B!");
+ }
+
+ // ActorDestroy() is just a callback from IPDL-generated code,
+ // which needs the top-level actor (this) to stay alive a little
+ // longer so other things can be cleaned up.
+ gParentThread->message_loop()->PostTask(NewRunnableFunction(
+ "ShutdownTestEndpointOpensOpenedParent",
+ ShutdownTestEndpointOpensOpenedParent, this, GetTransport()));
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+static TestEndpointOpensChild* gOpensChild;
+// Thread on which TestEndpointOpensOpenedChild runs
+static Thread* gChildThread;
+
+TestEndpointOpensChild::TestEndpointOpensChild() { gOpensChild = this; }
+
+static void OpenChild(TestEndpointOpensOpenedChild* aChild,
+ Endpoint<PTestEndpointOpensOpenedChild>&& endpoint) {
+ AssertNotMainThread();
+
+ // Open the actor on the off-main thread to park it there.
+ // Messages will be delivered to this thread's message loop
+ // instead of the main thread's.
+ if (!endpoint.Bind(aChild)) {
+ fail("binding child endpoint");
+ }
+
+ // Kick off the unit tests
+ if (!aChild->SendHello()) {
+ fail("sending Hello");
+ }
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensChild::RecvStart() {
+ Endpoint<PTestEndpointOpensOpenedParent> parent;
+ Endpoint<PTestEndpointOpensOpenedChild> child;
+ nsresult rv;
+ rv = PTestEndpointOpensOpened::CreateEndpoints(
+ OtherPid(), base::GetCurrentProcId(), &parent, &child);
+ if (NS_FAILED(rv)) {
+ fail("opening PTestEndpointOpensOpened");
+ }
+
+ gMainThread = MessageLoop::current();
+
+ gChildThread = new Thread("ChildThread");
+ if (!gChildThread->Start()) {
+ fail("starting child thread");
+ }
+
+ TestEndpointOpensOpenedChild* a = new TestEndpointOpensOpenedChild();
+ gChildThread->message_loop()->PostTask(
+ NewRunnableFunction("OpenChild", OpenChild, a, std::move(child)));
+
+ if (!SendStartSubprotocol(std::move(parent))) {
+ fail("send StartSubprotocol");
+ }
+
+ return IPC_OK();
+}
+
+void TestEndpointOpensChild::ActorDestroy(ActorDestroyReason why) {
+ // Stops the thread and joins it
+ delete gChildThread;
+
+ if (NormalShutdown != why) {
+ fail("unexpected destruction C!");
+ }
+ QuitChild();
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensOpenedChild::RecvHi() {
+ AssertNotMainThread();
+
+ if (!SendHelloSync()) {
+ fail("sending HelloSync");
+ }
+ if (!CallHelloRpc()) {
+ fail("calling HelloRpc");
+ }
+ if (!mGotHi) {
+ fail("didn't answer HiRpc");
+ }
+
+ // Need to close the channel without message-processing frames on
+ // the C++ stack
+ MessageLoop::current()->PostTask(
+ NewNonOwningRunnableMethod("ipc::IToplevelProtocol::Close", this,
+ &TestEndpointOpensOpenedChild::Close));
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestEndpointOpensOpenedChild::AnswerHiRpc() {
+ AssertNotMainThread();
+
+ mGotHi = true; // d00d
+ return IPC_OK();
+}
+
+static void ShutdownTestEndpointOpensOpenedChild(
+ TestEndpointOpensOpenedChild* child, Transport* transport) {
+ delete child;
+
+ // Kick off main-thread shutdown.
+ gMainThread->PostTask(
+ NewNonOwningRunnableMethod("ipc::IToplevelProtocol::Close", gOpensChild,
+ &TestEndpointOpensChild::Close));
+}
+
+void TestEndpointOpensOpenedChild::ActorDestroy(ActorDestroyReason why) {
+ AssertNotMainThread();
+
+ if (NormalShutdown != why) {
+ fail("unexpected destruction D!");
+ }
+
+ // ActorDestroy() is just a callback from IPDL-generated code,
+ // which needs the top-level actor (this) to stay alive a little
+ // longer so other things can be cleaned up. Defer shutdown to
+ // let cleanup finish.
+ gChildThread->message_loop()->PostTask(NewRunnableFunction(
+ "ShutdownTestEndpointOpensOpenedChild",
+ ShutdownTestEndpointOpensOpenedChild, this, GetTransport()));
+}
+
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestEndpointOpens.h b/ipc/ipdl/test/cxx/TestEndpointOpens.h
new file mode 100644
index 0000000000..6721274937
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestEndpointOpens.h
@@ -0,0 +1,102 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+
+#ifndef mozilla__ipdltest_TestEndpointOpens_h
+#define mozilla__ipdltest_TestEndpointOpens_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestEndpointOpensParent.h"
+#include "mozilla/_ipdltest/PTestEndpointOpensChild.h"
+
+#include "mozilla/_ipdltest2/PTestEndpointOpensOpenedParent.h"
+#include "mozilla/_ipdltest2/PTestEndpointOpensOpenedChild.h"
+
+namespace mozilla {
+
+// parent process
+
+namespace _ipdltest {
+
+class TestEndpointOpensParent : public PTestEndpointOpensParent {
+ friend class PTestEndpointOpensParent;
+
+ public:
+ TestEndpointOpensParent() {}
+ virtual ~TestEndpointOpensParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStartSubprotocol(
+ mozilla::ipc::Endpoint<PTestEndpointOpensOpenedParent>&& endpoint);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+} // namespace _ipdltest
+
+namespace _ipdltest2 {
+
+class TestEndpointOpensOpenedParent : public PTestEndpointOpensOpenedParent {
+ friend class PTestEndpointOpensOpenedParent;
+
+ public:
+ explicit TestEndpointOpensOpenedParent() {}
+ virtual ~TestEndpointOpensOpenedParent() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvHello();
+ mozilla::ipc::IPCResult RecvHelloSync();
+ mozilla::ipc::IPCResult AnswerHelloRpc();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+} // namespace _ipdltest2
+
+// child process
+
+namespace _ipdltest {
+
+class TestEndpointOpensChild : public PTestEndpointOpensChild {
+ friend class PTestEndpointOpensChild;
+
+ public:
+ TestEndpointOpensChild();
+ virtual ~TestEndpointOpensChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+} // namespace _ipdltest
+
+namespace _ipdltest2 {
+
+class TestEndpointOpensOpenedChild : public PTestEndpointOpensOpenedChild {
+ friend class PTestEndpointOpensOpenedChild;
+
+ public:
+ explicit TestEndpointOpensOpenedChild() : mGotHi(false) {}
+ virtual ~TestEndpointOpensOpenedChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvHi();
+ mozilla::ipc::IPCResult AnswerHiRpc();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ bool mGotHi;
+};
+
+} // namespace _ipdltest2
+
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestEndpointOpens_h
diff --git a/ipc/ipdl/test/cxx/TestFailedCtor.cpp b/ipc/ipdl/test/cxx/TestFailedCtor.cpp
new file mode 100644
index 0000000000..2f08d2eeb0
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestFailedCtor.cpp
@@ -0,0 +1,112 @@
+#include "TestFailedCtor.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+void TestFailedCtorParent::Main() {
+ PTestFailedCtorSubParent* p = CallPTestFailedCtorSubConstructor();
+ if (p) fail("expected ctor to fail");
+
+ Close();
+}
+
+PTestFailedCtorSubParent*
+TestFailedCtorParent::AllocPTestFailedCtorSubParent() {
+ return new TestFailedCtorSubParent();
+}
+bool TestFailedCtorParent::DeallocPTestFailedCtorSubParent(
+ PTestFailedCtorSubParent* actor) {
+ delete actor;
+ return true;
+}
+
+PTestFailedCtorSubsubParent*
+TestFailedCtorSubParent::AllocPTestFailedCtorSubsubParent() {
+ TestFailedCtorSubsub* a = new TestFailedCtorSubsub();
+ if (!mOne) {
+ return mOne = a;
+ } else if (!mTwo) {
+ return mTwo = a;
+ } else if (!mThree) {
+ return mThree = a;
+ } else {
+ fail("unexpected Alloc()");
+ return nullptr;
+ }
+}
+bool TestFailedCtorSubParent::DeallocPTestFailedCtorSubsubParent(
+ PTestFailedCtorSubsubParent* actor) {
+ static_cast<TestFailedCtorSubsub*>(actor)->mDealloced = true;
+ return true;
+}
+
+void TestFailedCtorSubParent::ActorDestroy(ActorDestroyReason why) {
+ if (mOne->mWhy != Deletion) fail("Subsub one got wrong ActorDestroyReason");
+ if (mTwo->mWhy != AncestorDeletion)
+ fail("Subsub two got wrong ActorDestroyReason");
+ if (mThree->mWhy != AncestorDeletion)
+ fail("Subsub three got wrong ActorDestroyReason");
+
+ if (FailedConstructor != why) fail("unexpected destruction!");
+}
+
+TestFailedCtorSubParent::~TestFailedCtorSubParent() {
+ if (!(mOne->mDealloced && mTwo->mDealloced && mThree->mDealloced))
+ fail("Not all subsubs were Dealloc'd");
+ delete mOne;
+ delete mTwo;
+ delete mThree;
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+PTestFailedCtorSubChild* TestFailedCtorChild::AllocPTestFailedCtorSubChild() {
+ return new TestFailedCtorSubChild();
+}
+
+mozilla::ipc::IPCResult
+TestFailedCtorChild::AnswerPTestFailedCtorSubConstructor(
+ PTestFailedCtorSubChild* actor) {
+ PTestFailedCtorSubsubChild* c1 =
+ actor->SendPTestFailedCtorSubsubConstructor();
+ PTestFailedCtorSubsubChild::Send__delete__(c1);
+
+ if (!actor->SendPTestFailedCtorSubsubConstructor() ||
+ !actor->SendPTestFailedCtorSubsubConstructor() || !actor->SendSync())
+ fail("setting up test");
+
+ // This causes our process to die
+ return IPC_FAIL_NO_REASON(this);
+}
+
+bool TestFailedCtorChild::DeallocPTestFailedCtorSubChild(
+ PTestFailedCtorSubChild* actor) {
+ delete actor;
+ return true;
+}
+
+void TestFailedCtorChild::ProcessingError(Result aCode, const char* aReason) {
+ if (OtherPid() != base::GetCurrentProcId()) // thread-mode
+ _exit(0);
+}
+
+PTestFailedCtorSubsubChild*
+TestFailedCtorSubChild::AllocPTestFailedCtorSubsubChild() {
+ return new TestFailedCtorSubsub();
+}
+
+bool TestFailedCtorSubChild::DeallocPTestFailedCtorSubsubChild(
+ PTestFailedCtorSubsubChild* actor) {
+ delete actor;
+ return true;
+}
+
+void TestFailedCtorSubChild::ActorDestroy(ActorDestroyReason why) {}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestFailedCtor.h b/ipc/ipdl/test/cxx/TestFailedCtor.h
new file mode 100644
index 0000000000..6fac4eb278
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestFailedCtor.h
@@ -0,0 +1,127 @@
+#ifndef mozilla_ipdltest_TestFailedCtor_h
+#define mozilla_ipdltest_TestFailedCtor_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestFailedCtorParent.h"
+#include "mozilla/_ipdltest/PTestFailedCtorChild.h"
+
+#include "mozilla/_ipdltest/PTestFailedCtorSubParent.h"
+#include "mozilla/_ipdltest/PTestFailedCtorSubChild.h"
+
+#include "mozilla/_ipdltest/PTestFailedCtorSubsubParent.h"
+#include "mozilla/_ipdltest/PTestFailedCtorSubsubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Top-level
+//
+class TestFailedCtorParent : public PTestFailedCtorParent {
+ friend class PTestFailedCtorParent;
+
+ public:
+ TestFailedCtorParent() {}
+ virtual ~TestFailedCtorParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+
+ // FIXME/bug 703322 Disabled because child calls exit() to end
+ // test, not clear how to handle failed ctor in
+ // threaded mode.
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ PTestFailedCtorSubParent* AllocPTestFailedCtorSubParent();
+ bool DeallocPTestFailedCtorSubParent(PTestFailedCtorSubParent* actor);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestFailedCtorChild : public PTestFailedCtorChild {
+ friend class PTestFailedCtorChild;
+
+ public:
+ TestFailedCtorChild() {}
+ virtual ~TestFailedCtorChild() {}
+
+ protected:
+ PTestFailedCtorSubChild* AllocPTestFailedCtorSubChild();
+
+ mozilla::ipc::IPCResult AnswerPTestFailedCtorSubConstructor(
+ PTestFailedCtorSubChild* actor) override;
+
+ bool DeallocPTestFailedCtorSubChild(PTestFailedCtorSubChild* actor);
+
+ virtual void ProcessingError(Result aCode, const char* aReason) override;
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ fail("should have _exit()ed");
+ }
+};
+
+//-----------------------------------------------------------------------------
+// First descendent
+//
+class TestFailedCtorSubsub;
+
+class TestFailedCtorSubParent : public PTestFailedCtorSubParent {
+ friend class PTestFailedCtorSubParent;
+
+ public:
+ TestFailedCtorSubParent() : mOne(nullptr), mTwo(nullptr), mThree(nullptr) {}
+ virtual ~TestFailedCtorSubParent();
+
+ protected:
+ PTestFailedCtorSubsubParent* AllocPTestFailedCtorSubsubParent();
+
+ bool DeallocPTestFailedCtorSubsubParent(PTestFailedCtorSubsubParent* actor);
+ mozilla::ipc::IPCResult RecvSync() { return IPC_OK(); }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ TestFailedCtorSubsub* mOne;
+ TestFailedCtorSubsub* mTwo;
+ TestFailedCtorSubsub* mThree;
+};
+
+class TestFailedCtorSubChild : public PTestFailedCtorSubChild {
+ friend class PTestFailedCtorSubChild;
+
+ public:
+ TestFailedCtorSubChild() {}
+ virtual ~TestFailedCtorSubChild() {}
+
+ protected:
+ PTestFailedCtorSubsubChild* AllocPTestFailedCtorSubsubChild();
+ bool DeallocPTestFailedCtorSubsubChild(PTestFailedCtorSubsubChild* actor);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+//-----------------------------------------------------------------------------
+// Grand-descendent
+//
+class TestFailedCtorSubsub : public PTestFailedCtorSubsubParent,
+ public PTestFailedCtorSubsubChild {
+ public:
+ TestFailedCtorSubsub() : mWhy(ActorDestroyReason(-1)), mDealloced(false) {}
+ virtual ~TestFailedCtorSubsub() {}
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { mWhy = why; }
+
+ ActorDestroyReason mWhy;
+ bool mDealloced;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla_ipdltest_TestFailedCtor_h
diff --git a/ipc/ipdl/test/cxx/TestHangs.cpp b/ipc/ipdl/test/cxx/TestHangs.cpp
new file mode 100644
index 0000000000..2694cbfdab
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestHangs.cpp
@@ -0,0 +1,127 @@
+#include "base/process_util.h"
+
+#include "TestHangs.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+using base::KillProcess;
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestHangsParent::TestHangsParent()
+ : mDetectedHang(false), mNumAnswerStackFrame(0) {
+ MOZ_COUNT_CTOR(TestHangsParent);
+}
+
+TestHangsParent::~TestHangsParent() { MOZ_COUNT_DTOR(TestHangsParent); }
+
+void TestHangsParent::Main() {
+ // Here we try to set things up to test the following sequence of events:
+ //
+ // - subprocess causes an OnMaybeDequeueOne() task to be posted to
+ // this thread
+ //
+ // - subprocess hangs just long enough for the hang timer to expire
+ //
+ // - hang-kill code in the parent starts running
+ //
+ // - subprocess replies to message while hang code runs
+ //
+ // - reply is processed in OnMaybeDequeueOne() before Close() has
+ // been called or the channel error notification has been posted
+
+ // this tells the subprocess to send us Nonce()
+ if (!SendStart()) fail("sending Start");
+
+ // now we sleep here for a while awaiting the Nonce() message from
+ // the child. since we're not blocked on anything, the IO thread
+ // will enqueue an OnMaybeDequeueOne() task to process that
+ // message
+ //
+ // NB: PR_Sleep is exactly what we want, only the current thread
+ // sleeping
+ PR_Sleep(5000);
+
+ // when we call into this, we'll pull the Nonce() message out of
+ // the mPending queue, but that doesn't matter ... the
+ // OnMaybeDequeueOne() event will remain
+ if (CallStackFrame() && mDetectedHang) fail("should have timed out!");
+
+ // the Close() task in the queue will shut us down
+}
+
+bool TestHangsParent::ShouldContinueFromReplyTimeout() {
+ mDetectedHang = true;
+
+ // so we've detected a timeout after 2 ms ... now we cheat and
+ // sleep for a long time, to allow the subprocess's reply to come
+ // in
+
+ PR_Sleep(5000);
+
+ // reply should be here; we'll post a task to shut things down.
+ // This must be after OnMaybeDequeueOne() in the event queue.
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestHangsParent::CleanUp", this, &TestHangsParent::CleanUp));
+
+ GetIPCChannel()->CloseWithTimeout();
+
+ return false;
+}
+
+mozilla::ipc::IPCResult TestHangsParent::AnswerStackFrame() {
+ ++mNumAnswerStackFrame;
+
+ if (mNumAnswerStackFrame == 1) {
+ if (CallStackFrame()) {
+ fail("should have timed out!");
+ }
+ } else if (mNumAnswerStackFrame == 2) {
+ // minimum possible, 2 ms. We want to detecting a hang to race
+ // with the reply coming in, as reliably as possible
+ SetReplyTimeoutMs(2);
+
+ if (CallHang()) fail("should have timed out!");
+ } else {
+ fail("unexpected state");
+ }
+
+ return IPC_OK();
+}
+
+void TestHangsParent::CleanUp() {
+ ipc::ScopedProcessHandle otherProcessHandle;
+ if (!base::OpenProcessHandle(OtherPid(), &otherProcessHandle.rwget())) {
+ fail("couldn't open child process");
+ } else {
+ if (!KillProcess(otherProcessHandle, 0, false)) {
+ fail("terminating child process");
+ }
+ }
+ Close();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestHangsChild::TestHangsChild() { MOZ_COUNT_CTOR(TestHangsChild); }
+
+TestHangsChild::~TestHangsChild() { MOZ_COUNT_DTOR(TestHangsChild); }
+
+mozilla::ipc::IPCResult TestHangsChild::AnswerHang() {
+ puts(" (child process is 'hanging' now)");
+
+ // just sleep until we're reasonably confident the 1ms hang
+ // detector fired in the parent process and it's sleeping in
+ // ShouldContinueFromReplyTimeout()
+ PR_Sleep(1000);
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestHangs.h b/ipc/ipdl/test/cxx/TestHangs.h
new file mode 100644
index 0000000000..a3dfb991f5
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestHangs.h
@@ -0,0 +1,75 @@
+#ifndef mozilla__ipdltest_TestHangs_h
+#define mozilla__ipdltest_TestHangs_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestHangsParent.h"
+#include "mozilla/_ipdltest/PTestHangsChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestHangsParent : public PTestHangsParent {
+ friend class PTestHangsParent;
+
+ public:
+ TestHangsParent();
+ virtual ~TestHangsParent();
+
+ static bool RunTestInProcesses() { return true; }
+
+ // FIXME/bug 703320 Disabled because parent kills child proc, not
+ // clear how that should work in threads.
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ virtual bool ShouldContinueFromReplyTimeout() override;
+
+ mozilla::ipc::IPCResult RecvNonce() { return IPC_OK(); }
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ void CleanUp();
+
+ bool mDetectedHang;
+ int32_t mNumAnswerStackFrame;
+};
+
+class TestHangsChild : public PTestHangsChild {
+ friend class PTestHangsChild;
+
+ public:
+ TestHangsChild();
+ virtual ~TestHangsChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart() {
+ if (!SendNonce()) fail("sending Nonce");
+ return IPC_OK();
+ }
+
+ mozilla::ipc::IPCResult AnswerStackFrame() {
+ if (CallStackFrame()) fail("should have failed");
+ return IPC_OK();
+ }
+
+ mozilla::ipc::IPCResult AnswerHang();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestHangs_h
diff --git a/ipc/ipdl/test/cxx/TestHighestPrio.cpp b/ipc/ipdl/test/cxx/TestHighestPrio.cpp
new file mode 100644
index 0000000000..499c352a5a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestHighestPrio.cpp
@@ -0,0 +1,91 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: sw=2 ts=4 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "TestHighestPrio.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#if defined(XP_UNIX)
+# include <unistd.h>
+#else
+# include <windows.h>
+#endif
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestHighestPrioParent::TestHighestPrioParent() : msg_num_(0) {
+ MOZ_COUNT_CTOR(TestHighestPrioParent);
+}
+
+TestHighestPrioParent::~TestHighestPrioParent() {
+ MOZ_COUNT_DTOR(TestHighestPrioParent);
+}
+
+void TestHighestPrioParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestHighestPrioParent::RecvMsg1() {
+ MOZ_ASSERT(msg_num_ == 0);
+ msg_num_ = 1;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestHighestPrioParent::RecvMsg2() {
+ MOZ_ASSERT(msg_num_ == 1);
+ msg_num_ = 2;
+
+ if (!SendStartInner()) fail("sending StartInner");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestHighestPrioParent::RecvMsg3() {
+ MOZ_ASSERT(msg_num_ == 2);
+ msg_num_ = 3;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestHighestPrioParent::RecvMsg4() {
+ MOZ_ASSERT(msg_num_ == 3);
+ msg_num_ = 4;
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestHighestPrioChild::TestHighestPrioChild() {
+ MOZ_COUNT_CTOR(TestHighestPrioChild);
+}
+
+TestHighestPrioChild::~TestHighestPrioChild() {
+ MOZ_COUNT_DTOR(TestHighestPrioChild);
+}
+
+mozilla::ipc::IPCResult TestHighestPrioChild::RecvStart() {
+ if (!SendMsg1()) fail("sending Msg1");
+
+ if (!SendMsg2()) fail("sending Msg2");
+
+ Close();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestHighestPrioChild::RecvStartInner() {
+ if (!SendMsg3()) fail("sending Msg3");
+
+ if (!SendMsg4()) fail("sending Msg4");
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestHighestPrio.h b/ipc/ipdl/test/cxx/TestHighestPrio.h
new file mode 100644
index 0000000000..34563d7708
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestHighestPrio.h
@@ -0,0 +1,55 @@
+#ifndef mozilla__ipdltest_TestHighestPrio_h
+#define mozilla__ipdltest_TestHighestPrio_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestHighestPrioParent.h"
+#include "mozilla/_ipdltest/PTestHighestPrioChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestHighestPrioParent : public PTestHighestPrioParent {
+ public:
+ TestHighestPrioParent();
+ virtual ~TestHighestPrioParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvMsg1();
+ mozilla::ipc::IPCResult RecvMsg2();
+ mozilla::ipc::IPCResult RecvMsg3();
+ mozilla::ipc::IPCResult RecvMsg4();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ if (msg_num_ != 4) fail("missed IPC call");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ int msg_num_;
+};
+
+class TestHighestPrioChild : public PTestHighestPrioChild {
+ public:
+ TestHighestPrioChild();
+ virtual ~TestHighestPrioChild();
+
+ mozilla::ipc::IPCResult RecvStart();
+ mozilla::ipc::IPCResult RecvStartInner();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestHighestPrio_h
diff --git a/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.cpp b/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.cpp
new file mode 100644
index 0000000000..3af7ad620d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.cpp
@@ -0,0 +1,138 @@
+#include "TestInterruptErrorCleanup.h"
+
+#include "base/task.h"
+#include "mozilla/CondVar.h"
+#include "mozilla/Mutex.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#include "IPDLUnitTestSubprocess.h"
+
+using mozilla::CondVar;
+using mozilla::Mutex;
+using mozilla::MutexAutoLock;
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+namespace {
+
+// NB: this test does its own shutdown, rather than going through
+// QuitParent(), because it's testing degenerate edge cases
+
+void DeleteSubprocess(Mutex* mutex, CondVar* cvar) {
+ MutexAutoLock lock(*mutex);
+
+ gSubprocess->Destroy();
+ gSubprocess = nullptr;
+
+ cvar->Notify();
+}
+
+void DeleteTheWorld() {
+ delete static_cast<TestInterruptErrorCleanupParent*>(gParentActor);
+ gParentActor = nullptr;
+
+ // needs to be synchronous to avoid affecting event ordering on
+ // the main thread
+ Mutex mutex MOZ_UNANNOTATED("TestInterruptErrorCleanup.DeleteTheWorld.mutex");
+ CondVar cvar(mutex, "TestInterruptErrorCleanup.DeleteTheWorld.cvar");
+
+ MutexAutoLock lock(mutex);
+
+ XRE_GetIOMessageLoop()->PostTask(
+ NewRunnableFunction("DeleteSubprocess", DeleteSubprocess, &mutex, &cvar));
+
+ cvar.Wait();
+}
+
+void Done() {
+ static NS_DEFINE_CID(kAppShellCID, NS_APPSHELL_CID);
+ nsCOMPtr<nsIAppShell> appShell(do_GetService(kAppShellCID));
+ appShell->Exit();
+
+ passed(__FILE__);
+}
+
+} // namespace
+
+TestInterruptErrorCleanupParent::TestInterruptErrorCleanupParent()
+ : mGotProcessingError(false) {
+ MOZ_COUNT_CTOR(TestInterruptErrorCleanupParent);
+}
+
+TestInterruptErrorCleanupParent::~TestInterruptErrorCleanupParent() {
+ MOZ_COUNT_DTOR(TestInterruptErrorCleanupParent);
+}
+
+void TestInterruptErrorCleanupParent::Main() {
+ // This test models the following sequence of events
+ //
+ // (1) Parent: Interrupt out-call
+ // (2) Child: crash
+ // --[Parent-only hereafter]--
+ // (3) Interrupt out-call return false
+ // (4) Close()
+ // --[event loop]--
+ // (5) delete parentActor
+ // (6) delete childProcess
+ // --[event loop]--
+ // (7) Channel::OnError notification
+ // --[event loop]--
+ // (8) Done, quit
+ //
+ // See bug 535298 and friends; this seqeunce of events captures
+ // three differnent potential errors
+ // - Close()-after-error (semantic error previously)
+ // - use-after-free of parentActor
+ // - use-after-free of channel
+ //
+ // Because of legacy constraints related to nsNPAPI* code, we need
+ // to ensure that this sequence of events can occur without
+ // errors/crashes.
+
+ MessageLoop::current()->PostTask(
+ NewRunnableFunction("DeleteTheWorld", DeleteTheWorld));
+
+ // it's a failure if this *succeeds*
+ if (CallError()) fail("expected an error!");
+
+ if (!mGotProcessingError) fail("expected a ProcessingError() notification");
+
+ // it's OK to Close() a channel after an error, because nsNPAPI*
+ // wants to do this
+ Close();
+
+ // we know that this event *must* be after the MaybeError
+ // notification enqueued by AsyncChannel, because that event is
+ // enqueued within the same mutex that ends up signaling the
+ // wakeup-on-error of |CallError()| above
+ MessageLoop::current()->PostTask(NewRunnableFunction("Done", Done));
+}
+
+void TestInterruptErrorCleanupParent::ProcessingError(Result aCode,
+ const char* aReason) {
+ if (aCode != MsgDropped) fail("unexpected processing error");
+ mGotProcessingError = true;
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestInterruptErrorCleanupChild::TestInterruptErrorCleanupChild() {
+ MOZ_COUNT_CTOR(TestInterruptErrorCleanupChild);
+}
+
+TestInterruptErrorCleanupChild::~TestInterruptErrorCleanupChild() {
+ MOZ_COUNT_DTOR(TestInterruptErrorCleanupChild);
+}
+
+mozilla::ipc::IPCResult TestInterruptErrorCleanupChild::AnswerError() {
+ _exit(0);
+ MOZ_CRASH("unreached");
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.h b/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.h
new file mode 100644
index 0000000000..9ae0493cf0
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptErrorCleanup.h
@@ -0,0 +1,52 @@
+#ifndef mozilla__ipdltest_TestInterruptErrorCleanup_h
+#define mozilla__ipdltest_TestInterruptErrorCleanup_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestInterruptErrorCleanupParent.h"
+#include "mozilla/_ipdltest/PTestInterruptErrorCleanupChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestInterruptErrorCleanupParent
+ : public PTestInterruptErrorCleanupParent {
+ public:
+ TestInterruptErrorCleanupParent();
+ virtual ~TestInterruptErrorCleanupParent();
+
+ static bool RunTestInProcesses() { return true; }
+ // FIXME/bug 703323 Could work if modified
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ }
+
+ virtual void ProcessingError(Result aCode, const char* aReason) override;
+
+ bool mGotProcessingError;
+};
+
+class TestInterruptErrorCleanupChild : public PTestInterruptErrorCleanupChild {
+ friend class PTestInterruptErrorCleanupChild;
+
+ public:
+ TestInterruptErrorCleanupChild();
+ virtual ~TestInterruptErrorCleanupChild();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerError();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ fail("should have 'crashed'!");
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestInterruptErrorCleanup_h
diff --git a/ipc/ipdl/test/cxx/TestInterruptRaces.cpp b/ipc/ipdl/test/cxx/TestInterruptRaces.cpp
new file mode 100644
index 0000000000..02b42cfbc3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptRaces.cpp
@@ -0,0 +1,169 @@
+#include "TestInterruptRaces.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+using mozilla::ipc::MessageChannel;
+
+namespace mozilla {
+namespace _ipdltest {
+
+ipc::RacyInterruptPolicy MediateRace(const MessageChannel::MessageInfo& parent,
+ const MessageChannel::MessageInfo& child) {
+ return (PTestInterruptRaces::Msg_Child__ID == parent.type())
+ ? ipc::RIPParentWins
+ : ipc::RIPChildWins;
+}
+
+//-----------------------------------------------------------------------------
+// parent
+void TestInterruptRacesParent::Main() {
+ if (!SendStart()) fail("sending Start()");
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::RecvStartRace() {
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestInterruptRacesParent::OnRaceTime", this,
+ &TestInterruptRacesParent::OnRaceTime));
+ return IPC_OK();
+}
+
+void TestInterruptRacesParent::OnRaceTime() {
+ if (!CallRace(&mChildHasReply)) fail("problem calling Race()");
+
+ if (!mChildHasReply) fail("child should have got a reply already");
+
+ mHasReply = true;
+
+ MessageLoop::current()->PostTask(
+ NewNonOwningRunnableMethod("_ipdltest::TestInterruptRacesParent::Test2",
+ this, &TestInterruptRacesParent::Test2));
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::AnswerRace(bool* hasReply) {
+ if (mHasReply) fail("apparently the parent won the Interrupt race!");
+ *hasReply = hasReply;
+ return IPC_OK();
+}
+
+void TestInterruptRacesParent::Test2() {
+ puts(" passed");
+ puts("Test 2");
+
+ mHasReply = false;
+ mChildHasReply = false;
+
+ if (!CallStackFrame()) fail("can't set up a stack frame");
+
+ puts(" passed");
+
+ MessageLoop::current()->PostTask(
+ NewNonOwningRunnableMethod("_ipdltest::TestInterruptRacesParent::Test3",
+ this, &TestInterruptRacesParent::Test3));
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::AnswerStackFrame() {
+ if (!SendWakeup()) fail("can't wake up the child");
+
+ if (!CallRace(&mChildHasReply)) fail("can't set up race condition");
+ mHasReply = true;
+
+ if (!mChildHasReply) fail("child should have got a reply already");
+
+ return IPC_OK();
+}
+
+void TestInterruptRacesParent::Test3() {
+ puts("Test 3");
+
+ if (!CallStackFrame3()) fail("can't set up a stack frame");
+
+ puts(" passed");
+
+ Close();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::AnswerStackFrame3() {
+ if (!SendWakeup3()) fail("can't wake up the child");
+
+ if (!CallChild()) fail("can't set up race condition");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::AnswerParent() {
+ mAnsweredParent = true;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesParent::RecvGetAnsweredParent(
+ bool* answeredParent) {
+ *answeredParent = mAnsweredParent;
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+mozilla::ipc::IPCResult TestInterruptRacesChild::RecvStart() {
+ puts("Test 1");
+
+ if (!SendStartRace()) fail("problem sending StartRace()");
+
+ bool dontcare;
+ if (!CallRace(&dontcare)) fail("problem calling Race()");
+
+ mHasReply = true;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::AnswerRace(bool* hasReply) {
+ if (!mHasReply) fail("apparently the child lost the Interrupt race!");
+
+ *hasReply = mHasReply;
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::AnswerStackFrame() {
+ // reset for the second test
+ mHasReply = false;
+
+ if (!CallStackFrame()) fail("can't set up stack frame");
+
+ if (!mHasReply) fail("should have had reply by now");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::RecvWakeup() {
+ bool dontcare;
+ if (!CallRace(&dontcare)) fail("can't set up race condition");
+
+ mHasReply = true;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::AnswerStackFrame3() {
+ if (!CallStackFrame3()) fail("can't set up stack frame");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::RecvWakeup3() {
+ if (!CallParent()) fail("can't set up race condition");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptRacesChild::AnswerChild() {
+ bool parentAnsweredParent;
+ // the parent is supposed to win the race, which means its
+ // message, Child(), is supposed to be processed before the
+ // child's message, Parent()
+ if (!SendGetAnsweredParent(&parentAnsweredParent))
+ fail("sending GetAnsweredParent");
+
+ if (parentAnsweredParent) fail("parent was supposed to win the race!");
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestInterruptRaces.h b/ipc/ipdl/test/cxx/TestInterruptRaces.h
new file mode 100644
index 0000000000..6fa184da1a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptRaces.h
@@ -0,0 +1,104 @@
+#ifndef mozilla__ipdltest_TestInterruptRaces_h
+#define mozilla__ipdltest_TestInterruptRaces_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestInterruptRacesParent.h"
+#include "mozilla/_ipdltest/PTestInterruptRacesChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+mozilla::ipc::RacyInterruptPolicy MediateRace(
+ const mozilla::ipc::MessageChannel::MessageInfo& parent,
+ const mozilla::ipc::MessageChannel::MessageInfo& child);
+
+class TestInterruptRacesParent : public PTestInterruptRacesParent {
+ friend class PTestInterruptRacesParent;
+
+ public:
+ TestInterruptRacesParent()
+ : mHasReply(false), mChildHasReply(false), mAnsweredParent(false) {}
+ virtual ~TestInterruptRacesParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStartRace();
+
+ mozilla::ipc::IPCResult AnswerRace(bool* hasRace);
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ mozilla::ipc::IPCResult AnswerStackFrame3();
+
+ mozilla::ipc::IPCResult AnswerParent();
+
+ mozilla::ipc::IPCResult RecvGetAnsweredParent(bool* answeredParent);
+
+ mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override {
+ return MediateRace(parent, child);
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ if (!(mHasReply && mChildHasReply)) fail("both sides should have replies!");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ void OnRaceTime();
+
+ void Test2();
+ void Test3();
+
+ bool mHasReply;
+ bool mChildHasReply;
+ bool mAnsweredParent;
+};
+
+class TestInterruptRacesChild : public PTestInterruptRacesChild {
+ friend class PTestInterruptRacesChild;
+
+ public:
+ TestInterruptRacesChild() : mHasReply(false) {}
+ virtual ~TestInterruptRacesChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult AnswerRace(bool* hasRace);
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ mozilla::ipc::IPCResult AnswerStackFrame3();
+
+ mozilla::ipc::IPCResult RecvWakeup();
+
+ mozilla::ipc::IPCResult RecvWakeup3();
+
+ mozilla::ipc::IPCResult AnswerChild();
+
+ virtual mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override {
+ return MediateRace(parent, child);
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ private:
+ bool mHasReply;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestInterruptRaces_h
diff --git a/ipc/ipdl/test/cxx/TestInterruptShutdownRace.cpp b/ipc/ipdl/test/cxx/TestInterruptShutdownRace.cpp
new file mode 100644
index 0000000000..5482893995
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptShutdownRace.cpp
@@ -0,0 +1,111 @@
+#include "TestInterruptShutdownRace.h"
+
+#include "base/task.h"
+#include "IPDLUnitTests.h" // fail etc.
+#include "IPDLUnitTestSubprocess.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+namespace {
+
+// NB: this test does its own shutdown, rather than going through
+// QuitParent(), because it's testing degenerate edge cases
+
+void DeleteSubprocess() {
+ gSubprocess->Destroy();
+ gSubprocess = nullptr;
+}
+
+void Done() {
+ passed(__FILE__);
+ QuitParent();
+}
+
+} // namespace
+
+TestInterruptShutdownRaceParent::TestInterruptShutdownRaceParent() {
+ MOZ_COUNT_CTOR(TestInterruptShutdownRaceParent);
+}
+
+TestInterruptShutdownRaceParent::~TestInterruptShutdownRaceParent() {
+ MOZ_COUNT_DTOR(TestInterruptShutdownRaceParent);
+}
+
+void TestInterruptShutdownRaceParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestInterruptShutdownRaceParent::RecvStartDeath() {
+ // this will be ordered before the OnMaybeDequeueOne event of
+ // Orphan in the queue
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestInterruptShutdownRaceParent::StartShuttingDown", this,
+ &TestInterruptShutdownRaceParent::StartShuttingDown));
+ return IPC_OK();
+}
+
+void TestInterruptShutdownRaceParent::StartShuttingDown() {
+ // NB: we sleep here to try and avoid receiving the Orphan message
+ // while waiting for the CallExit() reply. if we fail at that, it
+ // will cause the test to pass spuriously, because there won't be
+ // an OnMaybeDequeueOne task for Orphan
+ PR_Sleep(2000);
+
+ if (CallExit()) fail("connection was supposed to be interrupted");
+
+ Close();
+
+ delete static_cast<TestInterruptShutdownRaceParent*>(gParentActor);
+ gParentActor = nullptr;
+
+ XRE_GetIOMessageLoop()->PostTask(
+ NewRunnableFunction("DeleteSubprocess", DeleteSubprocess));
+
+ // this is ordered after the OnMaybeDequeueOne event in the queue
+ MessageLoop::current()->PostTask(NewRunnableFunction("Done", Done));
+
+ // |this| has been deleted, be mindful
+}
+
+mozilla::ipc::IPCResult TestInterruptShutdownRaceParent::RecvOrphan() {
+ // it would be nice to fail() here, but we'll process this message
+ // while waiting for the reply CallExit(). The OnMaybeDequeueOne
+ // task will still be in the queue, it just wouldn't have had any
+ // work to do, if we hadn't deleted ourself
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestInterruptShutdownRaceChild::TestInterruptShutdownRaceChild() {
+ MOZ_COUNT_CTOR(TestInterruptShutdownRaceChild);
+}
+
+TestInterruptShutdownRaceChild::~TestInterruptShutdownRaceChild() {
+ MOZ_COUNT_DTOR(TestInterruptShutdownRaceChild);
+}
+
+mozilla::ipc::IPCResult TestInterruptShutdownRaceChild::RecvStart() {
+ if (!SendStartDeath()) fail("sending StartDeath");
+
+ // See comment in StartShuttingDown(): we want to send Orphan()
+ // while the parent is in its PR_Sleep()
+ PR_Sleep(1000);
+
+ if (!SendOrphan()) fail("sending Orphan");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestInterruptShutdownRaceChild::AnswerExit() {
+ _exit(0);
+ MOZ_CRASH("unreached");
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestInterruptShutdownRace.h b/ipc/ipdl/test/cxx/TestInterruptShutdownRace.h
new file mode 100644
index 0000000000..17425fc06c
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestInterruptShutdownRace.h
@@ -0,0 +1,56 @@
+#ifndef mozilla__ipdltest_TestInterruptShutdownRace_h
+#define mozilla__ipdltest_TestInterruptShutdownRace_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestInterruptShutdownRaceParent.h"
+#include "mozilla/_ipdltest/PTestInterruptShutdownRaceChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestInterruptShutdownRaceParent
+ : public PTestInterruptShutdownRaceParent {
+ public:
+ TestInterruptShutdownRaceParent();
+ virtual ~TestInterruptShutdownRaceParent();
+
+ static bool RunTestInProcesses() { return true; }
+ // FIXME/bug 703323 Could work if modified
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvStartDeath();
+
+ mozilla::ipc::IPCResult RecvOrphan();
+
+ protected:
+ void StartShuttingDown();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (AbnormalShutdown != why) fail("unexpected destruction!");
+ }
+};
+
+class TestInterruptShutdownRaceChild : public PTestInterruptShutdownRaceChild {
+ friend class PTestInterruptShutdownRaceChild;
+
+ public:
+ TestInterruptShutdownRaceChild();
+ virtual ~TestInterruptShutdownRaceChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult AnswerExit();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ fail("should have 'crashed'!");
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestInterruptShutdownRace_h
diff --git a/ipc/ipdl/test/cxx/TestJSON.cpp b/ipc/ipdl/test/cxx/TestJSON.cpp
new file mode 100644
index 0000000000..42fac919d1
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestJSON.cpp
@@ -0,0 +1,113 @@
+#include "TestJSON.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+#define test_assert(_cond, _msg) \
+ if (!(_cond)) fail(_msg)
+
+namespace mozilla {
+namespace _ipdltest {
+
+static nsString String(const char* const str) {
+ return NS_ConvertUTF8toUTF16(str);
+}
+
+static void Array123(nsTArray<JSONVariant>& a123) {
+ a123.AppendElement(1);
+ a123.AppendElement(2);
+ a123.AppendElement(3);
+
+ test_assert(a123 == a123, "operator== is broken");
+}
+
+template <class HandleT>
+JSONVariant MakeTestVariant(HandleT* handle) {
+ // In JS syntax:
+ //
+ // return [
+ // undefined, null, true, 1.25, "test string",
+ // handle,
+ // [ 1, 2, 3 ],
+ // { "undefined" : undefined,
+ // "null" : null,
+ // "true" : true,
+ // "1.25" : 1.25,
+ // "string" : "string"
+ // "handle" : handle,
+ // "array" : [ 1, 2, 3 ]
+ // }
+ // ]
+ //
+ nsTArray<JSONVariant> outer;
+
+ outer.AppendElement(void_t());
+ outer.AppendElement(null_t());
+ outer.AppendElement(true);
+ outer.AppendElement(1.25);
+ outer.AppendElement(String("test string"));
+
+ outer.AppendElement(handle);
+
+ nsTArray<JSONVariant> tmp;
+ Array123(tmp);
+ outer.AppendElement(tmp);
+
+ nsTArray<KeyValue> obj;
+ obj.AppendElement(KeyValue(String("undefined"), void_t()));
+ obj.AppendElement(KeyValue(String("null"), null_t()));
+ obj.AppendElement(KeyValue(String("true"), true));
+ obj.AppendElement(KeyValue(String("1.25"), 1.25));
+ obj.AppendElement(KeyValue(String("string"), String("value")));
+ obj.AppendElement(KeyValue(String("handle"), handle));
+ nsTArray<JSONVariant> tmp2;
+ Array123(tmp2);
+ obj.AppendElement(KeyValue(String("array"), tmp2));
+
+ outer.AppendElement(obj);
+
+ test_assert(outer == outer, "operator== is broken");
+
+ return JSONVariant(outer);
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+void TestJSONParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestJSONParent::RecvTest(const JSONVariant& i,
+ JSONVariant* o) {
+ test_assert(i == i, "operator== is broken");
+ test_assert(i == MakeTestVariant(mKid), "inparam mangled en route");
+
+ *o = i;
+
+ test_assert(i == *o, "operator= is broken");
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+mozilla::ipc::IPCResult TestJSONChild::RecvStart() {
+ if (!SendPTestHandleConstructor()) fail("sending Handle ctor");
+
+ JSONVariant i(MakeTestVariant(mKid));
+ test_assert(i == i, "operator== is broken");
+ test_assert(i == MakeTestVariant(mKid), "copy ctor is broken");
+
+ JSONVariant o;
+ if (!SendTest(i, &o)) fail("sending Test");
+
+ test_assert(i == o, "round-trip mangled input data");
+ test_assert(o == MakeTestVariant(mKid), "outparam mangled en route");
+
+ Close();
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestJSON.h b/ipc/ipdl/test/cxx/TestJSON.h
new file mode 100644
index 0000000000..eaf7516525
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestJSON.h
@@ -0,0 +1,93 @@
+#ifndef mozilla__ipdltest_TestJSON_h
+#define mozilla__ipdltest_TestJSON_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestJSONParent.h"
+#include "mozilla/_ipdltest/PTestJSONChild.h"
+
+#include "mozilla/_ipdltest/PTestHandleParent.h"
+#include "mozilla/_ipdltest/PTestHandleChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestHandleParent : public PTestHandleParent {
+ public:
+ TestHandleParent() {}
+ virtual ~TestHandleParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestJSONParent : public PTestJSONParent {
+ friend class PTestJSONParent;
+
+ public:
+ TestJSONParent() {}
+ virtual ~TestJSONParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvTest(const JSONVariant& i, JSONVariant* o);
+
+ PTestHandleParent* AllocPTestHandleParent() {
+ return mKid = new TestHandleParent();
+ }
+
+ bool DeallocPTestHandleParent(PTestHandleParent* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ PTestHandleParent* mKid;
+};
+
+class TestHandleChild : public PTestHandleChild {
+ public:
+ TestHandleChild() {}
+ virtual ~TestHandleChild() {}
+};
+
+class TestJSONChild : public PTestJSONChild {
+ friend class PTestJSONChild;
+
+ public:
+ TestJSONChild() {}
+ virtual ~TestJSONChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ PTestHandleChild* AllocPTestHandleChild() {
+ return mKid = new TestHandleChild();
+ }
+
+ bool DeallocPTestHandleChild(PTestHandleChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ PTestHandleChild* mKid;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestJSON_h
diff --git a/ipc/ipdl/test/cxx/TestLatency.cpp b/ipc/ipdl/test/cxx/TestLatency.cpp
new file mode 100644
index 0000000000..f88d8ea644
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestLatency.cpp
@@ -0,0 +1,210 @@
+#include "TestLatency.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+// A ping/pong trial takes O(100us) or more, so if we don't have 10us
+// resolution or better, the results will not be terribly useful
+static const double kTimingResolutionCutoff = 0.00001; // 10us
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestLatencyParent::TestLatencyParent()
+ : mStart(),
+ mPPTimeTotal(),
+ mPP5TimeTotal(),
+ mRpcTimeTotal(),
+ mPPTrialsToGo(NR_TRIALS),
+ mPP5TrialsToGo(NR_TRIALS),
+ mNumChildProcessedCompressedSpams(0),
+ mWhichPong5(0) {
+ MOZ_COUNT_CTOR(TestLatencyParent);
+}
+
+TestLatencyParent::~TestLatencyParent() { MOZ_COUNT_DTOR(TestLatencyParent); }
+
+void TestLatencyParent::Main() {
+ TimeDuration resolution = TimeDuration::Resolution();
+ if (resolution.ToSeconds() > kTimingResolutionCutoff) {
+ puts(" (skipping TestLatency, timing resolution is too poor)");
+ Close();
+ return;
+ }
+
+ printf(" timing resolution: %g seconds\n", resolution.ToSecondsSigDigits());
+
+ if (mozilla::ipc::LoggingEnabled())
+ MOZ_CRASH(
+ "you really don't want to log all IPC messages during this test, trust "
+ "me");
+
+ PingPongTrial();
+}
+
+void TestLatencyParent::PingPongTrial() {
+ mStart = TimeStamp::Now();
+ if (!SendPing()) fail("sending Ping()");
+}
+
+void TestLatencyParent::Ping5Pong5Trial() {
+ mStart = TimeStamp::Now();
+
+ if (!SendPing5() || !SendPing5() || !SendPing5() || !SendPing5() ||
+ !SendPing5())
+ fail("sending Ping5()");
+}
+
+mozilla::ipc::IPCResult TestLatencyParent::RecvPong() {
+ TimeDuration thisTrial = (TimeStamp::Now() - mStart);
+ mPPTimeTotal += thisTrial;
+
+ if (0 == (mPPTrialsToGo % 1000))
+ printf(" PP trial %d: %g\n", mPPTrialsToGo,
+ thisTrial.ToSecondsSigDigits());
+
+ if (--mPPTrialsToGo > 0)
+ PingPongTrial();
+ else
+ Ping5Pong5Trial();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestLatencyParent::RecvPong5() {
+ ++mWhichPong5;
+
+ if (mWhichPong5 < 5) {
+ return IPC_OK();
+ }
+
+ mWhichPong5 = 0;
+
+ TimeDuration thisTrial = (TimeStamp::Now() - mStart);
+ mPP5TimeTotal += thisTrial;
+
+ if (0 == (mPP5TrialsToGo % 1000))
+ printf(" PP5 trial %d: %g\n", mPP5TrialsToGo,
+ thisTrial.ToSecondsSigDigits());
+
+ if (0 < --mPP5TrialsToGo)
+ Ping5Pong5Trial();
+ else
+ RpcTrials();
+
+ return IPC_OK();
+}
+
+void TestLatencyParent::RpcTrials() {
+ TimeStamp start = TimeStamp::Now();
+ for (int i = 0; i < NR_TRIALS; ++i) {
+ if (!CallRpc()) fail("can't call Rpc()");
+ if (0 == (i % 1000)) printf(" Rpc trial %d\n", i);
+ }
+ mRpcTimeTotal = (TimeStamp::Now() - start);
+
+ SpamTrial();
+}
+
+void TestLatencyParent::SpamTrial() {
+ TimeStamp start = TimeStamp::Now();
+ for (int i = 0; i < NR_SPAMS - 1; ++i) {
+ if (!SendSpam()) fail("sending Spam()");
+ if (0 == (i % 10000)) printf(" Spam trial %d\n", i);
+ }
+
+ // Synchronize with the child process to ensure all messages have
+ // been processed. This adds the overhead of a reply message from
+ // child-->here, but should be insignificant compared to >>
+ // NR_SPAMS.
+ if (!CallSynchro()) fail("calling Synchro()");
+
+ mSpamTimeTotal = (TimeStamp::Now() - start);
+
+ CompressedSpamTrial();
+}
+
+void TestLatencyParent::CompressedSpamTrial() {
+ for (int i = 0; i < NR_SPAMS; ++i) {
+ if (!SendCompressedSpam(i + 1)) fail("sending CompressedSpam()");
+ if (0 == (i % 10000)) printf(" CompressedSpam trial %d\n", i);
+ }
+
+ uint32_t lastSeqno;
+ if (!CallSynchro2(&lastSeqno, &mNumChildProcessedCompressedSpams))
+ fail("calling Synchro2()");
+
+ if (lastSeqno != NR_SPAMS)
+ fail("last seqno was %u, expected %u", lastSeqno, NR_SPAMS);
+
+ // NB: since this is testing an optimization, it's somewhat bogus.
+ // Need to make a warning if it actually intermittently fails in
+ // practice, which is doubtful.
+ if (!(mNumChildProcessedCompressedSpams < NR_SPAMS))
+ fail("Didn't compress any messages?");
+
+ Exit();
+}
+
+void TestLatencyParent::Exit() { Close(); }
+
+//-----------------------------------------------------------------------------
+// child
+
+TestLatencyChild::TestLatencyChild()
+ : mLastSeqno(0), mNumProcessedCompressedSpams(0), mWhichPing5(0) {
+ MOZ_COUNT_CTOR(TestLatencyChild);
+}
+
+TestLatencyChild::~TestLatencyChild() { MOZ_COUNT_DTOR(TestLatencyChild); }
+
+mozilla::ipc::IPCResult TestLatencyChild::RecvPing() {
+ SendPong();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestLatencyChild::RecvPing5() {
+ ++mWhichPing5;
+
+ if (mWhichPing5 < 5) {
+ return IPC_OK();
+ }
+
+ mWhichPing5 = 0;
+
+ if (!SendPong5() || !SendPong5() || !SendPong5() || !SendPong5() ||
+ !SendPong5())
+ fail("sending Pong5()");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestLatencyChild::AnswerRpc() { return IPC_OK(); }
+
+mozilla::ipc::IPCResult TestLatencyChild::RecvSpam() {
+ // no-op
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestLatencyChild::AnswerSynchro() { return IPC_OK(); }
+
+mozilla::ipc::IPCResult TestLatencyChild::RecvCompressedSpam(
+ const uint32_t& seqno) {
+ if (seqno <= mLastSeqno)
+ fail("compressed seqnos must monotonically increase");
+
+ mLastSeqno = seqno;
+ ++mNumProcessedCompressedSpams;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestLatencyChild::AnswerSynchro2(
+ uint32_t* lastSeqno, uint32_t* numMessagesDispatched) {
+ *lastSeqno = mLastSeqno;
+ *numMessagesDispatched = mNumProcessedCompressedSpams;
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestLatency.h b/ipc/ipdl/test/cxx/TestLatency.h
new file mode 100644
index 0000000000..687b107808
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestLatency.h
@@ -0,0 +1,107 @@
+#ifndef mozilla__ipdltest_TestLatency_h
+#define mozilla__ipdltest_TestLatency_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestLatencyParent.h"
+#include "mozilla/_ipdltest/PTestLatencyChild.h"
+
+#include "mozilla/TimeStamp.h"
+
+#define NR_TRIALS 10000
+#define NR_SPAMS 25000
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestLatencyParent : public PTestLatencyParent {
+ friend class PTestLatencyParent;
+
+ private:
+ typedef mozilla::TimeStamp TimeStamp;
+ typedef mozilla::TimeDuration TimeDuration;
+
+ public:
+ TestLatencyParent();
+ virtual ~TestLatencyParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPong();
+ mozilla::ipc::IPCResult RecvPong5();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+
+ passed(
+ "\n"
+ " average #ping-pong/sec: %g\n"
+ " average #ping5-pong5/sec: %g\n"
+ " average #RPC call-answer/sec: %g\n"
+ " average #spams/sec: %g\n"
+ " pct. spams compressed away: %g\n",
+ double(NR_TRIALS) / mPPTimeTotal.ToSecondsSigDigits(),
+ double(NR_TRIALS) / mPP5TimeTotal.ToSecondsSigDigits(),
+ double(NR_TRIALS) / mRpcTimeTotal.ToSecondsSigDigits(),
+ double(NR_SPAMS) / mSpamTimeTotal.ToSecondsSigDigits(),
+ 100.0 * (double(NR_SPAMS - mNumChildProcessedCompressedSpams) /
+ double(NR_SPAMS)));
+
+ QuitParent();
+ }
+
+ private:
+ void PingPongTrial();
+ void Ping5Pong5Trial();
+ void RpcTrials();
+ void SpamTrial();
+ void CompressedSpamTrial();
+ void Exit();
+
+ TimeStamp mStart;
+ TimeDuration mPPTimeTotal;
+ TimeDuration mPP5TimeTotal;
+ TimeDuration mRpcTimeTotal;
+ TimeDuration mSpamTimeTotal;
+
+ int mPPTrialsToGo;
+ int mPP5TrialsToGo;
+ uint32_t mNumChildProcessedCompressedSpams;
+ uint32_t mWhichPong5;
+};
+
+class TestLatencyChild : public PTestLatencyChild {
+ friend class PTestLatencyChild;
+
+ public:
+ TestLatencyChild();
+ virtual ~TestLatencyChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPing();
+ mozilla::ipc::IPCResult RecvPing5();
+ mozilla::ipc::IPCResult AnswerRpc();
+ mozilla::ipc::IPCResult RecvSpam();
+ mozilla::ipc::IPCResult AnswerSynchro();
+ mozilla::ipc::IPCResult RecvCompressedSpam(const uint32_t& seqno);
+ mozilla::ipc::IPCResult AnswerSynchro2(uint32_t* lastSeqno,
+ uint32_t* numMessagesDispatched);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ uint32_t mLastSeqno;
+ uint32_t mNumProcessedCompressedSpams;
+ uint32_t mWhichPing5;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestLatency_h
diff --git a/ipc/ipdl/test/cxx/TestManyChildAllocs.cpp b/ipc/ipdl/test/cxx/TestManyChildAllocs.cpp
new file mode 100644
index 0000000000..77d5786cfa
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestManyChildAllocs.cpp
@@ -0,0 +1,83 @@
+#include "TestManyChildAllocs.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+#define NALLOCS 10
+
+namespace mozilla {
+namespace _ipdltest {
+
+// parent code
+
+TestManyChildAllocsParent::TestManyChildAllocsParent() {
+ MOZ_COUNT_CTOR(TestManyChildAllocsParent);
+}
+
+TestManyChildAllocsParent::~TestManyChildAllocsParent() {
+ MOZ_COUNT_DTOR(TestManyChildAllocsParent);
+}
+
+void TestManyChildAllocsParent::Main() {
+ if (!SendGo()) fail("can't send Go()");
+}
+
+mozilla::ipc::IPCResult TestManyChildAllocsParent::RecvDone() {
+ // explicitly *not* cleaning up, so we can sanity-check IPDL's
+ // auto-shutdown/cleanup handling
+ Close();
+
+ return IPC_OK();
+}
+
+bool TestManyChildAllocsParent::DeallocPTestManyChildAllocsSubParent(
+ PTestManyChildAllocsSubParent* __a) {
+ delete __a;
+ return true;
+}
+
+PTestManyChildAllocsSubParent*
+TestManyChildAllocsParent::AllocPTestManyChildAllocsSubParent() {
+ return new TestManyChildAllocsSubParent();
+}
+
+// child code
+
+TestManyChildAllocsChild::TestManyChildAllocsChild() {
+ MOZ_COUNT_CTOR(TestManyChildAllocsChild);
+}
+
+TestManyChildAllocsChild::~TestManyChildAllocsChild() {
+ MOZ_COUNT_DTOR(TestManyChildAllocsChild);
+}
+
+mozilla::ipc::IPCResult TestManyChildAllocsChild::RecvGo() {
+ for (int i = 0; i < NALLOCS; ++i) {
+ PTestManyChildAllocsSubChild* child =
+ SendPTestManyChildAllocsSubConstructor();
+
+ if (!child) fail("can't send ctor()");
+
+ if (!child->SendHello()) fail("can't send Hello()");
+ }
+
+ size_t len = ManagedPTestManyChildAllocsSubChild().Count();
+ if (NALLOCS != len) fail("expected %lu kids, got %lu", NALLOCS, len);
+
+ if (!SendDone()) fail("can't send Done()");
+
+ return IPC_OK();
+}
+
+bool TestManyChildAllocsChild::DeallocPTestManyChildAllocsSubChild(
+ PTestManyChildAllocsSubChild* __a) {
+ delete __a;
+ return true;
+}
+
+PTestManyChildAllocsSubChild*
+TestManyChildAllocsChild::AllocPTestManyChildAllocsSubChild() {
+ return new TestManyChildAllocsSubChild();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestManyChildAllocs.h b/ipc/ipdl/test/cxx/TestManyChildAllocs.h
new file mode 100644
index 0000000000..3da6461810
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestManyChildAllocs.h
@@ -0,0 +1,82 @@
+#ifndef mozilla__ipdltest_TestManyChildAllocs_h
+#define mozilla__ipdltest_TestManyChildAllocs_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestManyChildAllocsParent.h"
+#include "mozilla/_ipdltest/PTestManyChildAllocsChild.h"
+
+#include "mozilla/_ipdltest/PTestManyChildAllocsSubParent.h"
+#include "mozilla/_ipdltest/PTestManyChildAllocsSubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+// top-level protocol
+
+class TestManyChildAllocsParent : public PTestManyChildAllocsParent {
+ friend class PTestManyChildAllocsParent;
+
+ public:
+ TestManyChildAllocsParent();
+ virtual ~TestManyChildAllocsParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvDone();
+ bool DeallocPTestManyChildAllocsSubParent(PTestManyChildAllocsSubParent* __a);
+ PTestManyChildAllocsSubParent* AllocPTestManyChildAllocsSubParent();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestManyChildAllocsChild : public PTestManyChildAllocsChild {
+ friend class PTestManyChildAllocsChild;
+
+ public:
+ TestManyChildAllocsChild();
+ virtual ~TestManyChildAllocsChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvGo();
+ bool DeallocPTestManyChildAllocsSubChild(PTestManyChildAllocsSubChild* __a);
+ PTestManyChildAllocsSubChild* AllocPTestManyChildAllocsSubChild();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+// do-nothing sub-protocol actors
+
+class TestManyChildAllocsSubParent : public PTestManyChildAllocsSubParent {
+ friend class PTestManyChildAllocsSubParent;
+
+ public:
+ TestManyChildAllocsSubParent() {}
+ virtual ~TestManyChildAllocsSubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+ mozilla::ipc::IPCResult RecvHello() { return IPC_OK(); }
+};
+
+class TestManyChildAllocsSubChild : public PTestManyChildAllocsSubChild {
+ public:
+ TestManyChildAllocsSubChild() {}
+ virtual ~TestManyChildAllocsSubChild() {}
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestManyChildAllocs_h
diff --git a/ipc/ipdl/test/cxx/TestMultiMgrs.cpp b/ipc/ipdl/test/cxx/TestMultiMgrs.cpp
new file mode 100644
index 0000000000..f09bb9ca7b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestMultiMgrs.cpp
@@ -0,0 +1,83 @@
+#include "TestMultiMgrs.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#include "mozilla/ipc/ProtocolUtils.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+void TestMultiMgrsParent::Main() {
+ TestMultiMgrsLeftParent* leftie = new TestMultiMgrsLeftParent();
+ if (!SendPTestMultiMgrsLeftConstructor(leftie)) fail("error sending ctor");
+
+ TestMultiMgrsRightParent* rightie = new TestMultiMgrsRightParent();
+ if (!SendPTestMultiMgrsRightConstructor(rightie)) fail("error sending ctor");
+
+ TestMultiMgrsBottomParent* bottomL = new TestMultiMgrsBottomParent();
+ if (!leftie->SendPTestMultiMgrsBottomConstructor(bottomL))
+ fail("error sending ctor");
+
+ TestMultiMgrsBottomParent* bottomR = new TestMultiMgrsBottomParent();
+ if (!rightie->SendPTestMultiMgrsBottomConstructor(bottomR))
+ fail("error sending ctor");
+
+ if (!leftie->HasChild(bottomL))
+ fail("leftie didn't have a child it was supposed to!");
+ if (leftie->HasChild(bottomR)) fail("leftie had rightie's child!");
+
+ if (!rightie->HasChild(bottomR))
+ fail("rightie didn't have a child it was supposed to!");
+ if (rightie->HasChild(bottomL)) fail("rightie had rightie's child!");
+
+ if (!SendCheck()) fail("couldn't kick off the child-side check");
+}
+
+mozilla::ipc::IPCResult TestMultiMgrsParent::RecvOK() {
+ Close();
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+mozilla::ipc::IPCResult
+TestMultiMgrsLeftChild::RecvPTestMultiMgrsBottomConstructor(
+ PTestMultiMgrsBottomChild* actor) {
+ static_cast<TestMultiMgrsChild*>(Manager())->mBottomL = actor;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult
+TestMultiMgrsRightChild::RecvPTestMultiMgrsBottomConstructor(
+ PTestMultiMgrsBottomChild* actor) {
+ static_cast<TestMultiMgrsChild*>(Manager())->mBottomR = actor;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestMultiMgrsChild::RecvCheck() {
+ if (1 != ManagedPTestMultiMgrsLeftChild().Count()) fail("where's leftie?");
+ if (1 != ManagedPTestMultiMgrsRightChild().Count()) fail("where's rightie?");
+
+ TestMultiMgrsLeftChild* leftie = static_cast<TestMultiMgrsLeftChild*>(
+ LoneManagedOrNullAsserts(ManagedPTestMultiMgrsLeftChild()));
+ TestMultiMgrsRightChild* rightie = static_cast<TestMultiMgrsRightChild*>(
+ LoneManagedOrNullAsserts(ManagedPTestMultiMgrsRightChild()));
+
+ if (!leftie->HasChild(mBottomL))
+ fail("leftie didn't have a child it was supposed to!");
+ if (leftie->HasChild(mBottomR)) fail("leftie had rightie's child!");
+
+ if (!rightie->HasChild(mBottomR))
+ fail("rightie didn't have a child it was supposed to!");
+ if (rightie->HasChild(mBottomL)) fail("rightie had leftie's child!");
+
+ if (!SendOK()) fail("couldn't send OK()");
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestMultiMgrs.h b/ipc/ipdl/test/cxx/TestMultiMgrs.h
new file mode 100644
index 0000000000..71826d42a7
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestMultiMgrs.h
@@ -0,0 +1,222 @@
+#ifndef mozilla__ipdltest_TestMultiMgrs_h
+#define mozilla__ipdltest_TestMultiMgrs_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestMultiMgrsParent.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsChild.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsBottomParent.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsBottomChild.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsLeftParent.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsLeftChild.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsRightParent.h"
+#include "mozilla/_ipdltest/PTestMultiMgrsRightChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Parent side
+//
+
+class TestMultiMgrsBottomParent : public PTestMultiMgrsBottomParent {
+ public:
+ TestMultiMgrsBottomParent() {}
+ virtual ~TestMultiMgrsBottomParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestMultiMgrsLeftParent : public PTestMultiMgrsLeftParent {
+ friend class PTestMultiMgrsLeftParent;
+
+ public:
+ TestMultiMgrsLeftParent() {}
+ virtual ~TestMultiMgrsLeftParent() {}
+
+ bool HasChild(TestMultiMgrsBottomParent* c) {
+ return ManagedPTestMultiMgrsBottomParent().Contains(c);
+ }
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+
+ PTestMultiMgrsBottomParent* AllocPTestMultiMgrsBottomParent() {
+ return new TestMultiMgrsBottomParent();
+ }
+
+ bool DeallocPTestMultiMgrsBottomParent(PTestMultiMgrsBottomParent* actor) {
+ delete actor;
+ return true;
+ }
+};
+
+class TestMultiMgrsRightParent : public PTestMultiMgrsRightParent {
+ friend class PTestMultiMgrsRightParent;
+
+ public:
+ TestMultiMgrsRightParent() {}
+ virtual ~TestMultiMgrsRightParent() {}
+
+ bool HasChild(TestMultiMgrsBottomParent* c) {
+ return ManagedPTestMultiMgrsBottomParent().Contains(c);
+ }
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+
+ PTestMultiMgrsBottomParent* AllocPTestMultiMgrsBottomParent() {
+ return new TestMultiMgrsBottomParent();
+ }
+
+ bool DeallocPTestMultiMgrsBottomParent(PTestMultiMgrsBottomParent* actor) {
+ delete actor;
+ return true;
+ }
+};
+
+class TestMultiMgrsParent : public PTestMultiMgrsParent {
+ friend class PTestMultiMgrsParent;
+
+ public:
+ TestMultiMgrsParent() {}
+ virtual ~TestMultiMgrsParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvOK();
+
+ PTestMultiMgrsLeftParent* AllocPTestMultiMgrsLeftParent() {
+ return new TestMultiMgrsLeftParent();
+ }
+
+ bool DeallocPTestMultiMgrsLeftParent(PTestMultiMgrsLeftParent* actor) {
+ delete actor;
+ return true;
+ }
+
+ PTestMultiMgrsRightParent* AllocPTestMultiMgrsRightParent() {
+ return new TestMultiMgrsRightParent();
+ }
+
+ bool DeallocPTestMultiMgrsRightParent(PTestMultiMgrsRightParent* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+//-----------------------------------------------------------------------------
+// Child side
+//
+
+class TestMultiMgrsBottomChild : public PTestMultiMgrsBottomChild {
+ public:
+ TestMultiMgrsBottomChild() {}
+ virtual ~TestMultiMgrsBottomChild() {}
+};
+
+class TestMultiMgrsLeftChild : public PTestMultiMgrsLeftChild {
+ friend class PTestMultiMgrsLeftChild;
+
+ public:
+ TestMultiMgrsLeftChild() {}
+ virtual ~TestMultiMgrsLeftChild() {}
+
+ bool HasChild(PTestMultiMgrsBottomChild* c) {
+ return ManagedPTestMultiMgrsBottomChild().Contains(c);
+ }
+
+ protected:
+ virtual mozilla::ipc::IPCResult RecvPTestMultiMgrsBottomConstructor(
+ PTestMultiMgrsBottomChild* actor) override;
+
+ PTestMultiMgrsBottomChild* AllocPTestMultiMgrsBottomChild() {
+ return new TestMultiMgrsBottomChild();
+ }
+
+ bool DeallocPTestMultiMgrsBottomChild(PTestMultiMgrsBottomChild* actor) {
+ delete actor;
+ return true;
+ }
+};
+
+class TestMultiMgrsRightChild : public PTestMultiMgrsRightChild {
+ friend class PTestMultiMgrsRightChild;
+
+ public:
+ TestMultiMgrsRightChild() {}
+ virtual ~TestMultiMgrsRightChild() {}
+
+ bool HasChild(PTestMultiMgrsBottomChild* c) {
+ return ManagedPTestMultiMgrsBottomChild().Contains(c);
+ }
+
+ protected:
+ virtual mozilla::ipc::IPCResult RecvPTestMultiMgrsBottomConstructor(
+ PTestMultiMgrsBottomChild* actor) override;
+
+ PTestMultiMgrsBottomChild* AllocPTestMultiMgrsBottomChild() {
+ return new TestMultiMgrsBottomChild();
+ }
+
+ bool DeallocPTestMultiMgrsBottomChild(PTestMultiMgrsBottomChild* actor) {
+ delete actor;
+ return true;
+ }
+};
+
+class TestMultiMgrsChild : public PTestMultiMgrsChild {
+ friend class PTestMultiMgrsChild;
+
+ public:
+ TestMultiMgrsChild() {}
+ virtual ~TestMultiMgrsChild() {}
+
+ void Main();
+
+ PTestMultiMgrsBottomChild* mBottomL;
+ PTestMultiMgrsBottomChild* mBottomR;
+
+ protected:
+ mozilla::ipc::IPCResult RecvCheck();
+
+ PTestMultiMgrsLeftChild* AllocPTestMultiMgrsLeftChild() {
+ return new TestMultiMgrsLeftChild();
+ }
+
+ bool DeallocPTestMultiMgrsLeftChild(PTestMultiMgrsLeftChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ PTestMultiMgrsRightChild* AllocPTestMultiMgrsRightChild() {
+ return new TestMultiMgrsRightChild();
+ }
+
+ bool DeallocPTestMultiMgrsRightChild(PTestMultiMgrsRightChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestMultiMgrs_h
diff --git a/ipc/ipdl/test/cxx/TestNestedLoops.cpp b/ipc/ipdl/test/cxx/TestNestedLoops.cpp
new file mode 100644
index 0000000000..3658d7dfb6
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestNestedLoops.cpp
@@ -0,0 +1,78 @@
+#include "base/basictypes.h"
+
+#include "nsThreadUtils.h"
+
+#include "TestNestedLoops.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestNestedLoopsParent::TestNestedLoopsParent() : mBreakNestedLoop(false) {
+ MOZ_COUNT_CTOR(TestNestedLoopsParent);
+}
+
+TestNestedLoopsParent::~TestNestedLoopsParent() {
+ MOZ_COUNT_DTOR(TestNestedLoopsParent);
+}
+
+void TestNestedLoopsParent::Main() {
+ if (!SendStart()) fail("sending Start");
+
+ // sigh ... spin for a while to let Nonce arrive
+ puts(" (sleeping to wait for nonce ... sorry)");
+ PR_Sleep(5000);
+
+ // while waiting for the reply to R, we'll receive Nonce
+ if (!CallR()) fail("calling R");
+
+ Close();
+}
+
+mozilla::ipc::IPCResult TestNestedLoopsParent::RecvNonce() {
+ // if we have an OnMaybeDequeueOne waiting for us (we may not, due
+ // to the inherent race condition in this test, then this event
+ // must be ordered after it in the queue
+ MessageLoop::current()->PostTask(NewNonOwningRunnableMethod(
+ "_ipdltest::TestNestedLoopsParent::BreakNestedLoop", this,
+ &TestNestedLoopsParent::BreakNestedLoop));
+
+ // sigh ... spin for a while to let the reply to R arrive
+ puts(" (sleeping to wait for reply to R ... sorry)");
+ PR_Sleep(5000);
+
+ // sigh ... we have no idea when code might do this
+ do {
+ if (!NS_ProcessNextEvent(nullptr, false))
+ fail("expected at least one pending event");
+ } while (!mBreakNestedLoop);
+
+ return IPC_OK();
+}
+
+void TestNestedLoopsParent::BreakNestedLoop() { mBreakNestedLoop = true; }
+
+//-----------------------------------------------------------------------------
+// child
+
+TestNestedLoopsChild::TestNestedLoopsChild() {
+ MOZ_COUNT_CTOR(TestNestedLoopsChild);
+}
+
+TestNestedLoopsChild::~TestNestedLoopsChild() {
+ MOZ_COUNT_DTOR(TestNestedLoopsChild);
+}
+
+mozilla::ipc::IPCResult TestNestedLoopsChild::RecvStart() {
+ if (!SendNonce()) fail("sending Nonce");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestNestedLoopsChild::AnswerR() { return IPC_OK(); }
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestNestedLoops.h b/ipc/ipdl/test/cxx/TestNestedLoops.h
new file mode 100644
index 0000000000..001b571494
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestNestedLoops.h
@@ -0,0 +1,59 @@
+#ifndef mozilla__ipdltest_TestNestedLoops_h
+#define mozilla__ipdltest_TestNestedLoops_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestNestedLoopsParent.h"
+#include "mozilla/_ipdltest/PTestNestedLoopsChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestNestedLoopsParent : public PTestNestedLoopsParent {
+ friend class PTestNestedLoopsParent;
+
+ public:
+ TestNestedLoopsParent();
+ virtual ~TestNestedLoopsParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvNonce();
+
+ void BreakNestedLoop();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ bool mBreakNestedLoop;
+};
+
+class TestNestedLoopsChild : public PTestNestedLoopsChild {
+ friend class PTestNestedLoopsChild;
+
+ public:
+ TestNestedLoopsChild();
+ virtual ~TestNestedLoopsChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult AnswerR();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestNestedLoops_h
diff --git a/ipc/ipdl/test/cxx/TestRPC.cpp b/ipc/ipdl/test/cxx/TestRPC.cpp
new file mode 100644
index 0000000000..cf7a1b6c36
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRPC.cpp
@@ -0,0 +1,107 @@
+#include "TestRPC.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#if defined(XP_UNIX)
+# include <unistd.h>
+#else
+# include <windows.h>
+#endif
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRPCParent::TestRPCParent()
+ : reentered_(false), resolved_first_cpow_(false) {
+ MOZ_COUNT_CTOR(TestRPCParent);
+}
+
+TestRPCParent::~TestRPCParent() { MOZ_COUNT_DTOR(TestRPCParent); }
+
+void TestRPCParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestRPCParent::RecvTest1_Start(uint32_t* aResult) {
+ uint32_t result;
+ if (!SendTest1_InnerQuery(&result)) fail("SendTest1_InnerQuery");
+ if (result != 300) fail("Wrong result (expected 300)");
+
+ *aResult = 100;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCParent::RecvTest1_InnerEvent(uint32_t* aResult) {
+ uint32_t result;
+ if (!SendTest1_NoReenter(&result)) fail("SendTest1_NoReenter");
+ if (result != 400) fail("Wrong result (expected 400)");
+
+ *aResult = 200;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCParent::RecvTest2_Start() {
+ // Send a CPOW. During this time, we must NOT process the RPC message, as
+ // we could start receiving CPOW replies out-of-order.
+ if (!SendTest2_FirstUrgent()) fail("SendTest2_FirstUrgent");
+
+ MOZ_ASSERT(!reentered_);
+ resolved_first_cpow_ = true;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCParent::RecvTest2_OutOfOrder() {
+ // Send a CPOW. If this RPC call was initiated while waiting for the first
+ // CPOW to resolve, replies will be processed out of order, and we'll crash.
+ if (!SendTest2_SecondUrgent()) fail("SendTest2_SecondUrgent");
+
+ reentered_ = true;
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRPCChild::TestRPCChild() { MOZ_COUNT_CTOR(TestRPCChild); }
+
+TestRPCChild::~TestRPCChild() { MOZ_COUNT_DTOR(TestRPCChild); }
+
+mozilla::ipc::IPCResult TestRPCChild::RecvStart() {
+ uint32_t result;
+ if (!SendTest1_Start(&result)) fail("SendTest1_Start");
+ if (result != 100) fail("Wrong result (expected 100)");
+
+ if (!SendTest2_Start()) fail("SendTest2_Start");
+
+ if (!SendTest2_OutOfOrder()) fail("SendTest2_OutOfOrder");
+
+ Close();
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCChild::RecvTest1_InnerQuery(uint32_t* aResult) {
+ uint32_t result;
+ if (!SendTest1_InnerEvent(&result)) fail("SendTest1_InnerEvent");
+ if (result != 200) fail("Wrong result (expected 200)");
+
+ *aResult = 300;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCChild::RecvTest1_NoReenter(uint32_t* aResult) {
+ *aResult = 400;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCChild::RecvTest2_FirstUrgent() {
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRPCChild::RecvTest2_SecondUrgent() {
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRPC.h b/ipc/ipdl/test/cxx/TestRPC.h
new file mode 100644
index 0000000000..907d3fde36
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRPC.h
@@ -0,0 +1,60 @@
+#ifndef mozilla__ipdltest_TestRPC_h
+#define mozilla__ipdltest_TestRPC_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRPCParent.h"
+#include "mozilla/_ipdltest/PTestRPCChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRPCParent : public PTestRPCParent {
+ public:
+ TestRPCParent();
+ virtual ~TestRPCParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvTest1_Start(uint32_t* aResult);
+ mozilla::ipc::IPCResult RecvTest1_InnerEvent(uint32_t* aResult);
+ mozilla::ipc::IPCResult RecvTest2_Start();
+ mozilla::ipc::IPCResult RecvTest2_OutOfOrder();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ if (!reentered_) fail("never processed raced RPC call!");
+ if (!resolved_first_cpow_) fail("never resolved first CPOW!");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ bool reentered_;
+ bool resolved_first_cpow_;
+};
+
+class TestRPCChild : public PTestRPCChild {
+ public:
+ TestRPCChild();
+ virtual ~TestRPCChild();
+
+ mozilla::ipc::IPCResult RecvStart();
+ mozilla::ipc::IPCResult RecvTest1_InnerQuery(uint32_t* aResult);
+ mozilla::ipc::IPCResult RecvTest1_NoReenter(uint32_t* aResult);
+ mozilla::ipc::IPCResult RecvTest2_FirstUrgent();
+ mozilla::ipc::IPCResult RecvTest2_SecondUrgent();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRPC_h
diff --git a/ipc/ipdl/test/cxx/TestRaceDeadlock.cpp b/ipc/ipdl/test/cxx/TestRaceDeadlock.cpp
new file mode 100644
index 0000000000..76defe97a5
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRaceDeadlock.cpp
@@ -0,0 +1,102 @@
+#include "TestRaceDeadlock.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+// #define TEST_TIMEOUT 5000
+
+using namespace mozilla::ipc;
+typedef mozilla::ipc::MessageChannel::Message Message;
+typedef mozilla::ipc::MessageChannel::MessageInfo MessageInfo;
+
+namespace mozilla {
+namespace _ipdltest {
+
+static RacyInterruptPolicy MediateRace(const MessageInfo& parent,
+ const MessageInfo& child) {
+ return (PTestRaceDeadlock::Msg_Win__ID == parent.type()) ? RIPParentWins
+ : RIPChildWins;
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRaceDeadlockParent::TestRaceDeadlockParent() {
+ MOZ_COUNT_CTOR(TestRaceDeadlockParent);
+}
+
+TestRaceDeadlockParent::~TestRaceDeadlockParent() {
+ MOZ_COUNT_DTOR(TestRaceDeadlockParent);
+}
+
+void TestRaceDeadlockParent::Main() {
+ Test1();
+
+ Close();
+}
+
+bool TestRaceDeadlockParent::ShouldContinueFromReplyTimeout() {
+ fail("This test should not hang");
+ GetIPCChannel()->CloseWithTimeout();
+ return false;
+}
+
+void TestRaceDeadlockParent::Test1() {
+#if defined(TEST_TIMEOUT)
+ SetReplyTimeoutMs(TEST_TIMEOUT);
+#endif
+ if (!SendStartRace()) {
+ fail("sending StartRace");
+ }
+ if (!CallRpc()) {
+ fail("calling Rpc");
+ }
+}
+
+mozilla::ipc::IPCResult TestRaceDeadlockParent::AnswerLose() {
+ return IPC_OK();
+}
+
+RacyInterruptPolicy TestRaceDeadlockParent::MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) {
+ return MediateRace(parent, child);
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRaceDeadlockChild::TestRaceDeadlockChild() {
+ MOZ_COUNT_CTOR(TestRaceDeadlockChild);
+}
+
+TestRaceDeadlockChild::~TestRaceDeadlockChild() {
+ MOZ_COUNT_DTOR(TestRaceDeadlockChild);
+}
+
+mozilla::ipc::IPCResult TestRaceDeadlockParent::RecvStartRace() {
+ if (!CallWin()) {
+ fail("calling Win");
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRaceDeadlockChild::RecvStartRace() {
+ if (!SendStartRace()) {
+ fail("calling SendStartRace");
+ }
+ if (!CallLose()) {
+ fail("calling Lose");
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRaceDeadlockChild::AnswerWin() { return IPC_OK(); }
+
+mozilla::ipc::IPCResult TestRaceDeadlockChild::AnswerRpc() { return IPC_OK(); }
+
+RacyInterruptPolicy TestRaceDeadlockChild::MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) {
+ return MediateRace(parent, child);
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRaceDeadlock.h b/ipc/ipdl/test/cxx/TestRaceDeadlock.h
new file mode 100644
index 0000000000..2c5617130d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRaceDeadlock.h
@@ -0,0 +1,68 @@
+#ifndef mozilla__ipdltest_TestRaceDeadlock_h
+#define mozilla__ipdltest_TestRaceDeadlock_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRaceDeadlockParent.h"
+#include "mozilla/_ipdltest/PTestRaceDeadlockChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRaceDeadlockParent : public PTestRaceDeadlockParent {
+ friend class PTestRaceDeadlockParent;
+
+ public:
+ TestRaceDeadlockParent();
+ virtual ~TestRaceDeadlockParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ virtual bool ShouldContinueFromReplyTimeout() override;
+
+ void Test1();
+
+ mozilla::ipc::IPCResult RecvStartRace();
+ mozilla::ipc::IPCResult AnswerLose();
+
+ virtual mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override;
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestRaceDeadlockChild : public PTestRaceDeadlockChild {
+ friend class PTestRaceDeadlockChild;
+
+ public:
+ TestRaceDeadlockChild();
+ virtual ~TestRaceDeadlockChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStartRace();
+
+ mozilla::ipc::IPCResult AnswerWin();
+
+ mozilla::ipc::IPCResult AnswerRpc();
+
+ virtual mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override;
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRaceDeadlock_h
diff --git a/ipc/ipdl/test/cxx/TestRaceDeferral.cpp b/ipc/ipdl/test/cxx/TestRaceDeferral.cpp
new file mode 100644
index 0000000000..c327b57c16
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRaceDeferral.cpp
@@ -0,0 +1,84 @@
+#include "TestRaceDeferral.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+using namespace mozilla::ipc;
+typedef mozilla::ipc::MessageChannel::Message Message;
+typedef mozilla::ipc::MessageChannel::MessageInfo MessageInfo;
+
+namespace mozilla {
+namespace _ipdltest {
+
+static RacyInterruptPolicy MediateRace(const MessageInfo& parent,
+ const MessageInfo& child) {
+ return (PTestRaceDeferral::Msg_Win__ID == parent.type()) ? RIPParentWins
+ : RIPChildWins;
+}
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRaceDeferralParent::TestRaceDeferralParent() : mProcessedLose(false) {
+ MOZ_COUNT_CTOR(TestRaceDeferralParent);
+}
+
+TestRaceDeferralParent::~TestRaceDeferralParent() {
+ MOZ_COUNT_DTOR(TestRaceDeferralParent);
+
+ if (!mProcessedLose) fail("never processed Lose");
+}
+
+void TestRaceDeferralParent::Main() {
+ Test1();
+
+ Close();
+}
+
+void TestRaceDeferralParent::Test1() {
+ if (!SendStartRace()) fail("sending StartRace");
+
+ if (!CallWin()) fail("calling Win");
+ if (mProcessedLose) fail("Lose didn't lose");
+
+ if (!CallRpc()) fail("calling Rpc");
+ if (!mProcessedLose) fail("didn't resolve Rpc vs. Lose 'race' correctly");
+}
+
+mozilla::ipc::IPCResult TestRaceDeferralParent::AnswerLose() {
+ if (mProcessedLose) fail("processed Lose twice");
+ mProcessedLose = true;
+ return IPC_OK();
+}
+
+RacyInterruptPolicy TestRaceDeferralParent::MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) {
+ return MediateRace(parent, child);
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRaceDeferralChild::TestRaceDeferralChild() {
+ MOZ_COUNT_CTOR(TestRaceDeferralChild);
+}
+
+TestRaceDeferralChild::~TestRaceDeferralChild() {
+ MOZ_COUNT_DTOR(TestRaceDeferralChild);
+}
+
+mozilla::ipc::IPCResult TestRaceDeferralChild::RecvStartRace() {
+ if (!CallLose()) fail("calling Lose");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRaceDeferralChild::AnswerWin() { return IPC_OK(); }
+
+mozilla::ipc::IPCResult TestRaceDeferralChild::AnswerRpc() { return IPC_OK(); }
+
+RacyInterruptPolicy TestRaceDeferralChild::MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) {
+ return MediateRace(parent, child);
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRaceDeferral.h b/ipc/ipdl/test/cxx/TestRaceDeferral.h
new file mode 100644
index 0000000000..b30264fb64
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRaceDeferral.h
@@ -0,0 +1,67 @@
+#ifndef mozilla__ipdltest_TestRaceDeferral_h
+#define mozilla__ipdltest_TestRaceDeferral_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRaceDeferralParent.h"
+#include "mozilla/_ipdltest/PTestRaceDeferralChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRaceDeferralParent : public PTestRaceDeferralParent {
+ friend class PTestRaceDeferralParent;
+
+ public:
+ TestRaceDeferralParent();
+ virtual ~TestRaceDeferralParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ void Test1();
+
+ mozilla::ipc::IPCResult AnswerLose();
+
+ virtual mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override;
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ bool mProcessedLose;
+};
+
+class TestRaceDeferralChild : public PTestRaceDeferralChild {
+ friend class PTestRaceDeferralChild;
+
+ public:
+ TestRaceDeferralChild();
+ virtual ~TestRaceDeferralChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStartRace();
+
+ mozilla::ipc::IPCResult AnswerWin();
+
+ mozilla::ipc::IPCResult AnswerRpc();
+
+ virtual mozilla::ipc::RacyInterruptPolicy MediateInterruptRace(
+ const MessageInfo& parent, const MessageInfo& child) override;
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRaceDeferral_h
diff --git a/ipc/ipdl/test/cxx/TestRacyInterruptReplies.cpp b/ipc/ipdl/test/cxx/TestRacyInterruptReplies.cpp
new file mode 100644
index 0000000000..cda950b1a1
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyInterruptReplies.cpp
@@ -0,0 +1,94 @@
+#include "TestRacyInterruptReplies.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRacyInterruptRepliesParent::TestRacyInterruptRepliesParent()
+ : mReplyNum(0) {
+ MOZ_COUNT_CTOR(TestRacyInterruptRepliesParent);
+}
+
+TestRacyInterruptRepliesParent::~TestRacyInterruptRepliesParent() {
+ MOZ_COUNT_DTOR(TestRacyInterruptRepliesParent);
+}
+
+void TestRacyInterruptRepliesParent::Main() {
+ int replyNum = -1;
+ if (!CallR_(&replyNum)) fail("calling R()");
+
+ if (1 != replyNum) fail("this should have been the first reply to R()");
+
+ if (!SendChildTest()) fail("sending ChildStart");
+}
+
+mozilla::ipc::IPCResult TestRacyInterruptRepliesParent::RecvA_() {
+ int replyNum = -1;
+ // this R() call races with the reply being generated by the other
+ // side to the R() call from Main(). This is a pretty nasty edge
+ // case for which one could argue we're breaking in-order message
+ // delivery, since this side will process the second reply to R()
+ // before the first.
+ if (!CallR_(&replyNum)) fail("calling R()");
+
+ if (2 != replyNum) fail("this should have been the second reply to R()");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyInterruptRepliesParent::Answer_R(
+ int* replyNum) {
+ *replyNum = ++mReplyNum;
+
+ if (1 == *replyNum)
+ if (!Send_A()) fail("sending _A()");
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRacyInterruptRepliesChild::TestRacyInterruptRepliesChild() : mReplyNum(0) {
+ MOZ_COUNT_CTOR(TestRacyInterruptRepliesChild);
+}
+
+TestRacyInterruptRepliesChild::~TestRacyInterruptRepliesChild() {
+ MOZ_COUNT_DTOR(TestRacyInterruptRepliesChild);
+}
+
+mozilla::ipc::IPCResult TestRacyInterruptRepliesChild::AnswerR_(int* replyNum) {
+ *replyNum = ++mReplyNum;
+
+ if (1 == *replyNum) SendA_();
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyInterruptRepliesChild::RecvChildTest() {
+ int replyNum = -1;
+ if (!Call_R(&replyNum)) fail("calling R()");
+
+ if (1 != replyNum) fail("this should have been the first reply to R()");
+
+ Close();
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyInterruptRepliesChild::Recv_A() {
+ int replyNum = -1;
+
+ if (!Call_R(&replyNum)) fail("calling _R()");
+
+ if (2 != replyNum) fail("this should have been the second reply to R()");
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRacyInterruptReplies.h b/ipc/ipdl/test/cxx/TestRacyInterruptReplies.h
new file mode 100644
index 0000000000..182c07f314
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyInterruptReplies.h
@@ -0,0 +1,65 @@
+#ifndef mozilla__ipdltest_TestRacyInterruptReplies_h
+#define mozilla__ipdltest_TestRacyInterruptReplies_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRacyInterruptRepliesParent.h"
+#include "mozilla/_ipdltest/PTestRacyInterruptRepliesChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRacyInterruptRepliesParent : public PTestRacyInterruptRepliesParent {
+ friend class PTestRacyInterruptRepliesParent;
+
+ public:
+ TestRacyInterruptRepliesParent();
+ virtual ~TestRacyInterruptRepliesParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvA_();
+
+ mozilla::ipc::IPCResult Answer_R(int* replyNum);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ int mReplyNum;
+};
+
+class TestRacyInterruptRepliesChild : public PTestRacyInterruptRepliesChild {
+ friend class PTestRacyInterruptRepliesChild;
+
+ public:
+ TestRacyInterruptRepliesChild();
+ virtual ~TestRacyInterruptRepliesChild();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerR_(int* replyNum);
+
+ mozilla::ipc::IPCResult RecvChildTest();
+
+ mozilla::ipc::IPCResult Recv_A();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ private:
+ int mReplyNum;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRacyInterruptReplies_h
diff --git a/ipc/ipdl/test/cxx/TestRacyReentry.cpp b/ipc/ipdl/test/cxx/TestRacyReentry.cpp
new file mode 100644
index 0000000000..4224018e11
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyReentry.cpp
@@ -0,0 +1,63 @@
+#include "TestRacyReentry.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRacyReentryParent::TestRacyReentryParent() : mRecvdE(false) {
+ MOZ_COUNT_CTOR(TestRacyReentryParent);
+}
+
+TestRacyReentryParent::~TestRacyReentryParent() {
+ MOZ_COUNT_DTOR(TestRacyReentryParent);
+}
+
+void TestRacyReentryParent::Main() {
+ if (!SendStart()) fail("sending Start");
+
+ if (!SendN()) fail("sending N");
+}
+
+mozilla::ipc::IPCResult TestRacyReentryParent::AnswerE() {
+ if (!mRecvdE) {
+ mRecvdE = true;
+ return IPC_OK();
+ }
+
+ if (!CallH()) fail("calling H");
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRacyReentryChild::TestRacyReentryChild() {
+ MOZ_COUNT_CTOR(TestRacyReentryChild);
+}
+
+TestRacyReentryChild::~TestRacyReentryChild() {
+ MOZ_COUNT_DTOR(TestRacyReentryChild);
+}
+
+mozilla::ipc::IPCResult TestRacyReentryChild::RecvStart() {
+ if (!CallE()) fail("calling E");
+
+ Close();
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyReentryChild::RecvN() {
+ if (!CallE()) fail("calling E");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyReentryChild::AnswerH() { return IPC_OK(); }
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRacyReentry.h b/ipc/ipdl/test/cxx/TestRacyReentry.h
new file mode 100644
index 0000000000..e31f90c0e3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyReentry.h
@@ -0,0 +1,59 @@
+#ifndef mozilla__ipdltest_TestRacyReentry_h
+#define mozilla__ipdltest_TestRacyReentry_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRacyReentryParent.h"
+#include "mozilla/_ipdltest/PTestRacyReentryChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRacyReentryParent : public PTestRacyReentryParent {
+ friend class PTestRacyReentryParent;
+
+ public:
+ TestRacyReentryParent();
+ virtual ~TestRacyReentryParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerE();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ bool mRecvdE;
+};
+
+class TestRacyReentryChild : public PTestRacyReentryChild {
+ friend class PTestRacyReentryChild;
+
+ public:
+ TestRacyReentryChild();
+ virtual ~TestRacyReentryChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult RecvN();
+
+ mozilla::ipc::IPCResult AnswerH();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRacyReentry_h
diff --git a/ipc/ipdl/test/cxx/TestRacyUndefer.cpp b/ipc/ipdl/test/cxx/TestRacyUndefer.cpp
new file mode 100644
index 0000000000..a46db5618e
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyUndefer.cpp
@@ -0,0 +1,83 @@
+#include "base/basictypes.h"
+
+#include "TestRacyUndefer.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestRacyUndeferParent::TestRacyUndeferParent() {
+ MOZ_COUNT_CTOR(TestRacyUndeferParent);
+}
+
+TestRacyUndeferParent::~TestRacyUndeferParent() {
+ MOZ_COUNT_DTOR(TestRacyUndeferParent);
+}
+
+void TestRacyUndeferParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferParent::AnswerSpam() {
+ static bool spammed = false;
+ static bool raced = false;
+ if (!spammed) {
+ spammed = true;
+
+ if (!SendAwakenSpam()) fail("sending AwakenSpam");
+ } else if (!raced) {
+ raced = true;
+
+ if (!SendAwakenRaceWinTwice()) fail("sending WinRaceTwice");
+
+ if (!CallRace()) fail("calling Race1");
+ }
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferParent::AnswerRaceWinTwice() {
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferParent::RecvDone() {
+ Close();
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestRacyUndeferChild::TestRacyUndeferChild() {
+ MOZ_COUNT_CTOR(TestRacyUndeferChild);
+}
+
+TestRacyUndeferChild::~TestRacyUndeferChild() {
+ MOZ_COUNT_DTOR(TestRacyUndeferChild);
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferChild::RecvStart() {
+ if (!CallSpam()) fail("calling Spam");
+
+ if (!SendDone()) fail("sending Done");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferChild::RecvAwakenSpam() {
+ if (!CallSpam()) fail("calling Spam");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferChild::RecvAwakenRaceWinTwice() {
+ if (!CallRaceWinTwice()) fail("calling RaceWinTwice");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestRacyUndeferChild::AnswerRace() { return IPC_OK(); }
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestRacyUndefer.h b/ipc/ipdl/test/cxx/TestRacyUndefer.h
new file mode 100644
index 0000000000..1e157a541b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestRacyUndefer.h
@@ -0,0 +1,62 @@
+#ifndef mozilla__ipdltest_TestRacyUndefer_h
+#define mozilla__ipdltest_TestRacyUndefer_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestRacyUndeferParent.h"
+#include "mozilla/_ipdltest/PTestRacyUndeferChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestRacyUndeferParent : public PTestRacyUndeferParent {
+ friend class PTestRacyUndeferParent;
+
+ public:
+ TestRacyUndeferParent();
+ virtual ~TestRacyUndeferParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerSpam();
+
+ mozilla::ipc::IPCResult AnswerRaceWinTwice();
+
+ mozilla::ipc::IPCResult RecvDone();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestRacyUndeferChild : public PTestRacyUndeferChild {
+ friend class PTestRacyUndeferChild;
+
+ public:
+ TestRacyUndeferChild();
+ virtual ~TestRacyUndeferChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult RecvAwakenSpam();
+ mozilla::ipc::IPCResult RecvAwakenRaceWinTwice();
+
+ mozilla::ipc::IPCResult AnswerRace();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestRacyUndefer_h
diff --git a/ipc/ipdl/test/cxx/TestSanity.cpp b/ipc/ipdl/test/cxx/TestSanity.cpp
new file mode 100644
index 0000000000..ba1920fdcc
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSanity.cpp
@@ -0,0 +1,52 @@
+#include "TestSanity.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestSanityParent::TestSanityParent() { MOZ_COUNT_CTOR(TestSanityParent); }
+
+TestSanityParent::~TestSanityParent() { MOZ_COUNT_DTOR(TestSanityParent); }
+
+void TestSanityParent::Main() {
+ if (!SendPing(0, 0.5f, 0)) fail("sending Ping");
+}
+
+mozilla::ipc::IPCResult TestSanityParent::RecvPong(const int& one,
+ const float& zeroPtTwoFive,
+ const uint8_t& /*unused*/) {
+ if (1 != one) fail("invalid argument `%d', should have been `1'", one);
+
+ if (0.25f != zeroPtTwoFive)
+ fail("invalid argument `%g', should have been `0.25'", zeroPtTwoFive);
+
+ Close();
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestSanityChild::TestSanityChild() { MOZ_COUNT_CTOR(TestSanityChild); }
+
+TestSanityChild::~TestSanityChild() { MOZ_COUNT_DTOR(TestSanityChild); }
+
+mozilla::ipc::IPCResult TestSanityChild::RecvPing(const int& zero,
+ const float& zeroPtFive,
+ const int8_t& /*unused*/) {
+ if (0 != zero) fail("invalid argument `%d', should have been `0'", zero);
+
+ if (0.5f != zeroPtFive)
+ fail("invalid argument `%g', should have been `0.5'", zeroPtFive);
+
+ if (!SendPong(1, 0.25f, 0)) fail("sending Pong");
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestSanity.h b/ipc/ipdl/test/cxx/TestSanity.h
new file mode 100644
index 0000000000..ca29d67672
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSanity.h
@@ -0,0 +1,55 @@
+#ifndef mozilla__ipdltest_TestSanity_h
+#define mozilla__ipdltest_TestSanity_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestSanityParent.h"
+#include "mozilla/_ipdltest/PTestSanityChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestSanityParent : public PTestSanityParent {
+ friend class PTestSanityParent;
+
+ public:
+ TestSanityParent();
+ virtual ~TestSanityParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPong(const int& one, const float& zeroPtTwoFive,
+ const uint8_t& dummy);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestSanityChild : public PTestSanityChild {
+ friend class PTestSanityChild;
+
+ public:
+ TestSanityChild();
+ virtual ~TestSanityChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvPing(const int& zero, const float& zeroPtFive,
+ const int8_t& dummy);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestSanity_h
diff --git a/ipc/ipdl/test/cxx/TestSelfManageRoot.cpp b/ipc/ipdl/test/cxx/TestSelfManageRoot.cpp
new file mode 100644
index 0000000000..5e09aa4d7e
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSelfManageRoot.cpp
@@ -0,0 +1,54 @@
+#include "TestSelfManageRoot.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+#define ASSERT(c) \
+ do { \
+ if (!(c)) fail(#c); \
+ } while (0)
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+void TestSelfManageRootParent::Main() {
+ TestSelfManageParent* a =
+ static_cast<TestSelfManageParent*>(SendPTestSelfManageConstructor());
+ if (!a) fail("constructing PTestSelfManage");
+
+ ASSERT(1 == ManagedPTestSelfManageParent().Count());
+
+ TestSelfManageParent* aa =
+ static_cast<TestSelfManageParent*>(a->SendPTestSelfManageConstructor());
+ if (!aa) fail("constructing PTestSelfManage");
+
+ ASSERT(1 == ManagedPTestSelfManageParent().Count() &&
+ 1 == a->ManagedPTestSelfManageParent().Count());
+
+ if (!PTestSelfManageParent::Send__delete__(aa))
+ fail("destroying PTestSelfManage");
+ ASSERT(Deletion == aa->mWhy && 1 == ManagedPTestSelfManageParent().Count() &&
+ 0 == a->ManagedPTestSelfManageParent().Count());
+ delete aa;
+
+ aa = static_cast<TestSelfManageParent*>(a->SendPTestSelfManageConstructor());
+ if (!aa) fail("constructing PTestSelfManage");
+
+ ASSERT(1 == ManagedPTestSelfManageParent().Count() &&
+ 1 == a->ManagedPTestSelfManageParent().Count());
+
+ if (!PTestSelfManageParent::Send__delete__(a))
+ fail("destroying PTestSelfManage");
+ ASSERT(Deletion == a->mWhy && AncestorDeletion == aa->mWhy &&
+ 0 == ManagedPTestSelfManageParent().Count() &&
+ 0 == a->ManagedPTestSelfManageParent().Count());
+ delete a;
+ delete aa;
+
+ Close();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestSelfManageRoot.h b/ipc/ipdl/test/cxx/TestSelfManageRoot.h
new file mode 100644
index 0000000000..5cea09b10d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSelfManageRoot.h
@@ -0,0 +1,117 @@
+#ifndef mozilla__ipdltest_TestSelfManageRoot_h
+#define mozilla__ipdltest_TestSelfManageRoot_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestSelfManageRootParent.h"
+#include "mozilla/_ipdltest/PTestSelfManageRootChild.h"
+#include "mozilla/_ipdltest/PTestSelfManageParent.h"
+#include "mozilla/_ipdltest/PTestSelfManageChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Parent side
+
+class TestSelfManageParent : public PTestSelfManageParent {
+ friend class PTestSelfManageParent;
+
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestSelfManageParent)
+ MOZ_COUNTED_DTOR_OVERRIDE(TestSelfManageParent)
+
+ ActorDestroyReason mWhy;
+
+ protected:
+ PTestSelfManageParent* AllocPTestSelfManageParent() {
+ return new TestSelfManageParent();
+ }
+
+ bool DeallocPTestSelfManageParent(PTestSelfManageParent* a) { return true; }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { mWhy = why; }
+};
+
+class TestSelfManageRootParent : public PTestSelfManageRootParent {
+ friend class PTestSelfManageRootParent;
+
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestSelfManageRootParent)
+ virtual ~TestSelfManageRootParent() {
+ MOZ_COUNT_DTOR(TestSelfManageRootParent);
+ }
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ PTestSelfManageParent* AllocPTestSelfManageParent() {
+ return new TestSelfManageParent();
+ }
+
+ bool DeallocPTestSelfManageParent(PTestSelfManageParent* a) { return true; }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+//-----------------------------------------------------------------------------
+// Child side
+
+class TestSelfManageChild : public PTestSelfManageChild {
+ friend class PTestSelfManageChild;
+
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestSelfManageChild)
+ MOZ_COUNTED_DTOR_OVERRIDE(TestSelfManageChild)
+
+ protected:
+ PTestSelfManageChild* AllocPTestSelfManageChild() {
+ return new TestSelfManageChild();
+ }
+
+ bool DeallocPTestSelfManageChild(PTestSelfManageChild* a) {
+ delete a;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {}
+};
+
+class TestSelfManageRootChild : public PTestSelfManageRootChild {
+ friend class PTestSelfManageRootChild;
+
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestSelfManageRootChild)
+ virtual ~TestSelfManageRootChild() {
+ MOZ_COUNT_DTOR(TestSelfManageRootChild);
+ }
+
+ void Main();
+
+ protected:
+ PTestSelfManageChild* AllocPTestSelfManageChild() {
+ return new TestSelfManageChild();
+ }
+
+ bool DeallocPTestSelfManageChild(PTestSelfManageChild* a) {
+ delete a;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestSelfManageRoot_h
diff --git a/ipc/ipdl/test/cxx/TestShmem.cpp b/ipc/ipdl/test/cxx/TestShmem.cpp
new file mode 100644
index 0000000000..0a778e5322
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestShmem.cpp
@@ -0,0 +1,106 @@
+#include "TestShmem.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Parent
+
+void TestShmemParent::Main() {
+ Shmem mem;
+ Shmem unsafe;
+
+ size_t size = 12345;
+ if (!AllocShmem(size, &mem)) fail("can't alloc shmem");
+ if (!AllocUnsafeShmem(size, &unsafe)) fail("can't alloc shmem");
+
+ if (mem.Size<char>() != size)
+ fail("shmem is wrong size: expected %lu, got %lu", size, mem.Size<char>());
+ if (unsafe.Size<char>() != size)
+ fail("shmem is wrong size: expected %lu, got %lu", size,
+ unsafe.Size<char>());
+
+ char* ptr = mem.get<char>();
+ memcpy(ptr, "Hello!", sizeof("Hello!"));
+
+ char* unsafeptr = unsafe.get<char>();
+ memcpy(unsafeptr, "Hello!", sizeof("Hello!"));
+
+ Shmem unsafecopy = unsafe;
+ if (!SendGive(std::move(mem), std::move(unsafe), size))
+ fail("can't send Give()");
+
+ // uncomment the following line for a (nondeterministic) surprise!
+ // char c1 = *ptr; (void)c1;
+
+ // uncomment the following line for a deterministic surprise!
+ // char c2 = *mem.get<char>(); (void)c2;
+
+ // unsafe shmem gets rid of those checks
+ char uc1 = *unsafeptr;
+ (void)uc1;
+ char uc2 = *unsafecopy.get<char>();
+ (void)uc2;
+}
+
+mozilla::ipc::IPCResult TestShmemParent::RecvTake(Shmem&& mem, Shmem&& unsafe,
+ const size_t& expectedSize) {
+ if (mem.Size<char>() != expectedSize)
+ fail("expected shmem size %lu, but it has size %lu", expectedSize,
+ mem.Size<char>());
+ if (unsafe.Size<char>() != expectedSize)
+ fail("expected shmem size %lu, but it has size %lu", expectedSize,
+ unsafe.Size<char>());
+
+ if (strcmp(mem.get<char>(), "And yourself!"))
+ fail("expected message was not written");
+ if (strcmp(unsafe.get<char>(), "And yourself!"))
+ fail("expected message was not written");
+
+ if (!DeallocShmem(mem)) fail("DeallocShmem");
+ if (!DeallocShmem(unsafe)) fail("DeallocShmem");
+
+ Close();
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// Child
+
+mozilla::ipc::IPCResult TestShmemChild::RecvGive(Shmem&& mem, Shmem&& unsafe,
+ const size_t& expectedSize) {
+ if (mem.Size<char>() != expectedSize)
+ fail("expected shmem size %lu, but it has size %lu", expectedSize,
+ mem.Size<char>());
+ if (unsafe.Size<char>() != expectedSize)
+ fail("expected shmem size %lu, but it has size %lu", expectedSize,
+ unsafe.Size<char>());
+
+ if (strcmp(mem.get<char>(), "Hello!"))
+ fail("expected message was not written");
+ if (strcmp(unsafe.get<char>(), "Hello!"))
+ fail("expected message was not written");
+
+ char* unsafeptr = unsafe.get<char>();
+
+ memcpy(mem.get<char>(), "And yourself!", sizeof("And yourself!"));
+ memcpy(unsafeptr, "And yourself!", sizeof("And yourself!"));
+
+ Shmem unsafecopy = unsafe;
+ if (!SendTake(std::move(mem), std::move(unsafe), expectedSize))
+ fail("can't send Take()");
+
+ // these checks also shouldn't fail in the child
+ char uc1 = *unsafeptr;
+ (void)uc1;
+ char uc2 = *unsafecopy.get<char>();
+ (void)uc2;
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestShmem.h b/ipc/ipdl/test/cxx/TestShmem.h
new file mode 100644
index 0000000000..4ef1f4fd7b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestShmem.h
@@ -0,0 +1,55 @@
+#ifndef mozilla__ipdltest_TestShmem_h
+#define mozilla__ipdltest_TestShmem_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestShmemParent.h"
+#include "mozilla/_ipdltest/PTestShmemChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestShmemParent : public PTestShmemParent {
+ friend class PTestShmemParent;
+
+ public:
+ TestShmemParent() {}
+ virtual ~TestShmemParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvTake(Shmem&& mem, Shmem&& unsafe,
+ const size_t& expectedSize);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestShmemChild : public PTestShmemChild {
+ friend class PTestShmemChild;
+
+ public:
+ TestShmemChild() {}
+ virtual ~TestShmemChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvGive(Shmem&& mem, Shmem&& unsafe,
+ const size_t& expectedSize);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestShmem_h
diff --git a/ipc/ipdl/test/cxx/TestShutdown.cpp b/ipc/ipdl/test/cxx/TestShutdown.cpp
new file mode 100644
index 0000000000..502695bd88
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestShutdown.cpp
@@ -0,0 +1,185 @@
+#include "TestShutdown.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Parent side
+void TestShutdownParent::Main() {
+ if (!SendStart()) fail("sending Start()");
+}
+
+void TestShutdownParent::ActorDestroy(ActorDestroyReason why) {
+ if (AbnormalShutdown != why) fail("should have ended test with crash!");
+
+ passed("ok");
+
+ QuitParent();
+}
+
+void TestShutdownSubParent::ActorDestroy(ActorDestroyReason why) {
+ if (Manager()->ManagedPTestShutdownSubParent().Count() == 0)
+ fail("manager should still have managees!");
+
+ if (mExpectCrash && AbnormalShutdown != why)
+ fail("expected crash!");
+ else if (!mExpectCrash && AbnormalShutdown == why)
+ fail("wasn't expecting crash!");
+
+ if (mExpectCrash && 0 == ManagedPTestShutdownSubsubParent().Count())
+ fail("expected to *still* have kids");
+}
+
+void TestShutdownSubsubParent::ActorDestroy(ActorDestroyReason why) {
+ if (Manager()->ManagedPTestShutdownSubsubParent().Count() == 0)
+ fail("manager should still have managees!");
+
+ if (mExpectParentDeleted && AncestorDeletion != why)
+ fail("expected ParentDeleted == why");
+ else if (!mExpectParentDeleted && AncestorDeletion == why)
+ fail("wasn't expecting parent delete");
+}
+
+//-----------------------------------------------------------------------------
+// Child side
+
+mozilla::ipc::IPCResult TestShutdownChild::RecvStart() {
+ // test 1: alloc some actors and subactors, delete in
+ // managee-before-manager order
+ {
+ bool expectCrash = false, expectParentDeleted = false;
+
+ PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c1) fail("problem sending ctor");
+
+ PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c1s1 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c1s2 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c2s1 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c2s2 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s2) fail("problem sending ctor");
+
+ if (!PTestShutdownSubsubChild::Send__delete__(c1s1))
+ fail("problem sending dtor");
+ if (!PTestShutdownSubsubChild::Send__delete__(c1s2))
+ fail("problem sending dtor");
+ if (!PTestShutdownSubsubChild::Send__delete__(c2s1))
+ fail("problem sending dtor");
+ if (!PTestShutdownSubsubChild::Send__delete__(c2s2))
+ fail("problem sending dtor");
+
+ if (!c1->CallStackFrame()) fail("problem creating dummy stack frame");
+ if (!c2->CallStackFrame()) fail("problem creating dummy stack frame");
+ }
+
+ // test 2: alloc some actors and subactors, delete managers first
+ {
+ bool expectCrash = false, expectParentDeleted = true;
+
+ PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c1) fail("problem sending ctor");
+
+ PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c1s1 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c1s2 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c2s1 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c2s2 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s2) fail("problem sending ctor");
+
+ // delete parents without deleting kids
+ if (!c1->CallStackFrame()) fail("problem creating dummy stack frame");
+ if (!c2->CallStackFrame()) fail("problem creating dummy stack frame");
+ }
+
+ // test 3: alloc some actors and subactors, then crash
+ {
+ bool expectCrash = true, expectParentDeleted = false;
+
+ PTestShutdownSubChild* c1 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c1) fail("problem sending ctor");
+
+ PTestShutdownSubChild* c2 = SendPTestShutdownSubConstructor(expectCrash);
+ if (!c2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c1s1 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c1s2 =
+ c1->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c1s2) fail("problem sending ctor");
+
+ PTestShutdownSubsubChild* c2s1 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s1) fail("problem sending ctor");
+ PTestShutdownSubsubChild* c2s2 =
+ c2->SendPTestShutdownSubsubConstructor(expectParentDeleted);
+ if (!c2s2) fail("problem sending ctor");
+
+ // make sure the ctors have been processed by the other side;
+ // the write end of the socket may temporarily be unwriteable
+ if (!SendSync()) fail("can't synchronize with parent");
+
+ // "crash", but without tripping tinderbox assert/abort
+ // detectors
+ _exit(0);
+ }
+}
+
+void TestShutdownChild::ActorDestroy(ActorDestroyReason why) {
+ fail("hey wait ... we should have crashed!");
+}
+
+mozilla::ipc::IPCResult TestShutdownSubChild::AnswerStackFrame() {
+ if (!PTestShutdownSubChild::Send__delete__(this))
+ fail("problem sending dtor");
+
+ // WATCH OUT! |this| has just deleted
+
+ return IPC_OK();
+}
+
+void TestShutdownSubChild::ActorDestroy(ActorDestroyReason why) {
+ if (Manager()->ManagedPTestShutdownSubChild().Count() == 0)
+ fail("manager should still have managees!");
+
+ if (mExpectCrash && AbnormalShutdown != why)
+ fail("expected crash!");
+ else if (!mExpectCrash && AbnormalShutdown == why)
+ fail("wasn't expecting crash!");
+
+ if (mExpectCrash && 0 == ManagedPTestShutdownSubsubChild().Count())
+ fail("expected to *still* have kids");
+}
+
+void TestShutdownSubsubChild::ActorDestroy(ActorDestroyReason why) {
+ if (Manager()->ManagedPTestShutdownSubsubChild().Count() == 0)
+ fail("manager should still have managees!");
+
+ if (mExpectParentDeleted && AncestorDeletion != why)
+ fail("expected ParentDeleted == why");
+ else if (!mExpectParentDeleted && AncestorDeletion == why)
+ fail("wasn't expecting parent delete");
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestShutdown.h b/ipc/ipdl/test/cxx/TestShutdown.h
new file mode 100644
index 0000000000..224e42496d
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestShutdown.h
@@ -0,0 +1,168 @@
+#ifndef mozilla__ipdltest_TestShutdown_h
+#define mozilla__ipdltest_TestShutdown_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestShutdownParent.h"
+#include "mozilla/_ipdltest/PTestShutdownChild.h"
+
+#include "mozilla/_ipdltest/PTestShutdownSubParent.h"
+#include "mozilla/_ipdltest/PTestShutdownSubChild.h"
+
+#include "mozilla/_ipdltest/PTestShutdownSubsubParent.h"
+#include "mozilla/_ipdltest/PTestShutdownSubsubChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// Parent side
+
+class TestShutdownSubsubParent : public PTestShutdownSubsubParent {
+ public:
+ explicit TestShutdownSubsubParent(bool expectParentDeleted)
+ : mExpectParentDeleted(expectParentDeleted) {}
+
+ virtual ~TestShutdownSubsubParent() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ private:
+ bool mExpectParentDeleted;
+};
+
+class TestShutdownSubParent : public PTestShutdownSubParent {
+ friend class PTestShutdownSubParent;
+
+ public:
+ explicit TestShutdownSubParent(bool expectCrash)
+ : mExpectCrash(expectCrash), mDeletedCount(0) {}
+
+ virtual ~TestShutdownSubParent() {
+ if (2 != mDeletedCount) fail("managees outliving manager!");
+ }
+
+ protected:
+ mozilla::ipc::IPCResult AnswerStackFrame() {
+ if (!CallStackFrame()) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+ }
+
+ PTestShutdownSubsubParent* AllocPTestShutdownSubsubParent(
+ const bool& expectParentDelete) {
+ return new TestShutdownSubsubParent(expectParentDelete);
+ }
+
+ bool DeallocPTestShutdownSubsubParent(PTestShutdownSubsubParent* actor) {
+ delete actor;
+ ++mDeletedCount;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ private:
+ bool mExpectCrash;
+ int mDeletedCount;
+};
+
+class TestShutdownParent : public PTestShutdownParent {
+ friend class PTestShutdownParent;
+
+ public:
+ TestShutdownParent() {}
+ virtual ~TestShutdownParent() {}
+
+ static bool RunTestInProcesses() { return true; }
+ // FIXME/bug 703323 Could work if modified
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvSync() { return IPC_OK(); }
+
+ PTestShutdownSubParent* AllocPTestShutdownSubParent(const bool& expectCrash) {
+ return new TestShutdownSubParent(expectCrash);
+ }
+
+ bool DeallocPTestShutdownSubParent(PTestShutdownSubParent* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+//-----------------------------------------------------------------------------
+// Child side
+
+class TestShutdownSubsubChild : public PTestShutdownSubsubChild {
+ public:
+ explicit TestShutdownSubsubChild(bool expectParentDeleted)
+ : mExpectParentDeleted(expectParentDeleted) {}
+ virtual ~TestShutdownSubsubChild() {}
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ private:
+ bool mExpectParentDeleted;
+};
+
+class TestShutdownSubChild : public PTestShutdownSubChild {
+ friend class PTestShutdownSubChild;
+
+ public:
+ explicit TestShutdownSubChild(bool expectCrash) : mExpectCrash(expectCrash) {}
+
+ virtual ~TestShutdownSubChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ PTestShutdownSubsubChild* AllocPTestShutdownSubsubChild(
+ const bool& expectParentDelete) {
+ return new TestShutdownSubsubChild(expectParentDelete);
+ }
+
+ bool DeallocPTestShutdownSubsubChild(PTestShutdownSubsubChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+
+ private:
+ bool mExpectCrash;
+};
+
+class TestShutdownChild : public PTestShutdownChild {
+ friend class PTestShutdownChild;
+
+ public:
+ TestShutdownChild() {}
+ virtual ~TestShutdownChild() {}
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ PTestShutdownSubChild* AllocPTestShutdownSubChild(const bool& expectCrash) {
+ return new TestShutdownSubChild(expectCrash);
+ }
+
+ bool DeallocPTestShutdownSubChild(PTestShutdownSubChild* actor) {
+ delete actor;
+ return true;
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestShutdown_h
diff --git a/ipc/ipdl/test/cxx/TestStackHooks.cpp b/ipc/ipdl/test/cxx/TestStackHooks.cpp
new file mode 100644
index 0000000000..9800ac54e7
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestStackHooks.cpp
@@ -0,0 +1,122 @@
+#include "TestStackHooks.h"
+
+#include "base/task.h"
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestStackHooksParent::TestStackHooksParent()
+ : mOnStack(false), mIncallDepth(0) {
+ MOZ_COUNT_CTOR(TestStackHooksParent);
+}
+
+TestStackHooksParent::~TestStackHooksParent() {
+ MOZ_COUNT_DTOR(TestStackHooksParent);
+}
+
+void TestStackHooksParent::Main() {
+ if (!SendStart()) fail("sending Start()");
+}
+
+mozilla::ipc::IPCResult TestStackHooksParent::AnswerStackFrame() {
+ if (!mOnStack) fail("not on C++ stack?!");
+
+ if (!CallStackFrame()) fail("calling StackFrame()");
+
+ if (!mOnStack) fail("not on C++ stack?!");
+
+ if (1 != mIncallDepth) fail("missed EnteredCall or ExitedCall hook");
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestStackHooksChild::TestStackHooksChild()
+ : mOnStack(false),
+ mEntered(0),
+ mExited(0),
+ mIncallDepth(0),
+ mNumAnswerStackFrame(0) {
+ MOZ_COUNT_CTOR(TestStackHooksChild);
+}
+
+TestStackHooksChild::~TestStackHooksChild() {
+ MOZ_COUNT_DTOR(TestStackHooksChild);
+}
+
+namespace {
+void RunTestsFn() {
+ static_cast<TestStackHooksChild*>(gChildActor)->RunTests();
+}
+} // namespace
+
+mozilla::ipc::IPCResult TestStackHooksChild::RecvStart() {
+ if (!mOnStack) fail("missed stack notification");
+
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+
+ // kick off tests from a runnable so that we can start with
+ // MessageChannel code on the C++ stack
+ MessageLoop::current()->PostTask(
+ NewRunnableFunction("RunTestsFn", RunTestsFn));
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestStackHooksChild::AnswerStackFrame() {
+ ++mNumAnswerStackFrame;
+
+ if (!mOnStack) fail("missed stack notification");
+
+ if (1 != mIncallDepth) fail("missed EnteredCall or ExitedCall hook");
+
+ if (mNumAnswerStackFrame == 1) {
+ if (!SendAsync()) fail("sending Async()");
+ } else if (mNumAnswerStackFrame == 2) {
+ if (!SendSync()) fail("sending Sync()");
+ } else {
+ fail("unexpected state");
+ }
+
+ if (!mOnStack) fail("bad stack exit notification");
+
+ return IPC_OK();
+}
+
+void TestStackHooksChild::RunTests() {
+ // 1 because of RecvStart()
+ if (1 != mEntered) fail("missed stack notification");
+ if (mOnStack) fail("spurious stack notification");
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+
+ if (!SendAsync()) fail("sending Async()");
+ if (mOnStack) fail("spurious stack notification");
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+ if (2 != mEntered) fail("missed stack notification");
+
+ if (!SendSync()) fail("sending Sync()");
+ if (mOnStack) fail("spurious stack notification");
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+ if (3 != mEntered) fail("missed stack notification");
+
+ if (!CallRpc()) fail("calling RPC()");
+ if (mOnStack) fail("spurious stack notification");
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+ if (4 != mEntered) fail("missed stack notification");
+
+ if (!CallStackFrame()) fail("calling StackFrame()");
+ if (mOnStack) fail("spurious stack notification");
+ if (0 != mIncallDepth) fail("EnteredCall/ExitedCall malfunction");
+ if (5 != mEntered) fail("missed stack notification");
+
+ Close();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestStackHooks.h b/ipc/ipdl/test/cxx/TestStackHooks.h
new file mode 100644
index 0000000000..315a3c1ae5
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestStackHooks.h
@@ -0,0 +1,107 @@
+#ifndef mozilla__ipdltest_TestStackHooks_h
+#define mozilla__ipdltest_TestStackHooks_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestStackHooksParent.h"
+#include "mozilla/_ipdltest/PTestStackHooksChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestStackHooksParent : public PTestStackHooksParent {
+ friend class PTestStackHooksParent;
+
+ public:
+ TestStackHooksParent();
+ virtual ~TestStackHooksParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvAsync() {
+ if (!mOnStack) fail("not on C++ stack?!");
+ return IPC_OK();
+ }
+
+ mozilla::ipc::IPCResult RecvSync() {
+ if (!mOnStack) fail("not on C++ stack?!");
+ return IPC_OK();
+ }
+
+ mozilla::ipc::IPCResult AnswerRpc() {
+ if (!mOnStack) fail("not on C++ stack?!");
+ return IPC_OK();
+ }
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+
+ virtual void EnteredCxxStack() override { mOnStack = true; }
+ virtual void ExitedCxxStack() override { mOnStack = false; }
+
+ virtual void EnteredCall() override { ++mIncallDepth; }
+ virtual void ExitedCall() override { --mIncallDepth; }
+
+ private:
+ bool mOnStack;
+ int mIncallDepth;
+};
+
+class TestStackHooksChild : public PTestStackHooksChild {
+ friend class PTestStackHooksChild;
+
+ public:
+ TestStackHooksChild();
+ virtual ~TestStackHooksChild();
+
+ void RunTests();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+
+ if (mEntered != mExited) fail("unbalanced enter/exit notifications");
+
+ if (mOnStack)
+ fail("computing mOnStack went awry; should have failed above assertion");
+
+ QuitChild();
+ }
+
+ virtual void EnteredCxxStack() override {
+ ++mEntered;
+ mOnStack = true;
+ }
+ virtual void ExitedCxxStack() override {
+ ++mExited;
+ mOnStack = false;
+ }
+
+ virtual void EnteredCall() override { ++mIncallDepth; }
+ virtual void ExitedCall() override { --mIncallDepth; }
+
+ private:
+ bool mOnStack;
+ int mEntered;
+ int mExited;
+ int mIncallDepth;
+ int32_t mNumAnswerStackFrame;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestStackHooks_h
diff --git a/ipc/ipdl/test/cxx/TestSyncError.cpp b/ipc/ipdl/test/cxx/TestSyncError.cpp
new file mode 100644
index 0000000000..6c21590a87
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncError.cpp
@@ -0,0 +1,45 @@
+#include "TestSyncError.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestSyncErrorParent::TestSyncErrorParent() {
+ MOZ_COUNT_CTOR(TestSyncErrorParent);
+}
+
+TestSyncErrorParent::~TestSyncErrorParent() {
+ MOZ_COUNT_DTOR(TestSyncErrorParent);
+}
+
+void TestSyncErrorParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestSyncErrorParent::RecvError() {
+ return IPC_FAIL_NO_REASON(this);
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestSyncErrorChild::TestSyncErrorChild() { MOZ_COUNT_CTOR(TestSyncErrorChild); }
+
+TestSyncErrorChild::~TestSyncErrorChild() {
+ MOZ_COUNT_DTOR(TestSyncErrorChild);
+}
+
+mozilla::ipc::IPCResult TestSyncErrorChild::RecvStart() {
+ if (SendError()) fail("Error() should have return false");
+
+ Close();
+
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestSyncError.h b/ipc/ipdl/test/cxx/TestSyncError.h
new file mode 100644
index 0000000000..8b84ed5e0b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncError.h
@@ -0,0 +1,61 @@
+#ifndef mozilla__ipdltest_TestSyncError_h
+#define mozilla__ipdltest_TestSyncError_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestSyncErrorParent.h"
+#include "mozilla/_ipdltest/PTestSyncErrorChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestSyncErrorParent : public PTestSyncErrorParent {
+ friend class PTestSyncErrorParent;
+
+ public:
+ TestSyncErrorParent();
+ virtual ~TestSyncErrorParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult RecvError();
+
+ virtual void ProcessingError(Result aCode, const char* aReason) override {
+ // Ignore errors
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestSyncErrorChild : public PTestSyncErrorChild {
+ friend class PTestSyncErrorChild;
+
+ public:
+ TestSyncErrorChild();
+ virtual ~TestSyncErrorChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ virtual void ProcessingError(Result aCode, const char* aReason) override {
+ // Ignore errors
+ }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestSyncError_h
diff --git a/ipc/ipdl/test/cxx/TestSyncHang.cpp b/ipc/ipdl/test/cxx/TestSyncHang.cpp
new file mode 100644
index 0000000000..f53054787b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncHang.cpp
@@ -0,0 +1,62 @@
+#include "TestSyncHang.h"
+#include "base/task.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+using std::string;
+using std::vector;
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+mozilla::ipc::GeckoChildProcessHost* gSyncHangSubprocess;
+
+TestSyncHangParent::TestSyncHangParent() { MOZ_COUNT_CTOR(TestSyncHangParent); }
+
+TestSyncHangParent::~TestSyncHangParent() {
+ MOZ_COUNT_DTOR(TestSyncHangParent);
+}
+
+void DeleteSyncHangSubprocess(MessageLoop* uiLoop) {
+ gSyncHangSubprocess->Destroy();
+ gSyncHangSubprocess = nullptr;
+}
+
+void DeferredSyncHangParentShutdown() {
+ // ping to DeleteSubprocess
+ XRE_GetIOMessageLoop()->PostTask(
+ NewRunnableFunction("DeleteSyncHangSubprocess", DeleteSyncHangSubprocess,
+ MessageLoop::current()));
+}
+
+void TestSyncHangParent::Main() {
+ vector<string> args;
+ args.push_back("fake/path");
+ gSyncHangSubprocess =
+ new mozilla::ipc::GeckoChildProcessHost(GeckoProcessType_Plugin);
+ bool launched = gSyncHangSubprocess->SyncLaunch(args, 2);
+ if (launched)
+ fail("Calling SyncLaunch with an invalid path should return false");
+
+ MessageLoop::current()->PostTask(NewRunnableFunction(
+ "DeferredSyncHangParentShutdown", DeferredSyncHangParentShutdown));
+ Close();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestSyncHangChild::TestSyncHangChild() { MOZ_COUNT_CTOR(TestSyncHangChild); }
+
+TestSyncHangChild::~TestSyncHangChild() { MOZ_COUNT_DTOR(TestSyncHangChild); }
+
+mozilla::ipc::IPCResult TestSyncHangChild::RecvUnusedMessage() {
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestSyncHang.h b/ipc/ipdl/test/cxx/TestSyncHang.h
new file mode 100644
index 0000000000..911f05cd31
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncHang.h
@@ -0,0 +1,50 @@
+#ifndef mozilla__ipdltest_TestSyncHang_h
+#define mozilla__ipdltest_TestSyncHang_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestSyncHangParent.h"
+#include "mozilla/_ipdltest/PTestSyncHangChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestSyncHangParent : public PTestSyncHangParent {
+ public:
+ TestSyncHangParent();
+ virtual ~TestSyncHangParent();
+
+ static bool RunTestInProcesses() { return true; }
+ // FIXME/bug 703323 Could work if modified
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ protected:
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestSyncHangChild : public PTestSyncHangChild {
+ friend class PTestSyncHangChild;
+
+ public:
+ TestSyncHangChild();
+ virtual ~TestSyncHangChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvUnusedMessage();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestSyncHang_h
diff --git a/ipc/ipdl/test/cxx/TestSyncWakeup.cpp b/ipc/ipdl/test/cxx/TestSyncWakeup.cpp
new file mode 100644
index 0000000000..90875b702b
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncWakeup.cpp
@@ -0,0 +1,106 @@
+#if defined(XP_UNIX)
+# include <unistd.h> // sleep()
+#endif
+
+#include "TestSyncWakeup.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestSyncWakeupParent::TestSyncWakeupParent() {
+ MOZ_COUNT_CTOR(TestSyncWakeupParent);
+}
+
+TestSyncWakeupParent::~TestSyncWakeupParent() {
+ MOZ_COUNT_DTOR(TestSyncWakeupParent);
+}
+
+void TestSyncWakeupParent::Main() {
+ if (!SendStart()) fail("sending Start()");
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupParent::AnswerStackFrame() {
+ if (!CallStackFrame()) fail("calling StackFrame()");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupParent::RecvSync1() {
+ if (!SendNote1()) fail("sending Note1()");
+
+ // XXX ugh ... need to ensure that the async message and sync
+ // reply come in "far enough" apart that this test doesn't pass on
+ // accident
+#if defined(XP_UNIX)
+ // NB: can't use PR_Sleep (i.e. Sleep() on windows) because it's
+ // only spec'd to block the current thread, not the current
+ // process. We need the IO thread to sleep as well.
+ puts(" (sleeping for 5 seconds. sorry!)");
+ sleep(5);
+#endif
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupParent::RecvSync2() {
+ if (!SendNote2()) fail("sending Note2()");
+
+#if defined(XP_UNIX)
+ // see above
+ sleep(5);
+ puts(" (sleeping for 5 seconds. sorry!)");
+#endif
+
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+TestSyncWakeupChild::TestSyncWakeupChild() : mDone(false) {
+ MOZ_COUNT_CTOR(TestSyncWakeupChild);
+}
+
+TestSyncWakeupChild::~TestSyncWakeupChild() {
+ MOZ_COUNT_DTOR(TestSyncWakeupChild);
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupChild::RecvStart() {
+ // First test: the parent fires back an async message while
+ // replying to a sync one
+ if (!SendSync1()) fail("sending Sync()");
+
+ // drop back into the event loop to get Note1(), then kick off the
+ // second test
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupChild::RecvNote1() {
+ // Second test: the parent fires back an async message while
+ // replying to a sync one, with a frame on the RPC stack
+ if (!CallStackFrame()) fail("calling StackFrame()");
+
+ if (!mDone) fail("should have received Note2()!");
+
+ Close();
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupChild::AnswerStackFrame() {
+ if (!SendSync2()) fail("sending Sync()");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestSyncWakeupChild::RecvNote2() {
+ mDone = true;
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestSyncWakeup.h b/ipc/ipdl/test/cxx/TestSyncWakeup.h
new file mode 100644
index 0000000000..5666307929
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestSyncWakeup.h
@@ -0,0 +1,66 @@
+#ifndef mozilla__ipdltest_TestSyncWakeup_h
+#define mozilla__ipdltest_TestSyncWakeup_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestSyncWakeupParent.h"
+#include "mozilla/_ipdltest/PTestSyncWakeupChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestSyncWakeupParent : public PTestSyncWakeupParent {
+ friend class PTestSyncWakeupParent;
+
+ public:
+ TestSyncWakeupParent();
+ virtual ~TestSyncWakeupParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return true; }
+
+ void Main();
+
+ protected:
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ mozilla::ipc::IPCResult RecvSync1();
+
+ mozilla::ipc::IPCResult RecvSync2();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestSyncWakeupChild : public PTestSyncWakeupChild {
+ friend class PTestSyncWakeupChild;
+
+ public:
+ TestSyncWakeupChild();
+ virtual ~TestSyncWakeupChild();
+
+ protected:
+ mozilla::ipc::IPCResult RecvStart();
+
+ mozilla::ipc::IPCResult RecvNote1();
+
+ mozilla::ipc::IPCResult AnswerStackFrame();
+
+ mozilla::ipc::IPCResult RecvNote2();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) fail("unexpected destruction!");
+ QuitChild();
+ }
+
+ private:
+ bool mDone;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestSyncWakeup_h
diff --git a/ipc/ipdl/test/cxx/TestUniquePtrIPC.cpp b/ipc/ipdl/test/cxx/TestUniquePtrIPC.cpp
new file mode 100644
index 0000000000..7d0e8dd6ca
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUniquePtrIPC.cpp
@@ -0,0 +1,81 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "TestUniquePtrIPC.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+// ---------------------------------------------------------------------------
+// PARENT PROCESS
+// ---------------------------------------------------------------------------
+
+void TestUniquePtrIPCParent::Main() {
+ UniquePtr<int> a1 = MakeUnique<int>(1);
+ UniquePtr<DummyStruct> a2 = MakeUnique<DummyStruct>(2);
+ DummyStruct a3(3);
+ UniquePtr<int> a4;
+
+ if (!SendTestMessage(std::move(a1), std::move(a2), a3, std::move(a4))) {
+ fail("failed sending UniquePtr items");
+ }
+
+ if (a1 || a2) {
+ fail("did not move TestMessage items in parent");
+ }
+
+ if (a4) {
+ fail("somehow turned null ptr into non-null by sending it");
+ }
+
+ // Pass UniquePtr by reference
+ UniquePtr<DummyStruct> b = MakeUnique<DummyStruct>(1);
+
+ if (!SendTestSendReference(std::move(b))) {
+ fail("failed sending UniquePtr by reference");
+ }
+ if (b) {
+ fail("did not move UniquePtr sent by reference");
+ }
+}
+
+// ---------------------------------------------------------------------------
+// CHILD PROCESS
+// ---------------------------------------------------------------------------
+
+mozilla::ipc::IPCResult TestUniquePtrIPCChild::RecvTestMessage(
+ UniquePtr<int>&& aA1, UniquePtr<DummyStruct>&& aA2, const DummyStruct& aA3,
+ UniquePtr<int>&& aA4) {
+ if ((!aA1) || (!aA2)) {
+ fail("TestMessage received NULL items in child");
+ }
+
+ if (aA4) {
+ fail("TestMessage received non-NULL when expecting NULL");
+ }
+
+ if ((*aA1 != 1) || (aA2->x() != 2) || (aA3.x() != 3)) {
+ fail("TestMessage received incorrect items in child");
+ }
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUniquePtrIPCChild::RecvTestSendReference(
+ UniquePtr<DummyStruct>&& aA) {
+ if (!aA) {
+ fail("TestSendReference received NULL item in child");
+ }
+
+ if (*aA != 1) {
+ fail("TestSendReference received incorrect item in child");
+ }
+
+ Close();
+ return IPC_OK();
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestUniquePtrIPC.h b/ipc/ipdl/test/cxx/TestUniquePtrIPC.h
new file mode 100644
index 0000000000..3c9de33df3
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUniquePtrIPC.h
@@ -0,0 +1,61 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_TestUniquePtrIPC_h
+#define mozilla_TestUniquePtrIPC_h
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestUniquePtrIPCParent.h"
+#include "mozilla/_ipdltest/PTestUniquePtrIPCChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestUniquePtrIPCParent : public PTestUniquePtrIPCParent {
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestUniquePtrIPCParent)
+ MOZ_COUNTED_DTOR_OVERRIDE(TestUniquePtrIPCParent)
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ bool ShouldContinueFromReplyTimeout() override { return false; }
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) {
+ fail("Abnormal shutdown of parent");
+ }
+ passed("ok");
+ QuitParent();
+ }
+};
+
+class TestUniquePtrIPCChild : public PTestUniquePtrIPCChild {
+ public:
+ MOZ_COUNTED_DEFAULT_CTOR(TestUniquePtrIPCChild)
+ MOZ_COUNTED_DTOR_OVERRIDE(TestUniquePtrIPCChild)
+
+ mozilla::ipc::IPCResult RecvTestMessage(UniquePtr<int>&& aA1,
+ UniquePtr<DummyStruct>&& aA2,
+ const DummyStruct& aA3,
+ UniquePtr<int>&& aA4);
+
+ mozilla::ipc::IPCResult RecvTestSendReference(UniquePtr<DummyStruct>&& aA);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (NormalShutdown != why) {
+ fail("Abnormal shutdown of child");
+ }
+ QuitChild();
+ }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // mozilla_TestUniquePtrIPC_h
diff --git a/ipc/ipdl/test/cxx/TestUrgency.cpp b/ipc/ipdl/test/cxx/TestUrgency.cpp
new file mode 100644
index 0000000000..840b9d71e9
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUrgency.cpp
@@ -0,0 +1,117 @@
+#include "TestUrgency.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#if defined(XP_UNIX)
+# include <unistd.h>
+#else
+# include <windows.h>
+#endif
+
+namespace mozilla {
+namespace _ipdltest {
+
+#if defined(XP_UNIX)
+static void Sleep(int ms) { sleep(ms / 1000); }
+#endif
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestUrgencyParent::TestUrgencyParent() : inreply_(false) {
+ MOZ_COUNT_CTOR(TestUrgencyParent);
+}
+
+TestUrgencyParent::~TestUrgencyParent() { MOZ_COUNT_DTOR(TestUrgencyParent); }
+
+void TestUrgencyParent::Main() {
+ if (!SendStart()) fail("sending Start");
+}
+
+mozilla::ipc::IPCResult TestUrgencyParent::RecvTest1(uint32_t* value) {
+ if (!SendReply1(value)) fail("sending Reply1");
+ if (*value != 99) fail("bad value");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgencyParent::RecvTest2() {
+ uint32_t value;
+ inreply_ = true;
+ if (!SendReply2(&value)) fail("sending Reply2");
+ inreply_ = false;
+ if (value != 500) fail("bad value");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgencyParent::RecvTest3(uint32_t* value) {
+ if (inreply_) fail("nested non-urgent on top of urgent rpc");
+ *value = 1000;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgencyParent::RecvFinalTest_Begin() {
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+enum {
+ kFirstTestBegin = 1,
+ kFirstTestGotReply,
+ kSecondTestBegin,
+ kSecondTestGotReply,
+};
+
+mozilla::ipc::IPCResult TestUrgencyChild::RecvStart() {
+ uint32_t result;
+
+ // Send a synchronous message, expect to get an urgent message while
+ // blocked.
+ test_ = kFirstTestBegin;
+ if (!SendTest1(&result)) fail("calling SendTest1");
+ if (result != 99) fail("bad result in RecvStart");
+ if (test_ != kFirstTestGotReply) fail("never received urgent message");
+
+ // Initiate the next test by sending an asynchronous message, then becoming
+ // blocked. This tests that the urgent message is still delivered properly,
+ // and that the parent does not try to service the sync
+ test_ = kSecondTestBegin;
+ if (!SendTest2()) fail("calling SendTest2");
+ if (!SendTest3(&result)) fail("calling SendTest3");
+ if (test_ != kSecondTestGotReply) fail("never received urgent message #2");
+ if (result != 1000) fail("wrong value from test3");
+
+ if (!SendFinalTest_Begin()) fail("Final test should have succeeded");
+
+ Close();
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgencyChild::RecvReply1(uint32_t* reply) {
+ if (test_ != kFirstTestBegin) fail("wrong test # in RecvReply1");
+
+ *reply = 99;
+ test_ = kFirstTestGotReply;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgencyChild::RecvReply2(uint32_t* reply) {
+ if (test_ != kSecondTestBegin) fail("wrong test # in RecvReply2");
+
+ // sleep for 5 seconds so the parent process tries to deliver more messages.
+ Sleep(5000);
+
+ *reply = 500;
+ test_ = kSecondTestGotReply;
+ return IPC_OK();
+}
+
+TestUrgencyChild::TestUrgencyChild() : test_(0) {
+ MOZ_COUNT_CTOR(TestUrgencyChild);
+}
+
+TestUrgencyChild::~TestUrgencyChild() { MOZ_COUNT_DTOR(TestUrgencyChild); }
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestUrgency.h b/ipc/ipdl/test/cxx/TestUrgency.h
new file mode 100644
index 0000000000..6af73177ee
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUrgency.h
@@ -0,0 +1,57 @@
+#ifndef mozilla__ipdltest_TestUrgency_h
+#define mozilla__ipdltest_TestUrgency_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestUrgencyParent.h"
+#include "mozilla/_ipdltest/PTestUrgencyChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestUrgencyParent : public PTestUrgencyParent {
+ public:
+ TestUrgencyParent();
+ virtual ~TestUrgencyParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+
+ mozilla::ipc::IPCResult RecvTest1(uint32_t* value);
+ mozilla::ipc::IPCResult RecvTest2();
+ mozilla::ipc::IPCResult RecvTest3(uint32_t* value);
+ mozilla::ipc::IPCResult RecvTest4_Begin();
+ mozilla::ipc::IPCResult RecvTest4_NestedSync();
+ mozilla::ipc::IPCResult RecvFinalTest_Begin();
+
+ bool ShouldContinueFromReplyTimeout() override { return false; }
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ bool inreply_;
+};
+
+class TestUrgencyChild : public PTestUrgencyChild {
+ public:
+ TestUrgencyChild();
+ virtual ~TestUrgencyChild();
+
+ mozilla::ipc::IPCResult RecvStart();
+ mozilla::ipc::IPCResult RecvReply1(uint32_t* reply);
+ mozilla::ipc::IPCResult RecvReply2(uint32_t* reply);
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { QuitChild(); }
+
+ private:
+ uint32_t test_;
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestUrgency_h
diff --git a/ipc/ipdl/test/cxx/TestUrgentHangs.cpp b/ipc/ipdl/test/cxx/TestUrgentHangs.cpp
new file mode 100644
index 0000000000..96227dd791
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUrgentHangs.cpp
@@ -0,0 +1,174 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
+ * vim: sw=2 ts=4 et :
+ */
+#include "TestUrgentHangs.h"
+
+#include "IPDLUnitTests.h" // fail etc.
+#include "prthread.h"
+#if defined(XP_UNIX)
+# include <unistd.h>
+#else
+# include <windows.h>
+#endif
+
+namespace mozilla {
+namespace _ipdltest {
+
+//-----------------------------------------------------------------------------
+// parent
+
+TestUrgentHangsParent::TestUrgentHangsParent()
+ : mInnerCount(0), mInnerUrgentCount(0) {
+ MOZ_COUNT_CTOR(TestUrgentHangsParent);
+}
+
+TestUrgentHangsParent::~TestUrgentHangsParent() {
+ MOZ_COUNT_DTOR(TestUrgentHangsParent);
+}
+
+void TestUrgentHangsParent::Main() {
+ SetReplyTimeoutMs(1000);
+
+ // Should succeed despite the nested sleep call because the content process
+ // responded to the transaction.
+ if (!SendTest1_1()) fail("sending Test1_1");
+
+ // Fails with a timeout.
+ if (SendTest2()) fail("sending Test2");
+
+ // Also fails since we haven't gotten a response for Test2 yet.
+ if (SendTest3()) fail("sending Test3");
+
+ // Do a second round of testing once the reply to Test2 comes back.
+ MessageLoop::current()->PostDelayedTask(
+ NewNonOwningRunnableMethod(
+ "_ipdltest::TestUrgentHangsParent::SecondStage", this,
+ &TestUrgentHangsParent::SecondStage),
+ 3000);
+}
+
+void TestUrgentHangsParent::SecondStage() {
+ // Send an async message that waits 2 seconds and then sends a sync message
+ // (which should be processed).
+ if (!SendTest4()) fail("sending Test4");
+
+ // Send a sync message that will time out because the child is waiting
+ // inside RecvTest4.
+ if (SendTest4_1()) fail("sending Test4_1");
+
+ MessageLoop::current()->PostDelayedTask(
+ NewNonOwningRunnableMethod("_ipdltest::TestUrgentHangsParent::ThirdStage",
+ this, &TestUrgentHangsParent::ThirdStage),
+ 3000);
+}
+
+void TestUrgentHangsParent::ThirdStage() {
+ // The third stage does the same thing as the second stage except that the
+ // child sends an urgent message to us. In this case, we actually answer
+ // that message unconditionally.
+
+ // Send an async message that waits 2 seconds and then sends a sync message
+ // (which should be processed).
+ if (!SendTest5()) fail("sending Test5");
+
+ // Send a sync message that will time out because the child is waiting
+ // inside RecvTest5.
+ if (SendTest5_1()) fail("sending Test5_1");
+
+ // Close the channel after the child finishes its work in RecvTest5.
+ MessageLoop::current()->PostDelayedTask(
+ NewNonOwningRunnableMethod("ipc::IToplevelProtocol::Close", this,
+ &TestUrgentHangsParent::Close),
+ 3000);
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsParent::RecvTest1_2() {
+ if (!SendTest1_3()) fail("sending Test1_3");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsParent::RecvTestInner() {
+ mInnerCount++;
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsParent::RecvTestInnerUrgent() {
+ mInnerUrgentCount++;
+ return IPC_OK();
+}
+
+//-----------------------------------------------------------------------------
+// child
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest1_1() {
+ if (!SendTest1_2()) fail("sending Test1_2");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest1_3() {
+ PR_Sleep(PR_SecondsToInterval(2));
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest2() {
+ PR_Sleep(PR_SecondsToInterval(2));
+
+ // Should fail because of the timeout.
+ if (SendTestInner()) fail("sending TestInner");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest3() {
+ fail("RecvTest3 should never be called");
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest4() {
+ PR_Sleep(PR_SecondsToInterval(2));
+
+ // This won't fail because we should handle Test4_1 here before actually
+ // sending TestInner to the parent.
+ if (!SendTestInner()) fail("sending TestInner");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest4_1() {
+ // This should fail because Test4_1 timed out and hasn't gotten a response
+ // yet.
+ if (SendTestInner()) fail("sending TestInner");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest5() {
+ PR_Sleep(PR_SecondsToInterval(2));
+
+ // This message will actually be handled by the parent even though it's in
+ // the timeout state.
+ if (!SendTestInnerUrgent()) fail("sending TestInner");
+
+ return IPC_OK();
+}
+
+mozilla::ipc::IPCResult TestUrgentHangsChild::RecvTest5_1() {
+ // This message will actually be handled by the parent even though it's in
+ // the timeout state.
+ if (!SendTestInnerUrgent()) fail("sending TestInner");
+
+ return IPC_OK();
+}
+
+TestUrgentHangsChild::TestUrgentHangsChild() {
+ MOZ_COUNT_CTOR(TestUrgentHangsChild);
+}
+
+TestUrgentHangsChild::~TestUrgentHangsChild() {
+ MOZ_COUNT_DTOR(TestUrgentHangsChild);
+}
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/cxx/TestUrgentHangs.h b/ipc/ipdl/test/cxx/TestUrgentHangs.h
new file mode 100644
index 0000000000..facda522bf
--- /dev/null
+++ b/ipc/ipdl/test/cxx/TestUrgentHangs.h
@@ -0,0 +1,64 @@
+#ifndef mozilla__ipdltest_TestUrgentHangs_h
+#define mozilla__ipdltest_TestUrgentHangs_h 1
+
+#include "mozilla/_ipdltest/IPDLUnitTests.h"
+
+#include "mozilla/_ipdltest/PTestUrgentHangsParent.h"
+#include "mozilla/_ipdltest/PTestUrgentHangsChild.h"
+
+namespace mozilla {
+namespace _ipdltest {
+
+class TestUrgentHangsParent : public PTestUrgentHangsParent {
+ public:
+ TestUrgentHangsParent();
+ virtual ~TestUrgentHangsParent();
+
+ static bool RunTestInProcesses() { return true; }
+ static bool RunTestInThreads() { return false; }
+
+ void Main();
+ void SecondStage();
+ void ThirdStage();
+
+ mozilla::ipc::IPCResult RecvTest1_2();
+ mozilla::ipc::IPCResult RecvTestInner();
+ mozilla::ipc::IPCResult RecvTestInnerUrgent();
+
+ bool ShouldContinueFromReplyTimeout() override { return false; }
+ virtual void ActorDestroy(ActorDestroyReason why) override {
+ if (mInnerCount != 1) {
+ fail("wrong mInnerCount");
+ }
+ if (mInnerUrgentCount != 2) {
+ fail("wrong mInnerUrgentCount");
+ }
+ passed("ok");
+ QuitParent();
+ }
+
+ private:
+ size_t mInnerCount, mInnerUrgentCount;
+};
+
+class TestUrgentHangsChild : public PTestUrgentHangsChild {
+ public:
+ TestUrgentHangsChild();
+ virtual ~TestUrgentHangsChild();
+
+ mozilla::ipc::IPCResult RecvTest1_1();
+ mozilla::ipc::IPCResult RecvTest1_3();
+ mozilla::ipc::IPCResult RecvTest2();
+ mozilla::ipc::IPCResult RecvTest3();
+ mozilla::ipc::IPCResult RecvTest4();
+ mozilla::ipc::IPCResult RecvTest4_1();
+ mozilla::ipc::IPCResult RecvTest5();
+ mozilla::ipc::IPCResult RecvTest5_1();
+
+ virtual void ActorDestroy(ActorDestroyReason why) override { QuitChild(); }
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
+#endif // ifndef mozilla__ipdltest_TestUrgentHangs_h
diff --git a/ipc/ipdl/test/cxx/app/TestIPDL.cpp b/ipc/ipdl/test/cxx/app/TestIPDL.cpp
new file mode 100644
index 0000000000..3891aead62
--- /dev/null
+++ b/ipc/ipdl/test/cxx/app/TestIPDL.cpp
@@ -0,0 +1,24 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#define MOZ_IPDL_TESTS
+#include "mozilla/Bootstrap.h"
+
+#if defined(XP_WIN)
+# include <windows.h>
+# include "nsWindowsWMain.cpp"
+#endif
+
+using namespace mozilla;
+
+int main(int argc, char** argv) {
+ // the first argument specifies which IPDL test case/suite to load
+ if (argc < 2) return 1;
+
+ Bootstrap::UniquePtr bootstrap = GetBootstrap();
+ if (!bootstrap) {
+ return 2;
+ }
+ return bootstrap->XRE_RunIPDLTest(argc, argv);
+}
diff --git a/ipc/ipdl/test/cxx/app/moz.build b/ipc/ipdl/test/cxx/app/moz.build
new file mode 100644
index 0000000000..909360062a
--- /dev/null
+++ b/ipc/ipdl/test/cxx/app/moz.build
@@ -0,0 +1,20 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+GeckoProgram("ipdlunittest", linkage="dependent")
+
+SOURCES += [
+ "TestIPDL.cpp",
+]
+include("/ipc/chromium/chromium-config.mozbuild")
+
+LOCAL_INCLUDES += [
+ "/toolkit/xre",
+ "/xpcom/base",
+]
+
+if CONFIG["CC_TYPE"] == "clang-cl":
+ WIN32_EXE_LDFLAGS += ["-ENTRY:wmainCRTStartup"]
diff --git a/ipc/ipdl/test/cxx/genIPDLUnitTests.py b/ipc/ipdl/test/cxx/genIPDLUnitTests.py
new file mode 100644
index 0000000000..160b90a031
--- /dev/null
+++ b/ipc/ipdl/test/cxx/genIPDLUnitTests.py
@@ -0,0 +1,193 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+import string
+import sys
+
+
+def usage():
+ print(
+ """
+%s template_file -t unit_tests... -e extra_protocols...
+
+ TEMPLATE_FILE is used to generate to generate the unit-tester .cpp
+ UNIT_TESTS are the top-level protocols defining unit tests
+ EXTRA_PROTOCOLS are top-level protocols for subprocesses that can be
+ spawned in tests but are not unit tests in and of
+ themselves
+"""
+ % (sys.argv[0]),
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+
+def main(argv):
+ template = argv[1]
+
+ if argv[2] != "-t":
+ usage()
+ i = 3
+ unittests = []
+ while argv[i] != "-e":
+ unittests.append(argv[i])
+ i += 1
+
+ extras = argv[(i + 1) :]
+
+ includes = "\n".join(['#include "%s.h"' % (t) for t in unittests])
+
+ enum_values = "\n".join([" %s," % (t) for t in unittests + extras])
+ last_enum = unittests[-1]
+
+ string_to_enums = "\n".join(
+ [
+ """ else if (!strcmp(aString, "%s"))
+ return %s;"""
+ % (t, t)
+ for t in unittests + extras
+ ]
+ )
+
+ enum_to_strings = "\n".join(
+ [
+ """ case %s:
+ return "%s";"""
+ % (t, t)
+ for t in unittests + extras
+ ]
+ )
+
+ parent_delete_cases = "\n".join(
+ [
+ """ case %s: {
+ delete reinterpret_cast<%sParent*>(gParentActor);
+ return;
+ }
+"""
+ % (t, t)
+ for t in unittests
+ ]
+ )
+
+ parent_enabled_cases_proc = "\n".join(
+ [
+ """ case %s: {
+ if (!%sParent::RunTestInProcesses()) {
+ passed("N/A to proc");
+ DeferredParentShutdown();
+ return;
+ }
+ break;
+ }
+"""
+ % (t, t)
+ for t in unittests
+ ]
+ )
+
+ parent_main_cases_proc = "\n".join(
+ [
+ """ case %s: {
+ %sParent** parent =
+ reinterpret_cast<%sParent**>(&gParentActor);
+ *parent = new %sParent();
+ (*parent)->Open(transport, child);
+ return (*parent)->Main();
+ }
+"""
+ % (t, t, t, t)
+ for t in unittests
+ ]
+ )
+
+ parent_enabled_cases_thread = "\n".join(
+ [
+ """ case %s: {
+ if (!%sParent::RunTestInThreads()) {
+ passed("N/A to threads");
+ DeferredParentShutdown();
+ return;
+ }
+ break;
+ }
+"""
+ % (t, t)
+ for t in unittests
+ ]
+ )
+
+ parent_main_cases_thread = "\n".join(
+ [
+ """ case %s: {
+ %sParent** parent =
+ reinterpret_cast<%sParent**>(&gParentActor);
+ *parent = new %sParent();
+
+ %sChild** child =
+ reinterpret_cast<%sChild**>(&gChildActor);
+ *child = new %sChild();
+
+ ::mozilla::ipc::MessageChannel *childChannel = (*child)->GetIPCChannel();
+ ::mozilla::ipc::Side parentSide =
+ ::mozilla::ipc::ParentSide;
+
+ (*parent)->Open(childChannel, childMessageLoop, parentSide);
+ return (*parent)->Main();
+ }
+"""
+ % (t, t, t, t, t, t, t)
+ for t in unittests
+ ]
+ )
+
+ child_delete_cases = "\n".join(
+ [
+ """ case %s: {
+ delete reinterpret_cast<%sChild*>(gChildActor);
+ return;
+ }
+"""
+ % (t, t)
+ for t in unittests + extras
+ ]
+ )
+
+ child_init_cases = "\n".join(
+ [
+ """ case %s: {
+ %sChild** child =
+ reinterpret_cast<%sChild**>(&gChildActor);
+ *child = new %sChild();
+ (*child)->Open(transport, parentPid, worker);
+ return;
+ }
+"""
+ % (t, t, t, t)
+ for t in unittests + extras
+ ]
+ )
+
+ templatefile = open(template, "r", encoding="utf-8")
+ sys.stdout.write(
+ string.Template(templatefile.read()).substitute(
+ INCLUDES=includes,
+ ENUM_VALUES=enum_values,
+ LAST_ENUM=last_enum,
+ STRING_TO_ENUMS=string_to_enums,
+ ENUM_TO_STRINGS=enum_to_strings,
+ PARENT_DELETE_CASES=parent_delete_cases,
+ PARENT_ENABLED_CASES_PROC=parent_enabled_cases_proc,
+ PARENT_MAIN_CASES_PROC=parent_main_cases_proc,
+ PARENT_ENABLED_CASES_THREAD=parent_enabled_cases_thread,
+ PARENT_MAIN_CASES_THREAD=parent_main_cases_thread,
+ CHILD_DELETE_CASES=child_delete_cases,
+ CHILD_INIT_CASES=child_init_cases,
+ )
+ )
+ templatefile.close()
+
+
+if __name__ == "__main__":
+ main(sys.argv)
diff --git a/ipc/ipdl/test/cxx/moz.build b/ipc/ipdl/test/cxx/moz.build
new file mode 100644
index 0000000000..e2650df0aa
--- /dev/null
+++ b/ipc/ipdl/test/cxx/moz.build
@@ -0,0 +1,172 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += ["app"]
+
+EXPORTS.mozilla._ipdltest += [
+ "IPDLUnitTestProcessChild.h",
+ "IPDLUnitTests.h",
+ "IPDLUnitTestTypes.h",
+ "IPDLUnitTestUtils.h",
+ "TestActorPunning.h",
+ "TestAsyncReturns.h",
+ "TestBadActor.h",
+ "TestCancel.h",
+ "TestCrashCleanup.h",
+ "TestDataStructures.h",
+ "TestDemon.h",
+ "TestDesc.h",
+ "TestEndpointBridgeMain.h",
+ "TestEndpointOpens.h",
+ "TestFailedCtor.h",
+ "TestHangs.h",
+ "TestHighestPrio.h",
+ "TestInterruptErrorCleanup.h",
+ "TestInterruptRaces.h",
+ "TestInterruptShutdownRace.h",
+ "TestJSON.h",
+ "TestLatency.h",
+ "TestManyChildAllocs.h",
+ "TestMultiMgrs.h",
+ "TestNestedLoops.h",
+ "TestOffMainThreadPainting.h",
+ "TestRaceDeadlock.h",
+ "TestRaceDeferral.h",
+ "TestRacyInterruptReplies.h",
+ "TestRacyReentry.h",
+ "TestRacyUndefer.h",
+ "TestRPC.h",
+ "TestSanity.h",
+ "TestSelfManageRoot.h",
+ "TestShmem.h",
+ "TestShutdown.h",
+ "TestStackHooks.h",
+ "TestSyncError.h",
+ "TestSyncHang.h",
+ "TestSyncWakeup.h",
+ "TestUniquePtrIPC.h",
+ "TestUrgency.h",
+ "TestUrgentHangs.h",
+]
+
+SOURCES += [
+ "TestActorPunning.cpp",
+ "TestAsyncReturns.cpp",
+ "TestBadActor.cpp",
+ "TestCancel.cpp",
+ "TestCrashCleanup.cpp",
+ "TestDataStructures.cpp",
+ "TestDemon.cpp",
+ "TestDesc.cpp",
+ "TestEndpointBridgeMain.cpp",
+ "TestEndpointOpens.cpp",
+ "TestFailedCtor.cpp",
+ "TestHangs.cpp",
+ "TestHighestPrio.cpp",
+ "TestInterruptErrorCleanup.cpp",
+ "TestInterruptRaces.cpp",
+ "TestInterruptShutdownRace.cpp",
+ "TestJSON.cpp",
+ "TestLatency.cpp",
+ "TestManyChildAllocs.cpp",
+ "TestMultiMgrs.cpp",
+ "TestNestedLoops.cpp",
+ "TestOffMainThreadPainting.cpp",
+ "TestRaceDeadlock.cpp",
+ "TestRaceDeferral.cpp",
+ "TestRacyInterruptReplies.cpp",
+ "TestRacyReentry.cpp",
+ "TestRacyUndefer.cpp",
+ "TestRPC.cpp",
+ "TestSanity.cpp",
+ "TestSelfManageRoot.cpp",
+ "TestShmem.cpp",
+ "TestShutdown.cpp",
+ "TestStackHooks.cpp",
+ "TestSyncError.cpp",
+ "TestSyncHang.cpp",
+ "TestSyncWakeup.cpp",
+ "TestUniquePtrIPC.cpp",
+ "TestUrgency.cpp",
+ "TestUrgentHangs.cpp",
+]
+
+SOURCES += [
+ "!IPDLUnitTests.cpp",
+ "IPDLUnitTestProcessChild.cpp",
+ "IPDLUnitTestSubprocess.cpp",
+]
+
+IPDL_SOURCES += [
+ "PTestActorPunning.ipdl",
+ "PTestActorPunningPunned.ipdl",
+ "PTestActorPunningSub.ipdl",
+ "PTestAsyncReturns.ipdl",
+ "PTestBadActor.ipdl",
+ "PTestBadActorSub.ipdl",
+ "PTestCancel.ipdl",
+ "PTestCrashCleanup.ipdl",
+ "PTestDataStructures.ipdl",
+ "PTestDataStructuresCommon.ipdlh",
+ "PTestDataStructuresSub.ipdl",
+ "PTestDemon.ipdl",
+ "PTestDesc.ipdl",
+ "PTestDescSub.ipdl",
+ "PTestDescSubsub.ipdl",
+ "PTestEndpointBridgeMain.ipdl",
+ "PTestEndpointBridgeMainSub.ipdl",
+ "PTestEndpointBridgeSub.ipdl",
+ "PTestEndpointOpens.ipdl",
+ "PTestEndpointOpensOpened.ipdl",
+ "PTestFailedCtor.ipdl",
+ "PTestFailedCtorSub.ipdl",
+ "PTestFailedCtorSubsub.ipdl",
+ "PTestHandle.ipdl",
+ "PTestHangs.ipdl",
+ "PTestHighestPrio.ipdl",
+ "PTestIndirectProtocolParam.ipdlh",
+ "PTestIndirectProtocolParamFirst.ipdl",
+ "PTestIndirectProtocolParamManage.ipdl",
+ "PTestIndirectProtocolParamSecond.ipdl",
+ "PTestInterruptErrorCleanup.ipdl",
+ "PTestInterruptRaces.ipdl",
+ "PTestInterruptShutdownRace.ipdl",
+ "PTestJSON.ipdl",
+ "PTestLatency.ipdl",
+ "PTestManyChildAllocs.ipdl",
+ "PTestManyChildAllocsSub.ipdl",
+ "PTestMultiMgrs.ipdl",
+ "PTestMultiMgrsBottom.ipdl",
+ "PTestMultiMgrsLeft.ipdl",
+ "PTestMultiMgrsRight.ipdl",
+ "PTestNestedLoops.ipdl",
+ "PTestPaintThread.ipdl",
+ "PTestPriority.ipdl",
+ "PTestRaceDeadlock.ipdl",
+ "PTestRaceDeferral.ipdl",
+ "PTestRacyInterruptReplies.ipdl",
+ "PTestRacyReentry.ipdl",
+ "PTestRacyUndefer.ipdl",
+ "PTestRPC.ipdl",
+ "PTestSanity.ipdl",
+ "PTestSelfManage.ipdl",
+ "PTestSelfManageRoot.ipdl",
+ "PTestShmem.ipdl",
+ "PTestShutdown.ipdl",
+ "PTestShutdownSub.ipdl",
+ "PTestShutdownSubsub.ipdl",
+ "PTestStackHooks.ipdl",
+ "PTestSyncError.ipdl",
+ "PTestSyncHang.ipdl",
+ "PTestSyncWakeup.ipdl",
+ "PTestUniquePtrIPC.ipdl",
+ "PTestUrgency.ipdl",
+ "PTestUrgentHangs.ipdl",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
diff --git a/ipc/ipdl/test/gtest/IPDLUnitTest.cpp b/ipc/ipdl/test/gtest/IPDLUnitTest.cpp
new file mode 100644
index 0000000000..0450019ba9
--- /dev/null
+++ b/ipc/ipdl/test/gtest/IPDLUnitTest.cpp
@@ -0,0 +1,308 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/_ipdltest/IPDLUnitTest.h"
+#include "mozilla/ipc/IOThreadChild.h"
+#include "mozilla/ipc/NodeController.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/ipc/ProcessChild.h"
+#include "mozilla/SpinEventLoopUntil.h"
+#include "nsDebugImpl.h"
+#include "nsThreadManager.h"
+
+#include <string>
+
+#ifdef MOZ_WIDGET_ANDROID
+# include "nsIAppShell.h"
+# include "nsServiceManagerUtils.h"
+# include "nsWidgetsCID.h"
+#endif
+
+namespace mozilla::_ipdltest {
+
+static std::unordered_map<std::string_view, ipc::IToplevelProtocol* (*)()>
+ sAllocChildActorRegistry;
+
+const char* RegisterAllocChildActor(const char* aName,
+ ipc::IToplevelProtocol* (*aFunc)()) {
+ sAllocChildActorRegistry[aName] = aFunc;
+ return aName;
+}
+
+already_AddRefed<IPDLUnitTestParent> IPDLUnitTestParent::CreateCrossProcess() {
+#ifdef MOZ_WIDGET_ANDROID
+ // Force-initialize the appshell on android, as android child process
+ // launching depends on widget component initialization.
+ nsCOMPtr<nsIAppShell> _appShell = do_GetService(NS_APPSHELL_CID);
+#endif
+
+ RefPtr<IPDLUnitTestParent> parent = new IPDLUnitTestParent();
+ parent->mSubprocess =
+ new ipc::GeckoChildProcessHost(GeckoProcessType_IPDLUnitTest);
+
+ std::vector<std::string> extraArgs;
+
+ auto prefSerializer = MakeUnique<ipc::SharedPreferenceSerializer>();
+ if (!prefSerializer->SerializeToSharedMemory(GeckoProcessType_IPDLUnitTest,
+ /* remoteType */ ""_ns)) {
+ ADD_FAILURE()
+ << "SharedPreferenceSerializer::SerializeToSharedMemory failed";
+ return nullptr;
+ }
+ prefSerializer->AddSharedPrefCmdLineArgs(*parent->mSubprocess, extraArgs);
+
+ if (!parent->mSubprocess->SyncLaunch(extraArgs)) {
+ ADD_FAILURE() << "Subprocess launch failed";
+ return nullptr;
+ }
+
+ if (!parent->mSubprocess->TakeInitialEndpoint().Bind(parent.get())) {
+ ADD_FAILURE() << "Opening the parent actor failed";
+ return nullptr;
+ }
+
+ EXPECT_TRUE(parent->CanSend());
+ return parent.forget();
+}
+
+already_AddRefed<IPDLUnitTestParent> IPDLUnitTestParent::CreateCrossThread() {
+ RefPtr<IPDLUnitTestParent> parent = new IPDLUnitTestParent();
+ RefPtr<IPDLUnitTestChild> child = new IPDLUnitTestChild();
+
+ nsresult rv =
+ NS_NewNamedThread("IPDL UnitTest", getter_AddRefs(parent->mOtherThread));
+ if (NS_FAILED(rv)) {
+ ADD_FAILURE() << "Failed to create IPDLUnitTest thread";
+ return nullptr;
+ }
+ if (!parent->Open(child, parent->mOtherThread)) {
+ ADD_FAILURE() << "Opening the actor failed";
+ return nullptr;
+ }
+
+ EXPECT_TRUE(parent->CanSend());
+ return parent.forget();
+}
+
+IPDLUnitTestParent::~IPDLUnitTestParent() {
+ if (mSubprocess) {
+ mSubprocess->Destroy();
+ mSubprocess = nullptr;
+ }
+ if (mOtherThread) {
+ mOtherThread->Shutdown();
+ }
+}
+
+bool IPDLUnitTestParent::Start(const char* aName,
+ ipc::IToplevelProtocol* aActor) {
+ nsID channelId = nsID::GenerateUUID();
+ auto [parentPort, childPort] =
+ ipc::NodeController::GetSingleton()->CreatePortPair();
+ if (!SendStart(nsDependentCString(aName), std::move(childPort), channelId)) {
+ ADD_FAILURE() << "IPDLUnitTestParent::SendStart failed";
+ return false;
+ }
+ if (!aActor->Open(std::move(parentPort), channelId, OtherPid())) {
+ ADD_FAILURE() << "Unable to open parent actor";
+ return false;
+ }
+ return true;
+}
+
+ipc::IPCResult IPDLUnitTestParent::RecvReport(const TestPartResult& aReport) {
+ if (!aReport.failed()) {
+ return IPC_OK();
+ }
+
+ // Report the failure
+ ADD_FAILURE_AT(aReport.filename().get(), aReport.lineNumber())
+ << "[child " << OtherPid() << "] " << aReport.summary();
+
+ // If the failure was fatal, kill the child process to avoid hangs.
+ if (aReport.fatal()) {
+ KillHard();
+ }
+ return IPC_OK();
+}
+
+ipc::IPCResult IPDLUnitTestParent::RecvComplete() {
+ mComplete = true;
+ Close();
+ return IPC_OK();
+}
+
+void IPDLUnitTestParent::KillHard() {
+ if (mCalledKillHard) {
+ return;
+ }
+ mCalledKillHard = true;
+
+ // We can't effectively kill a same-process situation, but we can trigger
+ // shutdown early to avoid hanging.
+ if (mOtherThread) {
+ Close();
+ nsCOMPtr<nsIThread> otherThread = mOtherThread.forget();
+ otherThread->Shutdown();
+ }
+
+ if (mSubprocess) {
+ ProcessHandle handle = mSubprocess->GetChildProcessHandle();
+ if (!base::KillProcess(handle, base::PROCESS_END_KILLED_BY_USER)) {
+ NS_WARNING("failed to kill subprocess!");
+ }
+ mSubprocess->SetAlreadyDead();
+ }
+}
+
+ipc::IPCResult IPDLUnitTestChild::RecvStart(const nsCString& aName,
+ ipc::ScopedPort aPort,
+ const nsID& aMessageChannelId) {
+ auto* allocChildActor =
+ sAllocChildActorRegistry[std::string_view{aName.get()}];
+ if (!allocChildActor) {
+ ADD_FAILURE() << "No AllocChildActor for name " << aName.get()
+ << " registered!";
+ return IPC_FAIL(this, "No AllocChildActor registered!");
+ }
+
+ // Store references to the node & port to watch for test completion.
+ RefPtr<ipc::NodeController> controller = aPort.Controller();
+ mojo::core::ports::PortRef port = aPort.Port();
+
+ RefPtr<IToplevelProtocol> child = allocChildActor();
+ if (!child->Open(std::move(aPort), aMessageChannelId, OtherPid())) {
+ ADD_FAILURE() << "Unable to open child actor";
+ return IPC_FAIL(this, "Unable to open child actor");
+ }
+
+ // Wait for the port which was created for this actor to be fully torn down.
+ SpinEventLoopUntil("IPDLUnitTestChild::RecvStart"_ns,
+ [&] { return controller->GetStatus(port).isNothing(); });
+
+ // Tear down the test actor to end the test.
+ SendComplete();
+ return IPC_OK();
+}
+
+void IPDLUnitTestChild::ActorDestroy(ActorDestroyReason aWhy) {
+ if (!XRE_IsParentProcess()) {
+ XRE_ShutdownChildProcess();
+ }
+}
+
+void IPDLTestHelper::TestWrapper(bool aCrossProcess) {
+ // Create the host and start the test actor with it.
+ RefPtr<IPDLUnitTestParent> host =
+ aCrossProcess ? IPDLUnitTestParent::CreateCrossProcess()
+ : IPDLUnitTestParent::CreateCrossThread();
+ ASSERT_TRUE(host);
+ if (!host->Start(GetName(), GetActor())) {
+ FAIL();
+ }
+
+ // XXX: Consider adding a test timeout?
+
+ // Run the test body. This will send the initial messages to our actor, which
+ // will eventually clean itself up.
+ TestBody();
+
+ // Spin the event loop until the test wrapper host has fully shut down.
+ SpinEventLoopUntil("IPDLTestHelper::TestWrapper"_ns,
+ [&] { return !host->CanSend(); });
+
+ EXPECT_TRUE(host->ReportedComplete())
+ << "child process exited without signalling completion";
+}
+
+// Listener registered within the IPDLUnitTest process used to relay GTest
+// failures to the parent process, so that the are marked as failing the overall
+// gtest.
+class IPDLChildProcessTestListener : public testing::EmptyTestEventListener {
+ public:
+ explicit IPDLChildProcessTestListener(IPDLUnitTestChild* aActor)
+ : mActor(aActor) {}
+
+ virtual void OnTestPartResult(
+ const testing::TestPartResult& aTestPartResult) override {
+ mActor->SendReport(TestPartResult(
+ aTestPartResult.failed(), aTestPartResult.fatally_failed(),
+ nsDependentCString(aTestPartResult.file_name()),
+ aTestPartResult.line_number(),
+ nsDependentCString(aTestPartResult.summary()),
+ nsDependentCString(aTestPartResult.message())));
+ }
+
+ RefPtr<IPDLUnitTestChild> mActor;
+};
+
+// ProcessChild instance used to run the IPDLUnitTest process.
+class IPDLUnitTestProcessChild : public ipc::ProcessChild {
+ public:
+ using ipc::ProcessChild::ProcessChild;
+ bool Init(int aArgc, char* aArgv[]) override {
+ nsDebugImpl::SetMultiprocessMode("IPDLUnitTest");
+
+ if (!ProcessChild::InitPrefs(aArgc, aArgv)) {
+ MOZ_CRASH("InitPrefs failed");
+ return false;
+ }
+
+ if (NS_WARN_IF(NS_FAILED(nsThreadManager::get().Init()))) {
+ MOZ_CRASH("nsThreadManager initialization failed");
+ return false;
+ }
+
+ RefPtr<IPDLUnitTestChild> child = new IPDLUnitTestChild();
+ if (!TakeInitialEndpoint().Bind(child.get())) {
+ MOZ_CRASH("Bind of IPDLUnitTestChild failed");
+ return false;
+ }
+
+ // Register a listener to forward test results from the child process to the
+ // parent process to be handled there.
+ mListener = new IPDLChildProcessTestListener(child);
+ testing::UnitTest::GetInstance()->listeners().Append(mListener);
+
+ if (NS_FAILED(NS_InitMinimalXPCOM())) {
+ MOZ_CRASH("NS_InitMinimalXPCOM failed");
+ return false;
+ }
+
+ ipc::SetThisProcessName("IPDLUnitTest");
+ return true;
+ }
+
+ void CleanUp() override {
+ // Clean up the test listener we registered to get a clean shutdown.
+ if (mListener) {
+ testing::UnitTest::GetInstance()->listeners().Release(mListener);
+ delete mListener;
+ }
+
+ NS_ShutdownXPCOM(nullptr);
+ }
+
+ IPDLChildProcessTestListener* mListener = nullptr;
+};
+
+// Defined in nsEmbedFunctions.cpp
+extern UniquePtr<ipc::ProcessChild> (*gMakeIPDLUnitTestProcessChild)(
+ base::ProcessId, const nsID&);
+
+// Initialize gMakeIPDLUnitTestProcessChild in a static constructor.
+int _childProcessEntryPointStaticConstructor = ([] {
+ gMakeIPDLUnitTestProcessChild =
+ [](base::ProcessId aParentPid,
+ const nsID& aMessageChannelId) -> UniquePtr<ipc::ProcessChild> {
+ return MakeUnique<IPDLUnitTestProcessChild>(aParentPid, aMessageChannelId);
+ };
+ return 0;
+})();
+
+} // namespace mozilla::_ipdltest
diff --git a/ipc/ipdl/test/gtest/IPDLUnitTest.h b/ipc/ipdl/test/gtest/IPDLUnitTest.h
new file mode 100644
index 0000000000..f4548b508c
--- /dev/null
+++ b/ipc/ipdl/test/gtest/IPDLUnitTest.h
@@ -0,0 +1,79 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTest_h
+#define mozilla__ipdltest_IPDLUnitTest_h
+
+#include "mozilla/_ipdltest/IPDLUnitTestChild.h"
+#include "mozilla/_ipdltest/IPDLUnitTestParent.h"
+#include "mozilla/ipc/ProtocolUtils.h"
+
+namespace mozilla::_ipdltest {
+
+// Should be called from static constructors to register a child actor
+// constructor so that it can be called from the child process.
+const char* RegisterAllocChildActor(
+ const char* aName, mozilla::ipc::IToplevelProtocol* (*aFunc)());
+
+// Internal helper type used to declare IPDL tests.
+class IPDLTestHelper {
+ public:
+ void TestWrapper(bool aCrossProcess);
+ virtual const char* GetName() = 0;
+ virtual ipc::IToplevelProtocol* GetActor() = 0;
+ virtual void TestBody() = 0;
+};
+
+#define IPDL_TEST_CLASS_NAME_(actorname) IPDL_TEST_##actorname
+
+#define IPDL_TEST_HEAD_(actorname) \
+ class IPDL_TEST_CLASS_NAME_(actorname) \
+ : public ::mozilla::_ipdltest::IPDLTestHelper { \
+ public: \
+ IPDL_TEST_CLASS_NAME_(actorname)() : mActor(new actorname##Parent) {} \
+ \
+ private: \
+ void TestBody() override; \
+ const char* GetName() override { return sName; }; \
+ actorname##Parent* GetActor() override { return mActor; }; \
+ \
+ RefPtr<actorname##Parent> mActor; \
+ static const char* sName; \
+ }; \
+ const char* IPDL_TEST_CLASS_NAME_(actorname)::sName = \
+ ::mozilla::_ipdltest::RegisterAllocChildActor( \
+ #actorname, []() -> ::mozilla::ipc::IToplevelProtocol* { \
+ return new actorname##Child; \
+ });
+
+#define IPDL_TEST_DECL_(testgroup, actorname, crossprocess) \
+ TEST(testgroup, actorname) \
+ { \
+ IPDL_TEST_CLASS_NAME_(actorname) test; \
+ test.TestWrapper(crossprocess); \
+ }
+
+#define IPDL_TEST_BODY_SEGUE_(actorname) \
+ void IPDL_TEST_CLASS_NAME_(actorname)::TestBody()
+
+// Declare a basic IPDL unit test which will be run in both both cross-thread
+// and cross-process configurations. The actor `actorname` will be instantiated
+// by default-constructing the parent & child actors in the relevant processes,
+// and the test block will be executed, with `mActor` being a pointer to the
+// parent actor. The test is asynchronous, and will end when the IPDL connection
+// between the created actors is destroyed.
+//
+// GTest assertions fired in the child process will be relayed to the parent
+// process, and should generally function correctly.
+#define IPDL_TEST(actorname) \
+ IPDL_TEST_HEAD_(actorname) \
+ IPDL_TEST_DECL_(IPDLTest_CrossProcess, actorname, true) \
+ IPDL_TEST_DECL_(IPDLTest_CrossThread, actorname, false) \
+ IPDL_TEST_BODY_SEGUE_(actorname)
+
+} // namespace mozilla::_ipdltest
+
+#endif // mozilla__ipdltest_IPDLUnitTest_h
diff --git a/ipc/ipdl/test/gtest/IPDLUnitTestChild.h b/ipc/ipdl/test/gtest/IPDLUnitTestChild.h
new file mode 100644
index 0000000000..3f9243b274
--- /dev/null
+++ b/ipc/ipdl/test/gtest/IPDLUnitTestChild.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTestChild_h
+#define mozilla__ipdltest_IPDLUnitTestChild_h
+
+#include "mozilla/_ipdltest/PIPDLUnitTestChild.h"
+#include "nsISupportsImpl.h"
+
+namespace mozilla::_ipdltest {
+
+class IPDLUnitTestChild : public PIPDLUnitTestChild {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(IPDLUnitTestChild, override)
+
+ private:
+ friend class PIPDLUnitTestChild;
+
+ ipc::IPCResult RecvStart(const nsCString& aName, ipc::ScopedPort aPort,
+ const nsID& aChannelId);
+
+ void ActorDestroy(ActorDestroyReason aReason) override;
+
+ ~IPDLUnitTestChild() = default;
+};
+
+} // namespace mozilla::_ipdltest
+
+#endif // mozilla__ipdltest_IPDLUnitTestChild_h
diff --git a/ipc/ipdl/test/gtest/IPDLUnitTestParent.h b/ipc/ipdl/test/gtest/IPDLUnitTestParent.h
new file mode 100644
index 0000000000..c292506932
--- /dev/null
+++ b/ipc/ipdl/test/gtest/IPDLUnitTestParent.h
@@ -0,0 +1,50 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_IPDLUnitTestParent_h
+#define mozilla__ipdltest_IPDLUnitTestParent_h
+
+#include "mozilla/_ipdltest/PIPDLUnitTestParent.h"
+#include "mozilla/ipc/GeckoChildProcessHost.h"
+#include "nsISupportsImpl.h"
+
+namespace mozilla::_ipdltest {
+
+class IPDLUnitTestParent : public PIPDLUnitTestParent {
+ public:
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(IPDLUnitTestParent, override)
+
+ static already_AddRefed<IPDLUnitTestParent> CreateCrossProcess();
+ static already_AddRefed<IPDLUnitTestParent> CreateCrossThread();
+
+ // Try to start a connection with the given name and open `aParentActor` with
+ // it. Fails the current test and returns false on failure.
+ bool Start(const char* aName, IToplevelProtocol* aParentActor);
+
+ bool ReportedComplete() const { return mComplete; }
+
+ private:
+ friend class PIPDLUnitTestParent;
+
+ ipc::IPCResult RecvReport(const TestPartResult& aResult);
+ ipc::IPCResult RecvComplete();
+
+ void KillHard();
+
+ ~IPDLUnitTestParent();
+
+ // Only one of these two will be set depending.
+ nsCOMPtr<nsIThread> mOtherThread;
+ mozilla::ipc::GeckoChildProcessHost* mSubprocess = nullptr;
+
+ // Set to true when the test is complete.
+ bool mComplete = false;
+ bool mCalledKillHard = false;
+};
+
+} // namespace mozilla::_ipdltest
+
+#endif // mozilla__ipdltest_IPDLUnitTestParent_h
diff --git a/ipc/ipdl/test/gtest/PIPDLUnitTest.ipdl b/ipc/ipdl/test/gtest/PIPDLUnitTest.ipdl
new file mode 100644
index 0000000000..6bc5693a72
--- /dev/null
+++ b/ipc/ipdl/test/gtest/PIPDLUnitTest.ipdl
@@ -0,0 +1,34 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+using mozilla::dom::NativeThreadId from "mozilla/dom/NativeThreadId.h";
+[MoveOnly] using class mozilla::ipc::ScopedPort from "mozilla/ipc/ScopedPort.h";
+using struct nsID from "nsID.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+// IPDL representation of GTest's TestPartResult type.
+struct TestPartResult {
+ bool failed;
+ bool fatal;
+ nsCString filename;
+ int32_t lineNumber;
+ nsCString summary;
+ nsCString message;
+};
+
+// Primary actor for the IPDLUnitTest process and thread.
+[NeedsOtherPid, ChildProc=any]
+async protocol PIPDLUnitTest {
+ child:
+ async Start(nsCString name, ScopedPort port, nsID channelId);
+
+ parent:
+ async Report(TestPartResult result);
+ async Complete();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/gtest/PTestBasic.ipdl b/ipc/ipdl/test/gtest/PTestBasic.ipdl
new file mode 100644
index 0000000000..9bc81f4830
--- /dev/null
+++ b/ipc/ipdl/test/gtest/PTestBasic.ipdl
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ChildProc=any]
+async protocol PTestBasic {
+child:
+ async Hello();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/gtest/PTestCrossProcessSemaphore.ipdl b/ipc/ipdl/test/gtest/PTestCrossProcessSemaphore.ipdl
new file mode 100644
index 0000000000..fd25afbd13
--- /dev/null
+++ b/ipc/ipdl/test/gtest/PTestCrossProcessSemaphore.ipdl
@@ -0,0 +1,17 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+[MoveOnly] using mozilla::CrossProcessSemaphoreHandle from "mozilla/ipc/CrossProcessSemaphore.h";
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ParentImpl=virtual, ChildImpl=virtual, ChildProc=any]
+async protocol PTestCrossProcessSemaphore {
+child:
+ async CrossProcessSemaphore(CrossProcessSemaphoreHandle aSem);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/gtest/PTestInduceConnectionError.ipdl b/ipc/ipdl/test/gtest/PTestInduceConnectionError.ipdl
new file mode 100644
index 0000000000..d5de893884
--- /dev/null
+++ b/ipc/ipdl/test/gtest/PTestInduceConnectionError.ipdl
@@ -0,0 +1,19 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ParentImpl=virtual, ChildImpl=virtual, ChildProc=any]
+async protocol PTestInduceConnectionError {
+child:
+ async Begin();
+parent:
+ [LazySend] async FirstMessage();
+ [LazySend] async FollowupMessage();
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
+
diff --git a/ipc/ipdl/test/gtest/PTestManyHandles.ipdl b/ipc/ipdl/test/gtest/PTestManyHandles.ipdl
new file mode 100644
index 0000000000..31e03cee6f
--- /dev/null
+++ b/ipc/ipdl/test/gtest/PTestManyHandles.ipdl
@@ -0,0 +1,15 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+namespace mozilla {
+namespace _ipdltest {
+
+[ParentImpl=virtual, ChildImpl=virtual, ChildProc=any]
+async protocol PTestManyHandles {
+child:
+ async ManyHandles(FileDescriptor[] descrs);
+};
+
+} // namespace _ipdltest
+} // namespace mozilla
diff --git a/ipc/ipdl/test/gtest/TestBasic.cpp b/ipc/ipdl/test/gtest/TestBasic.cpp
new file mode 100644
index 0000000000..36ad55ba99
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestBasic.cpp
@@ -0,0 +1,29 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/_ipdltest/IPDLUnitTest.h"
+#include "mozilla/_ipdltest/TestBasicChild.h"
+#include "mozilla/_ipdltest/TestBasicParent.h"
+
+using namespace mozilla::ipc;
+
+namespace mozilla::_ipdltest {
+
+IPCResult TestBasicChild::RecvHello() {
+ EXPECT_TRUE(CanSend());
+ Close();
+ EXPECT_FALSE(CanSend());
+ return IPC_OK();
+}
+
+IPDL_TEST(TestBasic) {
+ bool ok = mActor->SendHello();
+ ASSERT_TRUE(ok);
+}
+
+} // namespace mozilla::_ipdltest
diff --git a/ipc/ipdl/test/gtest/TestBasicChild.h b/ipc/ipdl/test/gtest/TestBasicChild.h
new file mode 100644
index 0000000000..9971073f4c
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestBasicChild.h
@@ -0,0 +1,26 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_TestBasicChild_h
+#define mozilla__ipdltest_TestBasicChild_h
+
+#include "mozilla/_ipdltest/PTestBasicChild.h"
+
+namespace mozilla::_ipdltest {
+
+class TestBasicChild : public PTestBasicChild {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestBasicChild, override)
+
+ public:
+ mozilla::ipc::IPCResult RecvHello();
+
+ private:
+ ~TestBasicChild() = default;
+};
+
+} // namespace mozilla::_ipdltest
+
+#endif // mozilla__ipdltest_TestBasicChild_h
diff --git a/ipc/ipdl/test/gtest/TestBasicParent.h b/ipc/ipdl/test/gtest/TestBasicParent.h
new file mode 100644
index 0000000000..22b07375ba
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestBasicParent.h
@@ -0,0 +1,23 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla__ipdltest_TestBasicParent_h
+#define mozilla__ipdltest_TestBasicParent_h
+
+#include "mozilla/_ipdltest/PTestBasicParent.h"
+
+namespace mozilla::_ipdltest {
+
+class TestBasicParent : public PTestBasicParent {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestBasicParent, override)
+
+ private:
+ ~TestBasicParent() = default;
+};
+
+} // namespace mozilla::_ipdltest
+
+#endif // mozilla__ipdltest_TestBasicParent_h
diff --git a/ipc/ipdl/test/gtest/TestCrossProcessSemaphore.cpp b/ipc/ipdl/test/gtest/TestCrossProcessSemaphore.cpp
new file mode 100644
index 0000000000..dc05614ded
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestCrossProcessSemaphore.cpp
@@ -0,0 +1,63 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/_ipdltest/IPDLUnitTest.h"
+#include "mozilla/_ipdltest/PTestCrossProcessSemaphoreChild.h"
+#include "mozilla/_ipdltest/PTestCrossProcessSemaphoreParent.h"
+
+#include "mozilla/ipc/CrossProcessSemaphore.h"
+
+using namespace mozilla::ipc;
+
+namespace mozilla::_ipdltest {
+
+class TestCrossProcessSemaphoreChild : public PTestCrossProcessSemaphoreChild {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestCrossProcessSemaphoreChild,
+ override)
+
+ public:
+ IPCResult RecvCrossProcessSemaphore(
+ CrossProcessSemaphoreHandle&& aSem) override {
+ UniquePtr<CrossProcessSemaphore> cps(
+ CrossProcessSemaphore::Create(std::move(aSem)));
+ EXPECT_TRUE(bool(cps));
+ cps->Signal();
+ Close();
+ return IPC_OK();
+ }
+
+ private:
+ ~TestCrossProcessSemaphoreChild() = default;
+};
+
+class TestCrossProcessSemaphoreParent
+ : public PTestCrossProcessSemaphoreParent {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestCrossProcessSemaphoreParent,
+ override)
+
+ private:
+ ~TestCrossProcessSemaphoreParent() = default;
+};
+
+IPDL_TEST(TestCrossProcessSemaphore) {
+ // Create a semaphore with an initial count of 1. The test will then try to
+ // send the semaphore over IPDL to the other end which will signal, increasing
+ // the count to 2. The test will then try to wait on (decrement) the semaphore
+ // twice, which should succeed only if the semaphore was properly signaled.
+ UniquePtr<CrossProcessSemaphore> cps(
+ CrossProcessSemaphore::Create("TestCrossProcessSemaphore", 1));
+ ASSERT_TRUE(bool(cps));
+ CrossProcessSemaphoreHandle handle = cps->CloneHandle();
+ ASSERT_TRUE(bool(handle));
+ bool ok = mActor->SendCrossProcessSemaphore(std::move(handle));
+ ASSERT_TRUE(ok);
+ EXPECT_TRUE(cps->Wait());
+ EXPECT_TRUE(cps->Wait(Some(TimeDuration::FromSeconds(10))));
+}
+
+} // namespace mozilla::_ipdltest
diff --git a/ipc/ipdl/test/gtest/TestInduceConnectionError.cpp b/ipc/ipdl/test/gtest/TestInduceConnectionError.cpp
new file mode 100644
index 0000000000..988e22fe5a
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestInduceConnectionError.cpp
@@ -0,0 +1,95 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/SpinEventLoopUntil.h"
+#include "mozilla/_ipdltest/IPDLUnitTest.h"
+#include "mozilla/_ipdltest/PTestInduceConnectionErrorChild.h"
+#include "mozilla/_ipdltest/PTestInduceConnectionErrorParent.h"
+
+using namespace mozilla::ipc;
+
+namespace mozilla::_ipdltest {
+
+class TestInduceConnectionErrorChild : public PTestInduceConnectionErrorChild {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestInduceConnectionErrorChild,
+ override)
+
+ public:
+ IPCResult RecvBegin() override {
+ SendFirstMessage();
+ SendFollowupMessage();
+ Close();
+ return IPC_OK();
+ }
+
+ private:
+ ~TestInduceConnectionErrorChild() = default;
+};
+
+class TestInduceConnectionErrorParent
+ : public PTestInduceConnectionErrorParent {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestInduceConnectionErrorParent,
+ override)
+
+ IPCResult RecvFirstMessage() override {
+ EXPECT_TRUE(CanSend()) << "Actor still alive before inducing";
+ GetIPCChannel()->InduceConnectionError();
+ EXPECT_TRUE(CanSend())
+ << "Actor still alive after inducing - notification will be async";
+ mRecvdFirstMessage = true;
+
+ GetCurrentSerialEventTarget()->Dispatch(NS_NewRunnableFunction(
+ "AfterRecvFirstMessage", [self = RefPtr{this}]() {
+ EXPECT_FALSE(self->CanSend())
+ << "Actor shut down after spinning the event loop";
+ self->mTestComplete = true;
+ }));
+ return IPC_OK();
+ }
+
+ IPCResult RecvFollowupMessage() override {
+ MOZ_CRASH(
+ "Should never receive followup message, despite them being sent "
+ "together");
+ }
+
+ void ActorDestroy(ActorDestroyReason aReason) override {
+ EXPECT_TRUE(mRecvdFirstMessage)
+ << "Should have mRecvdFirstMessage set before ActorDestroy";
+ EXPECT_FALSE(mTestComplete) << "The test has not completed";
+ EXPECT_EQ(aReason, ActorDestroyReason::AbnormalShutdown)
+ << "Should be an abnormal shutdown";
+ mDestroyReason = Some(aReason);
+ }
+
+ bool mRecvdFirstMessage = false;
+ bool mTestComplete = false;
+ Maybe<ActorDestroyReason> mDestroyReason;
+
+ private:
+ ~TestInduceConnectionErrorParent() = default;
+};
+
+IPDL_TEST(TestInduceConnectionError) {
+ bool ok = mActor->SendBegin();
+ GTEST_ASSERT_TRUE(ok);
+
+ // Wait for the actor to be shut down.
+ SpinEventLoopUntil("TestInduceConnectionError"_ns,
+ [&] { return mActor->mTestComplete; });
+ EXPECT_TRUE(mActor->mRecvdFirstMessage)
+ << "Actor should have received first message, but not second one";
+ EXPECT_FALSE(mActor->CanSend()) << "Actor can no longer send";
+ GTEST_ASSERT_TRUE(mActor->mDestroyReason.isSome())
+ << "Actor should have been destroyed";
+ EXPECT_EQ(*mActor->mDestroyReason,
+ IProtocol::ActorDestroyReason::AbnormalShutdown)
+ << "Actor should have an 'abnormal shutdown'";
+}
+
+} // namespace mozilla::_ipdltest
diff --git a/ipc/ipdl/test/gtest/TestManyHandles.cpp b/ipc/ipdl/test/gtest/TestManyHandles.cpp
new file mode 100644
index 0000000000..ead8af22b1
--- /dev/null
+++ b/ipc/ipdl/test/gtest/TestManyHandles.cpp
@@ -0,0 +1,78 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "gtest/gtest.h"
+
+#include "mozilla/_ipdltest/IPDLUnitTest.h"
+#include "mozilla/_ipdltest/PTestManyHandlesChild.h"
+#include "mozilla/_ipdltest/PTestManyHandlesParent.h"
+
+using namespace mozilla::ipc;
+
+namespace mozilla::_ipdltest {
+
+class TestManyHandlesChild : public PTestManyHandlesChild {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestManyHandlesChild, override)
+
+ public:
+ IPCResult RecvManyHandles(nsTArray<FileDescriptor>&& aDescrs) override {
+ EXPECT_EQ(aDescrs.Length(), 500u);
+ for (int i = 0; i < static_cast<int>(aDescrs.Length()); ++i) {
+ UniqueFileHandle handle = aDescrs[i].TakePlatformHandle();
+ int value;
+ const int size = sizeof(value);
+#ifdef XP_WIN
+ DWORD numberOfBytesRead;
+ EXPECT_TRUE(
+ ::ReadFile(handle.get(), &value, size, &numberOfBytesRead, nullptr));
+ EXPECT_EQ(numberOfBytesRead, (DWORD)size);
+#else
+ EXPECT_EQ(read(handle.get(), &value, size), size);
+#endif
+ EXPECT_EQ(value, i);
+ }
+ Close();
+ return IPC_OK();
+ }
+
+ private:
+ ~TestManyHandlesChild() = default;
+};
+
+class TestManyHandlesParent : public PTestManyHandlesParent {
+ NS_INLINE_DECL_THREADSAFE_REFCOUNTING(TestManyHandlesParent, override)
+
+ private:
+ ~TestManyHandlesParent() = default;
+};
+
+IPDL_TEST(TestManyHandles) {
+ nsTArray<FileDescriptor> descrs;
+ for (int i = 0; i < 500; ++i) {
+ const int size = sizeof(i);
+ UniqueFileHandle readPipe;
+ UniqueFileHandle writePipe;
+#ifdef XP_WIN
+ ASSERT_TRUE(::CreatePipe(getter_Transfers(readPipe),
+ getter_Transfers(writePipe), nullptr, size));
+ DWORD numberOfBytesWritten;
+ ASSERT_TRUE(
+ ::WriteFile(writePipe.get(), &i, size, &numberOfBytesWritten, nullptr));
+ ASSERT_EQ(numberOfBytesWritten, (DWORD)size);
+#else
+ int fds[2];
+ ASSERT_EQ(pipe(fds), 0);
+ readPipe.reset(fds[0]);
+ writePipe.reset(fds[1]);
+ ASSERT_EQ(write(writePipe.get(), &i, size), size);
+#endif
+ descrs.AppendElement(FileDescriptor(std::move(readPipe)));
+ }
+ bool ok = mActor->SendManyHandles(descrs);
+ ASSERT_TRUE(ok);
+}
+
+} // namespace mozilla::_ipdltest
diff --git a/ipc/ipdl/test/gtest/moz.build b/ipc/ipdl/test/gtest/moz.build
new file mode 100644
index 0000000000..129e366a4b
--- /dev/null
+++ b/ipc/ipdl/test/gtest/moz.build
@@ -0,0 +1,35 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+Library("ipdltest")
+
+EXPORTS.mozilla._ipdltest += [
+ "IPDLUnitTest.h",
+ "IPDLUnitTestChild.h",
+ "IPDLUnitTestParent.h",
+ "TestBasicChild.h",
+ "TestBasicParent.h",
+]
+
+SOURCES += [
+ "IPDLUnitTest.cpp",
+ "TestBasic.cpp",
+ "TestCrossProcessSemaphore.cpp",
+ "TestInduceConnectionError.cpp",
+ "TestManyHandles.cpp",
+]
+
+IPDL_SOURCES += [
+ "PIPDLUnitTest.ipdl",
+ "PTestBasic.ipdl",
+ "PTestCrossProcessSemaphore.ipdl",
+ "PTestInduceConnectionError.ipdl",
+ "PTestManyHandles.ipdl",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul-gtest"
diff --git a/ipc/ipdl/test/ipdl/IPDLCompile.py b/ipc/ipdl/test/ipdl/IPDLCompile.py
new file mode 100644
index 0000000000..bfaf7860d6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/IPDLCompile.py
@@ -0,0 +1,78 @@
+import copy
+import os
+import re
+import subprocess
+import tempfile
+
+# We test the compiler indirectly, rather than reaching into the ipdl/
+# module, to make the testing framework as general as possible.
+
+
+class IPDLCompile:
+ def __init__(self, specfilename, ipdlargv=["python", "ipdl.py"]):
+ self.argv = copy.deepcopy(ipdlargv)
+ self.specfilename = specfilename
+ self.stdout = None
+ self.stderr = None
+ self.returncode = None
+
+ def run(self):
+ """Run |self.specfilename| through the IPDL compiler."""
+ assert self.returncode is None
+
+ tmpoutdir = tempfile.mkdtemp(prefix="ipdl_unit_test")
+
+ try:
+ self.argv.extend(["-d", tmpoutdir, self.specfilename])
+
+ proc = subprocess.Popen(
+ args=self.argv,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ universal_newlines=True,
+ )
+ self.stdout, self.stderr = proc.communicate()
+
+ self.returncode = proc.returncode
+ assert self.returncode is not None
+
+ finally:
+ for root, dirs, files in os.walk(tmpoutdir, topdown=0):
+ for name in files:
+ os.remove(os.path.join(root, name))
+ for name in dirs:
+ os.rmdir(os.path.join(root, name))
+ os.rmdir(tmpoutdir)
+
+ if proc.returncode is None:
+ proc.kill()
+
+ def completed(self):
+ return (
+ self.returncode is not None
+ and isinstance(self.stdout, str)
+ and isinstance(self.stderr, str)
+ )
+
+ def error(self, expectedError):
+ """Return True iff compiling self.specstring resulted in an
+ IPDL compiler error."""
+ assert self.completed()
+
+ errorRe = re.compile(re.escape(expectedError))
+ return None is not re.search(errorRe, self.stderr)
+
+ def exception(self):
+ """Return True iff compiling self.specstring resulted in a Python
+ exception being raised."""
+ assert self.completed()
+
+ return None is not re.search(r"Traceback (most recent call last):", self.stderr)
+
+ def ok(self):
+ """Return True iff compiling self.specstring was successful."""
+ assert self.completed()
+
+ return (
+ not self.exception() and not self.error("error:") and (0 == self.returncode)
+ )
diff --git a/ipc/ipdl/test/ipdl/Makefile.in b/ipc/ipdl/test/ipdl/Makefile.in
new file mode 100644
index 0000000000..67f241775b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/Makefile.in
@@ -0,0 +1,17 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+include $(topsrcdir)/config/rules.mk
+
+OKTESTS := $(wildcard $(srcdir)/ok/*.ipdl) $(wildcard $(srcdir)/ok/*.ipdlh)
+ERRORTESTS := $(wildcard $(srcdir)/error/*.ipdl) $(wildcard $(srcdir)/error/*.ipdlh)
+
+check::
+ @$(PYTHON3) $(srcdir)/runtests.py \
+ $(srcdir)/ok $(srcdir)/error \
+ $(PYTHON3) $(topsrcdir)/ipc/ipdl/ipdl.py \
+ --sync-msg-list=$(srcdir)/sync-messages.ini \
+ --msg-metadata=$(srcdir)/message-metadata.ini \
+ OKTESTS $(OKTESTS) \
+ ERRORTESTS $(ERRORTESTS)
diff --git a/ipc/ipdl/test/ipdl/error/AsyncCtorReturns.ipdl b/ipc/ipdl/test/ipdl/error/AsyncCtorReturns.ipdl
new file mode 100644
index 0000000000..8295a1c9a7
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/AsyncCtorReturns.ipdl
@@ -0,0 +1,11 @@
+//error: asynchronous ctor/dtor message `AsyncCtorReturnsManageeConstructor' declares return values
+
+include protocol AsyncCtorReturnsManagee;
+
+[ChildProc=any]
+protocol AsyncCtorReturns {
+ manages AsyncCtorReturnsManagee;
+
+child:
+ async AsyncCtorReturnsManagee() returns (bool unused);
+};
diff --git a/ipc/ipdl/test/ipdl/error/AsyncCtorReturnsManagee.ipdl b/ipc/ipdl/test/ipdl/error/AsyncCtorReturnsManagee.ipdl
new file mode 100644
index 0000000000..46aeb6e9fd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/AsyncCtorReturnsManagee.ipdl
@@ -0,0 +1,11 @@
+//error: asynchronous ctor/dtor message `AsyncCtorReturnsManageeConstructor' declares return values
+
+include protocol AsyncCtorReturns;
+
+[ChildProc=any]
+protocol AsyncCtorReturnsManagee {
+ manager AsyncCtorReturns;
+
+parent:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/AsyncInsideSync.ipdl b/ipc/ipdl/test/ipdl/error/AsyncInsideSync.ipdl
new file mode 100644
index 0000000000..104ced1c72
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/AsyncInsideSync.ipdl
@@ -0,0 +1,10 @@
+// inside_sync nested messages must be sync
+
+//error: inside_sync nested messages must be sync (here, message `Msg' in protocol `AsyncInsideSync')
+//error: message `Msg' requires more powerful send semantics than its protocol `AsyncInsideSync' provides
+
+[ChildProc=any]
+protocol AsyncInsideSync {
+child:
+ [Nested=inside_sync] async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrBadValue.ipdlh b/ipc/ipdl/test/ipdl/error/ExtendedAttrBadValue.ipdlh
new file mode 100644
index 0000000000..880bf54179
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrBadValue.ipdlh
@@ -0,0 +1,5 @@
+//error: unexpected value for valueless attribute `RefCounted'
+
+[RefCounted=Invalid] using SomeType from "SomeFile.h";
+
+struct ExtendedAttrBadValue {}; \ No newline at end of file
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrEmpty.ipdlh b/ipc/ipdl/test/ipdl/error/ExtendedAttrEmpty.ipdlh
new file mode 100644
index 0000000000..625bedc58a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrEmpty.ipdlh
@@ -0,0 +1,5 @@
+//error: bad syntax near `]'
+
+[ ] using SomeType from "SomeFile.h";
+
+struct ExtendedAttrEmpty {};
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidNestedValue.ipdl b/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidNestedValue.ipdl
new file mode 100644
index 0000000000..64899286db
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidNestedValue.ipdl
@@ -0,0 +1,7 @@
+//error: invalid value for attribute `Nested', expected one of: not, inside_sync, inside_cpow
+
+[ChildProc=any]
+protocol ExtendedAttrInvalidNestedValue {
+child:
+ [Nested=invalid] async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidPriorityValue.ipdl b/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidPriorityValue.ipdl
new file mode 100644
index 0000000000..51f21f0458
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrInvalidPriorityValue.ipdl
@@ -0,0 +1,7 @@
+//error: invalid value for attribute `Priority', expected one of: normal, input, vsync, mediumhigh, control
+
+[ChildProc=any]
+protocol ExtendedAttrInvalidPriorityValue {
+child:
+ [Priority=invalid] async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrRepeated.ipdlh b/ipc/ipdl/test/ipdl/error/ExtendedAttrRepeated.ipdlh
new file mode 100644
index 0000000000..33defc8ca4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrRepeated.ipdlh
@@ -0,0 +1,5 @@
+//error: Repeated extended attribute `RefCounted'
+
+[RefCounted, RefCounted] using SomeType from "SomeFile.h";
+
+struct ExtendedAttrRepeated {};
diff --git a/ipc/ipdl/test/ipdl/error/ExtendedAttrUnknown.ipdlh b/ipc/ipdl/test/ipdl/error/ExtendedAttrUnknown.ipdlh
new file mode 100644
index 0000000000..c41e91008f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ExtendedAttrUnknown.ipdlh
@@ -0,0 +1,5 @@
+//error: unknown attribute `InvalidAttribute'
+
+[InvalidAttribute] using SomeType from "SomeFile.h";
+
+struct ExtendedAttrUnknown {};
diff --git a/ipc/ipdl/test/ipdl/error/ForgottenManagee.ipdl b/ipc/ipdl/test/ipdl/error/ForgottenManagee.ipdl
new file mode 100644
index 0000000000..35f6f02e4d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ForgottenManagee.ipdl
@@ -0,0 +1,12 @@
+//error: |manager| declaration in protocol `ForgottenManagee' does not match any |manages| declaration in protocol `ManagerForgot'
+
+include protocol ManagerForgot;
+
+// This protocol says ManagerForgot manages it,
+// but ManagerForgot does not manage it.
+
+protocol ForgottenManagee {
+ manager ManagerForgot;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ForgottenManager.ipdl b/ipc/ipdl/test/ipdl/error/ForgottenManager.ipdl
new file mode 100644
index 0000000000..f2c524056a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ForgottenManager.ipdl
@@ -0,0 +1,12 @@
+//error: |manages| declaration in protocol `ForgottenManager' does not match any |manager| declaration in protocol `ManageeForgot'
+
+include protocol ManageeForgot;
+
+// ManageeForgot should have this protocol as its manager.
+
+[ChildProc=any]
+protocol ForgottenManager {
+ manages ManageeForgot;
+child:
+ async ManageeForgot();
+};
diff --git a/ipc/ipdl/test/ipdl/error/InsideCpowToChild.ipdl b/ipc/ipdl/test/ipdl/error/InsideCpowToChild.ipdl
new file mode 100644
index 0000000000..054964a817
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/InsideCpowToChild.ipdl
@@ -0,0 +1,10 @@
+// inside_cpow nested parent-to-child messages are verboten
+
+//error: inside_cpow nested parent-to-child messages are verboten (here, message `Msg' in protocol `InsideCpowToChild')
+//error: message `Msg' requires more powerful send semantics than its protocol `InsideCpowToChild' provides
+
+[ChildProc=any]
+protocol InsideCpowToChild {
+child:
+ [Nested=inside_cpow] sync Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/IntrAsyncManagee.ipdl b/ipc/ipdl/test/ipdl/error/IntrAsyncManagee.ipdl
new file mode 100644
index 0000000000..527c007ec4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/IntrAsyncManagee.ipdl
@@ -0,0 +1,9 @@
+//error: protocol `IntrAsyncManagee' requires more powerful send semantics than its manager `IntrAsyncManager' provides
+
+include protocol IntrAsyncManager;
+
+intr protocol IntrAsyncManagee {
+ manager IntrAsyncManager;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/IntrAsyncManager.ipdl b/ipc/ipdl/test/ipdl/error/IntrAsyncManager.ipdl
new file mode 100644
index 0000000000..dc5768df28
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/IntrAsyncManager.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `IntrAsyncManagee' requires more powerful send semantics than its manager `IntrAsyncManager' provides
+
+include protocol IntrAsyncManagee;
+
+[ChildProc=any]
+async protocol IntrAsyncManager {
+ manages IntrAsyncManagee;
+parent:
+ async IntrAsyncManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/error/IntrSyncManagee.ipdl b/ipc/ipdl/test/ipdl/error/IntrSyncManagee.ipdl
new file mode 100644
index 0000000000..d0b1462e86
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/IntrSyncManagee.ipdl
@@ -0,0 +1,9 @@
+//error: protocol `IntrSyncManagee' requires more powerful send semantics than its manager `IntrSyncManager' provides
+
+include protocol IntrSyncManager;
+
+intr protocol IntrSyncManagee {
+ manager IntrSyncManager;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/IntrSyncManager.ipdl b/ipc/ipdl/test/ipdl/error/IntrSyncManager.ipdl
new file mode 100644
index 0000000000..f8e762093c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/IntrSyncManager.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `IntrSyncManagee' requires more powerful send semantics than its manager `IntrSyncManager' provides
+
+include protocol IntrSyncManagee;
+
+[ChildProc=any]
+sync protocol IntrSyncManager {
+ manages IntrSyncManagee;
+parent:
+ async IntrSyncManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ManageeForgot.ipdl b/ipc/ipdl/test/ipdl/error/ManageeForgot.ipdl
new file mode 100644
index 0000000000..9e11fe49fd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ManageeForgot.ipdl
@@ -0,0 +1,12 @@
+//error: |manages| declaration in protocol `ForgottenManager' does not match any |manager| declaration in protocol `ManageeForgot'
+
+include protocol ForgottenManager;
+
+// See ForgottenManager. This includes ForgottenManager to ensure that
+// loading this file fails.
+
+[ChildProc=any]
+protocol ManageeForgot {
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ManagerForgot.ipdl b/ipc/ipdl/test/ipdl/error/ManagerForgot.ipdl
new file mode 100644
index 0000000000..ae87534fb9
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ManagerForgot.ipdl
@@ -0,0 +1,12 @@
+//error: |manager| declaration in protocol `ForgottenManagee' does not match any |manages| declaration in protocol `ManagerForgot'
+
+include protocol ForgottenManagee;
+
+// See ForgottenManagee.ipdl. This includes ForgottenManagee to
+// ensure that loading this file fails.
+
+[ChildProc=any]
+protocol ManagerForgot {
+child:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/Nullable.ipdl b/ipc/ipdl/test/ipdl/error/Nullable.ipdl
new file mode 100644
index 0000000000..c5257accbb
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/Nullable.ipdl
@@ -0,0 +1,7 @@
+//error: `nullable' qualifier for type `int' is unsupported
+
+[ChildProc=any]
+protocol PNullable {
+child:
+ async Msg(nullable int i);
+};
diff --git a/ipc/ipdl/test/ipdl/error/Nullable2.ipdl b/ipc/ipdl/test/ipdl/error/Nullable2.ipdl
new file mode 100644
index 0000000000..3dcd66a321
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/Nullable2.ipdl
@@ -0,0 +1,11 @@
+//error: `nullable' qualifier for type `int' is unsupported
+
+union Union {
+ nullable int;
+};
+
+[ChildProc=any]
+protocol Nullable2 {
+child:
+ async Msg(Union i);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PBadArrayBase.ipdl b/ipc/ipdl/test/ipdl/error/PBadArrayBase.ipdl
new file mode 100644
index 0000000000..3d791761c2
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PBadArrayBase.ipdl
@@ -0,0 +1,8 @@
+//error: argument typename `X' of message `Test' has not been declared
+
+[ChildProc=any]
+protocol PBadArrayBase {
+child:
+ async Test(X[] x);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PBadNestedManagee.ipdl b/ipc/ipdl/test/ipdl/error/PBadNestedManagee.ipdl
new file mode 100644
index 0000000000..3fda366674
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PBadNestedManagee.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `PBadNestedManagee' requires more powerful send semantics than its manager `PBadNestedManager' provides
+
+include protocol PBadNestedManager;
+
+[NestedUpTo=inside_sync, ChildProc=any]
+async protocol PBadNestedManagee {
+ manager PBadNestedManager;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PBadNestedManager.ipdl b/ipc/ipdl/test/ipdl/error/PBadNestedManager.ipdl
new file mode 100644
index 0000000000..b395da2f30
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PBadNestedManager.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `PBadNestedManagee' requires more powerful send semantics than its manager `PBadNestedManager' provides
+
+include protocol PBadNestedManagee;
+
+[NestedUpTo=not, ChildProc=any]
+async protocol PBadNestedManager {
+ manages PBadNestedManagee;
+parent:
+ async PBadNestedManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PBadSideImpl.ipdl b/ipc/ipdl/test/ipdl/error/PBadSideImpl.ipdl
new file mode 100644
index 0000000000..787bba1d04
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PBadSideImpl.ipdl
@@ -0,0 +1,8 @@
+//error: invalid value for attribute `ParentImpl', expected one of: virtual, StringLiteral
+//error: invalid value for attribute `ChildImpl', expected one of: virtual, StringLiteral
+
+[ParentImpl=NotQuoted, ChildImpl, ChildProc=any]
+async protocol PBadSideImpl {
+ parent:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PBadUniquePtrBase.ipdl b/ipc/ipdl/test/ipdl/error/PBadUniquePtrBase.ipdl
new file mode 100644
index 0000000000..8058fb5334
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PBadUniquePtrBase.ipdl
@@ -0,0 +1,8 @@
+//error: argument typename `UndeclaredType' of message `Test' has not been declared
+
+[ChildProc=any]
+protocol PBadUniquePtrBase {
+child:
+ async Test(UniquePtr<UndeclaredType> x);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PCompressInvalid.ipdl b/ipc/ipdl/test/ipdl/error/PCompressInvalid.ipdl
new file mode 100644
index 0000000000..bc81e4544b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PCompressInvalid.ipdl
@@ -0,0 +1,9 @@
+//error: invalid value for attribute `Compress', expected one of: None, all
+
+include protocol compressCtor;
+
+[ChildProc=any]
+async protocol PCompressInvalid {
+child:
+ [Compress=Invalid] async Message();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PDouble.ipdl b/ipc/ipdl/test/ipdl/error/PDouble.ipdl
new file mode 100644
index 0000000000..a6c6dd3a8d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PDouble.ipdl
@@ -0,0 +1,12 @@
+//error: Trying to load `PDouble' from a file when we'd already seen it in file
+
+// This will load extra/PDouble.ipdl because extra/ is earlier
+// in the list of include directories than the current working
+// directory. Loading the same protocol from two files is
+// obviously bad.
+include protocol PDouble;
+
+[ChildProc=any]
+protocol PDouble {
+child: async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PExtendedAttrInvalidValue.ipdl b/ipc/ipdl/test/ipdl/error/PExtendedAttrInvalidValue.ipdl
new file mode 100644
index 0000000000..796f25d8c2
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PExtendedAttrInvalidValue.ipdl
@@ -0,0 +1,7 @@
+//error: invalid value for attribute `NestedUpTo', expected one of: not, inside_sync, inside_cpow
+
+[NestedUpTo=invalid, ChildProc=any]
+async protocol PExtendedAttrInvalidValue {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PExtendedAttrRepeated.ipdl b/ipc/ipdl/test/ipdl/error/PExtendedAttrRepeated.ipdl
new file mode 100644
index 0000000000..c15dbce788
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PExtendedAttrRepeated.ipdl
@@ -0,0 +1,7 @@
+//error: Repeated extended attribute `RefCounted'
+
+[RefCounted, RefCounted, ChildProc=any]
+async protocol PExtendedAttrRepeated {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PExtendedAttrUnexpectedValue.ipdl b/ipc/ipdl/test/ipdl/error/PExtendedAttrUnexpectedValue.ipdl
new file mode 100644
index 0000000000..dcc7b043c5
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PExtendedAttrUnexpectedValue.ipdl
@@ -0,0 +1,7 @@
+//error: unexpected value for valueless attribute `ManualDealloc'
+
+[ManualDealloc=invalid, ChildProc=any]
+async protocol PExtendedAttrUnexpectedValue {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PExtendedAttrUnknownAttribute.ipdl b/ipc/ipdl/test/ipdl/error/PExtendedAttrUnknownAttribute.ipdl
new file mode 100644
index 0000000000..193c1d6608
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PExtendedAttrUnknownAttribute.ipdl
@@ -0,0 +1,7 @@
+//error: unknown attribute `InvalidAttr'
+
+[InvalidAttr, ChildProc=any]
+async protocol PExtendedAttrUnknownValue {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PInconsistentMoveOnly.ipdl b/ipc/ipdl/test/ipdl/error/PInconsistentMoveOnly.ipdl
new file mode 100644
index 0000000000..9968b3b2ab
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PInconsistentMoveOnly.ipdl
@@ -0,0 +1,14 @@
+//error: inconsistent moveonly status of type `::mozilla::ipc::SomeMoveonlyType`
+//error: inconsistent moveonly status of type `::mozilla::ipc::SomeMoveonlySendType`
+
+[MoveOnly] using class mozilla::ipc::SomeMoveonlyType from "SomeFile.h";
+using class mozilla::ipc::SomeMoveonlyType from "SomeFile.h";
+
+[MoveOnly=send] using class mozilla::ipc::SomeMoveonlySendType from "SomeFile.h";
+[MoveOnly=data] using class mozilla::ipc::SomeMoveonlySendType from "SomeFile.h";
+
+[ChildProc=any]
+protocol PInconsistentMoveOnly {
+child:
+ async SomeMessage();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PIntrNested.ipdl b/ipc/ipdl/test/ipdl/error/PIntrNested.ipdl
new file mode 100644
index 0000000000..c487bcd49d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PIntrNested.ipdl
@@ -0,0 +1,7 @@
+//error: intr message `Msg' cannot specify [Nested]
+
+[ChildProc=any]
+intr protocol PIntrNested {
+child:
+ [Nested=inside_sync, LegacyIntr] intr Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PIntrNestedProtocol.ipdl b/ipc/ipdl/test/ipdl/error/PIntrNestedProtocol.ipdl
new file mode 100644
index 0000000000..dd95a7c002
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PIntrNestedProtocol.ipdl
@@ -0,0 +1,7 @@
+//error: intr protocol `PIntrNestedProtocol' cannot specify [NestedUpTo]
+
+[NestedUpTo=inside_sync, ChildProc=any]
+intr protocol PIntrNestedProtocol {
+child:
+ [LegacyIntr] intr Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PIntrPriority.ipdl b/ipc/ipdl/test/ipdl/error/PIntrPriority.ipdl
new file mode 100644
index 0000000000..c8bf75e9a3
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PIntrPriority.ipdl
@@ -0,0 +1,7 @@
+//error: intr message `Msg' cannot specify [Priority]
+
+[ChildProc=any]
+intr protocol PIntrPriority {
+child:
+ [Priority=vsync, LegacyIntr] intr Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PLazySendInvalid.ipdl b/ipc/ipdl/test/ipdl/error/PLazySendInvalid.ipdl
new file mode 100644
index 0000000000..b34f686132
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PLazySendInvalid.ipdl
@@ -0,0 +1,7 @@
+//error: unexpected value for valueless attribute `LazySend'
+
+[ChildProc=any]
+async protocol PLazySendInvalid {
+child:
+ [LazySend=Invalid] async Message();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PLazySendSync.ipdl b/ipc/ipdl/test/ipdl/error/PLazySendSync.ipdl
new file mode 100644
index 0000000000..76e9e60fb9
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PLazySendSync.ipdl
@@ -0,0 +1,7 @@
+//error: non-async message `Message' cannot specify [LazySend]
+
+[ChildProc=any]
+sync protocol PLazySendSync {
+child:
+ [LazySend] sync Message() returns (bool ok);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PManagerManualDealloc.ipdl b/ipc/ipdl/test/ipdl/error/PManagerManualDealloc.ipdl
new file mode 100644
index 0000000000..91ff4f4769
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PManagerManualDealloc.ipdl
@@ -0,0 +1,13 @@
+//error: [ManualDealloc] protocols cannot be managers
+
+include protocol PManagerManualDeallocTop;
+include protocol PManagerManualDeallocManaged;
+
+[ManualDealloc]
+async protocol PManagerManualDealloc {
+ manager PManagerManualDeallocTop;
+ manages PManagerManualDeallocManaged;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PMissingProc.ipdl b/ipc/ipdl/test/ipdl/error/PMissingProc.ipdl
new file mode 100644
index 0000000000..b4d32e55ac
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PMissingProc.ipdl
@@ -0,0 +1,6 @@
+//error: Toplevel protocols must specify [ChildProc]
+
+protocol PMissingProc {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PNoTaintWithoutTainted.ipdl b/ipc/ipdl/test/ipdl/error/PNoTaintWithoutTainted.ipdl
new file mode 100644
index 0000000000..b196050c48
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PNoTaintWithoutTainted.ipdl
@@ -0,0 +1,7 @@
+//error: argument typename `int' of message `foo' has a NoTaint attribute, but the message lacks the Tainted attribute
+
+[ChildProc=any]
+intr protocol PNoTaintWithoutTainted {
+child:
+ async foo([NoTaint=passback] int id);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PToplevelManualDealloc.ipdl b/ipc/ipdl/test/ipdl/error/PToplevelManualDealloc.ipdl
new file mode 100644
index 0000000000..1936fda2bb
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PToplevelManualDealloc.ipdl
@@ -0,0 +1,7 @@
+//error: Toplevel protocols cannot be [ManualDealloc]
+
+[ManualDealloc, ChildProc=any]
+async protocol PToplevelManualDealloc {
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PUniquePtrRecursive.ipdl b/ipc/ipdl/test/ipdl/error/PUniquePtrRecursive.ipdl
new file mode 100644
index 0000000000..98992f700e
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PUniquePtrRecursive.ipdl
@@ -0,0 +1,6 @@
+//error: bad syntax near `UniquePtr'
+
+[ChildProc=any]
+protocol PUniquePtrRecursive {
+child: async Msg( UniquePtr< UniquePtr<int> > aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecStruct.ipdl b/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecStruct.ipdl
new file mode 100644
index 0000000000..a0fb3b91c0
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecStruct.ipdl
@@ -0,0 +1,10 @@
+//error: struct `X' is only partially defined
+
+struct X {
+ UniquePtr<X> x;
+};
+
+[ChildProc=any]
+protocol PUniquePtrSelfRecStruct {
+child: async Msg(UniquePtr<X> aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecUnion.ipdl b/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecUnion.ipdl
new file mode 100644
index 0000000000..396ffef0e2
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PUniquePtrSelfRecUnion.ipdl
@@ -0,0 +1,8 @@
+//error: union `X' is only partially defined
+
+union X { UniquePtr<X>; };
+
+[ChildProc=any]
+protocol PUniquePtrSelfRecUnion {
+child: async Msg(UniquePtr<X> aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/PUnknownProc.ipdl b/ipc/ipdl/test/ipdl/error/PUnknownProc.ipdl
new file mode 100644
index 0000000000..0ec4e3f3c7
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PUnknownProc.ipdl
@@ -0,0 +1,7 @@
+//error: invalid value for attribute `ChildProc', expected one of: any, anychild, anydom, compositor, Parent, Content, IPDLUnitTest, GMPlugin, GPU, VR, RDD, Socket, RemoteSandboxBroker, ForkServer, Utility
+
+[ChildProc=unknowntype]
+protocol PUnknownProc {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/PasyncMessageListed.ipdl b/ipc/ipdl/test/ipdl/error/PasyncMessageListed.ipdl
new file mode 100644
index 0000000000..18d6e85ea4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/PasyncMessageListed.ipdl
@@ -0,0 +1,7 @@
+//error: IPC message PasyncMessageListed::Msg is async, can be delisted
+
+[ChildProc=any]
+protocol PasyncMessageListed {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/ReplyPrioWithoutReturns.ipdl b/ipc/ipdl/test/ipdl/error/ReplyPrioWithoutReturns.ipdl
new file mode 100644
index 0000000000..be499f6d4c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/ReplyPrioWithoutReturns.ipdl
@@ -0,0 +1,8 @@
+//error: non-returns message `NormalPrio' cannot specify [ReplyPriority]
+
+[ChildProc=any]
+async protocol ReplyPrioWithoutReturns
+{
+child:
+ [ReplyPriority=normal] async NormalPrio();
+};
diff --git a/ipc/ipdl/test/ipdl/error/SyncAsyncManagee.ipdl b/ipc/ipdl/test/ipdl/error/SyncAsyncManagee.ipdl
new file mode 100644
index 0000000000..e011e90d79
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/SyncAsyncManagee.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `SyncAsyncManagee' requires more powerful send semantics than its manager `SyncAsyncManager' provides
+
+include protocol SyncAsyncManager;
+
+[ChildProc=any]
+sync protocol SyncAsyncManagee {
+ manager SyncAsyncManager;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/SyncAsyncManager.ipdl b/ipc/ipdl/test/ipdl/error/SyncAsyncManager.ipdl
new file mode 100644
index 0000000000..f189df1cbd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/SyncAsyncManager.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `SyncAsyncManagee' requires more powerful send semantics than its manager `SyncAsyncManager' provides
+
+include protocol SyncAsyncManagee;
+
+[ChildProc=any]
+async protocol SyncAsyncManager {
+ manages SyncAsyncManagee;
+parent:
+ async SyncAsyncManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/error/SyncPrio.ipdl b/ipc/ipdl/test/ipdl/error/SyncPrio.ipdl
new file mode 100644
index 0000000000..73c0cdfd44
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/SyncPrio.ipdl
@@ -0,0 +1,8 @@
+//error: non-async message `NormalPrio' cannot specify [ReplyPriority]
+
+[ChildProc=any]
+sync protocol SyncPrio
+{
+child:
+ [ReplyPriority=normal] sync NormalPrio() returns (bool aValue);
+};
diff --git a/ipc/ipdl/test/ipdl/error/array_Recursive.ipdl b/ipc/ipdl/test/ipdl/error/array_Recursive.ipdl
new file mode 100644
index 0000000000..d89d4b3cad
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/array_Recursive.ipdl
@@ -0,0 +1,6 @@
+//error: bad syntax near `['
+
+[ChildProc=any]
+protocol array_Recursive {
+child: async Msg(int[][] aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/badProtocolInclude.ipdl b/ipc/ipdl/test/ipdl/error/badProtocolInclude.ipdl
new file mode 100644
index 0000000000..4ff6db2659
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/badProtocolInclude.ipdl
@@ -0,0 +1,10 @@
+//error: can't locate include file `IDONTEXIST.ipdl'
+
+include protocol IDONTEXIST;
+
+// error: nonexistent protocol ^^^
+
+[ChildProc=any]
+protocol badProtocolInclude {
+child: async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/compressCtor.ipdl b/ipc/ipdl/test/ipdl/error/compressCtor.ipdl
new file mode 100644
index 0000000000..93c300333d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/compressCtor.ipdl
@@ -0,0 +1,12 @@
+//error: destructor messages can't use compression (here, in protocol `compressCtorManagee')
+//error: constructor messages can't use compression (here, in protocol `compressCtor')
+
+include protocol compressCtorManagee;
+
+[ChildProc=any]
+intr protocol compressCtor {
+ manages compressCtorManagee;
+
+parent:
+ [Compress] async compressCtorManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/error/compressCtorManagee.ipdl b/ipc/ipdl/test/ipdl/error/compressCtorManagee.ipdl
new file mode 100644
index 0000000000..52ec2cc1cd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/compressCtorManagee.ipdl
@@ -0,0 +1,11 @@
+//error: constructor messages can't use compression (here, in protocol `compressCtor')
+//error: destructor messages can't use compression (here, in protocol `compressCtorManagee')
+
+include protocol compressCtor;
+
+intr protocol compressCtorManagee {
+ manager compressCtor;
+
+child:
+ [Compress] async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/conflictProtocolMsg.ipdl b/ipc/ipdl/test/ipdl/error/conflictProtocolMsg.ipdl
new file mode 100644
index 0000000000..4756e0c032
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/conflictProtocolMsg.ipdl
@@ -0,0 +1,10 @@
+//error: ctor for protocol `conflictProtocolMsg', which is not managed by protocol `conflictProtocolMsg'
+
+[ChildProc=any]
+protocol conflictProtocolMsg {
+
+ // it's an error to re-use the protocol name as a message ID; these
+ // are reserved
+child: async conflictProtocolMsg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/cyclecheck_Child.ipdl b/ipc/ipdl/test/ipdl/error/cyclecheck_Child.ipdl
new file mode 100644
index 0000000000..dd27586d8b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/cyclecheck_Child.ipdl
@@ -0,0 +1,15 @@
+//error: cycle(s) detected in manager/manages hierarchy: `cyclecheck_Parent -> cyclecheck_Child -> cyclecheck_Grandchild -> cyclecheck_Parent'
+//error: |manages| declaration in protocol `cyclecheck_Grandchild' does not match any |manager| declaration in protocol `cyclecheck_Parent'
+
+include protocol cyclecheck_Parent;
+include protocol cyclecheck_Grandchild;
+
+protocol cyclecheck_Child {
+ manager cyclecheck_Parent;
+ manages cyclecheck_Grandchild;
+
+child:
+ async cyclecheck_Grandchild();
+ async __delete__();
+};
+
diff --git a/ipc/ipdl/test/ipdl/error/cyclecheck_Grandchild.ipdl b/ipc/ipdl/test/ipdl/error/cyclecheck_Grandchild.ipdl
new file mode 100644
index 0000000000..9152a56a16
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/cyclecheck_Grandchild.ipdl
@@ -0,0 +1,15 @@
+//error: cycle(s) detected in manager/manages hierarchy: `cyclecheck_Parent -> cyclecheck_Child -> cyclecheck_Grandchild -> cyclecheck_Parent'
+//error: |manages| declaration in protocol `cyclecheck_Grandchild' does not match any |manager| declaration in protocol `cyclecheck_Parent'
+
+include protocol cyclecheck_Child;
+include protocol cyclecheck_Parent;
+
+protocol cyclecheck_Grandchild {
+ manager cyclecheck_Child;
+ manages cyclecheck_Parent;
+
+child:
+ async cyclecheck_Parent();
+ async __delete__();
+};
+
diff --git a/ipc/ipdl/test/ipdl/error/cyclecheck_Parent.ipdl b/ipc/ipdl/test/ipdl/error/cyclecheck_Parent.ipdl
new file mode 100644
index 0000000000..7b3a135518
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/cyclecheck_Parent.ipdl
@@ -0,0 +1,13 @@
+//error: cycle(s) detected in manager/manages hierarchy: `cyclecheck_Parent -> cyclecheck_Child -> cyclecheck_Grandchild -> cyclecheck_Parent'
+
+include protocol cyclecheck_Child;
+
+[ChildProc=any]
+protocol cyclecheck_Parent {
+ manages cyclecheck_Child;
+
+child:
+ async cyclecheck_Child();
+ async __delete__();
+};
+
diff --git a/ipc/ipdl/test/ipdl/error/dtorReserved.ipdl b/ipc/ipdl/test/ipdl/error/dtorReserved.ipdl
new file mode 100644
index 0000000000..ac5d37c7b6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/dtorReserved.ipdl
@@ -0,0 +1,11 @@
+//error: lexically invalid characters `~SomeMsg();
+
+[ChildProc=any]
+protocol dtorReserved {
+
+ // it's an error to use old-style dtor syntax
+
+child:
+ ~SomeMsg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/empty.ipdl b/ipc/ipdl/test/ipdl/error/empty.ipdl
new file mode 100644
index 0000000000..c6249c280b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/empty.ipdl
@@ -0,0 +1 @@
+//error: bad syntax near `???' \ No newline at end of file
diff --git a/ipc/ipdl/test/ipdl/error/extra/PDouble.ipdl b/ipc/ipdl/test/ipdl/error/extra/PDouble.ipdl
new file mode 100644
index 0000000000..2efae8fff4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/extra/PDouble.ipdl
@@ -0,0 +1,5 @@
+// This is a valid file.
+
+protocol PDouble {
+child: async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocManaged.ipdl b/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocManaged.ipdl
new file mode 100644
index 0000000000..65cddccf67
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocManaged.ipdl
@@ -0,0 +1,9 @@
+include protocol PManagerManualDealloc;
+
+[ManualDealloc]
+async protocol PManagerManualDeallocManaged {
+ manager PManagerManualDealloc;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocTop.ipdl b/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocTop.ipdl
new file mode 100644
index 0000000000..38eb7511f5
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/extra/PManagerManualDeallocTop.ipdl
@@ -0,0 +1,9 @@
+include protocol PManagerManualDealloc;
+
+[ChildProc=any]
+async protocol PManagerManualDeallocTop {
+ manager PManagerManualDealloc;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/inconsistentRC.ipdl b/ipc/ipdl/test/ipdl/error/inconsistentRC.ipdl
new file mode 100644
index 0000000000..a00bca66e4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/inconsistentRC.ipdl
@@ -0,0 +1,10 @@
+//error: inconsistent refcounted status of type `::mozilla::ipc::SomeRefcountedType`
+
+[RefCounted] using class mozilla::ipc::SomeRefcountedType from "SomeFile.h";
+using class mozilla::ipc::SomeRefcountedType from "SomeFile.h";
+
+[ChildProc=any]
+protocol inconsistentRC {
+child:
+ async SomeMessage();
+};
diff --git a/ipc/ipdl/test/ipdl/error/intrMessageCompress.ipdl b/ipc/ipdl/test/ipdl/error/intrMessageCompress.ipdl
new file mode 100644
index 0000000000..e56cfc5d8c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/intrMessageCompress.ipdl
@@ -0,0 +1,10 @@
+//error: message `foo' in protocol `intrMessageCompress' requests compression but is not async
+//error: message `bar' in protocol `intrMessageCompress' requests compression but is not async
+
+[ChildProc=any]
+intr protocol intrMessageCompress {
+parent:
+ [Compress, LegacyIntr] intr foo();
+child:
+ [Compress, LegacyIntr] intr bar();
+};
diff --git a/ipc/ipdl/test/ipdl/error/lex1.ipdl b/ipc/ipdl/test/ipdl/error/lex1.ipdl
new file mode 100644
index 0000000000..a00629cbca
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/lex1.ipdl
@@ -0,0 +1,2 @@
+//error: bad syntax near `slkdjfl'
+slkdjfl*&^*
diff --git a/ipc/ipdl/test/ipdl/error/manageSelfToplevel.ipdl b/ipc/ipdl/test/ipdl/error/manageSelfToplevel.ipdl
new file mode 100644
index 0000000000..4540c2c2f6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/manageSelfToplevel.ipdl
@@ -0,0 +1,10 @@
+//error: top-level protocol `manageSelfToplevel' cannot manage itself
+
+protocol manageSelfToplevel {
+ manager manageSelfToplevel;
+ manages manageSelfToplevel;
+
+child:
+ async manageSelfToplevel();
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/managedNoDtor.ipdl b/ipc/ipdl/test/ipdl/error/managedNoDtor.ipdl
new file mode 100644
index 0000000000..41bbd76689
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/managedNoDtor.ipdl
@@ -0,0 +1,7 @@
+//error: destructor declaration `__delete__(...)' required for managed protocol `managedNoDtor'
+include protocol managerNoDtor;
+
+protocol managedNoDtor {
+ manager managerNoDtor;
+ // empty
+};
diff --git a/ipc/ipdl/test/ipdl/error/managerNoDtor.ipdl b/ipc/ipdl/test/ipdl/error/managerNoDtor.ipdl
new file mode 100644
index 0000000000..0417cc5ace
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/managerNoDtor.ipdl
@@ -0,0 +1,11 @@
+//error: destructor declaration `__delete__(...)' required for managed protocol `managedNoDtor'
+
+include protocol managedNoDtor;
+
+protocol managerNoDtor {
+ manages managedNoDtor;
+
+parent:
+ async managedNoDtor();
+ // error: no ctor defined
+};
diff --git a/ipc/ipdl/test/ipdl/error/maybe_Recursive.ipdl b/ipc/ipdl/test/ipdl/error/maybe_Recursive.ipdl
new file mode 100644
index 0000000000..2f356b423a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/maybe_Recursive.ipdl
@@ -0,0 +1,6 @@
+//error: bad syntax near `?'
+
+[ChildProc=any]
+protocol maybe_Recursive {
+child: async Msg(int?? aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/maybe_SelfRecStruct.ipdl b/ipc/ipdl/test/ipdl/error/maybe_SelfRecStruct.ipdl
new file mode 100644
index 0000000000..9dff6a2152
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/maybe_SelfRecStruct.ipdl
@@ -0,0 +1,10 @@
+//error: struct `X' is only partially defined
+
+struct X {
+ X? x;
+};
+
+[ChildProc=any]
+protocol maybe_SelfRecStruct {
+child: async Msg(X? aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/maybe_SelfRecUnion.ipdl b/ipc/ipdl/test/ipdl/error/maybe_SelfRecUnion.ipdl
new file mode 100644
index 0000000000..b85497d9c1
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/maybe_SelfRecUnion.ipdl
@@ -0,0 +1,8 @@
+//error: union `X' is only partially defined
+
+union X { X?; };
+
+[ChildProc=any]
+protocol maybe_SelfRecUnion {
+child: async Msg(X? aa);
+};
diff --git a/ipc/ipdl/test/ipdl/error/messageNoDirection.ipdl b/ipc/ipdl/test/ipdl/error/messageNoDirection.ipdl
new file mode 100644
index 0000000000..5e889933cb
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/messageNoDirection.ipdl
@@ -0,0 +1,6 @@
+//error: missing message direction
+
+[ChildProc=any]
+protocol messageNoDirection {
+ async NoDirection();
+};
diff --git a/ipc/ipdl/test/ipdl/error/multimanDupMgrs.ipdl b/ipc/ipdl/test/ipdl/error/multimanDupMgrs.ipdl
new file mode 100644
index 0000000000..805a9f905e
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/multimanDupMgrs.ipdl
@@ -0,0 +1,10 @@
+//error: manager `multimanDupMgrsMgr' appears multiple times
+
+include protocol multimanDupMgrsMgr;
+
+protocol multimanDupMgrs {
+ manager multimanDupMgrsMgr or multimanDupMgrsMgr;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/multimanDupMgrsMgr.ipdl b/ipc/ipdl/test/ipdl/error/multimanDupMgrsMgr.ipdl
new file mode 100644
index 0000000000..76e838cc57
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/multimanDupMgrsMgr.ipdl
@@ -0,0 +1,12 @@
+//error: manager `multimanDupMgrsMgr' appears multiple times
+
+include protocol multimanDupMgrs;
+
+[ChildProc=any]
+protocol multimanDupMgrsMgr {
+ manages multimanDupMgrs;
+
+child:
+ async multimanDupMgrs();
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/multimanNonexistentMgrs.ipdl b/ipc/ipdl/test/ipdl/error/multimanNonexistentMgrs.ipdl
new file mode 100644
index 0000000000..24dafb8163
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/multimanNonexistentMgrs.ipdl
@@ -0,0 +1,10 @@
+//error: protocol `Starsky' referenced as |manager| of `multimanNonexistentMgrs' has not been declared
+//error: protocol `Hutch' referenced as |manager| of `multimanNonexistentMgrs' has not been declared
+
+protocol multimanNonexistentMgrs {
+ manager Starsky or Hutch;
+
+child:
+ async Dummy();
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/mutualRecStruct.ipdl b/ipc/ipdl/test/ipdl/error/mutualRecStruct.ipdl
new file mode 100644
index 0000000000..3224438e90
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/mutualRecStruct.ipdl
@@ -0,0 +1,25 @@
+//error: struct `X' is only partially defined
+//error: struct `Y' is only partially defined
+//error: struct `Z' is only partially defined
+
+struct X {
+ int i;
+ Y[] y;
+};
+
+struct Y {
+ X x;
+ Z z;
+};
+
+struct Z {
+ double d;
+ X x;
+};
+
+[ChildProc=any]
+protocol mutualRecStruct {
+child:
+ async Test(X x, Y y, Z z);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/mutualRecStructUnion.ipdl b/ipc/ipdl/test/ipdl/error/mutualRecStructUnion.ipdl
new file mode 100644
index 0000000000..65345642a5
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/mutualRecStructUnion.ipdl
@@ -0,0 +1,25 @@
+//error: struct `X' is only partially defined
+//error: union `Y' is only partially defined
+//error: struct `Z' is only partially defined
+
+struct X {
+ int i;
+ Y[] y;
+};
+
+union Y {
+ X;
+ Z;
+};
+
+struct Z {
+ double d;
+ X x;
+};
+
+[ChildProc=any]
+protocol mutualRecStructUnion {
+child:
+ async Test(X x, Y y, Z z);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/noProtocolInHeader.ipdlh b/ipc/ipdl/test/ipdl/error/noProtocolInHeader.ipdlh
new file mode 100644
index 0000000000..1997eb77d9
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/noProtocolInHeader.ipdlh
@@ -0,0 +1,7 @@
+//error: can't define a protocol in a header. Do it in a protocol spec instead.
+
+[ChildProc=any]
+protocol noProtocolInHeader {
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/oldIncludeSyntax.ipdl b/ipc/ipdl/test/ipdl/error/oldIncludeSyntax.ipdl
new file mode 100644
index 0000000000..6f90bc6d5f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/oldIncludeSyntax.ipdl
@@ -0,0 +1,8 @@
+//error: bad syntax near `"Foo.ipdl"'
+
+include protocol "Foo.ipdl";
+
+[ChildProc=any]
+protocol oldIncludeSyntax {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/parser.ipdl b/ipc/ipdl/test/ipdl/error/parser.ipdl
new file mode 100644
index 0000000000..8bfd63546a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/parser.ipdl
@@ -0,0 +1,3 @@
+//error: bad syntax near `???'
+
+protocol parser {
diff --git a/ipc/ipdl/test/ipdl/error/redeclMessage.ipdl b/ipc/ipdl/test/ipdl/error/redeclMessage.ipdl
new file mode 100644
index 0000000000..63a70d31a6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/redeclMessage.ipdl
@@ -0,0 +1,13 @@
+//error: message name `Msg' already declared as `MessageType'
+//error: redeclaration of symbol `Msg', first declared at
+
+[ChildProc=any]
+protocol redeclMessage {
+
+ // can't declare two messages with the same name
+
+child:
+ async Msg();
+ async Msg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/redeclParamReturn.ipdl b/ipc/ipdl/test/ipdl/error/redeclParamReturn.ipdl
new file mode 100644
index 0000000000..71a1532bb2
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/redeclParamReturn.ipdl
@@ -0,0 +1,10 @@
+//error: redeclaration of symbol `f', first declared at
+
+[ChildProc=any]
+sync protocol redeclParamReturn {
+
+ // it's an error to name a parameter with the same id as a return
+
+parent: async Msg(int f) returns (bool f);
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/redeclScope.ipdlh b/ipc/ipdl/test/ipdl/error/redeclScope.ipdlh
new file mode 100644
index 0000000000..a64439b599
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/redeclScope.ipdlh
@@ -0,0 +1,12 @@
+//error: redeclaration of symbol `Foo', first declared at
+
+struct Foo {
+ bool b;
+};
+
+struct Bar {
+ // This should produce an error saying that Foo is a redeclaration,
+ // even though the initial declaration was in a different frame of
+ // the symbol table.
+ bool Foo;
+};
diff --git a/ipc/ipdl/test/ipdl/error/shmem.ipdl b/ipc/ipdl/test/ipdl/error/shmem.ipdl
new file mode 100644
index 0000000000..4511ce65dd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/shmem.ipdl
@@ -0,0 +1,9 @@
+//error: redeclaration of symbol `Shmem', first declared at
+//error: redeclaration of symbol `::mozilla::ipc::Shmem', first declared at
+
+using class mozilla::ipc::Shmem from "mozilla/ipc/Shmem.h"; // redeclaration
+
+[ChildProc=any]
+protocol shmem {
+child: async Msg(Shmem s);
+};
diff --git a/ipc/ipdl/test/ipdl/error/structRedecl.ipdl b/ipc/ipdl/test/ipdl/error/structRedecl.ipdl
new file mode 100644
index 0000000000..37d87d6627
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/structRedecl.ipdl
@@ -0,0 +1,11 @@
+//error: redeclaration of symbol `a', first declared at
+
+struct Redecl {
+ int a;
+ double a;
+};
+
+[ChildProc=any]
+protocol structRedecl {
+child: async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/error/structUnknownField.ipdl b/ipc/ipdl/test/ipdl/error/structUnknownField.ipdl
new file mode 100644
index 0000000000..e8702a9b78
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/structUnknownField.ipdl
@@ -0,0 +1,10 @@
+//error: field `i' of struct `S' has unknown type `Foobers'
+
+struct S {
+ Foobers i;
+};
+
+[ChildProc=any]
+protocol structUnknownField {
+child: async __delete__(S s);
+};
diff --git a/ipc/ipdl/test/ipdl/error/syncMessageCompress.ipdl b/ipc/ipdl/test/ipdl/error/syncMessageCompress.ipdl
new file mode 100644
index 0000000000..0a3b63be2c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/syncMessageCompress.ipdl
@@ -0,0 +1,7 @@
+//error: message `foo' in protocol `syncMessageCompress' requests compression but is not async
+
+[ChildProc=any]
+sync protocol syncMessageCompress {
+parent:
+ [Compress] sync foo();
+};
diff --git a/ipc/ipdl/test/ipdl/error/syncParentToChild.ipdl b/ipc/ipdl/test/ipdl/error/syncParentToChild.ipdl
new file mode 100644
index 0000000000..8ce7c0be47
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/syncParentToChild.ipdl
@@ -0,0 +1,9 @@
+//error: sync parent-to-child messages are verboten (here, message `Msg' in protocol `syncParentToChild')
+
+[ChildProc=any]
+intr protocol syncParentToChild {
+
+ // can't declare sync parent-to-child messages
+child: sync Msg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/tooWeakIntrAsync.ipdl b/ipc/ipdl/test/ipdl/error/tooWeakIntrAsync.ipdl
new file mode 100644
index 0000000000..7dad5e68ef
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/tooWeakIntrAsync.ipdl
@@ -0,0 +1,10 @@
+//error: message `Msg' requires more powerful send semantics than its protocol `tooWeakIntrAsync' provides
+
+[ChildProc=any]
+protocol tooWeakIntrAsync {
+
+ // it's an error to declare an async protocol with an intr message
+
+parent: [LegacyIntr] intr Msg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/tooWeakIntrSync.ipdl b/ipc/ipdl/test/ipdl/error/tooWeakIntrSync.ipdl
new file mode 100644
index 0000000000..a56e884e73
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/tooWeakIntrSync.ipdl
@@ -0,0 +1,9 @@
+//error: message `Msg' requires more powerful send semantics than its protocol `tooWeakIntrSync' provides
+
+[ChildProc=any]
+sync protocol tooWeakIntrSync {
+
+ // it's an error to declare a sync protocol with an interrupt message
+parent:
+ [LegacyIntr] intr Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/tooWeakSyncAsync.ipdl b/ipc/ipdl/test/ipdl/error/tooWeakSyncAsync.ipdl
new file mode 100644
index 0000000000..8ebbfd25da
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/tooWeakSyncAsync.ipdl
@@ -0,0 +1,10 @@
+//error: message `Msg' requires more powerful send semantics than its protocol `tooWeakSyncAsync' provides
+
+[ChildProc=any]
+protocol tooWeakSyncAsync {
+
+ // it's an error to declare an async protocol with a sync message
+
+parent: sync Msg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/twoprotocols.ipdl b/ipc/ipdl/test/ipdl/error/twoprotocols.ipdl
new file mode 100644
index 0000000000..93222292a5
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/twoprotocols.ipdl
@@ -0,0 +1,13 @@
+// it's an error to define two protocols in the same file
+
+//error: only one protocol definition per file
+
+[ChildProc=any]
+protocol p1 {
+child: async Msg();
+};
+
+[ChildProc=any]
+protocol p2 {
+child: async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/undeclParamType.ipdl b/ipc/ipdl/test/ipdl/error/undeclParamType.ipdl
new file mode 100644
index 0000000000..efc21f0529
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undeclParamType.ipdl
@@ -0,0 +1,8 @@
+//error: argument typename `FARGLEGARGLE' of message `Msg' has not been declared
+
+[ChildProc=any]
+protocol undeclParamType {
+
+child: async Msg(FARGLEGARGLE p);
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/undeclProtocol.ipdl b/ipc/ipdl/test/ipdl/error/undeclProtocol.ipdl
new file mode 100644
index 0000000000..19532e3b9c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undeclProtocol.ipdl
@@ -0,0 +1,9 @@
+//error: protocol `undeclared', managed by `undeclProtocol', has not been declared
+
+[ChildProc=any]
+protocol undeclProtocol {
+ manages undeclared;
+
+child:
+ async undeclared();
+};
diff --git a/ipc/ipdl/test/ipdl/error/undeclReturnType.ipdl b/ipc/ipdl/test/ipdl/error/undeclReturnType.ipdl
new file mode 100644
index 0000000000..87fe0d6223
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undeclReturnType.ipdl
@@ -0,0 +1,8 @@
+//error: argument typename `FARGLEGARGLE' of message `Msg' has not been declared
+
+[ChildProc=any]
+sync protocol undeclReturnType {
+
+child: sync Msg() returns (FARGLEGARGLE r);
+
+};
diff --git a/ipc/ipdl/test/ipdl/error/undefMutualRecStruct.ipdl b/ipc/ipdl/test/ipdl/error/undefMutualRecStruct.ipdl
new file mode 100644
index 0000000000..79fa3729cc
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undefMutualRecStruct.ipdl
@@ -0,0 +1,12 @@
+//error: struct `X' is only partially defined
+//error: struct `Y' is only partially defined
+//error: struct `Z' is only partially defined
+
+struct X { Y y; };
+struct Y { Z z; };
+struct Z { X x; };
+
+[ChildProc=any]
+protocol undefMutualRecStruct {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/undefMutualRecStructUnion.ipdl b/ipc/ipdl/test/ipdl/error/undefMutualRecStructUnion.ipdl
new file mode 100644
index 0000000000..09e7116a68
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undefMutualRecStructUnion.ipdl
@@ -0,0 +1,12 @@
+//error: struct `X' is only partially defined
+//error: union `Y' is only partially defined
+//error: struct `Z' is only partially defined
+
+struct X { Y y; };
+union Y { Z; };
+struct Z { X x; };
+
+[ChildProc=any]
+protocol undefMutualRecStructUnion {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/undefMutualRecUnion.ipdl b/ipc/ipdl/test/ipdl/error/undefMutualRecUnion.ipdl
new file mode 100644
index 0000000000..497836ba4f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undefMutualRecUnion.ipdl
@@ -0,0 +1,12 @@
+//error: union `X' is only partially defined
+//error: union `Y' is only partially defined
+//error: union `Z' is only partially defined
+
+union X { Y; };
+union Y { Z; };
+union Z { X; };
+
+[ChildProc=any]
+protocol undefMutualRecUnion {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/undefSelfRecStruct.ipdl b/ipc/ipdl/test/ipdl/error/undefSelfRecStruct.ipdl
new file mode 100644
index 0000000000..1c23da1a77
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undefSelfRecStruct.ipdl
@@ -0,0 +1,8 @@
+//error: struct `X' is only partially defined
+
+struct X { X x; };
+
+[ChildProc=any]
+protocol undefSelfRecStruct {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/undefSelfRecUnion.ipdl b/ipc/ipdl/test/ipdl/error/undefSelfRecUnion.ipdl
new file mode 100644
index 0000000000..2c7572f11d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/undefSelfRecUnion.ipdl
@@ -0,0 +1,8 @@
+//error: union `X' is only partially defined
+
+union X { X; };
+
+[ChildProc=any]
+protocol undefSelfRecUnion {
+child: async __delete__(X x);
+};
diff --git a/ipc/ipdl/test/ipdl/error/unknownIntrMessage.ipdl b/ipc/ipdl/test/ipdl/error/unknownIntrMessage.ipdl
new file mode 100644
index 0000000000..7ce415aba0
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/unknownIntrMessage.ipdl
@@ -0,0 +1,7 @@
+//error: Unknown sync IPC message unknownIntrMessage::Msg
+
+[ChildProc=any]
+intr protocol unknownIntrMessage {
+parent:
+ [LegacyIntr] intr Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/error/unknownSyncMessage.ipdl b/ipc/ipdl/test/ipdl/error/unknownSyncMessage.ipdl
new file mode 100644
index 0000000000..ab1baecd35
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/error/unknownSyncMessage.ipdl
@@ -0,0 +1,7 @@
+//error: Unknown sync IPC message unknownSyncMessage::Msg
+
+[ChildProc=any]
+sync protocol unknownSyncMessage {
+parent:
+ sync Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/message-metadata.ini b/ipc/ipdl/test/ipdl/message-metadata.ini
new file mode 100644
index 0000000000..02ec1a992f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/message-metadata.ini
@@ -0,0 +1,2 @@
+# The IPDL parser expects this file to exist, even though we don't
+# need it for parsing tests, so here's an empty file. \ No newline at end of file
diff --git a/ipc/ipdl/test/ipdl/moz.build b/ipc/ipdl/test/ipdl/moz.build
new file mode 100644
index 0000000000..572682b594
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/moz.build
@@ -0,0 +1,8 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+# Copy test files so that they can be referenced in the docs.
+SPHINX_TREES["/ipc/_static"] = "ok"
diff --git a/ipc/ipdl/test/ipdl/ok/MutRecHeader1.ipdlh b/ipc/ipdl/test/ipdl/ok/MutRecHeader1.ipdlh
new file mode 100644
index 0000000000..56135b2197
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/MutRecHeader1.ipdlh
@@ -0,0 +1,34 @@
+include MutRecHeader2;
+
+/* MutRecHeader1 (H1) includes MutRecHeader2 (H2), and uses a struct from H2.
+ H2 includes MutRecHeader3 (H3).
+ H3 includes H1.
+
+When type checking H1, GatherDecls::visitInclude will recursively
+cause us to first check H2, which in turn will cause us to first check
+H3.
+
+H3 only includes H1, so when we check it, we do not have any
+declarations from H2 in the context. There used to be code in
+GatherDecls::visitTranslationUnit that would, as part of the "second
+pass", check the validity of all included structures. This would check
+Struct1, and fail, because Struct2 is not declared.
+
+Fundamentally, it doesn't make sense to check anything declared in an
+included file in the context of the file that included it.
+
+Note that this error did not show up when either H2 or H3 was
+checked. This is because in those cases we are not in the middle of
+checking H1 when we check H3, so we end up fully checking H1 before we
+get to the end of checking H3. This means the "visited" tag gets put
+on Struct1 before we get to the end of that troublesome block of code
+in visitTranslationUnit, and visitStructDecl doesn't do anything if
+that tag is set, so we don't end up actually checking H1 in the
+context of H3.
+
+*/
+
+struct Struct1
+{
+ Struct2 b;
+};
diff --git a/ipc/ipdl/test/ipdl/ok/MutRecHeader2.ipdlh b/ipc/ipdl/test/ipdl/ok/MutRecHeader2.ipdlh
new file mode 100644
index 0000000000..142979dc45
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/MutRecHeader2.ipdlh
@@ -0,0 +1,8 @@
+include MutRecHeader3;
+
+// See MutRecHeader1.ipdlh for explanation.
+
+struct Struct2
+{
+ bool b;
+};
diff --git a/ipc/ipdl/test/ipdl/ok/MutRecHeader3.ipdlh b/ipc/ipdl/test/ipdl/ok/MutRecHeader3.ipdlh
new file mode 100644
index 0000000000..2e303ae444
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/MutRecHeader3.ipdlh
@@ -0,0 +1,8 @@
+include MutRecHeader1;
+
+// See MutRecHeader1.ipdlh for explanation.
+
+struct Struct3
+{
+ bool b;
+};
diff --git a/ipc/ipdl/test/ipdl/ok/MyTypes.ipdlh b/ipc/ipdl/test/ipdl/ok/MyTypes.ipdlh
new file mode 100644
index 0000000000..9e33d71c51
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/MyTypes.ipdlh
@@ -0,0 +1,6 @@
+include protocol PMyManaged;
+
+struct MyActorPair {
+ PMyManaged actor1;
+ nullable PMyManaged actor2;
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PAsyncReturn.ipdl b/ipc/ipdl/test/ipdl/ok/PAsyncReturn.ipdl
new file mode 100644
index 0000000000..5deae9216b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PAsyncReturn.ipdl
@@ -0,0 +1,9 @@
+// Async messages are not allowed to return values.
+
+//error: asynchronous message `Msg' declares return values
+
+[ChildProc=any]
+protocol PAsyncReturn {
+child:
+ async Msg() returns(int32_t aNumber);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PDelete.ipdl b/ipc/ipdl/test/ipdl/ok/PDelete.ipdl
new file mode 100644
index 0000000000..006c73dc0d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PDelete.ipdl
@@ -0,0 +1,9 @@
+include protocol PDeleteSub;
+
+[ChildProc=any]
+sync protocol PDelete {
+ manages PDeleteSub;
+
+child:
+ async PDeleteSub();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PDeleteSub.ipdl b/ipc/ipdl/test/ipdl/ok/PDeleteSub.ipdl
new file mode 100644
index 0000000000..12b4c677eb
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PDeleteSub.ipdl
@@ -0,0 +1,10 @@
+include protocol PDelete;
+
+sync protocol PDeleteSub {
+ manager PDelete;
+
+parent:
+ sync __delete__(int x) returns (double d);
+
+};
+
diff --git a/ipc/ipdl/test/ipdl/ok/PEndpointDecl.ipdl b/ipc/ipdl/test/ipdl/ok/PEndpointDecl.ipdl
new file mode 100644
index 0000000000..f8fe51864a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PEndpointDecl.ipdl
@@ -0,0 +1,19 @@
+
+// Basic test that Endpoint types are declared for protocols, within
+// that protocol.
+
+struct Whatever {
+ Endpoint<PEndpointDeclParent> par;
+ Endpoint<PEndpointDeclChild> chi;
+};
+
+namespace mozilla {
+
+[ChildProc=any]
+protocol PEndpointDecl {
+ child:
+ async Message(Endpoint<PEndpointDeclParent> aEndpointParent,
+ Endpoint<PEndpointDeclChild> aEndpointChild);
+};
+
+}
diff --git a/ipc/ipdl/test/ipdl/ok/PEndpointUse.ipdl b/ipc/ipdl/test/ipdl/ok/PEndpointUse.ipdl
new file mode 100644
index 0000000000..8fde19c8e5
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PEndpointUse.ipdl
@@ -0,0 +1,10 @@
+include protocol PEndpointDecl;
+
+// Basic test that Endpoint types are declared for included protocols.
+
+[ChildProc=any]
+protocol PEndpointUse {
+ child:
+ async Message(Endpoint<PEndpointDeclParent> aEndpointParent,
+ Endpoint<PEndpointDeclChild> aEndpointChild);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PExtendedAttrMultipleAttributes.ipdl b/ipc/ipdl/test/ipdl/ok/PExtendedAttrMultipleAttributes.ipdl
new file mode 100644
index 0000000000..ce49ed8d2a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PExtendedAttrMultipleAttributes.ipdl
@@ -0,0 +1,5 @@
+[NestedUpTo=inside_sync, NeedsOtherPid, ChildProc=any]
+async protocol PExtendedAttrMultipleAttributes {
+parent:
+ async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PLazySend.ipdl b/ipc/ipdl/test/ipdl/ok/PLazySend.ipdl
new file mode 100644
index 0000000000..e67b35a153
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PLazySend.ipdl
@@ -0,0 +1,7 @@
+[ChildProc=any]
+protocol PLazySend {
+child:
+ [LazySend] async foo();
+parent:
+ [LazySend] async bar() returns (bool baz);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PManagedEndpointDecl.ipdl b/ipc/ipdl/test/ipdl/ok/PManagedEndpointDecl.ipdl
new file mode 100644
index 0000000000..13eb10fcc4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PManagedEndpointDecl.ipdl
@@ -0,0 +1,23 @@
+include protocol PManagedEndpointManager;
+
+// Basic test that ManagedEndpoint types are declared for protocols, within
+// that protocol.
+
+struct ManagedWhatever {
+ ManagedEndpoint<PManagedEndpointDeclParent> par;
+ ManagedEndpoint<PManagedEndpointDeclChild> chi;
+};
+
+namespace mozilla {
+
+protocol PManagedEndpointDecl {
+ manager PManagedEndpointManager;
+
+child:
+ async Message(ManagedEndpoint<PManagedEndpointDeclParent> aEndpointParent,
+ ManagedEndpoint<PManagedEndpointDeclChild> aEndpointChild);
+
+ async __delete__();
+};
+
+}
diff --git a/ipc/ipdl/test/ipdl/ok/PManagedEndpointManager.ipdl b/ipc/ipdl/test/ipdl/ok/PManagedEndpointManager.ipdl
new file mode 100644
index 0000000000..2ae381c72b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PManagedEndpointManager.ipdl
@@ -0,0 +1,15 @@
+include protocol PManagedEndpointDecl;
+
+namespace mozilla {
+
+[ChildProc=any]
+protocol PManagedEndpointManager {
+ manages PManagedEndpointDecl;
+
+child:
+ async Message(ManagedEndpoint<PManagedEndpointDeclParent> aEndpointParent,
+ ManagedEndpoint<PManagedEndpointDeclChild> aEndpointChild);
+};
+
+}
+
diff --git a/ipc/ipdl/test/ipdl/ok/PManualDealloc.ipdl b/ipc/ipdl/test/ipdl/ok/PManualDealloc.ipdl
new file mode 100644
index 0000000000..53660762ad
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PManualDealloc.ipdl
@@ -0,0 +1,8 @@
+include protocol PManualDealloc_manager;
+
+[ManualDealloc] async protocol PManualDealloc {
+ manager PManualDealloc_manager;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PManualDealloc_manager.ipdl b/ipc/ipdl/test/ipdl/ok/PManualDealloc_manager.ipdl
new file mode 100644
index 0000000000..d425a6781f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PManualDealloc_manager.ipdl
@@ -0,0 +1,8 @@
+include protocol PManualDealloc;
+
+// [ManualDealloc] types must have a manager, as all toplevel protocols are
+// refcounted.
+[ChildProc=any]
+async protocol PManualDealloc_manager {
+ manages PManualDealloc;
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PMessageTainted.ipdl b/ipc/ipdl/test/ipdl/ok/PMessageTainted.ipdl
new file mode 100644
index 0000000000..deb10fb7ac
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PMessageTainted.ipdl
@@ -0,0 +1,5 @@
+[ChildProc=any]
+intr protocol PMessageTainted {
+child:
+ [Tainted] async foo();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PMessageTaintedWithPassback.ipdl b/ipc/ipdl/test/ipdl/ok/PMessageTaintedWithPassback.ipdl
new file mode 100644
index 0000000000..8db2c8b742
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PMessageTaintedWithPassback.ipdl
@@ -0,0 +1,5 @@
+[ChildProc=any]
+intr protocol PMessageTaintedWithPassback {
+child:
+ [Tainted] async foo([NoTaint=passback] int id);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PMyManaged.ipdl b/ipc/ipdl/test/ipdl/ok/PMyManaged.ipdl
new file mode 100644
index 0000000000..d6ddb34bf8
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PMyManaged.ipdl
@@ -0,0 +1,13 @@
+include protocol PMyManager;
+
+namespace mozilla {
+namespace myns {
+
+protocol PMyManaged {
+ manager PMyManager;
+ child:
+ async __delete__(Shmem aShmem);
+};
+
+} // namespace myns
+} // namespace mozilla
diff --git a/ipc/ipdl/test/ipdl/ok/PMyManager.ipdl b/ipc/ipdl/test/ipdl/ok/PMyManager.ipdl
new file mode 100644
index 0000000000..4ed2706ffd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PMyManager.ipdl
@@ -0,0 +1,31 @@
+include protocol PMyManaged;
+include MyTypes; // for MyActorPair
+
+using MyActorEnum from "mozilla/myns/MyActorUtils.h";
+using mozilla::myns::MyData from "mozilla/MyDataTypes.h";
+[MoveOnly] using class mozilla::myns::MyOtherData from "mozilla/MyDataTypes.h";
+[RefCounted] using class mozilla::myns::MyThirdData from "mozilla/MyDataTypes.h";
+
+namespace mozilla {
+namespace myns {
+
+[Comparable] union MyUnion {
+ float;
+ MyOtherData;
+};
+
+[ChildProc=any]
+sync protocol PMyManager {
+ manages PMyManaged;
+ parent:
+ async __delete__(nsString aNote);
+ sync SomeMsg(MyActorPair? aActors, MyData[] aMyData)
+ returns (int32_t x, int32_t y, MyUnion aUnion);
+ async PMyManaged();
+ both:
+ [Tainted] async AnotherMsg(MyActorEnum aEnum, int32_t aNumber)
+ returns (MyOtherData aOtherData);
+};
+
+} // namespace myns
+} // namespace mozilla
diff --git a/ipc/ipdl/test/ipdl/ok/PNested.ipdl b/ipc/ipdl/test/ipdl/ok/PNested.ipdl
new file mode 100644
index 0000000000..94865bca6b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PNested.ipdl
@@ -0,0 +1,8 @@
+[NestedUpTo=inside_cpow, ChildProc=any]
+sync protocol PNested {
+parent:
+ [Nested=not] async NotNested();
+ [Nested=inside_sync] sync InsideSync();
+ [Nested=inside_cpow] async InsideCpow();
+ [Nested=inside_cpow] sync InsideCpowSync();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PNullable.ipdl b/ipc/ipdl/test/ipdl/ok/PNullable.ipdl
new file mode 100644
index 0000000000..b7b21ff885
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PNullable.ipdl
@@ -0,0 +1,22 @@
+[RefCounted] using class nsIURI from "nsIURI.h";
+
+union Union {
+ nullable PNullable;
+ nullable PNullable[];
+ nullable PNullable?;
+ nullable nsIURI;
+ nullable nsIURI[];
+ nullable nsIURI?;
+};
+
+[ChildProc=any]
+protocol PNullable {
+child:
+ async Msg(nullable PNullable n);
+ async Msg2(nullable PNullable[] N);
+ async Msg3(nullable PNullable? n);
+ async Msg4(nullable nsIURI u);
+ async Msg5(nullable nsIURI[] u);
+ async Msg6(nullable nsIURI? u);
+ async Msg7(Union u);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PSideImpl.ipdl b/ipc/ipdl/test/ipdl/ok/PSideImpl.ipdl
new file mode 100644
index 0000000000..4ebb1b8ec3
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PSideImpl.ipdl
@@ -0,0 +1,5 @@
+[ParentImpl=virtual, ChildImpl="mozilla::FooBarImpl", ChildProc=any]
+async protocol PSideImpl {
+ parent:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PStruct.ipdl b/ipc/ipdl/test/ipdl/ok/PStruct.ipdl
new file mode 100644
index 0000000000..f76f7db98f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PStruct.ipdl
@@ -0,0 +1,11 @@
+struct S {
+ int i;
+ double d;
+};
+
+[ChildProc=any]
+sync protocol PStruct {
+parent:
+ sync test(S s) returns (S ss);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PStructComparable.ipdl b/ipc/ipdl/test/ipdl/ok/PStructComparable.ipdl
new file mode 100644
index 0000000000..89576368ec
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PStructComparable.ipdl
@@ -0,0 +1,11 @@
+[Comparable] struct S {
+ int i;
+ double d;
+};
+
+[ChildProc=any]
+sync protocol PStructComparable {
+parent:
+ sync test(S s) returns (S ss);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PSyncSyncManagee.ipdl b/ipc/ipdl/test/ipdl/ok/PSyncSyncManagee.ipdl
new file mode 100644
index 0000000000..458f0c83c0
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PSyncSyncManagee.ipdl
@@ -0,0 +1,7 @@
+include protocol PSyncSyncManager;
+
+sync protocol PSyncSyncManagee {
+ manager PSyncSyncManager;
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PSyncSyncManager.ipdl b/ipc/ipdl/test/ipdl/ok/PSyncSyncManager.ipdl
new file mode 100644
index 0000000000..d3fc236ff8
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PSyncSyncManager.ipdl
@@ -0,0 +1,12 @@
+include protocol PSyncSyncManagee;
+
+/* The main reason for this test is that it would have caught a bug
+ * in the Rust IPDL parser that was treating "sync" like "async" in the
+ * nested case.
+ */
+[NestedUpTo=not, ChildProc=any]
+sync protocol PSyncSyncManager {
+ manages PSyncSyncManagee;
+parent:
+ async PSyncSyncManagee();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PUniquePtrBasic.ipdl b/ipc/ipdl/test/ipdl/ok/PUniquePtrBasic.ipdl
new file mode 100644
index 0000000000..097dd04684
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PUniquePtrBasic.ipdl
@@ -0,0 +1,5 @@
+[ChildProc=any]
+protocol PUniquePtrBasic {
+child:
+ async Msg(UniquePtr<int> maybe);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActors.ipdl b/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActors.ipdl
new file mode 100644
index 0000000000..24631db712
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActors.ipdl
@@ -0,0 +1,11 @@
+include protocol PUniquePtrOfActorsSub;
+
+[ChildProc=any]
+protocol PUniquePtrOfActors {
+ manages PUniquePtrOfActorsSub;
+
+child:
+ async Msg(UniquePtr<PUniquePtrOfActorsSub> p);
+
+ async PUniquePtrOfActorsSub();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActorsSub.ipdl b/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActorsSub.ipdl
new file mode 100644
index 0000000000..a60c8e475f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PUniquePtrOfActorsSub.ipdl
@@ -0,0 +1,7 @@
+include protocol PUniquePtrOfActors;
+
+protocol PUniquePtrOfActorsSub {
+ manager PUniquePtrOfActors;
+
+child: async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PUniquePtrRecUnion.ipdl b/ipc/ipdl/test/ipdl/ok/PUniquePtrRecUnion.ipdl
new file mode 100644
index 0000000000..40ac466b40
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PUniquePtrRecUnion.ipdl
@@ -0,0 +1,22 @@
+union X {
+ int;
+ Y[];
+ UniquePtr<Y>;
+};
+
+union Y {
+ X;
+ Z;
+};
+
+union Z {
+ double;
+ X;
+};
+
+[ChildProc=any]
+protocol PUniquePtrRecUnion {
+child:
+ async Test(X x, Y y, Z z);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PUniquePtrUnion.ipdl b/ipc/ipdl/test/ipdl/ok/PUniquePtrUnion.ipdl
new file mode 100644
index 0000000000..de4529c639
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PUniquePtrUnion.ipdl
@@ -0,0 +1,11 @@
+union UniquePtrUnion {
+ int[];
+ int;
+ double;
+};
+
+[ChildProc=any]
+sync protocol PUniquePtrUnion {
+parent:
+ async Msg(UniquePtrUnion u, UniquePtr<UniquePtrUnion> au) returns (UniquePtrUnion r);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PVirtualSendImpl.ipdl b/ipc/ipdl/test/ipdl/ok/PVirtualSendImpl.ipdl
new file mode 100644
index 0000000000..ff09108965
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PVirtualSendImpl.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+async protocol PVirtualSendImpl
+{
+child:
+ [VirtualSendImpl] async MockableFoo();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pactorparam.ipdl b/ipc/ipdl/test/ipdl/ok/Pactorparam.ipdl
new file mode 100644
index 0000000000..bb7bb85518
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pactorparam.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+protocol Pactorparam {
+
+child: async Msg(Pactorparam p);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pactorreturn.ipdl b/ipc/ipdl/test/ipdl/ok/Pactorreturn.ipdl
new file mode 100644
index 0000000000..4e8e53a9d6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pactorreturn.ipdl
@@ -0,0 +1,7 @@
+[ChildProc=any]
+sync protocol Pactorreturn {
+
+parent:
+ sync Msg(Pactorreturn p) returns (Pactorreturn r);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Parray_Basic.ipdl b/ipc/ipdl/test/ipdl/ok/Parray_Basic.ipdl
new file mode 100644
index 0000000000..7ce682f154
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Parray_Basic.ipdl
@@ -0,0 +1,5 @@
+[ChildProc=any]
+protocol Parray_Basic {
+child:
+ async Msg(int[] array);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Parray_OfActors.ipdl b/ipc/ipdl/test/ipdl/ok/Parray_OfActors.ipdl
new file mode 100644
index 0000000000..170f4e902a
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Parray_OfActors.ipdl
@@ -0,0 +1,11 @@
+include protocol Parray_OfActorsSub;
+
+[ChildProc=any]
+protocol Parray_OfActors {
+ manages Parray_OfActorsSub;
+
+child:
+ async Msg(Parray_OfActorsSub[] p);
+
+ async Parray_OfActorsSub();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Parray_OfActorsSub.ipdl b/ipc/ipdl/test/ipdl/ok/Parray_OfActorsSub.ipdl
new file mode 100644
index 0000000000..6769e98abb
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Parray_OfActorsSub.ipdl
@@ -0,0 +1,7 @@
+include protocol Parray_OfActors;
+
+protocol Parray_OfActorsSub {
+ manager Parray_OfActors;
+
+child: async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Parray_Union.ipdl b/ipc/ipdl/test/ipdl/ok/Parray_Union.ipdl
new file mode 100644
index 0000000000..2733d5fc04
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Parray_Union.ipdl
@@ -0,0 +1,11 @@
+union Union {
+ int[];
+ int;
+ double;
+};
+
+[ChildProc=any]
+sync protocol Parray_Union {
+parent:
+ sync Msg(Union u, Union[] au) returns (Union r);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PbasicUsing.ipdl b/ipc/ipdl/test/ipdl/ok/PbasicUsing.ipdl
new file mode 100644
index 0000000000..94d57b08d0
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PbasicUsing.ipdl
@@ -0,0 +1,51 @@
+using SomeType from "SomeFile.h";
+using class SomeClass from "SomeFile.h";
+using struct SomeStruct from "SomeFile.h";
+
+[RefCounted] using SomeRefcountedType from "SomeFile.h";
+[RefCounted] using class SomeRefcountedClass from "SomeFile.h";
+[RefCounted] using struct SomeRefcountedStruct from "SomeFile.h";
+
+[MoveOnly] using SomeMoveonlyType from "SomeFile.h";
+[MoveOnly] using class SomeMoveonlyClass from "SomeFile.h";
+[MoveOnly] using struct SomeMoveonlyStruct from "SomeFile.h";
+
+[RefCounted, MoveOnly] using SomeRefcountedMoveonlyType from "SomeFile.h";
+[RefCounted, MoveOnly] using class SomeRefcountedMoveonlyClass from "SomeFile.h";
+[RefCounted, MoveOnly] using struct SomeRefcountedMoveonlyStruct from "SomeFile.h";
+
+[MoveOnly=data] using SomeMoveonlyDataType from "SomeFile.h";
+[MoveOnly=data] using class SomeMoveonlyDataClass from "SomeFile.h";
+[MoveOnly=data] using struct SomeMoveonlyDataStruct from "SomeFile.h";
+
+[MoveOnly=send] using SomeMoveonlySendType from "SomeFile.h";
+[MoveOnly=send] using class SomeMoveonlySendClass from "SomeFile.h";
+[MoveOnly=send] using struct SomeMoveonlySendStruct from "SomeFile.h";
+
+union SomeUnion
+{
+ SomeType;
+ SomeClass;
+ SomeStruct;
+ SomeRefcountedType;
+ SomeRefcountedClass;
+ SomeRefcountedStruct;
+ SomeMoveonlyType;
+ SomeMoveonlyClass;
+ SomeMoveonlyStruct;
+ SomeRefcountedMoveonlyType;
+ SomeRefcountedMoveonlyClass;
+ SomeRefcountedMoveonlyStruct;
+ SomeMoveonlyDataType;
+ SomeMoveonlyDataClass;
+ SomeMoveonlyDataStruct;
+ SomeMoveonlySendType;
+ SomeMoveonlySendClass;
+ SomeMoveonlySendStruct;
+};
+
+[ChildProc=any]
+protocol PbasicUsing {
+child:
+ async Msg(SomeUnion foo);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pbuiltins.ipdl b/ipc/ipdl/test/ipdl/ok/Pbuiltins.ipdl
new file mode 100644
index 0000000000..3cd023a0b6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pbuiltins.ipdl
@@ -0,0 +1,22 @@
+[ChildProc=any]
+protocol Pbuiltins {
+
+ // sanity-check that "essential" builtins are being declared
+
+child: async Msg(bool b,
+ char c,
+ int i,
+ long l,
+
+ float f,
+ double d,
+
+ int8_t i8t,
+ uint8_t u8t,
+ int16_t i16t,
+ uint16_t u16t,
+ int32_t i32t,
+ uint32_t u32t,
+ int64_t i64t,
+ uint64_t u64t);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pbytebuf.ipdl b/ipc/ipdl/test/ipdl/ok/Pbytebuf.ipdl
new file mode 100644
index 0000000000..a0ceac937f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pbytebuf.ipdl
@@ -0,0 +1,14 @@
+union Foo {
+ int;
+ ByteBuf;
+};
+
+[ChildProc=any]
+intr protocol Pbytebuf {
+parent:
+ async Msg(ByteBuf s, Foo f);
+ sync SyncMsg(ByteBuf s, Foo f)
+ returns (ByteBuf t, Foo g);
+ [LegacyIntr] intr InterruptMsg(ByteBuf s, Foo f)
+ returns (ByteBuf t, Foo g);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pempty.ipdl b/ipc/ipdl/test/ipdl/ok/Pempty.ipdl
new file mode 100644
index 0000000000..4ab603dbc8
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pempty.ipdl
@@ -0,0 +1,4 @@
+[ChildProc=any]
+protocol Pempty {
+child: async Msg();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PemptyStruct.ipdl b/ipc/ipdl/test/ipdl/ok/PemptyStruct.ipdl
new file mode 100644
index 0000000000..a3317cb872
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PemptyStruct.ipdl
@@ -0,0 +1,4 @@
+struct empty { };
+
+[ChildProc=any]
+protocol PemptyStruct { child: async __delete__(); };
diff --git a/ipc/ipdl/test/ipdl/ok/PheaderProto.ipdl b/ipc/ipdl/test/ipdl/ok/PheaderProto.ipdl
new file mode 100644
index 0000000000..5c9af7c3f9
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PheaderProto.ipdl
@@ -0,0 +1,11 @@
+include header;
+
+namespace c {
+
+[ChildProc=any]
+protocol PheaderProto {
+child:
+ async __delete__(foo a, baz b, Inner1 c, Inner2 d, X x);
+};
+
+}
diff --git a/ipc/ipdl/test/ipdl/ok/PintrProtocol.ipdl b/ipc/ipdl/test/ipdl/ok/PintrProtocol.ipdl
new file mode 100644
index 0000000000..4b663327e6
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PintrProtocol.ipdl
@@ -0,0 +1,14 @@
+[ChildProc=any]
+intr protocol PintrProtocol {
+
+ // sanity check of Interrupt protocols
+child:
+ async AsyncMsg();
+
+parent:
+ sync SyncMsg(int i) returns (int r);
+
+both:
+ [LegacyIntr] intr InterruptMsg(int x) returns (int y);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pjetpack.ipdl b/ipc/ipdl/test/ipdl/ok/Pjetpack.ipdl
new file mode 100644
index 0000000000..7744f59f8f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pjetpack.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+sync protocol Pjetpack {
+child:
+ async __delete__();
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmanageSelf.ipdl b/ipc/ipdl/test/ipdl/ok/PmanageSelf.ipdl
new file mode 100644
index 0000000000..992f374a58
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmanageSelf.ipdl
@@ -0,0 +1,10 @@
+include protocol PmanageSelf_Toplevel;
+
+protocol PmanageSelf {
+ manager PmanageSelf_Toplevel or PmanageSelf;
+ manages PmanageSelf;
+
+child:
+ async PmanageSelf();
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmanageSelf_Toplevel.ipdl b/ipc/ipdl/test/ipdl/ok/PmanageSelf_Toplevel.ipdl
new file mode 100644
index 0000000000..15be35f838
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmanageSelf_Toplevel.ipdl
@@ -0,0 +1,10 @@
+include protocol PmanageSelf;
+
+[ChildProc=any]
+protocol PmanageSelf_Toplevel {
+ manages PmanageSelf;
+
+child:
+ async PmanageSelf();
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmanagedProtocol.ipdl b/ipc/ipdl/test/ipdl/ok/PmanagedProtocol.ipdl
new file mode 100644
index 0000000000..cab07d06e7
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmanagedProtocol.ipdl
@@ -0,0 +1,8 @@
+include protocol PmanagerProtocol;
+
+protocol PmanagedProtocol {
+ manager PmanagerProtocol;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmanagerProtocol.ipdl b/ipc/ipdl/test/ipdl/ok/PmanagerProtocol.ipdl
new file mode 100644
index 0000000000..28483426d3
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmanagerProtocol.ipdl
@@ -0,0 +1,12 @@
+include protocol PmanagedProtocol;
+
+// sanity check of managed/manager protocols
+
+[ChildProc=any]
+protocol PmanagerProtocol {
+ manages PmanagedProtocol;
+
+parent:
+ async PmanagedProtocol(int i);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pmaybe_Basic.ipdl b/ipc/ipdl/test/ipdl/ok/Pmaybe_Basic.ipdl
new file mode 100644
index 0000000000..52243d5ca3
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pmaybe_Basic.ipdl
@@ -0,0 +1,5 @@
+[ChildProc=any]
+protocol Pmaybe_Basic {
+child:
+ async Msg(int? maybe);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActors.ipdl b/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActors.ipdl
new file mode 100644
index 0000000000..2252c32827
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActors.ipdl
@@ -0,0 +1,11 @@
+include protocol Pmaybe_OfActorsSub;
+
+[ChildProc=any]
+protocol Pmaybe_OfActors {
+ manages Pmaybe_OfActorsSub;
+
+child:
+ async Msg(Pmaybe_OfActorsSub? p);
+
+ async Pmaybe_OfActorsSub();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActorsSub.ipdl b/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActorsSub.ipdl
new file mode 100644
index 0000000000..6a4759953f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pmaybe_OfActorsSub.ipdl
@@ -0,0 +1,7 @@
+include protocol Pmaybe_OfActors;
+
+protocol Pmaybe_OfActorsSub {
+ manager Pmaybe_OfActors;
+
+child: async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pmaybe_Union.ipdl b/ipc/ipdl/test/ipdl/ok/Pmaybe_Union.ipdl
new file mode 100644
index 0000000000..5701b08fd9
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pmaybe_Union.ipdl
@@ -0,0 +1,11 @@
+union MaybeUnion {
+ int[];
+ int;
+ double;
+};
+
+[ChildProc=any]
+sync protocol Pmaybe_Union {
+parent:
+ async Msg(MaybeUnion u, MaybeUnion? au) returns (MaybeUnion r);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pmedia.ipdl b/ipc/ipdl/test/ipdl/ok/Pmedia.ipdl
new file mode 100644
index 0000000000..e0f95d2a34
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pmedia.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+sync protocol Pmedia {
+child:
+ async __delete__();
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmessageCompress.ipdl b/ipc/ipdl/test/ipdl/ok/PmessageCompress.ipdl
new file mode 100644
index 0000000000..7e14c888dd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmessageCompress.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+intr protocol PmessageCompress {
+child:
+ [Compress] async foo();
+ [Compress=all] async bar();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmultiManaged.ipdl b/ipc/ipdl/test/ipdl/ok/PmultiManaged.ipdl
new file mode 100644
index 0000000000..d8c47fc9e3
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmultiManaged.ipdl
@@ -0,0 +1,9 @@
+include protocol PmultiManager1;
+include protocol PmultiManager2;
+
+protocol PmultiManaged {
+ manager PmultiManager1 or PmultiManager2;
+
+child:
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmultiManager1.ipdl b/ipc/ipdl/test/ipdl/ok/PmultiManager1.ipdl
new file mode 100644
index 0000000000..ec38412422
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmultiManager1.ipdl
@@ -0,0 +1,9 @@
+include protocol PmultiManaged;
+
+[ChildProc=any]
+protocol PmultiManager1 {
+ manages PmultiManaged;
+
+child:
+ async PmultiManaged();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmultiManager2.ipdl b/ipc/ipdl/test/ipdl/ok/PmultiManager2.ipdl
new file mode 100644
index 0000000000..b8295fd057
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmultiManager2.ipdl
@@ -0,0 +1,9 @@
+include protocol PmultiManaged;
+
+[ChildProc=any]
+protocol PmultiManager2 {
+ manages PmultiManaged;
+
+child:
+ async PmultiManaged();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmultipleUsingCxxTypes.ipdl b/ipc/ipdl/test/ipdl/ok/PmultipleUsingCxxTypes.ipdl
new file mode 100644
index 0000000000..5d5ae5e9a8
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmultipleUsingCxxTypes.ipdl
@@ -0,0 +1,8 @@
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+using struct mozilla::void_t from "mozilla/ipc/IPCCore.h";
+
+[ChildProc=any]
+protocol PmultipleUsingCxxTypes {
+child:
+ async Msg(void_t foo);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmutualRecStructUnion.ipdl b/ipc/ipdl/test/ipdl/ok/PmutualRecStructUnion.ipdl
new file mode 100644
index 0000000000..b28df7969b
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmutualRecStructUnion.ipdl
@@ -0,0 +1,22 @@
+struct X {
+ int i;
+ Y[] y;
+};
+
+union Y {
+ double;
+ X;
+ Z;
+};
+
+struct Z {
+ X x;
+ Y y;
+};
+
+[ChildProc=any]
+protocol PmutualRecStructUnion {
+child:
+ async Test(X x, Y y, Z z);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PmutualRecUnion.ipdl b/ipc/ipdl/test/ipdl/ok/PmutualRecUnion.ipdl
new file mode 100644
index 0000000000..73c869278f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PmutualRecUnion.ipdl
@@ -0,0 +1,22 @@
+union X {
+ int;
+ Y[];
+ Y?;
+};
+
+union Y {
+ X;
+ Z;
+};
+
+union Z {
+ double;
+ X;
+};
+
+[ChildProc=any]
+protocol PmutualRecUnion {
+child:
+ async Test(X x, Y y, Z z);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pnamespace_Basic.ipdl b/ipc/ipdl/test/ipdl/ok/Pnamespace_Basic.ipdl
new file mode 100644
index 0000000000..3b2f2fa27f
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pnamespace_Basic.ipdl
@@ -0,0 +1,13 @@
+namespace basic {
+
+// sanity check of namespaced protocols
+
+[ChildProc=any]
+protocol Pnamespace_Basic {
+
+child:
+ async Msg();
+
+};
+
+} // namespace basic
diff --git a/ipc/ipdl/test/ipdl/ok/PnoRedeclCrossMessage.ipdl b/ipc/ipdl/test/ipdl/ok/PnoRedeclCrossMessage.ipdl
new file mode 100644
index 0000000000..30c7179e8c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PnoRedeclCrossMessage.ipdl
@@ -0,0 +1,10 @@
+[ChildProc=any]
+protocol PnoRedeclCrossMessage {
+
+ // each message has its own scope for param/return names
+
+child:
+ async Msg1(int f);
+ async Msg2(int f);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pplugin.ipdl b/ipc/ipdl/test/ipdl/ok/Pplugin.ipdl
new file mode 100644
index 0000000000..f7d9352a08
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pplugin.ipdl
@@ -0,0 +1,6 @@
+[ChildProc=any]
+intr protocol Pplugin {
+child:
+ async __delete__();
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Prio.ipdl b/ipc/ipdl/test/ipdl/ok/Prio.ipdl
new file mode 100644
index 0000000000..fdda57f784
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Prio.ipdl
@@ -0,0 +1,12 @@
+[ChildProc=any]
+async protocol Prio
+{
+child:
+ [Priority=normal] async NormalPrio();
+ [Priority=vsync] async VsyncPrio();
+ [Priority=input] async InputPrio();
+ [Priority=mediumhigh] async MediumHighPrio();
+ [Priority=control] async ControlPrio();
+ [ReplyPriority=control] async ControlPrioReturns() returns (bool aValue);
+ [Priority=normal, ReplyPriority=control] async NormalControlPrioReturns() returns (bool aValue);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PselfRecUnion.ipdl b/ipc/ipdl/test/ipdl/ok/PselfRecUnion.ipdl
new file mode 100644
index 0000000000..9d5e3de487
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PselfRecUnion.ipdl
@@ -0,0 +1,12 @@
+union R {
+ int;
+ double;
+ R;
+};
+
+[ChildProc=any]
+protocol PselfRecUnion {
+child:
+ async Test(R r);
+ async __delete__();
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Pshmem.ipdl b/ipc/ipdl/test/ipdl/ok/Pshmem.ipdl
new file mode 100644
index 0000000000..a46e777d8c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Pshmem.ipdl
@@ -0,0 +1,14 @@
+union Foo {
+ int;
+ Shmem;
+};
+
+[ChildProc=any]
+intr protocol Pshmem {
+parent:
+ async Msg(Shmem s, Foo f);
+ sync SyncMsg(Shmem s, Foo f)
+ returns (Shmem t, Foo g);
+ [LegacyIntr] intr InterruptMsg(Shmem s, Foo f)
+ returns (Shmem t, Foo g);
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PsyncProtocol.ipdl b/ipc/ipdl/test/ipdl/ok/PsyncProtocol.ipdl
new file mode 100644
index 0000000000..f73be554e4
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PsyncProtocol.ipdl
@@ -0,0 +1,12 @@
+[ChildProc=any]
+sync protocol PsyncProtocol {
+
+ // sanity check of sync protocols
+
+child:
+ async AsyncMsg();
+
+parent:
+ sync SyncMsg() returns (int i);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/PthreeDirections.ipdl b/ipc/ipdl/test/ipdl/ok/PthreeDirections.ipdl
new file mode 100644
index 0000000000..6474ca5d0d
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/PthreeDirections.ipdl
@@ -0,0 +1,14 @@
+[ChildProc=any]
+protocol PthreeDirections {
+
+ // sanity check that the three direction specifiers are being accepted
+child:
+ async ChildMsg();
+
+parent:
+ async ParentMsg();
+
+both:
+ async BothMsg();
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Punion_Basic.ipdl b/ipc/ipdl/test/ipdl/ok/Punion_Basic.ipdl
new file mode 100644
index 0000000000..a049d52e75
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Punion_Basic.ipdl
@@ -0,0 +1,12 @@
+union Basic {
+ int;
+ double;
+};
+
+[ChildProc=any]
+sync protocol Punion_Basic {
+
+parent:
+ sync Msg(Basic p) returns (Basic r);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Punion_Comparable.ipdl b/ipc/ipdl/test/ipdl/ok/Punion_Comparable.ipdl
new file mode 100644
index 0000000000..05b26f32aa
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Punion_Comparable.ipdl
@@ -0,0 +1,12 @@
+[Comparable] union Basic {
+ int;
+ double;
+};
+
+[ChildProc=any]
+sync protocol Punion_Comparable {
+
+parent:
+ sync Msg(Basic p) returns (Basic r);
+
+};
diff --git a/ipc/ipdl/test/ipdl/ok/Punion_Namespaced.ipdl b/ipc/ipdl/test/ipdl/ok/Punion_Namespaced.ipdl
new file mode 100644
index 0000000000..4108dfd4df
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/Punion_Namespaced.ipdl
@@ -0,0 +1,19 @@
+namespace kitties {
+
+union Socks {
+ int;
+ double;
+};
+
+} // namespace kitties
+
+
+namespace puppies {
+
+[ChildProc=any]
+protocol Punion_Namespaced {
+child:
+ async Msg(Socks s);
+};
+
+} // namespace puppies
diff --git a/ipc/ipdl/test/ipdl/ok/header.ipdlh b/ipc/ipdl/test/ipdl/ok/header.ipdlh
new file mode 100644
index 0000000000..fc3f8c8279
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/ok/header.ipdlh
@@ -0,0 +1,15 @@
+using foo from "foo.h";
+using bar::baz from "foo.h";
+
+struct Outer { };
+
+namespace a { struct Inner1 { }; }
+
+namespace b { struct Inner2 { }; }
+
+namespace c {
+union X {
+ int32_t;
+ float;
+};
+}
diff --git a/ipc/ipdl/test/ipdl/runtests.py b/ipc/ipdl/test/ipdl/runtests.py
new file mode 100644
index 0000000000..4296eab65c
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/runtests.py
@@ -0,0 +1,119 @@
+import os
+import unittest
+
+from IPDLCompile import IPDLCompile
+
+
+class IPDLTestCase(unittest.TestCase):
+ def __init__(self, ipdlargv, filename):
+ unittest.TestCase.__init__(self, "test")
+ self.filename = filename
+ self.compile = IPDLCompile(filename, ipdlargv)
+
+ def test(self):
+ self.compile.run()
+ self.assertFalse(self.compile.exception(), self.mkFailMsg())
+ self.checkPassed()
+
+ def mkCustomMsg(self, msg):
+ return """
+### Command: %s
+### %s
+### stderr:
+%s""" % (
+ " ".join(self.compile.argv),
+ msg,
+ self.compile.stderr,
+ )
+
+ def mkFailMsg(self):
+ return """
+### Command: %s
+### stderr:
+%s""" % (
+ " ".join(self.compile.argv),
+ self.compile.stderr,
+ )
+
+ def shortDescription(self):
+ return '%s test of "%s"' % (self.__class__.__name__, self.filename)
+
+
+class OkTestCase(IPDLTestCase):
+ """An invocation of the IPDL compiler on a valid specification.
+ The IPDL compiler should not produce errors or exceptions."""
+
+ def __init__(self, ipdlargv, filename):
+ IPDLTestCase.__init__(self, ipdlargv, filename)
+
+ def checkPassed(self):
+ self.assertTrue(self.compile.ok(), self.mkFailMsg())
+
+
+class ErrorTestCase(IPDLTestCase):
+ """An invocation of the IPDL compiler on an *invalid* specification.
+ The IPDL compiler *should* produce errors but not exceptions."""
+
+ def __init__(self, ipdlargv, filename):
+ IPDLTestCase.__init__(self, ipdlargv, filename)
+
+ # Look for expected errors in the input file.
+ f = open(filename, "r")
+ self.expectedErrorMessage = []
+ for l in f:
+ if l.startswith("//error:"):
+ self.expectedErrorMessage.append(l[2:-1])
+ f.close()
+
+ def checkPassed(self):
+ self.assertNotEqual(
+ self.expectedErrorMessage,
+ [],
+ self.mkCustomMsg(
+ "Error test should contain at least "
+ + "one line starting with //error: "
+ + "that indicates the expected failure."
+ ),
+ )
+
+ for e in self.expectedErrorMessage:
+ self.assertTrue(
+ self.compile.error(e),
+ self.mkCustomMsg('Did not see expected error "' + e + '"'),
+ )
+
+
+if __name__ == "__main__":
+ import sys
+
+ okdir = sys.argv[1]
+ assert os.path.isdir(okdir)
+ errordir = sys.argv[2]
+ assert os.path.isdir(errordir)
+
+ ipdlargv = []
+ oksuite = unittest.TestSuite()
+ errorsuite = unittest.TestSuite()
+
+ oktests, errortests = False, False
+ for arg in sys.argv[3:]:
+ if errortests:
+ # The extra subdirectory is used for non-failing files we want
+ # to include from failing files.
+ errorIncludes = ["-I", os.path.join(errordir, "extra"), "-I", errordir]
+ errorsuite.addTest(ErrorTestCase(ipdlargv + errorIncludes, arg))
+ elif oktests:
+ if "ERRORTESTS" == arg:
+ errortests = True
+ continue
+ oksuite.addTest(OkTestCase(ipdlargv + ["-I", okdir], arg))
+ else:
+ if "OKTESTS" == arg:
+ oktests = True
+ continue
+ ipdlargv.append(arg)
+
+ test_result = (unittest.TextTestRunner()).run(
+ unittest.TestSuite([oksuite, errorsuite])
+ )
+ sys.exit(not test_result.wasSuccessful())
diff --git a/ipc/ipdl/test/ipdl/sync-messages.ini b/ipc/ipdl/test/ipdl/sync-messages.ini
new file mode 100644
index 0000000000..989964f0dd
--- /dev/null
+++ b/ipc/ipdl/test/ipdl/sync-messages.ini
@@ -0,0 +1,50 @@
+[Pactorreturn::Msg]
+description = test only
+[Parray_Union::Msg]
+description = test only
+[Punion_Basic::Msg]
+description = test only
+[PStruct::test]
+description = test only
+[PStructComparable::test]
+description = test only
+[Punion_Comparable::Msg]
+description = test only
+[PintrProtocol::SyncMsg]
+description = test only
+[PintrProtocol::InterruptMsg]
+description = test only
+[Pshmem::SyncMsg]
+description = test only
+[Pshmem::InterruptMsg]
+description = test only
+[Pbytebuf::SyncMsg]
+description = test only
+[Pbytebuf::InterruptMsg]
+description = test only
+[PsyncProtocol::SyncMsg]
+description = test only
+[PDeleteSub::__delete__]
+description = test only
+[PintrMessageCompress::foo]
+description = test only
+[PintrMessageCompress::bar]
+description = test only
+[PsyncMessageCompress::foo]
+description = test only
+[PsyncParentToChild::Msg]
+description = test only
+[PtooWeakIntrSync::Msg]
+description = test only
+[PtooWeakSyncAsync::Msg]
+description = test only
+[PundeclReturnType::Msg]
+description = test only
+[PasyncMessageListed::Msg]
+description = test only
+[PNested::InsideSync]
+description = test only
+[PNested::InsideCpowSync]
+description = test only
+[PMyManager::SomeMsg]
+description = test and docs only
diff --git a/ipc/ipdl/test/moz.build b/ipc/ipdl/test/moz.build
new file mode 100644
index 0000000000..a323b4a2eb
--- /dev/null
+++ b/ipc/ipdl/test/moz.build
@@ -0,0 +1,9 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += ["ipdl"]
+
+TEST_DIRS += ["gtest"]
diff --git a/ipc/moz.build b/ipc/moz.build
new file mode 100644
index 0000000000..a89607c83a
--- /dev/null
+++ b/ipc/moz.build
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += [
+ "app",
+ "chromium",
+ "glue",
+ "ipdl",
+ "testshell",
+]
+
+if CONFIG["OS_ARCH"] == "WINNT":
+ DIRS += ["mscom"]
+
+TEST_DIRS += [
+ "gtest",
+]
+
+with Files("**"):
+ BUG_COMPONENT = ("Core", "IPC")
+
+SPHINX_TREES["/ipc"] = "docs"
+
+with Files("docs/**"):
+ SCHEDULES.exclusive = ["docs"]
diff --git a/ipc/mscom/Aggregation.h b/ipc/mscom/Aggregation.h
new file mode 100644
index 0000000000..ca171e39cc
--- /dev/null
+++ b/ipc/mscom/Aggregation.h
@@ -0,0 +1,83 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_Aggregation_h
+#define mozilla_mscom_Aggregation_h
+
+#include "mozilla/Attributes.h"
+
+#include <stddef.h>
+#include <unknwn.h>
+
+namespace mozilla {
+namespace mscom {
+
+/**
+ * This is used for stabilizing a COM object's reference count during
+ * construction when that object aggregates other objects. Since the aggregated
+ * object(s) may AddRef() or Release(), we need to artifically boost the
+ * refcount to prevent premature destruction. Note that we increment/decrement
+ * instead of AddRef()/Release() in this class because we want to adjust the
+ * refcount without causing any other side effects (like object destruction).
+ */
+template <typename RefCntT>
+class MOZ_RAII StabilizedRefCount {
+ public:
+ explicit StabilizedRefCount(RefCntT& aRefCnt) : mRefCnt(aRefCnt) {
+ ++aRefCnt;
+ }
+
+ ~StabilizedRefCount() { --mRefCnt; }
+
+ StabilizedRefCount(const StabilizedRefCount&) = delete;
+ StabilizedRefCount(StabilizedRefCount&&) = delete;
+ StabilizedRefCount& operator=(const StabilizedRefCount&) = delete;
+ StabilizedRefCount& operator=(StabilizedRefCount&&) = delete;
+
+ private:
+ RefCntT& mRefCnt;
+};
+
+namespace detail {
+
+template <typename T>
+class InternalUnknown : public IUnknown {
+ public:
+ STDMETHODIMP QueryInterface(REFIID aIid, void** aOutInterface) override {
+ return This()->InternalQueryInterface(aIid, aOutInterface);
+ }
+
+ STDMETHODIMP_(ULONG) AddRef() override { return This()->InternalAddRef(); }
+
+ STDMETHODIMP_(ULONG) Release() override { return This()->InternalRelease(); }
+
+ private:
+ T* This() {
+ return reinterpret_cast<T*>(reinterpret_cast<char*>(this) -
+ offsetof(T, mInternalUnknown));
+ }
+};
+
+} // namespace detail
+} // namespace mscom
+} // namespace mozilla
+
+#define DECLARE_AGGREGATABLE(Type) \
+ public: \
+ STDMETHODIMP QueryInterface(REFIID riid, void** ppv) override { \
+ return mOuter->QueryInterface(riid, ppv); \
+ } \
+ STDMETHODIMP_(ULONG) AddRef() override { return mOuter->AddRef(); } \
+ STDMETHODIMP_(ULONG) Release() override { return mOuter->Release(); } \
+ \
+ protected: \
+ STDMETHODIMP InternalQueryInterface(REFIID riid, void** ppv); \
+ STDMETHODIMP_(ULONG) InternalAddRef(); \
+ STDMETHODIMP_(ULONG) InternalRelease(); \
+ friend class mozilla::mscom::detail::InternalUnknown<Type>; \
+ mozilla::mscom::detail::InternalUnknown<Type> mInternalUnknown
+
+#endif // mozilla_mscom_Aggregation_h
diff --git a/ipc/mscom/AgileReference.cpp b/ipc/mscom/AgileReference.cpp
new file mode 100644
index 0000000000..76fe773b0a
--- /dev/null
+++ b/ipc/mscom/AgileReference.cpp
@@ -0,0 +1,64 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/mscom/AgileReference.h"
+
+#include <utility>
+#include "mozilla/Assertions.h"
+#include "mozilla/mscom/Utils.h"
+
+#if defined(__MINGW32__)
+
+// Declarations from Windows SDK specific to Windows 8.1
+
+enum AgileReferenceOptions {
+ AGILEREFERENCE_DEFAULT = 0,
+ AGILEREFERENCE_DELAYEDMARSHAL = 1,
+};
+
+HRESULT WINAPI RoGetAgileReference(AgileReferenceOptions options, REFIID riid,
+ IUnknown* pUnk,
+ IAgileReference** ppAgileReference);
+
+// Unfortunately, at time of writing, MinGW doesn't know how to statically link
+// to RoGetAgileReference. On these builds only, we substitute a runtime-linked
+// function pointer.
+
+# include "mozilla/DynamicallyLinkedFunctionPtr.h"
+
+static const mozilla::StaticDynamicallyLinkedFunctionPtr<
+ decltype(&::RoGetAgileReference)>
+ pRoGetAgileReference(L"ole32.dll", "RoGetAgileReference");
+
+# define RoGetAgileReference pRoGetAgileReference
+
+#endif // defined(__MINGW32__)
+
+namespace mozilla::mscom::detail {
+
+HRESULT AgileReference_CreateImpl(RefPtr<IAgileReference>& aRefPtr, REFIID riid,
+ IUnknown* aObject) {
+ MOZ_ASSERT(aObject);
+ MOZ_ASSERT(IsCOMInitializedOnCurrentThread());
+ return ::RoGetAgileReference(AGILEREFERENCE_DEFAULT, riid, aObject,
+ getter_AddRefs(aRefPtr));
+}
+
+HRESULT AgileReference_ResolveImpl(RefPtr<IAgileReference> const& aRefPtr,
+ REFIID riid, void** aOutInterface) {
+ MOZ_ASSERT(aRefPtr);
+ MOZ_ASSERT(aOutInterface);
+ MOZ_ASSERT(IsCOMInitializedOnCurrentThread());
+
+ if (!aRefPtr || !aOutInterface) {
+ return E_INVALIDARG;
+ }
+
+ *aOutInterface = nullptr;
+ return aRefPtr->Resolve(riid, aOutInterface);
+}
+
+} // namespace mozilla::mscom::detail
diff --git a/ipc/mscom/AgileReference.h b/ipc/mscom/AgileReference.h
new file mode 100644
index 0000000000..384c391ac7
--- /dev/null
+++ b/ipc/mscom/AgileReference.h
@@ -0,0 +1,143 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_AgileReference_h
+#define mozilla_mscom_AgileReference_h
+
+#include "mozilla/Attributes.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/Result.h"
+#include "mozilla/Unused.h"
+#include "nsDebug.h"
+#include "nsISupportsImpl.h"
+
+#include <objidl.h>
+
+namespace mozilla::mscom {
+
+namespace detail {
+// Detemplatized implementation details of `AgileReference`.
+HRESULT AgileReference_CreateImpl(RefPtr<IAgileReference>&, REFIID, IUnknown*);
+HRESULT AgileReference_ResolveImpl(RefPtr<IAgileReference> const&, REFIID,
+ void**);
+} // namespace detail
+
+/**
+ * This class encapsulates an "agile reference". These are references that allow
+ * you to pass COM interfaces between apartments. When you have an interface
+ * that you would like to pass between apartments, you wrap that interface in an
+ * AgileReference and pass that instead. Then you can "unwrap" the interface by
+ * calling Resolve(), which will return a proxy object implementing the same
+ * interface.
+ *
+ * Sample usage:
+ *
+ * ```
+ * // From a non-main thread, where `foo` is an `IFoo*` or `RefPtr<IFoo>`:
+ * auto myAgileRef = AgileReference(foo);
+ * NS_DispatchToMainThread([mar = std::move(myAgileRef)] {
+ * RefPtr<IFoo> foo = mar.Resolve();
+ * // Now methods may be invoked on `foo`
+ * });
+ * ```
+ */
+template <typename InterfaceT>
+class AgileReference final {
+ static_assert(
+ std::is_base_of_v<IUnknown, InterfaceT>,
+ "template parameter of AgileReference must be a COM interface type");
+
+ public:
+ AgileReference() = default;
+ ~AgileReference() = default;
+
+ AgileReference(const AgileReference& aOther) = default;
+ AgileReference(AgileReference&& aOther) noexcept = default;
+
+ AgileReference& operator=(const AgileReference& aOther) = default;
+ AgileReference& operator=(AgileReference&& aOther) noexcept = default;
+
+ AgileReference& operator=(std::nullptr_t) {
+ mAgileRef = nullptr;
+ return *this;
+ }
+
+ // Create a new AgileReference from an existing COM object.
+ //
+ // These constructors do not provide the HRESULT on failure. If that's
+ // desired, use `AgileReference::Create()`, below.
+ explicit AgileReference(InterfaceT* aObject) {
+ HRESULT const hr = detail::AgileReference_CreateImpl(
+ mAgileRef, __uuidof(InterfaceT), aObject);
+ Unused << NS_WARN_IF(FAILED(hr));
+ }
+ explicit AgileReference(RefPtr<InterfaceT> const& aObject)
+ : AgileReference(aObject.get()) {}
+
+ // Create a new AgileReference from an existing COM object, or alternatively,
+ // return the HRESULT explaining why one couldn't be created.
+ //
+ // A convenience wrapper `MakeAgileReference()` which infers `InterfaceT` from
+ // the RefPtr's concrete type is provided below.
+ static Result<AgileReference<InterfaceT>, HRESULT> Create(
+ RefPtr<InterfaceT> const& aObject) {
+ AgileReference ret;
+ HRESULT const hr = detail::AgileReference_CreateImpl(
+ ret.mAgileRef, __uuidof(InterfaceT), aObject.get());
+ if (FAILED(hr)) {
+ return Err(hr);
+ }
+ return ret;
+ }
+
+ explicit operator bool() const { return !!mAgileRef; }
+
+ // Common case: resolve directly to the originally-specified interface-type.
+ RefPtr<InterfaceT> Resolve() const {
+ auto res = ResolveAs<InterfaceT>();
+ if (res.isErr()) return nullptr;
+ return res.unwrap();
+ }
+
+ // Uncommon cases: resolve directly to a different interface type, and/or
+ // provide IAgileReference::Resolve()'s HRESULT.
+ //
+ // When used in other COM apartments, `IAgileInterface::Resolve()` returns a
+ // proxy object which (at time of writing) is not documented to provide any
+ // interface other than the one for which it was instantiated. (Calling
+ // `QueryInterface` _might_ work, but isn't explicitly guaranteed.)
+ //
+ template <typename OtherInterface = InterfaceT>
+ Result<RefPtr<OtherInterface>, HRESULT> ResolveAs() const {
+ RefPtr<OtherInterface> p;
+ auto const hr = ResolveRaw(__uuidof(OtherInterface), getter_AddRefs(p));
+ if (FAILED(hr)) {
+ return Err(hr);
+ }
+ return p;
+ }
+
+ // Raw version of Resolve/ResolveAs. Rarely, if ever, preferable to the
+ // statically-typed versions.
+ HRESULT ResolveRaw(REFIID aIid, void** aOutInterface) const {
+ return detail::AgileReference_ResolveImpl(mAgileRef, aIid, aOutInterface);
+ }
+
+ private:
+ RefPtr<IAgileReference> mAgileRef;
+};
+
+// Attempt to create an AgileReference from a refcounted interface pointer,
+// providing the HRESULT as a secondary return-value.
+template <typename InterfaceT>
+inline Result<AgileReference<InterfaceT>, HRESULT> MakeAgileReference(
+ RefPtr<InterfaceT> const& aObj) {
+ return AgileReference<InterfaceT>::Create(aObj);
+}
+
+} // namespace mozilla::mscom
+
+#endif // mozilla_mscom_AgileReference_h
diff --git a/ipc/mscom/ApartmentRegion.h b/ipc/mscom/ApartmentRegion.h
new file mode 100644
index 0000000000..ea942b95b5
--- /dev/null
+++ b/ipc/mscom/ApartmentRegion.h
@@ -0,0 +1,106 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_ApartmentRegion_h
+#define mozilla_mscom_ApartmentRegion_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/mscom/COMWrappers.h"
+
+namespace mozilla::mscom {
+
+// This runtime-dynamic apartment class is used in ProcessRuntime.cpp, to
+// initialize the process's main thread. Do not use it in new contexts if at all
+// possible; instead, prefer ApartmentRegionT, below.
+//
+// For backwards compatibility, this class does not yet automatically disable
+// OLE1/DDE, although there is believed to be no code relying on it.
+//
+// (TODO: phase out all uses of CoInitialize without `COINIT_DISABLE_OLE1DDE`?)
+class MOZ_NON_TEMPORARY_CLASS ApartmentRegion final {
+ public:
+ /**
+ * This constructor is to be used when we want to instantiate the object but
+ * we do not yet know which type of apartment we want. Call Init() to
+ * complete initialization.
+ */
+ constexpr ApartmentRegion() : mInitResult(CO_E_NOTINITIALIZED) {}
+
+ explicit ApartmentRegion(COINIT aAptType)
+ : mInitResult(wrapped::CoInitializeEx(nullptr, aAptType)) {
+ // If this fires then we're probably mixing apartments on the same thread
+ MOZ_ASSERT(IsValid());
+ }
+
+ ~ApartmentRegion() {
+ if (IsValid()) {
+ wrapped::CoUninitialize();
+ }
+ }
+
+ explicit operator bool() const { return IsValid(); }
+
+ bool IsValidOutermost() const { return mInitResult == S_OK; }
+
+ bool IsValid() const { return SUCCEEDED(mInitResult); }
+
+ bool Init(COINIT aAptType) {
+ MOZ_ASSERT(mInitResult == CO_E_NOTINITIALIZED);
+ mInitResult = wrapped::CoInitializeEx(nullptr, aAptType);
+ MOZ_ASSERT(IsValid());
+ return IsValid();
+ }
+
+ HRESULT GetHResult() const { return mInitResult; }
+
+ ApartmentRegion(const ApartmentRegion&) = delete;
+ ApartmentRegion& operator=(const ApartmentRegion&) = delete;
+ ApartmentRegion(ApartmentRegion&&) = delete;
+ ApartmentRegion& operator=(ApartmentRegion&&) = delete;
+
+ private:
+ HRESULT mInitResult;
+};
+
+template <COINIT AptType, bool UseOLE1 = false>
+class MOZ_NON_TEMPORARY_CLASS ApartmentRegionT final {
+ static COINIT ActualType() {
+ static_assert(
+ !((AptType & COINIT_DISABLE_OLE1DDE) == 0 && UseOLE1),
+ "only one of `UseOLE1` and `COINIT_DISABLE_OLE1DDE` permitted");
+ if (UseOLE1) return AptType;
+ return static_cast<COINIT>(AptType | COINIT_DISABLE_OLE1DDE);
+ }
+
+ public:
+ ApartmentRegionT() : mAptRgn(ActualType()) {}
+
+ ~ApartmentRegionT() = default;
+
+ explicit operator bool() const { return mAptRgn.IsValid(); }
+
+ bool IsValidOutermost() const { return mAptRgn.IsValidOutermost(); }
+
+ bool IsValid() const { return mAptRgn.IsValid(); }
+
+ HRESULT GetHResult() const { return mAptRgn.GetHResult(); }
+
+ ApartmentRegionT(const ApartmentRegionT&) = delete;
+ ApartmentRegionT& operator=(const ApartmentRegionT&) = delete;
+ ApartmentRegionT(ApartmentRegionT&&) = delete;
+ ApartmentRegionT& operator=(ApartmentRegionT&&) = delete;
+
+ private:
+ ApartmentRegion mAptRgn;
+};
+
+using STARegion = ApartmentRegionT<COINIT_APARTMENTTHREADED>;
+using MTARegion = ApartmentRegionT<COINIT_MULTITHREADED>;
+
+} // namespace mozilla::mscom
+
+#endif // mozilla_mscom_ApartmentRegion_h
diff --git a/ipc/mscom/COMWrappers.cpp b/ipc/mscom/COMWrappers.cpp
new file mode 100644
index 0000000000..1bc48a4927
--- /dev/null
+++ b/ipc/mscom/COMWrappers.cpp
@@ -0,0 +1,101 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/mscom/COMWrappers.h"
+
+#include <objbase.h>
+
+#include "mozilla/Assertions.h"
+#include "mozilla/DynamicallyLinkedFunctionPtr.h"
+
+namespace mozilla::mscom::wrapped {
+
+HRESULT CoInitializeEx(LPVOID pvReserved, DWORD dwCoInit) {
+ static const StaticDynamicallyLinkedFunctionPtr<decltype(&::CoInitializeEx)>
+ pCoInitializeEx(L"combase.dll", "CoInitializeEx");
+ if (!pCoInitializeEx) {
+ return ::CoInitializeEx(pvReserved, dwCoInit);
+ }
+
+ return pCoInitializeEx(pvReserved, dwCoInit);
+}
+
+void CoUninitialize() {
+ static const StaticDynamicallyLinkedFunctionPtr<decltype(&::CoUninitialize)>
+ pCoUninitialize(L"combase.dll", "CoUninitialize");
+ if (!pCoUninitialize) {
+ return ::CoUninitialize();
+ }
+
+ return pCoUninitialize();
+}
+
+HRESULT CoIncrementMTAUsage(CO_MTA_USAGE_COOKIE* pCookie) {
+ static const StaticDynamicallyLinkedFunctionPtr<
+ decltype(&::CoIncrementMTAUsage)>
+ pCoIncrementMTAUsage(L"combase.dll", "CoIncrementMTAUsage");
+ // This API is only available beginning with Windows 8.
+ if (!pCoIncrementMTAUsage) {
+ return E_NOTIMPL;
+ }
+
+ HRESULT hr = pCoIncrementMTAUsage(pCookie);
+ MOZ_ASSERT(SUCCEEDED(hr));
+ return hr;
+}
+
+HRESULT CoGetApartmentType(APTTYPE* pAptType, APTTYPEQUALIFIER* pAptQualifier) {
+ static const StaticDynamicallyLinkedFunctionPtr<
+ decltype(&::CoGetApartmentType)>
+ pCoGetApartmentType(L"combase.dll", "CoGetApartmentType");
+ if (!pCoGetApartmentType) {
+ return ::CoGetApartmentType(pAptType, pAptQualifier);
+ }
+
+ return pCoGetApartmentType(pAptType, pAptQualifier);
+}
+
+HRESULT CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
+ SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
+ void* pReserved1, DWORD dwAuthnLevel,
+ DWORD dwImpLevel, void* pAuthList,
+ DWORD dwCapabilities, void* pReserved3) {
+ static const StaticDynamicallyLinkedFunctionPtr<
+ decltype(&::CoInitializeSecurity)>
+ pCoInitializeSecurity(L"combase.dll", "CoInitializeSecurity");
+ if (!pCoInitializeSecurity) {
+ return ::CoInitializeSecurity(pSecDesc, cAuthSvc, asAuthSvc, pReserved1,
+ dwAuthnLevel, dwImpLevel, pAuthList,
+ dwCapabilities, pReserved3);
+ }
+
+ return pCoInitializeSecurity(pSecDesc, cAuthSvc, asAuthSvc, pReserved1,
+ dwAuthnLevel, dwImpLevel, pAuthList,
+ dwCapabilities, pReserved3);
+}
+
+HRESULT CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter,
+ DWORD dwClsContext, REFIID riid, LPVOID* ppv) {
+ static const StaticDynamicallyLinkedFunctionPtr<decltype(&::CoCreateInstance)>
+ pCoCreateInstance(L"combase.dll", "CoCreateInstance");
+ if (!pCoCreateInstance) {
+ return ::CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv);
+ }
+
+ return pCoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv);
+}
+
+HRESULT CoCreateGuid(GUID* pguid) {
+ static const StaticDynamicallyLinkedFunctionPtr<decltype(&::CoCreateGuid)>
+ pCoCreateGuid(L"combase.dll", "CoCreateGuid");
+ if (!pCoCreateGuid) {
+ return ::CoCreateGuid(pguid);
+ }
+
+ return pCoCreateGuid(pguid);
+}
+
+} // namespace mozilla::mscom::wrapped
diff --git a/ipc/mscom/COMWrappers.h b/ipc/mscom/COMWrappers.h
new file mode 100644
index 0000000000..4550d4d347
--- /dev/null
+++ b/ipc/mscom/COMWrappers.h
@@ -0,0 +1,38 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_COMWrappers_h
+#define mozilla_mscom_COMWrappers_h
+
+#include <objbase.h>
+
+// A set of wrapped COM functions, so that we can dynamically link to the
+// functions in combase.dll on win8+. This prevents ole32.dll and many other
+// DLLs loading, which are not required when we have win32k locked down.
+namespace mozilla::mscom::wrapped {
+
+HRESULT CoInitializeEx(LPVOID pvReserved, DWORD dwCoInit);
+
+void CoUninitialize();
+
+HRESULT CoIncrementMTAUsage(CO_MTA_USAGE_COOKIE* pCookie);
+
+HRESULT CoGetApartmentType(APTTYPE* pAptType, APTTYPEQUALIFIER* pAptQualifier);
+
+HRESULT CoInitializeSecurity(PSECURITY_DESCRIPTOR pSecDesc, LONG cAuthSvc,
+ SOLE_AUTHENTICATION_SERVICE* asAuthSvc,
+ void* pReserved1, DWORD dwAuthnLevel,
+ DWORD dwImpLevel, void* pAuthList,
+ DWORD dwCapabilities, void* pReserved3);
+
+HRESULT CoCreateInstance(REFCLSID rclsid, LPUNKNOWN pUnkOuter,
+ DWORD dwClsContext, REFIID riid, LPVOID* ppv);
+
+HRESULT CoCreateGuid(GUID* pguid);
+
+} // namespace mozilla::mscom::wrapped
+
+#endif // mozilla_mscom_COMWrappers_h
diff --git a/ipc/mscom/EnsureMTA.cpp b/ipc/mscom/EnsureMTA.cpp
new file mode 100644
index 0000000000..49d8446fa2
--- /dev/null
+++ b/ipc/mscom/EnsureMTA.cpp
@@ -0,0 +1,189 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/mscom/EnsureMTA.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/ClearOnShutdown.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/mscom/COMWrappers.h"
+#include "mozilla/mscom/ProcessRuntime.h"
+#include "mozilla/mscom/Utils.h"
+#include "mozilla/SchedulerGroup.h"
+#include "mozilla/StaticLocalPtr.h"
+#include "nsThreadManager.h"
+#include "nsThreadUtils.h"
+
+#include "private/pprthred.h"
+
+namespace {
+
+class EnterMTARunnable : public mozilla::Runnable {
+ public:
+ EnterMTARunnable() : mozilla::Runnable("EnterMTARunnable") {}
+ NS_IMETHOD Run() override {
+ mozilla::DebugOnly<HRESULT> hr =
+ mozilla::mscom::wrapped::CoInitializeEx(nullptr, COINIT_MULTITHREADED);
+ MOZ_ASSERT(SUCCEEDED(hr));
+ return NS_OK;
+ }
+};
+
+class BackgroundMTAData {
+ public:
+ BackgroundMTAData() {
+ nsCOMPtr<nsIRunnable> runnable = new EnterMTARunnable();
+ mozilla::DebugOnly<nsresult> rv = NS_NewNamedThread(
+ "COM MTA", getter_AddRefs(mThread), runnable.forget());
+ NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "NS_NewNamedThread failed");
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+ }
+
+ ~BackgroundMTAData() {
+ if (mThread) {
+ mThread->Dispatch(
+ NS_NewRunnableFunction("BackgroundMTAData::~BackgroundMTAData",
+ &mozilla::mscom::wrapped::CoUninitialize),
+ NS_DISPATCH_NORMAL);
+ mThread->Shutdown();
+ }
+ }
+
+ nsCOMPtr<nsIThread> GetThread() const { return mThread; }
+
+ private:
+ nsCOMPtr<nsIThread> mThread;
+};
+
+} // anonymous namespace
+
+namespace mozilla {
+namespace mscom {
+
+EnsureMTA::EnsureMTA() {
+ MOZ_ASSERT(NS_IsMainThread());
+
+ // It is possible that we're running so early that we might need to start
+ // the thread manager ourselves. We do this here to guarantee that we have
+ // the ability to start the persistent MTA thread at any moment beyond this
+ // point.
+ nsresult rv = nsThreadManager::get().Init();
+ // We intentionally don't check rv unless we need it when
+ // CoIncremementMTAUsage is unavailable.
+
+ // Calling this function initializes the MTA without needing to explicitly
+ // create a thread and call CoInitializeEx to do it.
+ // We don't retain the cookie because once we've incremented the MTA, we
+ // leave it that way for the lifetime of the process.
+ CO_MTA_USAGE_COOKIE mtaCookie = nullptr;
+ HRESULT hr = wrapped::CoIncrementMTAUsage(&mtaCookie);
+ if (SUCCEEDED(hr)) {
+ if (NS_SUCCEEDED(rv)) {
+ // Start the persistent MTA thread (mostly) asynchronously.
+ Unused << GetPersistentMTAThread();
+ }
+
+ return;
+ }
+
+ // In the fallback case, we simply initialize our persistent MTA thread.
+
+ // Make sure thread manager init succeeded before trying to initialize the
+ // persistent MTA thread.
+ MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
+ if (NS_FAILED(rv)) {
+ return;
+ }
+
+ // Before proceeding any further, pump a runnable through the persistent MTA
+ // thread to ensure that it is up and running and has finished initializing
+ // the multi-threaded apartment.
+ nsCOMPtr<nsIRunnable> runnable(NS_NewRunnableFunction(
+ "EnsureMTA::EnsureMTA()",
+ []() { MOZ_RELEASE_ASSERT(IsCurrentThreadExplicitMTA()); }));
+ SyncDispatchToPersistentThread(runnable);
+}
+
+/* static */
+nsCOMPtr<nsIThread> EnsureMTA::GetPersistentMTAThread() {
+ static StaticLocalAutoPtr<BackgroundMTAData> sMTAData(
+ []() -> BackgroundMTAData* {
+ BackgroundMTAData* bgData = new BackgroundMTAData();
+
+ auto setClearOnShutdown = [ptr = &sMTAData]() -> void {
+ ClearOnShutdown(ptr, ShutdownPhase::XPCOMShutdownThreads);
+ };
+
+ if (NS_IsMainThread()) {
+ setClearOnShutdown();
+ return bgData;
+ }
+
+ SchedulerGroup::Dispatch(
+ NS_NewRunnableFunction("mscom::EnsureMTA::GetPersistentMTAThread",
+ std::move(setClearOnShutdown)));
+
+ return bgData;
+ }());
+
+ MOZ_ASSERT(sMTAData);
+
+ return sMTAData->GetThread();
+}
+
+/* static */
+void EnsureMTA::SyncDispatchToPersistentThread(nsIRunnable* aRunnable) {
+ nsCOMPtr<nsIThread> thread(GetPersistentMTAThread());
+ MOZ_ASSERT(thread);
+ if (!thread) {
+ return;
+ }
+
+ // Note that, due to APC dispatch, we might reenter this function while we
+ // wait on this event. We therefore need a unique event object for each
+ // entry into this function. If perf becomes an issue then we will want to
+ // maintain an array of events where the Nth event is unique to the Nth
+ // reentry.
+ nsAutoHandle event(::CreateEventW(nullptr, FALSE, FALSE, nullptr));
+ if (!event) {
+ return;
+ }
+
+ HANDLE eventHandle = event.get();
+ auto eventSetter = [&aRunnable, eventHandle]() -> void {
+ aRunnable->Run();
+ ::SetEvent(eventHandle);
+ };
+
+ nsresult rv = thread->Dispatch(
+ NS_NewRunnableFunction("mscom::EnsureMTA::SyncDispatchToPersistentThread",
+ std::move(eventSetter)),
+ NS_DISPATCH_NORMAL);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+ if (NS_FAILED(rv)) {
+ return;
+ }
+
+ AUTO_PROFILER_THREAD_SLEEP;
+ DWORD waitResult;
+ while ((waitResult = ::WaitForSingleObjectEx(event, INFINITE, FALSE)) ==
+ WAIT_IO_COMPLETION) {
+ }
+ MOZ_ASSERT(waitResult == WAIT_OBJECT_0);
+}
+
+/**
+ * While this function currently appears to be redundant, it may become more
+ * sophisticated in the future. For example, we could optionally dispatch to an
+ * MTA context if we wanted to utilize the MTA thread pool.
+ */
+/* static */
+void EnsureMTA::SyncDispatch(nsCOMPtr<nsIRunnable>&& aRunnable, Option aOpt) {
+ SyncDispatchToPersistentThread(aRunnable);
+}
+
+} // namespace mscom
+} // namespace mozilla
diff --git a/ipc/mscom/EnsureMTA.h b/ipc/mscom/EnsureMTA.h
new file mode 100644
index 0000000000..662192c476
--- /dev/null
+++ b/ipc/mscom/EnsureMTA.h
@@ -0,0 +1,129 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_EnsureMTA_h
+#define mozilla_mscom_EnsureMTA_h
+
+#include "MainThreadUtils.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/MozPromise.h"
+#include "mozilla/Unused.h"
+#include "mozilla/mscom/AgileReference.h"
+#include "mozilla/mscom/Utils.h"
+#include "mozilla/RefPtr.h"
+#include "nsCOMPtr.h"
+#include "nsIThread.h"
+#include "nsThreadUtils.h"
+#include "nsWindowsHelpers.h"
+
+#include <windows.h>
+
+namespace mozilla {
+namespace mscom {
+namespace detail {
+
+// Forward declarations
+template <typename T>
+struct MTADelete;
+
+template <typename T>
+struct MTARelease;
+
+template <typename T>
+struct MTAReleaseInChildProcess;
+
+struct PreservedStreamDeleter;
+
+} // namespace detail
+
+class ProcessRuntime;
+
+// This class is OK to use as a temporary on the stack.
+class MOZ_STACK_CLASS EnsureMTA final {
+ public:
+ enum class Option {
+ Default,
+ // Forcibly dispatch to the thread returned by GetPersistentMTAThread(),
+ // even if the current thread is already inside a MTA.
+ ForceDispatchToPersistentThread,
+ };
+
+ /**
+ * Synchronously run |aClosure| on a thread living in the COM multithreaded
+ * apartment. If the current thread lives inside the COM MTA, then it runs
+ * |aClosure| immediately unless |aOpt| ==
+ * Option::ForceDispatchToPersistentThread.
+ */
+ template <typename FuncT>
+ explicit EnsureMTA(FuncT&& aClosure, Option aOpt = Option::Default) {
+ if (aOpt != Option::ForceDispatchToPersistentThread &&
+ IsCurrentThreadMTA()) {
+ // We're already on the MTA, we can run aClosure directly
+ aClosure();
+ return;
+ }
+
+ // In this case we need to run aClosure on a background thread in the MTA
+ nsCOMPtr<nsIRunnable> runnable(
+ NS_NewRunnableFunction("EnsureMTA::EnsureMTA", std::move(aClosure)));
+ SyncDispatch(std::move(runnable), aOpt);
+ }
+
+ private:
+ static nsCOMPtr<nsIThread> GetPersistentMTAThread();
+
+ static void SyncDispatch(nsCOMPtr<nsIRunnable>&& aRunnable, Option aOpt);
+ static void SyncDispatchToPersistentThread(nsIRunnable* aRunnable);
+
+ // The following function is private in order to force any consumers to be
+ // declared as friends of EnsureMTA. The intention is to prevent
+ // AsyncOperation from becoming some kind of free-for-all mechanism for
+ // asynchronously executing work on a background thread.
+ template <typename FuncT>
+ static void AsyncOperation(FuncT&& aClosure) {
+ if (IsCurrentThreadMTA()) {
+ aClosure();
+ return;
+ }
+
+ nsCOMPtr<nsIThread> thread(GetPersistentMTAThread());
+ MOZ_ASSERT(thread);
+ if (!thread) {
+ return;
+ }
+
+ DebugOnly<nsresult> rv = thread->Dispatch(
+ NS_NewRunnableFunction("mscom::EnsureMTA::AsyncOperation",
+ std::move(aClosure)),
+ NS_DISPATCH_NORMAL);
+ MOZ_ASSERT(NS_SUCCEEDED(rv));
+ }
+
+ /**
+ * This constructor just ensures that the MTA is up and running. This should
+ * only be called by ProcessRuntime.
+ */
+ EnsureMTA();
+
+ friend class mozilla::mscom::ProcessRuntime;
+
+ template <typename T>
+ friend struct mozilla::mscom::detail::MTADelete;
+
+ template <typename T>
+ friend struct mozilla::mscom::detail::MTARelease;
+
+ template <typename T>
+ friend struct mozilla::mscom::detail::MTAReleaseInChildProcess;
+
+ friend struct mozilla::mscom::detail::PreservedStreamDeleter;
+};
+
+} // namespace mscom
+} // namespace mozilla
+
+#endif // mozilla_mscom_EnsureMTA_h
diff --git a/ipc/mscom/ProcessRuntime.cpp b/ipc/mscom/ProcessRuntime.cpp
new file mode 100644
index 0000000000..ae4e32247c
--- /dev/null
+++ b/ipc/mscom/ProcessRuntime.cpp
@@ -0,0 +1,486 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/mscom/ProcessRuntime.h"
+
+#include "mozilla/Assertions.h"
+#include "mozilla/DynamicallyLinkedFunctionPtr.h"
+#include "mozilla/mscom/COMWrappers.h"
+#include "mozilla/mscom/ProcessRuntimeShared.h"
+#include "mozilla/RefPtr.h"
+#include "mozilla/UniquePtr.h"
+#include "mozilla/Unused.h"
+#include "mozilla/Vector.h"
+#include "mozilla/WindowsProcessMitigations.h"
+
+#if defined(MOZILLA_INTERNAL_API)
+# include "mozilla/mscom/EnsureMTA.h"
+# if defined(MOZ_SANDBOX)
+# include "mozilla/sandboxTarget.h"
+# endif // defined(MOZ_SANDBOX)
+#endif // defined(MOZILLA_INTERNAL_API)
+
+#include <accctrl.h>
+#include <aclapi.h>
+#include <objbase.h>
+#include <objidl.h>
+
+// This API from oleaut32.dll is not declared in Windows SDK headers
+extern "C" void __cdecl SetOaNoCache(void);
+
+using namespace mozilla::mscom::detail;
+
+namespace mozilla {
+namespace mscom {
+
+#if defined(MOZILLA_INTERNAL_API)
+ProcessRuntime* ProcessRuntime::sInstance = nullptr;
+
+ProcessRuntime::ProcessRuntime() : ProcessRuntime(XRE_GetProcessType()) {}
+
+ProcessRuntime::ProcessRuntime(const GeckoProcessType aProcessType)
+ : ProcessRuntime(aProcessType == GeckoProcessType_Default
+ ? ProcessCategory::GeckoBrowserParent
+ : ProcessCategory::GeckoChild) {}
+#endif // defined(MOZILLA_INTERNAL_API)
+
+ProcessRuntime::ProcessRuntime(const ProcessCategory aProcessCategory)
+ : mInitResult(CO_E_NOTINITIALIZED), mProcessCategory(aProcessCategory) {
+#if defined(MOZILLA_INTERNAL_API)
+ MOZ_DIAGNOSTIC_ASSERT(!sInstance);
+ sInstance = this;
+
+ EnsureMTA();
+ /**
+ * From this point forward, all threads in this process are implicitly
+ * members of the multi-threaded apartment, with the following exceptions:
+ * 1. If any Win32 GUI APIs were called on the current thread prior to
+ * executing this constructor, then this thread has already been implicitly
+ * initialized as the process's main STA thread; or
+ * 2. A thread explicitly and successfully calls CoInitialize(Ex) to specify
+ * otherwise.
+ */
+
+ const bool isCurThreadImplicitMTA = IsCurrentThreadImplicitMTA();
+ // We only assert that the implicit MTA precondition holds when not running
+ // as the Gecko parent process.
+ MOZ_DIAGNOSTIC_ASSERT(aProcessCategory ==
+ ProcessCategory::GeckoBrowserParent ||
+ isCurThreadImplicitMTA);
+
+# if defined(MOZ_SANDBOX)
+ const bool isLockedDownChildProcess =
+ mProcessCategory == ProcessCategory::GeckoChild && IsWin32kLockedDown();
+ // If our process is running under Win32k lockdown, we cannot initialize
+ // COM with a single-threaded apartment. This is because STAs create a hidden
+ // window, which implicitly requires user32 and Win32k, which are blocked.
+ // Instead we start the multi-threaded apartment and conduct our process-wide
+ // COM initialization there.
+ if (isLockedDownChildProcess) {
+ // Make sure we're still running with the sandbox's privileged impersonation
+ // token.
+ HANDLE rawCurThreadImpToken;
+ if (!::OpenThreadToken(::GetCurrentThread(), TOKEN_DUPLICATE | TOKEN_QUERY,
+ FALSE, &rawCurThreadImpToken)) {
+ mInitResult = HRESULT_FROM_WIN32(::GetLastError());
+ return;
+ }
+ nsAutoHandle curThreadImpToken(rawCurThreadImpToken);
+
+ // Ensure that our current token is still an impersonation token (ie, we
+ // have not yet called RevertToSelf() on this thread).
+ DWORD len;
+ TOKEN_TYPE tokenType;
+ MOZ_RELEASE_ASSERT(
+ ::GetTokenInformation(rawCurThreadImpToken, TokenType, &tokenType,
+ sizeof(tokenType), &len) &&
+ len == sizeof(tokenType) && tokenType == TokenImpersonation);
+
+ // Ideally we want our current thread to be running implicitly inside the
+ // MTA, but if for some wacky reason we did not end up with that, we may
+ // compensate by completing initialization via EnsureMTA's persistent
+ // thread.
+ if (!isCurThreadImplicitMTA) {
+ InitUsingPersistentMTAThread(curThreadImpToken);
+ return;
+ }
+ }
+# endif // defined(MOZ_SANDBOX)
+#endif // defined(MOZILLA_INTERNAL_API)
+
+ mAptRegion.Init(GetDesiredApartmentType(mProcessCategory));
+
+ // It can happen that we are not the outermost COM initialization on this
+ // thread. In fact it should regularly be the case that the outermost
+ // initialization occurs from outside of XUL, before we show the skeleton UI,
+ // at which point we still need to run some things here from within XUL.
+ if (!mAptRegion.IsValidOutermost()) {
+ mInitResult = mAptRegion.GetHResult();
+#if defined(MOZILLA_INTERNAL_API)
+ MOZ_ASSERT(mProcessCategory == ProcessCategory::GeckoBrowserParent);
+ if (mProcessCategory != ProcessCategory::GeckoBrowserParent) {
+ // This is unexpected unless we're GeckoBrowserParent
+ return;
+ }
+
+ ProcessInitLock lock;
+
+ // Is another instance of ProcessRuntime responsible for the outer
+ // initialization?
+ const bool prevInit =
+ lock.GetInitState() == ProcessInitState::FullyInitialized;
+ MOZ_ASSERT(prevInit);
+ if (prevInit) {
+ PostInit();
+ }
+#endif // defined(MOZILLA_INTERNAL_API)
+ return;
+ }
+
+ InitInsideApartment();
+ if (FAILED(mInitResult)) {
+ return;
+ }
+
+#if defined(MOZILLA_INTERNAL_API)
+# if defined(MOZ_SANDBOX)
+ if (isLockedDownChildProcess) {
+ // In locked-down child processes, defer PostInit until priv drop
+ SandboxTarget::Instance()->RegisterSandboxStartCallback([self = this]() {
+ // Ensure that we're still live and the init was successful before
+ // calling PostInit()
+ if (self == sInstance && SUCCEEDED(self->mInitResult)) {
+ PostInit();
+ }
+ });
+ return;
+ }
+# endif // defined(MOZ_SANDBOX)
+
+ PostInit();
+#endif // defined(MOZILLA_INTERNAL_API)
+}
+
+#if defined(MOZILLA_INTERNAL_API)
+ProcessRuntime::~ProcessRuntime() {
+ MOZ_DIAGNOSTIC_ASSERT(sInstance == this);
+ sInstance = nullptr;
+}
+
+# if defined(MOZ_SANDBOX)
+void ProcessRuntime::InitUsingPersistentMTAThread(
+ const nsAutoHandle& aCurThreadToken) {
+ // Create an impersonation token based on the current thread's token
+ HANDLE rawMtaThreadImpToken = nullptr;
+ if (!::DuplicateToken(aCurThreadToken, SecurityImpersonation,
+ &rawMtaThreadImpToken)) {
+ mInitResult = HRESULT_FROM_WIN32(::GetLastError());
+ return;
+ }
+ nsAutoHandle mtaThreadImpToken(rawMtaThreadImpToken);
+
+ // Impersonate and initialize.
+ bool tokenSet = false;
+ EnsureMTA(
+ [this, rawMtaThreadImpToken, &tokenSet]() -> void {
+ if (!::SetThreadToken(nullptr, rawMtaThreadImpToken)) {
+ mInitResult = HRESULT_FROM_WIN32(::GetLastError());
+ return;
+ }
+
+ tokenSet = true;
+ InitInsideApartment();
+ },
+ EnsureMTA::Option::ForceDispatchToPersistentThread);
+
+ if (!tokenSet) {
+ return;
+ }
+
+ SandboxTarget::Instance()->RegisterSandboxStartCallback(
+ [self = this]() -> void {
+ EnsureMTA(
+ []() -> void {
+ // This is a security risk if it fails, so we release assert
+ MOZ_RELEASE_ASSERT(::RevertToSelf(),
+ "mscom::ProcessRuntime RevertToSelf failed");
+ },
+ EnsureMTA::Option::ForceDispatchToPersistentThread);
+
+ // Ensure that we're still live and the init was successful before
+ // calling PostInit()
+ if (self == sInstance && SUCCEEDED(self->mInitResult)) {
+ PostInit();
+ }
+ });
+}
+# endif // defined(MOZ_SANDBOX)
+#endif // defined(MOZILLA_INTERNAL_API)
+
+/* static */
+COINIT ProcessRuntime::GetDesiredApartmentType(
+ const ProcessRuntime::ProcessCategory aProcessCategory) {
+ switch (aProcessCategory) {
+ case ProcessCategory::GeckoBrowserParent:
+ return COINIT_APARTMENTTHREADED;
+ case ProcessCategory::GeckoChild:
+ if (!IsWin32kLockedDown()) {
+ // If Win32k is not locked down then we probably still need STA.
+ // We disable DDE since that is not usable from child processes.
+ return static_cast<COINIT>(COINIT_APARTMENTTHREADED |
+ COINIT_DISABLE_OLE1DDE);
+ }
+
+ [[fallthrough]];
+ default:
+ return COINIT_MULTITHREADED;
+ }
+}
+
+void ProcessRuntime::InitInsideApartment() {
+ ProcessInitLock lock;
+ const ProcessInitState prevInitState = lock.GetInitState();
+ if (prevInitState == ProcessInitState::FullyInitialized) {
+ // COM has already been initialized by a previous ProcessRuntime instance
+ mInitResult = S_OK;
+ return;
+ }
+
+ if (prevInitState < ProcessInitState::PartialSecurityInitialized) {
+ // We are required to initialize security prior to configuring global
+ // options.
+ mInitResult = InitializeSecurity(mProcessCategory);
+ MOZ_DIAGNOSTIC_ASSERT(SUCCEEDED(mInitResult));
+
+ // Even though this isn't great, we should try to proceed even when
+ // CoInitializeSecurity has previously been called: the additional settings
+ // we want to change are important enough that we don't want to skip them.
+ if (FAILED(mInitResult) && mInitResult != RPC_E_TOO_LATE) {
+ return;
+ }
+
+ lock.SetInitState(ProcessInitState::PartialSecurityInitialized);
+ }
+
+ if (prevInitState < ProcessInitState::PartialGlobalOptions) {
+ RefPtr<IGlobalOptions> globalOpts;
+ mInitResult = wrapped::CoCreateInstance(
+ CLSID_GlobalOptions, nullptr, CLSCTX_INPROC_SERVER, IID_IGlobalOptions,
+ getter_AddRefs(globalOpts));
+ MOZ_ASSERT(SUCCEEDED(mInitResult));
+ if (FAILED(mInitResult)) {
+ return;
+ }
+
+ // Disable COM's catch-all exception handler
+ mInitResult = globalOpts->Set(COMGLB_EXCEPTION_HANDLING,
+ COMGLB_EXCEPTION_DONOT_HANDLE_ANY);
+ MOZ_ASSERT(SUCCEEDED(mInitResult));
+ if (FAILED(mInitResult)) {
+ return;
+ }
+
+ lock.SetInitState(ProcessInitState::PartialGlobalOptions);
+ }
+
+ // Disable the BSTR cache (as it never invalidates, thus leaking memory)
+ // (This function is itself idempotent, so we do not concern ourselves with
+ // tracking whether or not we've already called it.)
+ ::SetOaNoCache();
+
+ lock.SetInitState(ProcessInitState::FullyInitialized);
+}
+
+#if defined(MOZILLA_INTERNAL_API)
+/**
+ * Guaranteed to run *after* the COM (and possible sandboxing) initialization
+ * has successfully completed and stabilized. This method MUST BE IDEMPOTENT!
+ */
+/* static */ void ProcessRuntime::PostInit() {
+ // Currently "roughed-in" but unused.
+}
+#endif // defined(MOZILLA_INTERNAL_API)
+
+/* static */
+DWORD
+ProcessRuntime::GetClientThreadId() {
+ DWORD callerTid;
+ HRESULT hr = ::CoGetCallerTID(&callerTid);
+ // Don't return callerTid unless the call succeeded and returned S_FALSE,
+ // indicating that the caller originates from a different process.
+ if (hr != S_FALSE) {
+ return 0;
+ }
+
+ return callerTid;
+}
+
+/* static */
+HRESULT
+ProcessRuntime::InitializeSecurity(const ProcessCategory aProcessCategory) {
+ HANDLE rawToken = nullptr;
+ BOOL ok = ::OpenProcessToken(::GetCurrentProcess(), TOKEN_QUERY, &rawToken);
+ if (!ok) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+ nsAutoHandle token(rawToken);
+
+ DWORD len = 0;
+ ok = ::GetTokenInformation(token, TokenUser, nullptr, len, &len);
+ DWORD win32Error = ::GetLastError();
+ if (!ok && win32Error != ERROR_INSUFFICIENT_BUFFER) {
+ return HRESULT_FROM_WIN32(win32Error);
+ }
+
+ auto tokenUserBuf = MakeUnique<BYTE[]>(len);
+ TOKEN_USER& tokenUser = *reinterpret_cast<TOKEN_USER*>(tokenUserBuf.get());
+ ok = ::GetTokenInformation(token, TokenUser, tokenUserBuf.get(), len, &len);
+ if (!ok) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ len = 0;
+ ok = ::GetTokenInformation(token, TokenPrimaryGroup, nullptr, len, &len);
+ win32Error = ::GetLastError();
+ if (!ok && win32Error != ERROR_INSUFFICIENT_BUFFER) {
+ return HRESULT_FROM_WIN32(win32Error);
+ }
+
+ auto tokenPrimaryGroupBuf = MakeUnique<BYTE[]>(len);
+ TOKEN_PRIMARY_GROUP& tokenPrimaryGroup =
+ *reinterpret_cast<TOKEN_PRIMARY_GROUP*>(tokenPrimaryGroupBuf.get());
+ ok = ::GetTokenInformation(token, TokenPrimaryGroup,
+ tokenPrimaryGroupBuf.get(), len, &len);
+ if (!ok) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ SECURITY_DESCRIPTOR sd;
+ if (!::InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ BYTE systemSid[SECURITY_MAX_SID_SIZE];
+ DWORD systemSidSize = sizeof(systemSid);
+ if (!::CreateWellKnownSid(WinLocalSystemSid, nullptr, systemSid,
+ &systemSidSize)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ BYTE adminSid[SECURITY_MAX_SID_SIZE];
+ DWORD adminSidSize = sizeof(adminSid);
+ if (!::CreateWellKnownSid(WinBuiltinAdministratorsSid, nullptr, adminSid,
+ &adminSidSize)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ const bool allowAllNonRestrictedAppContainers =
+ aProcessCategory == ProcessCategory::GeckoBrowserParent;
+
+ BYTE appContainersSid[SECURITY_MAX_SID_SIZE];
+ DWORD appContainersSidSize = sizeof(appContainersSid);
+ if (allowAllNonRestrictedAppContainers) {
+ if (!::CreateWellKnownSid(WinBuiltinAnyPackageSid, nullptr,
+ appContainersSid, &appContainersSidSize)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+ }
+
+ UniquePtr<BYTE[]> tokenAppContainerInfBuf;
+ len = 0;
+ ::GetTokenInformation(token, TokenAppContainerSid, nullptr, len, &len);
+ if (len) {
+ tokenAppContainerInfBuf = MakeUnique<BYTE[]>(len);
+ ok = ::GetTokenInformation(token, TokenAppContainerSid,
+ tokenAppContainerInfBuf.get(), len, &len);
+ if (!ok) {
+ // Don't fail if we get an error retrieving an app container SID.
+ tokenAppContainerInfBuf = nullptr;
+ }
+ }
+
+ // Grant access to SYSTEM, Administrators, the user, our app container (if in
+ // one) and when running as the browser process on Windows 8+, all non
+ // restricted app containers.
+ const size_t kMaxInlineEntries = 5;
+ mozilla::Vector<EXPLICIT_ACCESS_W, kMaxInlineEntries> entries;
+
+ Unused << entries.append(EXPLICIT_ACCESS_W{
+ COM_RIGHTS_EXECUTE,
+ GRANT_ACCESS,
+ NO_INHERITANCE,
+ {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER,
+ reinterpret_cast<LPWSTR>(systemSid)}});
+
+ Unused << entries.append(EXPLICIT_ACCESS_W{
+ COM_RIGHTS_EXECUTE,
+ GRANT_ACCESS,
+ NO_INHERITANCE,
+ {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID,
+ TRUSTEE_IS_WELL_KNOWN_GROUP, reinterpret_cast<LPWSTR>(adminSid)}});
+
+ Unused << entries.append(EXPLICIT_ACCESS_W{
+ COM_RIGHTS_EXECUTE,
+ GRANT_ACCESS,
+ NO_INHERITANCE,
+ {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER,
+ reinterpret_cast<LPWSTR>(tokenUser.User.Sid)}});
+
+ if (allowAllNonRestrictedAppContainers) {
+ Unused << entries.append(
+ EXPLICIT_ACCESS_W{COM_RIGHTS_EXECUTE,
+ GRANT_ACCESS,
+ NO_INHERITANCE,
+ {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID,
+ TRUSTEE_IS_WELL_KNOWN_GROUP,
+ reinterpret_cast<LPWSTR>(appContainersSid)}});
+ }
+
+ if (tokenAppContainerInfBuf) {
+ TOKEN_APPCONTAINER_INFORMATION& tokenAppContainerInf =
+ *reinterpret_cast<TOKEN_APPCONTAINER_INFORMATION*>(
+ tokenAppContainerInfBuf.get());
+
+ // TokenAppContainer will be null if we are not in an app container.
+ if (tokenAppContainerInf.TokenAppContainer) {
+ Unused << entries.append(EXPLICIT_ACCESS_W{
+ COM_RIGHTS_EXECUTE,
+ GRANT_ACCESS,
+ NO_INHERITANCE,
+ {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_SID, TRUSTEE_IS_USER,
+ reinterpret_cast<LPWSTR>(tokenAppContainerInf.TokenAppContainer)}});
+ }
+ }
+
+ PACL rawDacl = nullptr;
+ win32Error =
+ ::SetEntriesInAclW(entries.length(), entries.begin(), nullptr, &rawDacl);
+ if (win32Error != ERROR_SUCCESS) {
+ return HRESULT_FROM_WIN32(win32Error);
+ }
+
+ UniquePtr<ACL, LocalFreeDeleter> dacl(rawDacl);
+
+ if (!::SetSecurityDescriptorDacl(&sd, TRUE, dacl.get(), FALSE)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ if (!::SetSecurityDescriptorOwner(&sd, tokenUser.User.Sid, FALSE)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ if (!::SetSecurityDescriptorGroup(&sd, tokenPrimaryGroup.PrimaryGroup,
+ FALSE)) {
+ return HRESULT_FROM_WIN32(::GetLastError());
+ }
+
+ return wrapped::CoInitializeSecurity(
+ &sd, -1, nullptr, nullptr, RPC_C_AUTHN_LEVEL_DEFAULT,
+ RPC_C_IMP_LEVEL_IDENTIFY, nullptr, EOAC_NONE, nullptr);
+}
+
+} // namespace mscom
+} // namespace mozilla
diff --git a/ipc/mscom/ProcessRuntime.h b/ipc/mscom/ProcessRuntime.h
new file mode 100644
index 0000000000..568281f360
--- /dev/null
+++ b/ipc/mscom/ProcessRuntime.h
@@ -0,0 +1,87 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_ProcessRuntime_h
+#define mozilla_mscom_ProcessRuntime_h
+
+#include "mozilla/Attributes.h"
+#include "mozilla/mscom/ApartmentRegion.h"
+#include "nsWindowsHelpers.h"
+#if defined(MOZILLA_INTERNAL_API)
+# include "nsXULAppAPI.h"
+#endif // defined(MOZILLA_INTERNAL_API)
+
+namespace mozilla {
+namespace mscom {
+
+class MOZ_NON_TEMPORARY_CLASS ProcessRuntime final {
+#if !defined(MOZILLA_INTERNAL_API)
+ public:
+#endif // defined(MOZILLA_INTERNAL_API)
+ enum class ProcessCategory {
+ GeckoBrowserParent,
+ // We give Launcher its own process category, but internally to this class
+ // it should be treated identically to GeckoBrowserParent.
+ Launcher = GeckoBrowserParent,
+ GeckoChild,
+ Service,
+ };
+
+ // This constructor is only public when compiled outside of XUL
+ explicit ProcessRuntime(const ProcessCategory aProcessCategory);
+
+ public:
+#if defined(MOZILLA_INTERNAL_API)
+ ProcessRuntime();
+ ~ProcessRuntime();
+#else
+ ~ProcessRuntime() = default;
+#endif // defined(MOZILLA_INTERNAL_API)
+
+ explicit operator bool() const { return SUCCEEDED(mInitResult); }
+ HRESULT GetHResult() const { return mInitResult; }
+
+ ProcessRuntime(const ProcessRuntime&) = delete;
+ ProcessRuntime(ProcessRuntime&&) = delete;
+ ProcessRuntime& operator=(const ProcessRuntime&) = delete;
+ ProcessRuntime& operator=(ProcessRuntime&&) = delete;
+
+ /**
+ * @return 0 if call is in-process or resolving the calling thread failed,
+ * otherwise contains the thread id of the calling thread.
+ */
+ static DWORD GetClientThreadId();
+
+ private:
+#if defined(MOZILLA_INTERNAL_API)
+ explicit ProcessRuntime(const GeckoProcessType aProcessType);
+# if defined(MOZ_SANDBOX)
+ void InitUsingPersistentMTAThread(const nsAutoHandle& aCurThreadToken);
+# endif // defined(MOZ_SANDBOX)
+#endif // defined(MOZILLA_INTERNAL_API)
+ void InitInsideApartment();
+
+#if defined(MOZILLA_INTERNAL_API)
+ static void PostInit();
+#endif // defined(MOZILLA_INTERNAL_API)
+ static HRESULT InitializeSecurity(const ProcessCategory aProcessCategory);
+ static COINIT GetDesiredApartmentType(const ProcessCategory aProcessCategory);
+
+ private:
+ HRESULT mInitResult;
+ const ProcessCategory mProcessCategory;
+ ApartmentRegion mAptRegion;
+
+ private:
+#if defined(MOZILLA_INTERNAL_API)
+ static ProcessRuntime* sInstance;
+#endif // defined(MOZILLA_INTERNAL_API)
+};
+
+} // namespace mscom
+} // namespace mozilla
+
+#endif // mozilla_mscom_ProcessRuntime_h
diff --git a/ipc/mscom/ProfilerMarkers.cpp b/ipc/mscom/ProfilerMarkers.cpp
new file mode 100644
index 0000000000..29d033723f
--- /dev/null
+++ b/ipc/mscom/ProfilerMarkers.cpp
@@ -0,0 +1,236 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "ProfilerMarkers.h"
+
+#include "MainThreadUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/Atomics.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/mscom/Utils.h"
+#include "mozilla/ProfilerMarkers.h"
+#include "mozilla/Services.h"
+#include "nsCOMPtr.h"
+#include "nsIObserver.h"
+#include "nsIObserverService.h"
+#include "nsISupportsImpl.h"
+#include "nsString.h"
+#include "nsXULAppAPI.h"
+
+#include <objbase.h>
+#include <objidlbase.h>
+
+// {9DBE6B28-E5E7-4FDE-AF00-9404604E74DC}
+static const GUID GUID_MozProfilerMarkerExtension = {
+ 0x9dbe6b28, 0xe5e7, 0x4fde, {0xaf, 0x0, 0x94, 0x4, 0x60, 0x4e, 0x74, 0xdc}};
+
+namespace {
+
+class ProfilerMarkerChannelHook final : public IChannelHook {
+ ~ProfilerMarkerChannelHook() = default;
+
+ public:
+ ProfilerMarkerChannelHook() : mRefCnt(0) {}
+
+ // IUnknown
+ STDMETHODIMP QueryInterface(REFIID aIid, void** aOutInterface) override;
+ STDMETHODIMP_(ULONG) AddRef() override;
+ STDMETHODIMP_(ULONG) Release() override;
+
+ /**
+ * IChannelHook exposes six methods: The Client* methods are called when
+ * a client is sending an IPC request, whereas the Server* methods are called
+ * when a server is receiving an IPC request.
+ *
+ * For our purposes, we only care about the client-side methods. The COM
+ * runtime invokes the methods in the following order:
+ * 1. ClientGetSize, where the hook specifies the size of its payload;
+ * 2. ClientFillBuffer, where the hook fills the channel's buffer with its
+ * payload information. NOTE: This method is only called when ClientGetSize
+ * specifies a non-zero payload size. For our purposes, since we are not
+ * sending a payload, this method will never be called!
+ * 3. ClientNotify, when the response has been received from the server.
+ *
+ * Since we want to use these hooks to record the beginning and end of a COM
+ * IPC call, we use ClientGetSize for logging the start, and ClientNotify for
+ * logging the end.
+ *
+ * Finally, our implementation responds to any request matching our extension
+ * ID, however we only care about main thread COM calls.
+ */
+
+ // IChannelHook
+ STDMETHODIMP_(void)
+ ClientGetSize(REFGUID aExtensionId, REFIID aIid,
+ ULONG* aOutDataSize) override;
+
+ // No-op (see the large comment above)
+ STDMETHODIMP_(void)
+ ClientFillBuffer(REFGUID aExtensionId, REFIID aIid, ULONG* aDataSize,
+ void* aDataBuf) override {}
+
+ STDMETHODIMP_(void)
+ ClientNotify(REFGUID aExtensionId, REFIID aIid, ULONG aDataSize,
+ void* aDataBuffer, DWORD aDataRep, HRESULT aFault) override;
+
+ // We don't care about the server-side notifications, so leave as no-ops.
+ STDMETHODIMP_(void)
+ ServerNotify(REFGUID aExtensionId, REFIID aIid, ULONG aDataSize,
+ void* aDataBuf, DWORD aDataRep) override {}
+
+ STDMETHODIMP_(void)
+ ServerGetSize(REFGUID aExtensionId, REFIID aIid, HRESULT aFault,
+ ULONG* aOutDataSize) override {}
+
+ STDMETHODIMP_(void)
+ ServerFillBuffer(REFGUID aExtensionId, REFIID aIid, ULONG* aDataSize,
+ void* aDataBuf, HRESULT aFault) override {}
+
+ private:
+ void BuildMarkerName(REFIID aIid, nsACString& aOutMarkerName);
+
+ private:
+ mozilla::Atomic<ULONG> mRefCnt;
+};
+
+HRESULT ProfilerMarkerChannelHook::QueryInterface(REFIID aIid,
+ void** aOutInterface) {
+ if (aIid == IID_IChannelHook || aIid == IID_IUnknown) {
+ RefPtr<IChannelHook> ptr(this);
+ ptr.forget(aOutInterface);
+ return S_OK;
+ }
+
+ return E_NOINTERFACE;
+}
+
+ULONG ProfilerMarkerChannelHook::AddRef() { return ++mRefCnt; }
+
+ULONG ProfilerMarkerChannelHook::Release() {
+ ULONG result = --mRefCnt;
+ if (!result) {
+ delete this;
+ }
+
+ return result;
+}
+
+void ProfilerMarkerChannelHook::BuildMarkerName(REFIID aIid,
+ nsACString& aOutMarkerName) {
+ aOutMarkerName.AssignLiteral("ORPC Call for ");
+
+ nsAutoCString iidStr;
+ mozilla::mscom::DiagnosticNameForIID(aIid, iidStr);
+ aOutMarkerName.Append(iidStr);
+}
+
+void ProfilerMarkerChannelHook::ClientGetSize(REFGUID aExtensionId, REFIID aIid,
+ ULONG* aOutDataSize) {
+ if (aExtensionId == GUID_MozProfilerMarkerExtension) {
+ if (NS_IsMainThread()) {
+ nsAutoCString markerName;
+ BuildMarkerName(aIid, markerName);
+ PROFILER_MARKER(markerName, IPC, mozilla::MarkerTiming::IntervalStart(),
+ Tracing, "MSCOM");
+ }
+
+ if (aOutDataSize) {
+ // We don't add any payload data to the channel
+ *aOutDataSize = 0UL;
+ }
+ }
+}
+
+void ProfilerMarkerChannelHook::ClientNotify(REFGUID aExtensionId, REFIID aIid,
+ ULONG aDataSize, void* aDataBuffer,
+ DWORD aDataRep, HRESULT aFault) {
+ if (NS_IsMainThread() && aExtensionId == GUID_MozProfilerMarkerExtension) {
+ nsAutoCString markerName;
+ BuildMarkerName(aIid, markerName);
+ PROFILER_MARKER(markerName, IPC, mozilla::MarkerTiming::IntervalEnd(),
+ Tracing, "MSCOM");
+ }
+}
+
+} // anonymous namespace
+
+static void RegisterChannelHook() {
+ RefPtr<ProfilerMarkerChannelHook> hook(new ProfilerMarkerChannelHook());
+ mozilla::DebugOnly<HRESULT> hr =
+ ::CoRegisterChannelHook(GUID_MozProfilerMarkerExtension, hook);
+ MOZ_ASSERT(SUCCEEDED(hr));
+}
+
+namespace {
+
+class ProfilerStartupObserver final : public nsIObserver {
+ ~ProfilerStartupObserver() = default;
+
+ public:
+ NS_DECL_ISUPPORTS
+ NS_DECL_NSIOBSERVER
+};
+
+NS_IMPL_ISUPPORTS(ProfilerStartupObserver, nsIObserver)
+
+NS_IMETHODIMP ProfilerStartupObserver::Observe(nsISupports* aSubject,
+ const char* aTopic,
+ const char16_t* aData) {
+ if (strcmp(aTopic, "profiler-started")) {
+ return NS_OK;
+ }
+
+ RegisterChannelHook();
+
+ // Once we've set the channel hook, we don't care about this notification
+ // anymore; our channel hook will remain set for the lifetime of the process.
+ nsCOMPtr<nsIObserverService> obsServ(mozilla::services::GetObserverService());
+ MOZ_ASSERT(!!obsServ);
+ if (!obsServ) {
+ return NS_OK;
+ }
+
+ obsServ->RemoveObserver(this, "profiler-started");
+ return NS_OK;
+}
+
+} // anonymous namespace
+
+namespace mozilla {
+namespace mscom {
+
+void InitProfilerMarkers() {
+ if (!XRE_IsParentProcess()) {
+ return;
+ }
+
+ MOZ_ASSERT(NS_IsMainThread());
+ if (!NS_IsMainThread()) {
+ return;
+ }
+
+ if (profiler_is_active()) {
+ // If the profiler is already running, we'll immediately register our
+ // channel hook.
+ RegisterChannelHook();
+ return;
+ }
+
+ // The profiler is not running yet. To avoid unnecessary invocations of the
+ // channel hook, we won't bother with installing it until the profiler starts.
+ // Set up an observer to watch for this.
+ nsCOMPtr<nsIObserverService> obsServ(mozilla::services::GetObserverService());
+ MOZ_ASSERT(!!obsServ);
+ if (!obsServ) {
+ return;
+ }
+
+ nsCOMPtr<nsIObserver> obs(new ProfilerStartupObserver());
+ obsServ->AddObserver(obs, "profiler-started", false);
+}
+
+} // namespace mscom
+} // namespace mozilla
diff --git a/ipc/mscom/ProfilerMarkers.h b/ipc/mscom/ProfilerMarkers.h
new file mode 100644
index 0000000000..a21d5b375a
--- /dev/null
+++ b/ipc/mscom/ProfilerMarkers.h
@@ -0,0 +1,18 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_ProfilerMarkers_h
+#define mozilla_mscom_ProfilerMarkers_h
+
+namespace mozilla {
+namespace mscom {
+
+void InitProfilerMarkers();
+
+} // namespace mscom
+} // namespace mozilla
+
+#endif // mozilla_mscom_ProfilerMarkers_h
diff --git a/ipc/mscom/Utils.cpp b/ipc/mscom/Utils.cpp
new file mode 100644
index 0000000000..d93e012587
--- /dev/null
+++ b/ipc/mscom/Utils.cpp
@@ -0,0 +1,324 @@
+/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#if defined(MOZILLA_INTERNAL_API)
+# include "MainThreadUtils.h"
+# include "mozilla/dom/ContentChild.h"
+#endif
+
+#include "mozilla/ArrayUtils.h"
+#include "mozilla/mscom/COMWrappers.h"
+#include "mozilla/DebugOnly.h"
+#include "mozilla/mscom/Utils.h"
+#include "mozilla/RefPtr.h"
+
+#include <objidl.h>
+#include <winnt.h>
+
+#include <utility>
+
+#if defined(_MSC_VER)
+extern "C" IMAGE_DOS_HEADER __ImageBase;
+#endif
+
+namespace mozilla {
+namespace mscom {
+
+bool IsCOMInitializedOnCurrentThread() {
+ APTTYPE aptType;
+ APTTYPEQUALIFIER aptTypeQualifier;
+ HRESULT hr = wrapped::CoGetApartmentType(&aptType, &aptTypeQualifier);
+ return hr != CO_E_NOTINITIALIZED;
+}
+
+bool IsCurrentThreadMTA() {
+ APTTYPE aptType;
+ APTTYPEQUALIFIER aptTypeQualifier;
+ HRESULT hr = wrapped::CoGetApartmentType(&aptType, &aptTypeQualifier);
+ if (FAILED(hr)) {
+ return false;
+ }
+
+ return aptType == APTTYPE_MTA;
+}
+
+bool IsCurrentThreadExplicitMTA() {
+ APTTYPE aptType;
+ APTTYPEQUALIFIER aptTypeQualifier;
+ HRESULT hr = wrapped::CoGetApartmentType(&aptType, &aptTypeQualifier);
+ if (FAILED(hr)) {
+ return false;
+ }
+
+ return aptType == APTTYPE_MTA &&
+ aptTypeQualifier != APTTYPEQUALIFIER_IMPLICIT_MTA;
+}
+
+bool IsCurrentThreadImplicitMTA() {
+ APTTYPE aptType;
+ APTTYPEQUALIFIER aptTypeQualifier;
+ HRESULT hr = wrapped::CoGetApartmentType(&aptType, &aptTypeQualifier);
+ if (FAILED(hr)) {
+ return false;
+ }
+
+ return aptType == APTTYPE_MTA &&
+ aptTypeQualifier == APTTYPEQUALIFIER_IMPLICIT_MTA;
+}
+
+#if defined(MOZILLA_INTERNAL_API)
+bool IsCurrentThreadNonMainMTA() {
+ if (NS_IsMainThread()) {
+ return false;
+ }
+
+ return IsCurrentThreadMTA();
+}
+#endif // defined(MOZILLA_INTERNAL_API)
+
+bool IsProxy(IUnknown* aUnknown) {
+ if (!aUnknown) {
+ return false;
+ }
+
+ // Only proxies implement this interface, so if it is present then we must
+ // be dealing with a proxied object.
+ RefPtr<IClientSecurity> clientSecurity;
+ HRESULT hr = aUnknown->QueryInterface(IID_IClientSecurity,
+ (void**)getter_AddRefs(clientSecurity));
+ if (SUCCEEDED(hr) || hr == RPC_E_WRONG_THREAD) {
+ return true;
+ }
+ return false;
+}
+
+bool IsValidGUID(REFGUID aCheckGuid) {
+ // This function determines whether or not aCheckGuid conforms to RFC4122
+ // as it applies to Microsoft COM.
+
+ BYTE variant = aCheckGuid.Data4[0];
+ if (!(variant & 0x80)) {
+ // NCS Reserved
+ return false;
+ }
+ if ((variant & 0xE0) == 0xE0) {
+ // Reserved for future use
+ return false;
+ }
+ if ((variant & 0xC0) == 0xC0) {
+ // Microsoft Reserved.
+ return true;
+ }
+
+ BYTE version = HIBYTE(aCheckGuid.Data3) >> 4;
+ // Other versions are specified in RFC4122 but these are the two used by COM.
+ return version == 1 || version == 4;
+}
+
+uintptr_t GetContainingModuleHandle() {
+ HMODULE thisModule = nullptr;
+#if defined(_MSC_VER)
+ thisModule = reinterpret_cast<HMODULE>(&__ImageBase);
+#else
+ if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
+ GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
+ reinterpret_cast<LPCTSTR>(&GetContainingModuleHandle),
+ &thisModule)) {
+ return 0;
+ }
+#endif
+ return reinterpret_cast<uintptr_t>(thisModule);
+}
+
+namespace detail {
+
+long BuildRegGuidPath(REFGUID aGuid, const GuidType aGuidType, wchar_t* aBuf,
+ const size_t aBufLen) {
+ constexpr wchar_t kClsid[] = L"CLSID\\";
+ constexpr wchar_t kAppid[] = L"AppID\\";
+ constexpr wchar_t kSubkeyBase[] = L"SOFTWARE\\Classes\\";
+
+ // We exclude null terminators in these length calculations because we include
+ // the stringified GUID's null terminator at the end. Since kClsid and kAppid
+ // have identical lengths, we just choose one to compute this length.
+ constexpr size_t kSubkeyBaseLen = mozilla::ArrayLength(kSubkeyBase) - 1;
+ constexpr size_t kSubkeyLen =
+ kSubkeyBaseLen + mozilla::ArrayLength(kClsid) - 1;
+ // Guid length as formatted for the registry (including curlies and dashes),
+ // but excluding null terminator.
+ constexpr size_t kGuidLen = kGuidRegFormatCharLenInclNul - 1;
+ constexpr size_t kExpectedPathLenInclNul = kSubkeyLen + kGuidLen + 1;
+
+ if (aBufLen < kExpectedPathLenInclNul) {
+ // Buffer is too short
+ return E_INVALIDARG;
+ }
+
+ if (wcscpy_s(aBuf, aBufLen, kSubkeyBase)) {
+ return E_INVALIDARG;
+ }
+
+ const wchar_t* strGuidType = aGuidType == GuidType::CLSID ? kClsid : kAppid;
+ if (wcscat_s(aBuf, aBufLen, strGuidType)) {
+ return E_INVALIDARG;
+ }
+
+ int guidConversionResult =
+ ::StringFromGUID2(aGuid, &aBuf[kSubkeyLen], aBufLen - kSubkeyLen);
+ if (!guidConversionResult) {
+ return E_INVALIDARG;
+ }
+
+ return S_OK;
+}
+
+} // namespace detail
+
+long CreateStream(const uint8_t* aInitBuf, const uint32_t aInitBufSize,
+ IStream** aOutStream) {
+ if (!aInitBufSize || !aOutStream) {
+ return E_INVALIDARG;
+ }
+
+ *aOutStream = nullptr;
+
+ HRESULT hr;
+ RefPtr<IStream> stream;
+
+ // If aInitBuf is null then initSize must be 0.
+ UINT initSize = aInitBuf ? aInitBufSize : 0;
+ stream = already_AddRefed<IStream>(::SHCreateMemStream(aInitBuf, initSize));
+ if (!stream) {
+ return E_OUTOFMEMORY;
+ }
+
+ if (!aInitBuf) {
+ // Now we'll set the required size
+ ULARGE_INTEGER newSize;
+ newSize.QuadPart = aInitBufSize;
+ hr = stream->SetSize(newSize);
+ if (FAILED(hr)) {
+ return hr;
+ }
+ }
+
+ // Ensure that the stream is rewound
+ LARGE_INTEGER streamOffset;
+ streamOffset.QuadPart = 0LL;
+ hr = stream->Seek(streamOffset, STREAM_SEEK_SET, nullptr);
+ if (FAILED(hr)) {
+ return hr;
+ }
+
+ stream.forget(aOutStream);
+ return S_OK;
+}
+
+#if defined(MOZILLA_INTERNAL_API)
+
+void GUIDToString(REFGUID aGuid, nsAString& aOutString) {
+ // This buffer length is long enough to hold a GUID string that is formatted
+ // to include curly braces and dashes.
+ const int kBufLenWithNul = 39;
+ aOutString.SetLength(kBufLenWithNul);
+ int result = StringFromGUID2(aGuid, char16ptr_t(aOutString.BeginWriting()),
+ kBufLenWithNul);
+ MOZ_ASSERT(result);
+ if (result) {
+ // Truncate the terminator
+ aOutString.SetLength(result - 1);
+ }
+}
+
+// Undocumented IIDs that are relevant for diagnostic purposes
+static const IID IID_ISCMLocalActivator = {
+ 0x00000136,
+ 0x0000,
+ 0x0000,
+ {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
+static const IID IID_IRundown = {
+ 0x00000134,
+ 0x0000,
+ 0x0000,
+ {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
+static const IID IID_IRemUnknown = {
+ 0x00000131,
+ 0x0000,
+ 0x0000,
+ {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
+static const IID IID_IRemUnknown2 = {
+ 0x00000143,
+ 0x0000,
+ 0x0000,
+ {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}};
+
+struct IIDToLiteralMapEntry {
+ constexpr IIDToLiteralMapEntry(REFIID aIid, nsLiteralCString&& aStr)
+ : mIid(aIid), mStr(std::forward<nsLiteralCString>(aStr)) {}
+
+ REFIID mIid;
+ const nsLiteralCString mStr;
+};
+
+/**
+ * Given the name of an interface, the IID_ENTRY macro generates a pair
+ * containing a reference to the interface ID and a stringified version of
+ * the interface name.
+ *
+ * For example:
+ *
+ * {IID_ENTRY(IUnknown)}
+ * is expanded to:
+ * {IID_IUnknown, "IUnknown"_ns}
+ *
+ */
+// clang-format off
+# define IID_ENTRY_STRINGIFY(iface) #iface##_ns
+# define IID_ENTRY(iface) IID_##iface, IID_ENTRY_STRINGIFY(iface)
+// clang-format on
+
+// Mapping of selected IIDs to friendly, human readable descriptions for each
+// interface.
+static constexpr IIDToLiteralMapEntry sIidDiagStrs[] = {
+ {IID_ENTRY(IUnknown)},
+ {IID_IRemUnknown, "cross-apartment IUnknown"_ns},
+ {IID_IRundown, "cross-apartment object management"_ns},
+ {IID_ISCMLocalActivator, "out-of-process object instantiation"_ns},
+ {IID_IRemUnknown2, "cross-apartment IUnknown"_ns}};
+
+# undef IID_ENTRY
+# undef IID_ENTRY_STRINGIFY
+
+void DiagnosticNameForIID(REFIID aIid, nsACString& aOutString) {
+ // If the IID matches something in sIidDiagStrs, output its string.
+ for (const auto& curEntry : sIidDiagStrs) {
+ if (curEntry.mIid == aIid) {
+ aOutString.Assign(curEntry.mStr);
+ return;
+ }
+ }
+
+ // Otherwise just convert the IID to string form and output that.
+ nsAutoString strIid;
+ GUIDToString(aIid, strIid);
+
+ aOutString.AssignLiteral("IID ");
+ AppendUTF16toUTF8(strIid, aOutString);
+}
+
+#else
+
+void GUIDToString(REFGUID aGuid,
+ wchar_t (&aOutBuf)[kGuidRegFormatCharLenInclNul]) {
+ DebugOnly<int> result =
+ ::StringFromGUID2(aGuid, aOutBuf, ArrayLength(aOutBuf));
+ MOZ_ASSERT(result);
+}
+
+#endif // defined(MOZILLA_INTERNAL_API)
+
+} // namespace mscom
+} // namespace mozilla
diff --git a/ipc/mscom/Utils.h b/ipc/mscom/Utils.h
new file mode 100644
index 0000000000..aabf5f5891
--- /dev/null
+++ b/ipc/mscom/Utils.h
@@ -0,0 +1,123 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_Utils_h
+#define mozilla_mscom_Utils_h
+
+#if defined(MOZILLA_INTERNAL_API)
+# include "nsString.h"
+#endif // defined(MOZILLA_INTERNAL_API)
+
+#include "mozilla/Attributes.h"
+#include <guiddef.h>
+#include <stdint.h>
+
+struct IStream;
+struct IUnknown;
+
+namespace mozilla {
+namespace mscom {
+namespace detail {
+
+enum class GuidType {
+ CLSID,
+ AppID,
+};
+
+long BuildRegGuidPath(REFGUID aGuid, const GuidType aGuidType, wchar_t* aBuf,
+ const size_t aBufLen);
+
+} // namespace detail
+
+bool IsCOMInitializedOnCurrentThread();
+bool IsCurrentThreadMTA();
+bool IsCurrentThreadExplicitMTA();
+bool IsCurrentThreadImplicitMTA();
+#if defined(MOZILLA_INTERNAL_API)
+bool IsCurrentThreadNonMainMTA();
+#endif // defined(MOZILLA_INTERNAL_API)
+bool IsProxy(IUnknown* aUnknown);
+bool IsValidGUID(REFGUID aCheckGuid);
+uintptr_t GetContainingModuleHandle();
+
+template <size_t N>
+inline long BuildAppidPath(REFGUID aAppId, wchar_t (&aPath)[N]) {
+ return detail::BuildRegGuidPath(aAppId, detail::GuidType::AppID, aPath, N);
+}
+
+template <size_t N>
+inline long BuildClsidPath(REFCLSID aClsid, wchar_t (&aPath)[N]) {
+ return detail::BuildRegGuidPath(aClsid, detail::GuidType::CLSID, aPath, N);
+}
+
+/**
+ * Given a buffer, create a new IStream object.
+ * @param aBuf Buffer containing data to initialize the stream. This parameter
+ * may be nullptr, causing the stream to be created with aBufLen
+ * bytes of uninitialized data.
+ * @param aBufLen Length of data in aBuf, or desired stream size if aBuf is
+ * nullptr.
+ * @param aOutStream Outparam to receive the newly created stream.
+ * @return HRESULT error code.
+ */
+long CreateStream(const uint8_t* aBuf, const uint32_t aBufLen,
+ IStream** aOutStream);
+
+/**
+ * Length of a stringified GUID as formatted for the registry, i.e. including
+ * curly-braces and dashes.
+ */
+constexpr size_t kGuidRegFormatCharLenInclNul = 39;
+
+#if defined(MOZILLA_INTERNAL_API)
+void GUIDToString(REFGUID aGuid, nsAString& aOutString);
+
+/**
+ * Converts an IID to a human-readable string for the purposes of diagnostic
+ * tools such as the profiler. For some special cases, we output a friendly
+ * string that describes the purpose of the interface. If no such description
+ * exists, we simply fall back to outputting the IID as a string formatted by
+ * GUIDToString().
+ */
+void DiagnosticNameForIID(REFIID aIid, nsACString& aOutString);
+#else
+void GUIDToString(REFGUID aGuid,
+ wchar_t (&aOutBuf)[kGuidRegFormatCharLenInclNul]);
+#endif // defined(MOZILLA_INTERNAL_API)
+
+/**
+ * Execute cleanup code when going out of scope if a condition is met.
+ * This is useful when, for example, particular cleanup needs to be performed
+ * whenever a call returns a failure HRESULT.
+ * Both the condition and cleanup code are provided as functions (usually
+ * lambdas).
+ */
+template <typename CondFnT, typename ExeFnT>
+class MOZ_RAII ExecuteWhen final {
+ public:
+ ExecuteWhen(CondFnT& aCondFn, ExeFnT& aExeFn)
+ : mCondFn(aCondFn), mExeFn(aExeFn) {}
+
+ ~ExecuteWhen() {
+ if (mCondFn()) {
+ mExeFn();
+ }
+ }
+
+ ExecuteWhen(const ExecuteWhen&) = delete;
+ ExecuteWhen(ExecuteWhen&&) = delete;
+ ExecuteWhen& operator=(const ExecuteWhen&) = delete;
+ ExecuteWhen& operator=(ExecuteWhen&&) = delete;
+
+ private:
+ CondFnT& mCondFn;
+ ExeFnT& mExeFn;
+};
+
+} // namespace mscom
+} // namespace mozilla
+
+#endif // mozilla_mscom_Utils_h
diff --git a/ipc/mscom/moz.build b/ipc/mscom/moz.build
new file mode 100644
index 0000000000..e11b7314f4
--- /dev/null
+++ b/ipc/mscom/moz.build
@@ -0,0 +1,42 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+EXPORTS.mozilla.mscom += [
+ "Aggregation.h",
+ "AgileReference.h",
+ "ApartmentRegion.h",
+ "COMWrappers.h",
+ "EnsureMTA.h",
+ "ProcessRuntime.h",
+ "ProfilerMarkers.h",
+ "Utils.h",
+]
+
+DIRS += [
+ "mozglue",
+]
+
+UNIFIED_SOURCES += [
+ "AgileReference.cpp",
+ "COMWrappers.cpp",
+ "EnsureMTA.cpp",
+ "ProcessRuntime.cpp",
+ "ProfilerMarkers.cpp",
+ "Utils.cpp",
+]
+
+LOCAL_INCLUDES += [
+ "/xpcom/base",
+ "/xpcom/build",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
+
+with Files("**"):
+ BUG_COMPONENT = ("Core", "IPC: MSCOM")
+ SCHEDULES.exclusive = ["windows"]
diff --git a/ipc/mscom/mozglue/ProcessRuntimeShared.cpp b/ipc/mscom/mozglue/ProcessRuntimeShared.cpp
new file mode 100644
index 0000000000..ee4f6b221f
--- /dev/null
+++ b/ipc/mscom/mozglue/ProcessRuntimeShared.cpp
@@ -0,0 +1,31 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "mozilla/mscom/ProcessRuntimeShared.h"
+
+#include "mozilla/glue/WinUtils.h"
+
+// We allow multiple ProcessRuntime instances to exist simultaneously (even
+// on separate threads), but only one should be doing the process-wide
+// initialization. These variables provide that mutual exclusion.
+static mozilla::glue::Win32SRWLock gLock;
+static mozilla::mscom::detail::ProcessInitState gProcessInitState =
+ mozilla::mscom::detail::ProcessInitState::Uninitialized;
+
+namespace mozilla {
+namespace mscom {
+namespace detail {
+
+MFBT_API ProcessInitState& BeginProcessRuntimeInit() {
+ gLock.LockExclusive();
+ return gProcessInitState;
+}
+
+MFBT_API void EndProcessRuntimeInit() { gLock.UnlockExclusive(); }
+
+} // namespace detail
+} // namespace mscom
+} // namespace mozilla
diff --git a/ipc/mscom/mozglue/ProcessRuntimeShared.h b/ipc/mscom/mozglue/ProcessRuntimeShared.h
new file mode 100644
index 0000000000..d5a58a7b92
--- /dev/null
+++ b/ipc/mscom/mozglue/ProcessRuntimeShared.h
@@ -0,0 +1,55 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_mscom_ProcessRuntimeShared_h
+#define mozilla_mscom_ProcessRuntimeShared_h
+
+#include "mozilla/Assertions.h"
+#include "mozilla/Attributes.h"
+#include "mozilla/Types.h"
+
+namespace mozilla {
+namespace mscom {
+namespace detail {
+
+enum class ProcessInitState : uint32_t {
+ Uninitialized = 0,
+ PartialSecurityInitialized,
+ PartialGlobalOptions,
+ FullyInitialized,
+};
+
+MFBT_API ProcessInitState& BeginProcessRuntimeInit();
+MFBT_API void EndProcessRuntimeInit();
+
+} // namespace detail
+
+class MOZ_RAII ProcessInitLock final {
+ public:
+ ProcessInitLock() : mInitState(detail::BeginProcessRuntimeInit()) {}
+
+ ~ProcessInitLock() { detail::EndProcessRuntimeInit(); }
+
+ detail::ProcessInitState GetInitState() const { return mInitState; }
+
+ void SetInitState(const detail::ProcessInitState aNewState) {
+ MOZ_DIAGNOSTIC_ASSERT(aNewState > mInitState);
+ mInitState = aNewState;
+ }
+
+ ProcessInitLock(const ProcessInitLock&) = delete;
+ ProcessInitLock(ProcessInitLock&&) = delete;
+ ProcessInitLock operator=(const ProcessInitLock&) = delete;
+ ProcessInitLock operator=(ProcessInitLock&&) = delete;
+
+ private:
+ detail::ProcessInitState& mInitState;
+};
+
+} // namespace mscom
+} // namespace mozilla
+
+#endif // mozilla_mscom_ProcessRuntimeShared_h
diff --git a/ipc/mscom/mozglue/moz.build b/ipc/mscom/mozglue/moz.build
new file mode 100644
index 0000000000..f52a772324
--- /dev/null
+++ b/ipc/mscom/mozglue/moz.build
@@ -0,0 +1,15 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+FINAL_LIBRARY = "mozglue"
+
+EXPORTS.mozilla.mscom += [
+ "ProcessRuntimeShared.h",
+]
+
+UNIFIED_SOURCES += [
+ "ProcessRuntimeShared.cpp",
+]
diff --git a/ipc/pull-chromium.py b/ipc/pull-chromium.py
new file mode 100644
index 0000000000..688098b511
--- /dev/null
+++ b/ipc/pull-chromium.py
@@ -0,0 +1,55 @@
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+"""
+Pull a specified revision of chromium from SVN.
+
+Usage: python pull-chromium.py <topsrcdir> <chromiumtree> <revision>
+
+You will have to set up a Chromium tree before running this step. See
+http://dev.chromium.org/developers/how-tos/get-the-code for details about
+doing this efficiently.
+"""
+
+import os
+import sys
+from shutil import rmtree
+from subprocess import check_call
+
+topsrcdir, chromiumtree, rev = sys.argv[1:]
+
+if not os.path.exists(os.path.join(topsrcdir, "client.py")):
+ print >> sys.stderr, "Incorrect topsrcdir"
+ sys.exit(1)
+
+if not os.path.exists(os.path.join(chromiumtree, "src/DEPS")):
+ print >> sys.stderr, "Incorrect chromium directory, missing DEPS"
+ sys.exit(1)
+
+check_call(["gclient", "sync", "--force", "--revision=src@%s" % rev], cwd=chromiumtree)
+
+chromiumsrc = os.path.join(topsrcdir, "ipc/chromium/src")
+os.path.exists(chromiumsrc) and rmtree(chromiumsrc)
+
+
+def doexport(svnpath):
+ localpath = os.path.join(chromiumsrc, svnpath)
+ os.makedirs(os.path.dirname(localpath))
+ check_call(
+ [
+ "svn",
+ "export",
+ "-r",
+ "BASE",
+ os.path.join(chromiumtree, "src", svnpath),
+ localpath,
+ ]
+ )
+
+
+doexport("base")
+doexport("chrome/common")
+doexport("build/build_config.h")
+doexport("testing/gtest/include")
+doexport("third_party/libevent")
diff --git a/ipc/testshell/PTestShell.ipdl b/ipc/testshell/PTestShell.ipdl
new file mode 100644
index 0000000000..db4d7eedcb
--- /dev/null
+++ b/ipc/testshell/PTestShell.ipdl
@@ -0,0 +1,27 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PContent;
+include protocol PTestShellCommand;
+
+namespace mozilla {
+namespace ipc {
+
+async protocol PTestShell
+{
+ manager PContent;
+
+ manages PTestShellCommand;
+
+child:
+ async __delete__();
+
+ async ExecuteCommand(nsString aCommand);
+
+ async PTestShellCommand(nsString aCommand);
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/testshell/PTestShellCommand.ipdl b/ipc/testshell/PTestShellCommand.ipdl
new file mode 100644
index 0000000000..a99c22630d
--- /dev/null
+++ b/ipc/testshell/PTestShellCommand.ipdl
@@ -0,0 +1,23 @@
+/* -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 8 -*- */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+include protocol PTestShell;
+
+include "mozilla/ipc/TestShellParent.h";
+
+namespace mozilla {
+namespace ipc {
+
+[ManualDealloc, ChildImpl=virtual, ParentImpl="TestShellCommandParent"]
+protocol PTestShellCommand
+{
+ manager PTestShell;
+
+parent:
+ async __delete__(nsString aResponse);
+};
+
+} // namespace ipc
+} // namespace mozilla
diff --git a/ipc/testshell/TestShellChild.cpp b/ipc/testshell/TestShellChild.cpp
new file mode 100644
index 0000000000..6af5630d2d
--- /dev/null
+++ b/ipc/testshell/TestShellChild.cpp
@@ -0,0 +1,54 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "TestShellChild.h"
+
+using mozilla::ipc::PTestShellCommandChild;
+using mozilla::ipc::TestShellChild;
+using mozilla::ipc::XPCShellEnvironment;
+
+TestShellChild::TestShellChild()
+ : mXPCShell(XPCShellEnvironment::CreateEnvironment()) {}
+
+mozilla::ipc::IPCResult TestShellChild::RecvExecuteCommand(
+ const nsAString& aCommand) {
+ if (mXPCShell->IsQuitting()) {
+ NS_WARNING("Commands sent after quit command issued!");
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!mXPCShell->EvaluateString(aCommand)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
+
+PTestShellCommandChild* TestShellChild::AllocPTestShellCommandChild(
+ const nsAString& aCommand) {
+ return new PTestShellCommandChild();
+}
+
+bool TestShellChild::DeallocPTestShellCommandChild(
+ PTestShellCommandChild* aCommand) {
+ delete aCommand;
+ return true;
+}
+
+mozilla::ipc::IPCResult TestShellChild::RecvPTestShellCommandConstructor(
+ PTestShellCommandChild* aActor, const nsAString& aCommand) {
+ if (mXPCShell->IsQuitting()) {
+ NS_WARNING("Commands sent after quit command issued!");
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ nsString response;
+ if (!mXPCShell->EvaluateString(aCommand, &response)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+
+ if (!PTestShellCommandChild::Send__delete__(aActor, response)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+}
diff --git a/ipc/testshell/TestShellChild.h b/ipc/testshell/TestShellChild.h
new file mode 100644
index 0000000000..77f2a19832
--- /dev/null
+++ b/ipc/testshell/TestShellChild.h
@@ -0,0 +1,44 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef ipc_testshell_TestShellChild_h
+#define ipc_testshell_TestShellChild_h 1
+
+#include "mozilla/ipc/ProtocolUtils.h"
+#include "mozilla/ipc/PTestShellChild.h"
+#include "mozilla/ipc/PTestShellCommandChild.h"
+#include "mozilla/ipc/XPCShellEnvironment.h"
+
+namespace mozilla {
+
+namespace ipc {
+
+class XPCShellEnvironment;
+
+class TestShellChild : public PTestShellChild {
+ public:
+ NS_INLINE_DECL_REFCOUNTING(TestShellChild, override)
+
+ TestShellChild();
+
+ mozilla::ipc::IPCResult RecvExecuteCommand(const nsAString& aCommand);
+
+ PTestShellCommandChild* AllocPTestShellCommandChild(
+ const nsAString& aCommand);
+
+ mozilla::ipc::IPCResult RecvPTestShellCommandConstructor(
+ PTestShellCommandChild* aActor, const nsAString& aCommand) override;
+
+ bool DeallocPTestShellCommandChild(PTestShellCommandChild* aCommand);
+
+ private:
+ ~TestShellChild() = default;
+
+ UniquePtr<XPCShellEnvironment> mXPCShell;
+};
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* ipc_testshell_TestShellChild_h */
diff --git a/ipc/testshell/TestShellParent.cpp b/ipc/testshell/TestShellParent.cpp
new file mode 100644
index 0000000000..8cd8dad08e
--- /dev/null
+++ b/ipc/testshell/TestShellParent.cpp
@@ -0,0 +1,90 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "TestShellParent.h"
+
+/* This must occur *after* TestShellParent.h to avoid typedefs conflicts. */
+#include "jsfriendapi.h"
+#include "js/CallAndConstruct.h" // JS_CallFunctionValue
+
+#include "mozilla/dom/AutoEntryScript.h"
+
+using namespace mozilla;
+using mozilla::ipc::PTestShellCommandParent;
+using mozilla::ipc::TestShellCommandParent;
+using mozilla::ipc::TestShellParent;
+
+void TestShellParent::ActorDestroy(ActorDestroyReason aWhy) {
+ // Implement me! Bug 1005177
+}
+
+PTestShellCommandParent* TestShellParent::AllocPTestShellCommandParent(
+ const nsAString& aCommand) {
+ return new TestShellCommandParent();
+}
+
+bool TestShellParent::DeallocPTestShellCommandParent(
+ PTestShellCommandParent* aActor) {
+ delete aActor;
+ return true;
+}
+
+bool TestShellParent::CommandDone(TestShellCommandParent* command,
+ const nsAString& aResponse) {
+ // XXX what should happen if the callback fails?
+ /*bool ok = */ command->RunCallback(aResponse);
+ command->ReleaseCallback();
+
+ return true;
+}
+
+bool TestShellCommandParent::SetCallback(JSContext* aCx,
+ const JS::Value& aCallback) {
+ if (!mCallback.initialized()) {
+ mCallback.init(aCx, aCallback);
+ return true;
+ }
+
+ mCallback = aCallback;
+
+ return true;
+}
+
+bool TestShellCommandParent::RunCallback(const nsAString& aResponse) {
+ NS_ENSURE_TRUE(mCallback.isObject(), false);
+
+ MOZ_RELEASE_ASSERT(js::IsFunctionObject(&mCallback.toObject()));
+
+ // We're about to run script via JS_CallFunctionValue, so we need an
+ // AutoEntryScript. This is just for testing and not in any spec.
+ dom::AutoEntryScript aes(&mCallback.toObject(), "TestShellCommand");
+ JSContext* cx = aes.cx();
+ JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
+
+ JSString* str =
+ JS_NewUCStringCopyN(cx, aResponse.BeginReading(), aResponse.Length());
+ NS_ENSURE_TRUE(str, false);
+
+ JS::Rooted<JS::Value> strVal(cx, JS::StringValue(str));
+
+ JS::Rooted<JS::Value> rval(cx);
+ JS::Rooted<JS::Value> callback(cx, mCallback);
+ bool ok = JS_CallFunctionValue(cx, global, callback,
+ JS::HandleValueArray(strVal), &rval);
+ NS_ENSURE_TRUE(ok, false);
+
+ return true;
+}
+
+void TestShellCommandParent::ReleaseCallback() { mCallback.reset(); }
+
+bool TestShellCommandParent::ExecuteCallback(const nsAString& aResponse) {
+ return static_cast<TestShellParent*>(Manager())->CommandDone(this, aResponse);
+}
+
+void TestShellCommandParent::ActorDestroy(ActorDestroyReason why) {
+ if (why == AbnormalShutdown) {
+ ExecuteCallback(u""_ns);
+ }
+}
diff --git a/ipc/testshell/TestShellParent.h b/ipc/testshell/TestShellParent.h
new file mode 100644
index 0000000000..de4f73a94b
--- /dev/null
+++ b/ipc/testshell/TestShellParent.h
@@ -0,0 +1,74 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
+ * vim: sw=2 ts=8 et :
+ */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef ipc_testshell_TestShellParent_h
+#define ipc_testshell_TestShellParent_h 1
+
+#include "mozilla/ipc/PTestShellParent.h"
+#include "mozilla/ipc/PTestShellCommandParent.h"
+
+#include "js/RootingAPI.h"
+#include "js/Value.h"
+#include "nsString.h"
+
+namespace mozilla {
+
+namespace ipc {
+
+class TestShellCommandParent;
+
+class TestShellParent : public PTestShellParent {
+ friend class PTestShellParent;
+
+ public:
+ NS_INLINE_DECL_REFCOUNTING(TestShellParent, override)
+
+ virtual void ActorDestroy(ActorDestroyReason aWhy) override;
+
+ PTestShellCommandParent* AllocPTestShellCommandParent(
+ const nsAString& aCommand);
+
+ bool DeallocPTestShellCommandParent(PTestShellCommandParent* aActor);
+
+ bool CommandDone(TestShellCommandParent* aActor, const nsAString& aResponse);
+
+ private:
+ ~TestShellParent() = default;
+};
+
+class TestShellCommandParent : public PTestShellCommandParent {
+ friend class PTestShellCommandParent;
+
+ public:
+ TestShellCommandParent() = default;
+
+ bool SetCallback(JSContext* aCx, const JS::Value& aCallback);
+
+ bool RunCallback(const nsAString& aResponse);
+
+ void ReleaseCallback();
+
+ protected:
+ bool ExecuteCallback(const nsAString& aResponse);
+
+ void ActorDestroy(ActorDestroyReason why) override;
+
+ mozilla::ipc::IPCResult Recv__delete__(const nsAString& aResponse) {
+ if (!ExecuteCallback(aResponse)) {
+ return IPC_FAIL_NO_REASON(this);
+ }
+ return IPC_OK();
+ }
+
+ private:
+ JS::PersistentRooted<JS::Value> mCallback;
+};
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* ipc_testshell_TestShellParent_h */
diff --git a/ipc/testshell/XPCShellEnvironment.cpp b/ipc/testshell/XPCShellEnvironment.cpp
new file mode 100644
index 0000000000..3d83b36ab4
--- /dev/null
+++ b/ipc/testshell/XPCShellEnvironment.cpp
@@ -0,0 +1,468 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80:
+ * This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifdef HAVE_IO_H
+# include <io.h> /* for isatty() */
+#endif
+#ifdef HAVE_UNISTD_H
+# include <unistd.h> /* for isatty() */
+#endif
+
+#include "jsapi.h"
+#include "js/CharacterEncoding.h"
+#include "js/CompilationAndEvaluation.h" // JS::Compile{,Utf8File}
+#include "js/PropertyAndElement.h" // JS_DefineFunctions, JS_DefineProperty, JS_GetProperty
+#include "js/PropertySpec.h"
+#include "js/RealmOptions.h"
+#include "js/SourceText.h" // JS::Source{Ownership,Text}
+
+#include "xpcpublic.h"
+
+#include "XPCShellEnvironment.h"
+
+#include "mozilla/Utf8.h" // mozilla::Utf8Unit
+#include "mozilla/dom/AutoEntryScript.h"
+#include "mozilla/dom/ScriptSettings.h"
+
+#include "nsIPrincipal.h"
+#include "nsIScriptSecurityManager.h"
+#include "nsIXPConnect.h"
+#include "nsServiceManagerUtils.h"
+
+#include "nsJSUtils.h"
+
+#include "BackstagePass.h"
+
+#include "TestShellChild.h"
+
+using mozilla::dom::AutoEntryScript;
+using mozilla::dom::AutoJSAPI;
+using mozilla::ipc::XPCShellEnvironment;
+using namespace JS;
+
+namespace {
+
+static const char kDefaultRuntimeScriptFilename[] = "xpcshell.js";
+
+inline XPCShellEnvironment* Environment(JS::Handle<JSObject*> global) {
+ AutoJSAPI jsapi;
+ if (!jsapi.Init(global)) {
+ return nullptr;
+ }
+ JSContext* cx = jsapi.cx();
+ Rooted<Value> v(cx);
+ if (!JS_GetProperty(cx, global, "__XPCShellEnvironment", &v) ||
+ !v.get().isDouble()) {
+ return nullptr;
+ }
+ return static_cast<XPCShellEnvironment*>(v.get().toPrivate());
+}
+
+static bool Print(JSContext* cx, unsigned argc, JS::Value* vp) {
+ JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
+
+ for (unsigned i = 0; i < args.length(); i++) {
+ JS::Rooted<JSString*> str(cx, JS::ToString(cx, args[i]));
+ if (!str) return false;
+ JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, str);
+ if (!bytes) return false;
+ fprintf(stdout, "%s%s", i ? " " : "", bytes.get());
+ fflush(stdout);
+ }
+ fputc('\n', stdout);
+ args.rval().setUndefined();
+ return true;
+}
+
+static bool GetLine(char* bufp, FILE* file, const char* prompt) {
+ char line[256];
+ fputs(prompt, stdout);
+ fflush(stdout);
+ if (!fgets(line, sizeof line, file)) return false;
+ strcpy(bufp, line);
+ return true;
+}
+
+static bool Dump(JSContext* cx, unsigned argc, JS::Value* vp) {
+ JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
+
+ if (!args.length()) return true;
+
+ JS::Rooted<JSString*> str(cx, JS::ToString(cx, args[0]));
+ if (!str) return false;
+ JS::UniqueChars bytes = JS_EncodeStringToUTF8(cx, str);
+ if (!bytes) return false;
+
+ fputs(bytes.get(), stdout);
+ fflush(stdout);
+ return true;
+}
+
+static bool Load(JSContext* cx, unsigned argc, JS::Value* vp) {
+ JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
+
+ JS::RootedObject thisObject(cx);
+ if (!args.computeThis(cx, &thisObject)) return false;
+ if (!JS_IsGlobalObject(thisObject)) {
+ JS_ReportErrorASCII(cx, "Trying to load() into a non-global object");
+ return false;
+ }
+
+ for (unsigned i = 0; i < args.length(); i++) {
+ JS::Rooted<JSString*> str(cx, JS::ToString(cx, args[i]));
+ if (!str) {
+ return false;
+ }
+ JS::UniqueChars filename = JS_EncodeStringToUTF8(cx, str);
+ if (!filename) {
+ return false;
+ }
+
+ JS::CompileOptions options(cx);
+ JS::Rooted<JSScript*> script(
+ cx, JS::CompileUtf8Path(cx, options, filename.get()));
+ if (!script) {
+ return false;
+ }
+
+ if (!JS_ExecuteScript(cx, script)) {
+ return false;
+ }
+ }
+ args.rval().setUndefined();
+ return true;
+}
+
+static bool Quit(JSContext* cx, unsigned argc, JS::Value* vp) {
+ Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
+ XPCShellEnvironment* env = Environment(global);
+ env->SetIsQuitting();
+
+ return false;
+}
+
+static bool DumpXPC(JSContext* cx, unsigned argc, JS::Value* vp) {
+ JS::CallArgs args = CallArgsFromVp(argc, vp);
+
+ uint16_t depth = 2;
+ if (args.length() > 0) {
+ if (!JS::ToUint16(cx, args[0], &depth)) return false;
+ }
+
+ nsCOMPtr<nsIXPConnect> xpc = nsIXPConnect::XPConnect();
+ if (xpc) xpc->DebugDump(int16_t(depth));
+ args.rval().setUndefined();
+ return true;
+}
+
+static bool GC(JSContext* cx, unsigned argc, JS::Value* vp) {
+ JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
+
+ JS_GC(cx);
+
+ args.rval().setUndefined();
+ return true;
+}
+
+#ifdef JS_GC_ZEAL
+static bool GCZeal(JSContext* cx, unsigned argc, JS::Value* vp) {
+ CallArgs args = CallArgsFromVp(argc, vp);
+
+ uint32_t zeal;
+ if (!ToUint32(cx, args.get(0), &zeal)) return false;
+
+ JS_SetGCZeal(cx, uint8_t(zeal), JS_DEFAULT_ZEAL_FREQ);
+ return true;
+}
+#endif
+
+#ifdef ANDROID
+static bool ChangeTestShellDir(JSContext* cx, unsigned argc, Value* vp) {
+ // This method should only be used by testing/xpcshell/head.js to change to
+ // the correct directory on Android Remote XPCShell tests.
+ //
+ // TODO: Bug 1801725 - Find a more ergonomic way to do this than exposing
+ // identical methods in XPCShellEnvironment and XPCShellImpl to chdir on
+ // android for Remote XPCShell tests on Android.
+ CallArgs args = CallArgsFromVp(argc, vp);
+
+ if (args.length() != 1) {
+ JS_ReportErrorASCII(cx, "changeTestShellDir() takes one argument");
+ return false;
+ }
+
+ nsAutoJSCString path;
+ if (!path.init(cx, args[0])) {
+ JS_ReportErrorASCII(
+ cx, "changeTestShellDir(): could not convert argument 1 to string");
+ return false;
+ }
+
+ if (chdir(path.get())) {
+ JS_ReportErrorASCII(cx, "changeTestShellDir(): could not change directory");
+ return false;
+ }
+
+ return true;
+}
+#endif
+
+const JSFunctionSpec gGlobalFunctions[] = {
+ JS_FN("print", Print, 0, 0),
+ JS_FN("load", Load, 1, 0),
+ JS_FN("quit", Quit, 0, 0),
+ JS_FN("dumpXPC", DumpXPC, 1, 0),
+ JS_FN("dump", Dump, 1, 0),
+ JS_FN("gc", GC, 0, 0),
+#ifdef JS_GC_ZEAL
+ JS_FN("gczeal", GCZeal, 1, 0),
+#endif
+#ifdef ANDROID
+ JS_FN("changeTestShellDir", ChangeTestShellDir, 1, 0),
+#endif
+ JS_FS_END};
+
+typedef enum JSShellErrNum {
+#define MSG_DEF(name, number, count, exception, format) name = number,
+#include "jsshell.msg"
+#undef MSG_DEF
+ JSShellErr_Limit
+#undef MSGDEF
+} JSShellErrNum;
+
+} /* anonymous namespace */
+
+void XPCShellEnvironment::ProcessFile(JSContext* cx, const char* filename,
+ FILE* file, bool forceTTY) {
+ XPCShellEnvironment* env = this;
+
+ JS::Rooted<JS::Value> result(cx);
+ int lineno, startline;
+ bool ok, hitEOF;
+ char *bufp, buffer[4096];
+ JSString* str;
+
+ JS::Rooted<JSObject*> global(cx, JS::CurrentGlobalOrNull(cx));
+ MOZ_ASSERT(global);
+
+ if (forceTTY) {
+ file = stdin;
+ } else if (!isatty(fileno(file))) {
+ /*
+ * It's not interactive - just execute it.
+ *
+ * Support the UNIX #! shell hack; gobble the first line if it starts
+ * with '#'.
+ */
+ int ch = fgetc(file);
+ if (ch == '#') {
+ while ((ch = fgetc(file)) != EOF) {
+ if (ch == '\n' || ch == '\r') break;
+ }
+ }
+ ungetc(ch, file);
+
+ JS::CompileOptions options(cx);
+ options.setFileAndLine(filename, 1);
+
+ JS::Rooted<JSScript*> script(cx, JS::CompileUtf8File(cx, options, file));
+ if (script) {
+ (void)JS_ExecuteScript(cx, script, &result);
+ }
+
+ return;
+ }
+
+ /* It's an interactive filehandle; drop into read-eval-print loop. */
+ lineno = 1;
+ hitEOF = false;
+ do {
+ bufp = buffer;
+ *bufp = '\0';
+
+ /*
+ * Accumulate lines until we get a 'compilable unit' - one that either
+ * generates an error (before running out of source) or that compiles
+ * cleanly. This should be whenever we get a complete statement that
+ * coincides with the end of a line.
+ */
+ startline = lineno;
+ do {
+ if (!GetLine(bufp, file, startline == lineno ? "js> " : "")) {
+ hitEOF = true;
+ break;
+ }
+ bufp += strlen(bufp);
+ lineno++;
+ } while (
+ !JS_Utf8BufferIsCompilableUnit(cx, global, buffer, strlen(buffer)));
+
+ /* Clear any pending exception from previous failed compiles. */
+ JS_ClearPendingException(cx);
+
+ JS::CompileOptions options(cx);
+ options.setFileAndLine("typein", startline);
+
+ JS::SourceText<mozilla::Utf8Unit> srcBuf;
+ JS::Rooted<JSScript*> script(cx);
+
+ if (srcBuf.init(cx, buffer, strlen(buffer),
+ JS::SourceOwnership::Borrowed) &&
+ (script = JS::Compile(cx, options, srcBuf))) {
+ ok = JS_ExecuteScript(cx, script, &result);
+ if (ok && !result.isUndefined()) {
+ /* Suppress warnings from JS::ToString(). */
+ JS::AutoSuppressWarningReporter suppressWarnings(cx);
+ str = JS::ToString(cx, result);
+ JS::UniqueChars bytes;
+ if (str) bytes = JS_EncodeStringToLatin1(cx, str);
+
+ if (!!bytes)
+ fprintf(stdout, "%s\n", bytes.get());
+ else
+ ok = false;
+ }
+ }
+ } while (!hitEOF && !env->IsQuitting());
+
+ fprintf(stdout, "\n");
+}
+
+// static
+XPCShellEnvironment* XPCShellEnvironment::CreateEnvironment() {
+ auto* env = new XPCShellEnvironment();
+ if (env && !env->Init()) {
+ delete env;
+ env = nullptr;
+ }
+ return env;
+}
+
+XPCShellEnvironment::XPCShellEnvironment() : mQuitting(false) {}
+
+XPCShellEnvironment::~XPCShellEnvironment() {
+ if (GetGlobalObject()) {
+ AutoJSAPI jsapi;
+ if (!jsapi.Init(GetGlobalObject())) {
+ return;
+ }
+ JS_SetAllNonReservedSlotsToUndefined(mGlobalHolder);
+ mGlobalHolder.reset();
+
+ JS_GC(jsapi.cx());
+ }
+}
+
+bool XPCShellEnvironment::Init() {
+ nsresult rv;
+
+ // unbuffer stdout so that output is in the correct order; note that stderr
+ // is unbuffered by default
+ setbuf(stdout, 0);
+
+ AutoSafeJSContext cx;
+
+ mGlobalHolder.init(cx);
+
+ nsCOMPtr<nsIPrincipal> principal;
+ nsCOMPtr<nsIScriptSecurityManager> securityManager =
+ do_GetService(NS_SCRIPTSECURITYMANAGER_CONTRACTID, &rv);
+ if (NS_SUCCEEDED(rv) && securityManager) {
+ rv = securityManager->GetSystemPrincipal(getter_AddRefs(principal));
+ if (NS_FAILED(rv)) {
+ fprintf(stderr,
+ "+++ Failed to obtain SystemPrincipal from ScriptSecurityManager "
+ "service.\n");
+ }
+ } else {
+ fprintf(stderr,
+ "+++ Failed to get ScriptSecurityManager service, running without "
+ "principals");
+ }
+
+ auto backstagePass = MakeRefPtr<BackstagePass>();
+
+ JS::RealmOptions options;
+ options.creationOptions().setNewCompartmentInSystemZone();
+ xpc::SetPrefableRealmOptions(options);
+
+ JS::Rooted<JSObject*> globalObj(cx);
+ rv = xpc::InitClassesWithNewWrappedGlobal(
+ cx, static_cast<nsIGlobalObject*>(backstagePass), principal, 0, options,
+ &globalObj);
+ if (NS_FAILED(rv)) {
+ NS_ERROR("InitClassesWithNewWrappedGlobal failed!");
+ return false;
+ }
+
+ if (!globalObj) {
+ NS_ERROR("Failed to get global JSObject!");
+ return false;
+ }
+ JSAutoRealm ar(cx, globalObj);
+
+ backstagePass->SetGlobalObject(globalObj);
+
+ JS::Rooted<Value> privateVal(cx, PrivateValue(this));
+ if (!JS_DefineProperty(cx, globalObj, "__XPCShellEnvironment", privateVal,
+ JSPROP_READONLY | JSPROP_PERMANENT) ||
+ !JS_DefineFunctions(cx, globalObj, gGlobalFunctions)) {
+ NS_ERROR("JS_DefineFunctions failed!");
+ return false;
+ }
+
+ mGlobalHolder = globalObj;
+
+ FILE* runtimeScriptFile = fopen(kDefaultRuntimeScriptFilename, "r");
+ if (runtimeScriptFile) {
+ fprintf(stdout, "[loading '%s'...]\n", kDefaultRuntimeScriptFilename);
+ ProcessFile(cx, kDefaultRuntimeScriptFilename, runtimeScriptFile, false);
+ fclose(runtimeScriptFile);
+ }
+
+ return true;
+}
+
+bool XPCShellEnvironment::EvaluateString(const nsAString& aString,
+ nsString* aResult) {
+ AutoEntryScript aes(GetGlobalObject(),
+ "ipc XPCShellEnvironment::EvaluateString");
+ JSContext* cx = aes.cx();
+
+ JS::CompileOptions options(cx);
+ options.setFileAndLine("typein", 0);
+
+ JS::SourceText<char16_t> srcBuf;
+ if (!srcBuf.init(cx, aString.BeginReading(), aString.Length(),
+ JS::SourceOwnership::Borrowed)) {
+ return false;
+ }
+
+ JS::Rooted<JSScript*> script(cx, JS::Compile(cx, options, srcBuf));
+ if (!script) {
+ return false;
+ }
+
+ if (aResult) {
+ aResult->Truncate();
+ }
+
+ JS::Rooted<JS::Value> result(cx);
+ bool ok = JS_ExecuteScript(cx, script, &result);
+ if (ok && !result.isUndefined()) {
+ /* Suppress warnings from JS::ToString(). */
+ JS::AutoSuppressWarningReporter suppressWarnings(cx);
+ JSString* str = JS::ToString(cx, result);
+ nsAutoJSString autoStr;
+ if (str) autoStr.init(cx, str);
+
+ if (!autoStr.IsEmpty() && aResult) {
+ aResult->Assign(autoStr);
+ }
+ }
+
+ return true;
+}
diff --git a/ipc/testshell/XPCShellEnvironment.h b/ipc/testshell/XPCShellEnvironment.h
new file mode 100644
index 0000000000..b479ec85b6
--- /dev/null
+++ b/ipc/testshell/XPCShellEnvironment.h
@@ -0,0 +1,57 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef _IPC_TESTSHELL_XPCSHELLENVIRONMENT_H_
+#define _IPC_TESTSHELL_XPCSHELLENVIRONMENT_H_
+
+#include "base/basictypes.h"
+
+#include <string>
+#include <stdio.h>
+
+#include "nsCOMPtr.h"
+#include "nsDebug.h"
+#include "nsString.h"
+#include "nsJSPrincipals.h"
+#include "nsContentUtils.h"
+#include "js/RootingAPI.h"
+#include "js/TypeDecls.h"
+
+struct JSPrincipals;
+
+namespace mozilla {
+namespace ipc {
+
+class XPCShellEnvironment {
+ public:
+ static XPCShellEnvironment* CreateEnvironment();
+ ~XPCShellEnvironment();
+
+ void ProcessFile(JSContext* cx, const char* filename, FILE* file,
+ bool forceTTY);
+ bool EvaluateString(const nsAString& aString, nsString* aResult = nullptr);
+
+ JSPrincipals* GetPrincipal() {
+ return nsJSPrincipals::get(nsContentUtils::GetSystemPrincipal());
+ }
+
+ JSObject* GetGlobalObject() { return mGlobalHolder; }
+
+ void SetIsQuitting() { mQuitting = true; }
+ bool IsQuitting() { return mQuitting; }
+
+ protected:
+ XPCShellEnvironment();
+ bool Init();
+
+ private:
+ JS::PersistentRooted<JSObject*> mGlobalHolder;
+
+ bool mQuitting;
+};
+
+} /* namespace ipc */
+} /* namespace mozilla */
+
+#endif /* _IPC_TESTSHELL_XPCSHELLENVIRONMENT_H_ */
diff --git a/ipc/testshell/moz.build b/ipc/testshell/moz.build
new file mode 100644
index 0000000000..c30175c0c0
--- /dev/null
+++ b/ipc/testshell/moz.build
@@ -0,0 +1,37 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+EXPORTS.mozilla.ipc += [
+ "TestShellChild.h",
+ "TestShellParent.h",
+ "XPCShellEnvironment.h",
+]
+
+XPCSHELL_TESTS_MANIFESTS += ["tests/xpcshell.toml"]
+
+SOURCES += [
+ "TestShellChild.cpp",
+ "TestShellParent.cpp",
+ "XPCShellEnvironment.cpp",
+]
+
+IPDL_SOURCES = [
+ "PTestShell.ipdl",
+ "PTestShellCommand.ipdl",
+]
+
+include("/ipc/chromium/chromium-config.mozbuild")
+
+FINAL_LIBRARY = "xul"
+
+# For xpcshell error messages and nsAutoJSString
+LOCAL_INCLUDES += [
+ "/dom/base",
+ "/js/xpconnect/src",
+]
+
+with Files("**"):
+ BUG_COMPONENT = ("Core", "XPConnect")
diff --git a/ipc/testshell/tests/test_ipcshell.js b/ipc/testshell/tests/test_ipcshell.js
new file mode 100644
index 0000000000..3e2e54e670
--- /dev/null
+++ b/ipc/testshell/tests/test_ipcshell.js
@@ -0,0 +1,34 @@
+// eslint-disable-next-line mozilla/use-services
+const runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
+
+function callback(result) {
+ Assert.equal(result, Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT);
+ do_test_finished();
+}
+
+function run_test() {
+ do_test_pending();
+
+ Assert.equal(runtime.processType, Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
+
+ sendCommand("load('test_ipcshell_child.js');");
+
+ sendCommand("runtime.processType;", callback);
+
+ [
+ ["C", "D"],
+ ["D", "C"],
+ ["\u010C", "D"],
+ ["D", "\u010C"],
+ ].forEach(function (pair) {
+ do_test_pending();
+ var cmp = pair[0].localeCompare(pair[1]);
+ sendCommand(
+ "'" + pair[0] + "'.localeCompare('" + pair[1] + "');",
+ function (result) {
+ Assert.equal(cmp, result);
+ do_test_finished();
+ }
+ );
+ });
+}
diff --git a/ipc/testshell/tests/test_ipcshell_child.js b/ipc/testshell/tests/test_ipcshell_child.js
new file mode 100644
index 0000000000..f2a0e1e245
--- /dev/null
+++ b/ipc/testshell/tests/test_ipcshell_child.js
@@ -0,0 +1,6 @@
+// eslint-disable-next-line mozilla/use-services
+const runtime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);
+
+function run_test() {
+ Assert.equal(runtime.processType, Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT);
+}
diff --git a/ipc/testshell/tests/xpcshell.toml b/ipc/testshell/tests/xpcshell.toml
new file mode 100644
index 0000000000..9e3b377e24
--- /dev/null
+++ b/ipc/testshell/tests/xpcshell.toml
@@ -0,0 +1,9 @@
+[DEFAULT]
+head = ""
+skip-if = ["os == 'android'"]
+
+["test_ipcshell.js"]
+# Bug 676963: test fails consistently on Android
+fail-if = ["os == 'android'"]
+
+["test_ipcshell_child.js"]